AnimatedImageView.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. assumeIsolatedDuringDeinit { view in
  224. view.displayLink.invalidate()
  225. }
  226. }
  227. }
  228. #if os(macOS)
  229. public override init(frame frameRect: NSRect) {
  230. super.init(frame: frameRect)
  231. commonInit()
  232. }
  233. public required init?(coder: NSCoder) {
  234. super.init(coder: coder)
  235. commonInit()
  236. }
  237. private func commonInit() {
  238. super.animates = false
  239. wantsLayer = true
  240. }
  241. open override var animates: Bool {
  242. get {
  243. if isDisplayLinkInitialized {
  244. return !displayLink.isPaused
  245. } else {
  246. return super.animates
  247. }
  248. }
  249. set {
  250. if newValue {
  251. startAnimating()
  252. } else {
  253. stopAnimating()
  254. }
  255. }
  256. }
  257. open func startAnimating() {
  258. guard let animator = animator else { return }
  259. guard !animator.isReachMaxRepeatCount else { return }
  260. displayLink.isPaused = false
  261. }
  262. open func stopAnimating() {
  263. if isDisplayLinkInitialized {
  264. displayLink.isPaused = true
  265. }
  266. }
  267. open override var wantsUpdateLayer: Bool {
  268. return true
  269. }
  270. open override func updateLayer() {
  271. if let frame = animator?.currentFrameImage ?? currentFrame, let layer = layer {
  272. layer.contents = frame.kf.cgImage
  273. layer.contentsScale = frame.kf.scale
  274. layer.contentsGravity = determineContentsGravity(for: frame)
  275. currentFrame = frame
  276. }
  277. }
  278. private func determineContentsGravity(for image: NSImage) -> CALayerContentsGravity {
  279. switch imageScaling {
  280. case .scaleProportionallyDown:
  281. if image.size.width > bounds.width || image.size.height > bounds.height {
  282. return .resizeAspect
  283. } else {
  284. return .center
  285. }
  286. case .scaleProportionallyUpOrDown:
  287. return .resizeAspect
  288. case .scaleAxesIndependently:
  289. return .resize
  290. case .scaleNone:
  291. return .center
  292. default:
  293. return .resizeAspect
  294. }
  295. }
  296. open override func viewDidMoveToWindow() {
  297. super.viewDidMoveToWindow()
  298. didMove()
  299. }
  300. open override func viewDidMoveToSuperview() {
  301. super.viewDidMoveToSuperview()
  302. didMove()
  303. }
  304. #else
  305. override open var isAnimating: Bool {
  306. if isDisplayLinkInitialized {
  307. return !displayLink.isPaused
  308. } else {
  309. return super.isAnimating
  310. }
  311. }
  312. override open func startAnimating() {
  313. guard !isAnimating else { return }
  314. guard let animator = animator else { return }
  315. guard !animator.isReachMaxRepeatCount else { return }
  316. displayLink.isPaused = false
  317. }
  318. override open func stopAnimating() {
  319. super.stopAnimating()
  320. if isDisplayLinkInitialized {
  321. displayLink.isPaused = true
  322. }
  323. }
  324. override open func display(_ layer: CALayer) {
  325. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  326. }
  327. override open func didMoveToWindow() {
  328. super.didMoveToWindow()
  329. didMove()
  330. }
  331. override open func didMoveToSuperview() {
  332. super.didMoveToSuperview()
  333. didMove()
  334. }
  335. #endif
  336. // This is for back compatibility that using regular `UIImageView` to show animated image.
  337. override func shouldPreloadAllAnimation() -> Bool {
  338. return false
  339. }
  340. // Reset the animator.
  341. private func reset() {
  342. animator = nil
  343. currentFrame = nil
  344. if let image = image, let frameSource = image.kf.frameSource {
  345. #if os(visionOS)
  346. let scale = UITraitCollection.current.displayScale
  347. #elseif os(macOS)
  348. let scale = image.recommendedLayerContentsScale(window?.backingScaleFactor ?? 0.0)
  349. let contentMode = imageScaling
  350. #else
  351. var scale: CGFloat = 0
  352. if #available(iOS 13.0, tvOS 13.0, *) {
  353. scale = UITraitCollection.current.displayScale
  354. } else {
  355. scale = UIScreen.main.scale
  356. }
  357. #endif
  358. currentFrame = image
  359. let targetSize = bounds.scaled(scale).size
  360. let animator = Animator(
  361. frameSource: frameSource,
  362. contentMode: contentMode,
  363. size: targetSize,
  364. imageSize: image.kf.size,
  365. imageScale: image.kf.scale,
  366. framePreloadCount: framePreloadCount,
  367. repeatCount: repeatCount,
  368. preloadQueue: preloadQueue)
  369. animator.delegate = self
  370. animator.needsPrescaling = needsPrescaling
  371. animator.prepareFramesAsynchronously()
  372. self.animator = animator
  373. }
  374. didMove()
  375. }
  376. private func didMove() {
  377. if autoPlayAnimatedImage && animator != nil {
  378. if let _ = superview, let _ = window {
  379. startAnimating()
  380. } else {
  381. stopAnimating()
  382. }
  383. }
  384. }
  385. /// If the Animator cannot prepare the next frame in time, `animator.currentFrameImage` will return nil.
  386. /// To prevent unexpected blinking in the ImageView, we maintain a cache of the currently displayed frame
  387. /// to use as a fallback in such scenarios.
  388. private var currentFrame: KFCrossPlatformImage?
  389. /// Update the current frame with the displayLink duration.
  390. @MainActor
  391. private func updateFrameIfNeeded() {
  392. guard let animator = animator else {
  393. return
  394. }
  395. guard !animator.isFinished else {
  396. stopAnimating()
  397. delegate?.animatedImageViewDidFinishAnimating(self)
  398. return
  399. }
  400. let duration: CFTimeInterval
  401. // CA based display link is opt-out from ProMotion by default.
  402. // So the duration and its FPS might not match.
  403. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  404. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  405. // cause the preferredFramesPerSecond being 0
  406. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  407. if preferredFramesPerSecond == 0 {
  408. duration = displayLink.duration
  409. } else {
  410. // Some devices (like iPad Pro 10.5) will have a different FPS.
  411. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  412. }
  413. if animator.shouldChangeFrame(with: duration) {
  414. #if os(macOS)
  415. layer?.setNeedsDisplay()
  416. #else
  417. layer.setNeedsDisplay()
  418. #endif
  419. }
  420. }
  421. }
  422. extension AnimatedImageView {
  423. // An actor's deinit is nonisolated so we need to cleanup state that needs to exist past this instance's deinit.
  424. // Currently there is no way to accomplish this that wouldn't be an error in Swift 6, hopefully that changes at
  425. // some point. This evolution proposal attempts to address this problem:
  426. // https://github.com/swiftlang/swift-evolution/blob/main/proposals/0371-isolated-synchronous-deinit.md
  427. // Method influenced from
  428. // https://github.com/swiftlang/swift/blob/47803aad3b0d326e5231ad0d7936d40264f56edd/stdlib/public/Concurrency/ExecutorAssertions.swift#L351
  429. @_unavailableFromAsync(message: "express the closure as an explicit function declared on the specified 'actor' instead")
  430. private nonisolated func assumeIsolatedDuringDeinit<T>(_ operation: @MainActor (AnimatedImageView) throws -> T) rethrows -> T {
  431. typealias Isolated = (AnimatedImageView) throws -> T
  432. // To do the unsafe cast, we have to pretend it's @escaping.
  433. return try withoutActuallyEscaping(operation) { (_ fn: @escaping Isolated) throws -> T in
  434. return try fn(self)
  435. }
  436. }
  437. }
  438. @MainActor
  439. protocol AnimatorDelegate: AnyObject {
  440. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  441. }
  442. extension AnimatedImageView: AnimatorDelegate {
  443. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  444. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  445. }
  446. }
  447. extension AnimatedImageView {
  448. // Represents a single frame in a GIF.
  449. struct AnimatedFrame {
  450. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  451. let image: KFCrossPlatformImage?
  452. // The duration that this frame should remain active.
  453. let duration: TimeInterval
  454. // A placeholder frame with no image assigned.
  455. // Used to replace frames that are no longer needed in the animation.
  456. var placeholderFrame: AnimatedFrame {
  457. return AnimatedFrame(image: nil, duration: duration)
  458. }
  459. // Whether this frame instance contains an image or not.
  460. var isPlaceholder: Bool {
  461. return image == nil
  462. }
  463. // Returns a new instance from an optional image.
  464. //
  465. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  466. // - returns: An `AnimatedFrame` instance.
  467. func makeAnimatedFrame(image: KFCrossPlatformImage?) -> AnimatedFrame {
  468. return AnimatedFrame(image: image, duration: duration)
  469. }
  470. }
  471. }
  472. extension AnimatedImageView {
  473. // MARK: - Animator
  474. // TODO: Check the thread-safety of `Animator` for Sendable again.
  475. /// An animator which is used to drive the data behind ``AnimatedImageView``.
  476. public class Animator: @unchecked Sendable {
  477. private let size: CGSize
  478. private let imageSize: CGSize
  479. private let imageScale: CGFloat
  480. /// The maximum count of image frames that need to be preloaded.
  481. public let maxFrameCount: Int
  482. private let frameSource: any ImageFrameSource
  483. private let maxRepeatCount: RepeatCount
  484. private let maxTimeStep: TimeInterval = 1.0
  485. private let animatedFrames = SafeArray<AnimatedFrame>()
  486. private var frameCount = 0
  487. private var timeSinceLastFrameChange: TimeInterval = 0.0
  488. private var currentRepeatCount: UInt = 0
  489. var isFinished: Bool = false
  490. var needsPrescaling = true
  491. weak var delegate: (any AnimatorDelegate)?
  492. // Total duration of one animation loop
  493. var loopDuration: TimeInterval = 0
  494. /// The image of the current frame.
  495. public var currentFrameImage: KFCrossPlatformImage? {
  496. return frame(at: currentFrameIndex)
  497. }
  498. /// The duration of the current active frame.
  499. public var currentFrameDuration: TimeInterval {
  500. return duration(at: currentFrameIndex)
  501. }
  502. /// The index of the current animation frame.
  503. public internal(set) var currentFrameIndex = 0 {
  504. didSet {
  505. previousFrameIndex = oldValue
  506. }
  507. }
  508. var previousFrameIndex = 0 {
  509. didSet {
  510. preloadQueue.async {
  511. self.updatePreloadedFrames()
  512. }
  513. }
  514. }
  515. var isReachMaxRepeatCount: Bool {
  516. switch maxRepeatCount {
  517. case .once:
  518. return currentRepeatCount >= 1
  519. case .finite(let maxCount):
  520. return currentRepeatCount >= maxCount
  521. case .infinite:
  522. return false
  523. }
  524. }
  525. /// Whether the current frame is the last frame or not in the animation sequence.
  526. public var isLastFrame: Bool {
  527. return currentFrameIndex == frameCount - 1
  528. }
  529. var preloadingIsNeeded: Bool {
  530. return maxFrameCount < frameCount - 1
  531. }
  532. #if os(macOS)
  533. var contentMode = NSImageScaling.scaleAxesIndependently
  534. #else
  535. var contentMode = UIView.ContentMode.scaleToFill
  536. #endif
  537. private lazy var preloadQueue: DispatchQueue = {
  538. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  539. }()
  540. /// Creates an animator with image source reference.
  541. ///
  542. /// - Parameters:
  543. /// - source: The reference of animated image.
  544. /// - mode: Content mode of the `AnimatedImageView`.
  545. /// - size: Size of the `AnimatedImageView`.
  546. /// - imageSize: Size of the `KingfisherWrapper`.
  547. /// - imageScale: Scale of the `KingfisherWrapper`.
  548. /// - count: Count of frames needed to be preloaded.
  549. /// - repeatCount: The repeat count should this animator uses.
  550. /// - preloadQueue: Dispatch queue used for preloading images.
  551. convenience init(imageSource source: CGImageSource,
  552. contentMode mode: KFCrossPlatformContentMode,
  553. size: CGSize,
  554. imageSize: CGSize,
  555. imageScale: CGFloat,
  556. framePreloadCount count: Int,
  557. repeatCount: RepeatCount,
  558. preloadQueue: DispatchQueue) {
  559. let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil)
  560. self.init(frameSource: frameSource,
  561. contentMode: mode,
  562. size: size,
  563. imageSize: imageSize,
  564. imageScale: imageScale,
  565. framePreloadCount: count,
  566. repeatCount: repeatCount,
  567. preloadQueue: preloadQueue)
  568. }
  569. /// Creates an animator with a custom image frame source.
  570. ///
  571. /// - Parameters:
  572. /// - frameSource: The reference of animated image.
  573. /// - mode: Content mode of the `AnimatedImageView`.
  574. /// - size: Size of the `AnimatedImageView`.
  575. /// - imageSize: Size of the `KingfisherWrapper`.
  576. /// - imageScale: Scale of the `KingfisherWrapper`.
  577. /// - count: Count of frames needed to be preloaded.
  578. /// - repeatCount: The repeat count should this animator uses.
  579. /// - preloadQueue: Dispatch queue used for preloading images.
  580. init(frameSource source: any ImageFrameSource,
  581. contentMode mode: KFCrossPlatformContentMode,
  582. size: CGSize,
  583. imageSize: CGSize,
  584. imageScale: CGFloat,
  585. framePreloadCount count: Int,
  586. repeatCount: RepeatCount,
  587. preloadQueue: DispatchQueue) {
  588. self.frameSource = source
  589. self.contentMode = mode
  590. self.size = size
  591. self.imageSize = imageSize
  592. self.imageScale = imageScale
  593. self.maxFrameCount = count
  594. self.maxRepeatCount = repeatCount
  595. self.preloadQueue = preloadQueue
  596. }
  597. /// Gets the image frame of a given index.
  598. /// - Parameter index: The index of the desired image.
  599. /// - Returns: The decoded image at the frame. `nil` if the index is out of bounds or the image is not yet loaded.
  600. public func frame(at index: Int) -> KFCrossPlatformImage? {
  601. return animatedFrames[index]?.image
  602. }
  603. /// Gets the duration of an image for the given frame index.
  604. /// - Parameter index: The index of the desired image.
  605. /// - Returns: The duration of that frame.
  606. public func duration(at index: Int) -> TimeInterval {
  607. return animatedFrames[index]?.duration ?? .infinity
  608. }
  609. func prepareFramesAsynchronously() {
  610. frameCount = frameSource.frameCount
  611. animatedFrames.reserveCapacity(frameCount)
  612. preloadQueue.async { [weak self] in
  613. self?.setupAnimatedFrames()
  614. }
  615. }
  616. @MainActor
  617. func shouldChangeFrame(with duration: CFTimeInterval) -> Bool {
  618. incrementTimeSinceLastFrameChange(with: duration)
  619. if currentFrameDuration > timeSinceLastFrameChange {
  620. return false
  621. } else {
  622. resetTimeSinceLastFrameChange()
  623. incrementCurrentFrameIndex()
  624. return true
  625. }
  626. }
  627. private func setupAnimatedFrames() {
  628. resetAnimatedFrames()
  629. var duration: TimeInterval = 0
  630. (0..<frameCount).forEach { index in
  631. let frameDuration = frameSource.duration(at: index)
  632. duration += min(frameDuration, maxTimeStep)
  633. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  634. if index > maxFrameCount { return }
  635. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  636. }
  637. self.loopDuration = duration
  638. }
  639. private func resetAnimatedFrames() {
  640. animatedFrames.removeAll()
  641. }
  642. private func loadFrame(at index: Int) -> KFCrossPlatformImage? {
  643. let resize = needsPrescaling && size != .zero
  644. let maxSize = resize ? size : nil
  645. guard let cgImage = frameSource.frame(at: index, maxSize: maxSize) else {
  646. return nil
  647. }
  648. #if os(macOS)
  649. return KFCrossPlatformImage(cgImage: cgImage, size: .zero)
  650. #else
  651. if #available(iOS 15, tvOS 15, *) {
  652. // From iOS 15, a plain image loading causes iOS calling `-[_UIImageCGImageContent initWithCGImage:scale:]`
  653. // in ImageIO, which holds the image ref on the creating thread.
  654. // To get a workaround, create another image ref and use that to create the final image. This leads to
  655. // some performance loss, but there is little we can do.
  656. // https://github.com/onevcat/Kingfisher/issues/1844
  657. // https://github.com/onevcat/Kingfisher/pulls/2194
  658. guard let unretainedImage = CGImage.create(ref: cgImage) else {
  659. return KFCrossPlatformImage(cgImage: cgImage)
  660. }
  661. return KFCrossPlatformImage(cgImage: unretainedImage)
  662. } else {
  663. return KFCrossPlatformImage(cgImage: cgImage)
  664. }
  665. #endif
  666. }
  667. private func updatePreloadedFrames() {
  668. guard preloadingIsNeeded else {
  669. return
  670. }
  671. let previousFrame = animatedFrames[previousFrameIndex]
  672. animatedFrames[previousFrameIndex] = previousFrame?.placeholderFrame
  673. // ensure the image dealloc in main thread
  674. defer {
  675. if let image = previousFrame?.image {
  676. DispatchQueue.main.async {
  677. _ = image
  678. }
  679. }
  680. }
  681. preloadIndexes(start: currentFrameIndex).forEach { index in
  682. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  683. if !currentAnimatedFrame.isPlaceholder { return }
  684. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  685. }
  686. }
  687. @MainActor private func incrementCurrentFrameIndex() {
  688. let wasLastFrame = isLastFrame
  689. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  690. if isLastFrame {
  691. currentRepeatCount += 1
  692. if isReachMaxRepeatCount {
  693. isFinished = true
  694. // Notify the delegate here because the animation is stopping.
  695. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  696. }
  697. } else if wasLastFrame {
  698. // Notify the delegate that the loop completed
  699. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  700. }
  701. }
  702. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  703. timeSinceLastFrameChange += min(maxTimeStep, duration)
  704. }
  705. private func resetTimeSinceLastFrameChange() {
  706. timeSinceLastFrameChange -= currentFrameDuration
  707. }
  708. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  709. return (frameIndex + value) % frameCount
  710. }
  711. private func preloadIndexes(start index: Int) -> [Int] {
  712. let nextIndex = increment(frameIndex: index)
  713. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  714. if lastIndex >= nextIndex {
  715. return [Int](nextIndex...lastIndex)
  716. } else {
  717. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  718. }
  719. }
  720. }
  721. }
  722. class SafeArray<Element> {
  723. private var array: Array<Element> = []
  724. private let lock = NSLock()
  725. subscript(index: Int) -> Element? {
  726. get {
  727. lock.lock()
  728. defer { lock.unlock() }
  729. return array.indices ~= index ? array[index] : nil
  730. }
  731. set {
  732. lock.lock()
  733. defer { lock.unlock() }
  734. if let newValue = newValue, array.indices ~= index {
  735. array[index] = newValue
  736. }
  737. }
  738. }
  739. var count : Int {
  740. lock.lock()
  741. defer { lock.unlock() }
  742. return array.count
  743. }
  744. func reserveCapacity(_ count: Int) {
  745. lock.lock()
  746. defer { lock.unlock() }
  747. array.reserveCapacity(count)
  748. }
  749. func append(_ element: Element) {
  750. lock.lock()
  751. defer { lock.unlock() }
  752. array += [element]
  753. }
  754. func removeAll() {
  755. lock.lock()
  756. defer { lock.unlock() }
  757. array = []
  758. }
  759. }
  760. #endif