Blame view

Pods/Kingfisher/Sources/AnimatedImageView.swift 12.2 KB
d774f0637   Trịnh Văn Quân   fisrt comit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
  //
  //  AnimatableImageView.swift
  //  Kingfisher
  //
  //  Created by bl4ckra1sond3tre on 4/22/16.
  //
  //  The AnimatableImageView, AnimatedFrame and Animator is a modified version of 
  //  some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
  //
  //  The MIT License (MIT)
  //
  //  Copyright (c) 2017 Reda Lemeden.
  //
  //  Permission is hereby granted, free of charge, to any person obtaining a copy of
  //  this software and associated documentation files (the "Software"), to deal in
  //  the Software without restriction, including without limitation the rights to
  //  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  //  the Software, and to permit persons to whom the Software is furnished to do so,
  //  subject to the following conditions:
  //
  //  The above copyright notice and this permission notice shall be included in all
  //  copies or substantial portions of the Software.
  //
  //  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  //  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  //  FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  //  COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  //  IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  //  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  //
  //  The name and characters used in the demo of this software are property of their
  //  respective owners.
  
  import UIKit
  import ImageIO
  
  /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
  open class AnimatedImageView: UIImageView {
      
      /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
      class TargetProxy {
          private weak var target: AnimatedImageView?
          
          init(target: AnimatedImageView) {
              self.target = target
          }
          
          @objc func onScreenUpdate() {
              target?.updateFrame()
          }
      }
      
      // MARK: - Public property
      /// Whether automatically play the animation when the view become visible. Default is true.
      public var autoPlayAnimatedImage = true
      
      /// The size of the frame cache.
      public var framePreloadCount = 10
      
      /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
      public var needsPrescaling = true
      
      /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
      public var runLoopMode = RunLoopMode.commonModes {
          willSet {
              if runLoopMode == newValue {
                  return
              } else {
                  stopAnimating()
                  displayLink.remove(from: .main, forMode: runLoopMode)
                  displayLink.add(to: .main, forMode: newValue)
                  startAnimating()
              }
          }
      }
      
      // MARK: - Private property
      /// `Animator` instance that holds the frames of a specific image in memory.
      private var animator: Animator?
      
      /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
      private var isDisplayLinkInitialized: Bool = false
      
      /// A display link that keeps calling the `updateFrame` method on every screen refresh.
      private lazy var displayLink: CADisplayLink = {
          self.isDisplayLinkInitialized = true
          let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
          displayLink.add(to: .main, forMode: self.runLoopMode)
          displayLink.isPaused = true
          return displayLink
      }()
      
      // MARK: - Override
      override open var image: Image? {
          didSet {
              if image != oldValue {
                  reset()
              }
              setNeedsDisplay()
              layer.setNeedsDisplay()
          }
      }
      
      deinit {
          if isDisplayLinkInitialized {
              displayLink.invalidate()
          }
      }
      
      override open var isAnimating: Bool {
          if isDisplayLinkInitialized {
              return !displayLink.isPaused
          } else {
              return super.isAnimating
          }
      }
      
      /// Starts the animation.
      override open func startAnimating() {
          if self.isAnimating {
              return
          } else {
              displayLink.isPaused = false
          }
      }
      
      /// Stops the animation.
      override open func stopAnimating() {
          super.stopAnimating()
          if isDisplayLinkInitialized {
              displayLink.isPaused = true
          }
      }
      
      override open func display(_ layer: CALayer) {
          if let currentFrame = animator?.currentFrame {
              layer.contents = currentFrame.cgImage
          } else {
              layer.contents = image?.cgImage
          }
      }
      
      override open func didMoveToWindow() {
          super.didMoveToWindow()
          didMove()
      }
      
      override open func didMoveToSuperview() {
          super.didMoveToSuperview()
          didMove()
      }
      
      // This is for back compatibility that using regular UIImageView to show GIF.
      override func shouldPreloadAllGIF() -> Bool {
          return false
      }
      
      // MARK: - Private method
      /// Reset the animator.
      private func reset() {
          animator = nil
          if let imageSource = image?.kf.imageSource?.imageRef {
              animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
              animator?.needsPrescaling = needsPrescaling
              animator?.prepareFramesAsynchronously()
          }
          didMove()
      }
      
      private func didMove() {
          if autoPlayAnimatedImage && animator != nil {
              if let _ = superview, let _ = window {
                  startAnimating()
              } else {
                  stopAnimating()
              }
          }
      }
      
      /// Update the current frame with the displayLink duration.
      private func updateFrame() {
          if animator?.updateCurrentFrame(duration: displayLink.duration) ?? false {
              layer.setNeedsDisplay()
          }
      }
  }
  
  /// Keeps a reference to an `Image` instance and its duration as a GIF frame.
  struct AnimatedFrame {
      var image: Image?
      let duration: TimeInterval
      
      static let null: AnimatedFrame = AnimatedFrame(image: .none, duration: 0.0)
  }
  
  // MARK: - Animator
  class Animator {
      // MARK: Private property
      fileprivate let size: CGSize
      fileprivate let maxFrameCount: Int
      fileprivate let imageSource: CGImageSource
      
      fileprivate var animatedFrames = [AnimatedFrame]()
      fileprivate let maxTimeStep: TimeInterval = 1.0
      fileprivate var frameCount = 0
      fileprivate var currentFrameIndex = 0
      fileprivate var currentPreloadIndex = 0
      fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0
      fileprivate var needsPrescaling = true
      
      /// Loop count of animatd image.
      private var loopCount = 0
      
      var currentFrame: UIImage? {
          return frame(at: currentFrameIndex)
      }
      
      var contentMode = UIViewContentMode.scaleToFill
      
      private lazy var preloadQueue: DispatchQueue = {
          return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
      }()
      
      /**
       Init an animator with image source reference.
       
       - parameter imageSource: The reference of animated image.
       - parameter contentMode: Content mode of AnimatedImageView.
       - parameter size: Size of AnimatedImageView.
       - parameter framePreloadCount: Frame cache size.
       
       - returns: The animator object.
       */
      init(imageSource source: CGImageSource, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount count: Int) {
          self.imageSource = source
          self.contentMode = mode
          self.size = size
          self.maxFrameCount = count
      }
      
      func frame(at index: Int) -> Image? {
          return animatedFrames[safe: index]?.image
      }
      
      func prepareFramesAsynchronously() {
          preloadQueue.async { [weak self] in
              self?.prepareFrames()
          }
      }
      
      private func prepareFrames() {
          frameCount = CGImageSourceGetCount(imageSource)
          
          if let properties = CGImageSourceCopyProperties(imageSource, nil),
              let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
              let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
          {
              self.loopCount = loopCount
          }
          
          let frameToProcess = min(frameCount, maxFrameCount)
          animatedFrames.reserveCapacity(frameToProcess)
          animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
          currentPreloadIndex = (frameToProcess + 1) % frameCount
      }
      
      private func prepareFrame(at index: Int) -> AnimatedFrame {
          
          guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
              return AnimatedFrame.null
          }
          
          let defaultGIFFrameDuration = 0.100
          let frameDuration = imageSource.kf.gifProperties(at: index).map {
              gifInfo -> Double in
              
              let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
              let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
              let duration = unclampedDelayTime ?? delayTime ?? 0.0
              
              /**
               http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
               Many annoying ads specify a 0 duration to make an image flash as quickly as
               possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
               for any frames that specify a duration of <= 10 ms.
               See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
               
               See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
               */
              return duration > 0.011 ? duration : defaultGIFFrameDuration
          } ?? defaultGIFFrameDuration
          
          let image = Image(cgImage: imageRef)
          let scaledImage: Image?
          
          if needsPrescaling {
              scaledImage = image.kf.resize(to: size, for: contentMode)
          } else {
              scaledImage = image
          }
          
          return AnimatedFrame(image: scaledImage, duration: frameDuration)
      }
      
      /**
       Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
       */
      func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
          timeSinceLastFrameChange += min(maxTimeStep, duration)
          guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else {
              return false
          }
          
          timeSinceLastFrameChange -= frameDuration
          
          let lastFrameIndex = currentFrameIndex
          currentFrameIndex += 1
          currentFrameIndex = currentFrameIndex % animatedFrames.count
          
          if animatedFrames.count < frameCount {
              preloadFrameAsynchronously(at: lastFrameIndex)
          }
          return true
      }
      
      private func preloadFrameAsynchronously(at index: Int) {
          preloadQueue.async { [weak self] in
              self?.preloadFrame(at: index)
          }
      }
      
      private func preloadFrame(at index: Int) {
          animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
          currentPreloadIndex += 1
          currentPreloadIndex = currentPreloadIndex % frameCount
      }
  }
  
  extension CGImageSource: KingfisherCompatible { }
  extension Kingfisher where Base: CGImageSource {
      func gifProperties(at index: Int) -> [String: Double]? {
          let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
          return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
      }
  }
  
  extension Array {
      subscript(safe index: Int) -> Element? {
          return indices ~= index ? self[index] : nil
      }
  }
  
  private func pure<T>(_ value: T) -> [T] {
      return [value]
  }