ImageProgressive.swift 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. //
  2. // ImageProgressive.swift
  3. // Kingfisher
  4. //
  5. // Created by lixiang on 2019/5/10.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. import CoreGraphics
  28. private let sharedProcessingQueue: CallbackQueue =
  29. .dispatch(DispatchQueue(label: "com.onevcat.Kingfisher.ImageDownloader.Process"))
  30. public struct ImageProgressive {
  31. /// A default `ImageProgressive` could be used across.
  32. public static let `default` = ImageProgressive(
  33. isBlur: true,
  34. isWait: false,
  35. isFastestScan: true,
  36. scanInterval: 0
  37. )
  38. /// Whether to enable blur effect processing
  39. let isBlur: Bool
  40. /// Whether to wait for the scan to complete
  41. let isWait: Bool
  42. /// Whether to enable the fastest scan
  43. let isFastestScan: Bool
  44. /// Minimum time interval for each scan
  45. let scanInterval: TimeInterval
  46. public init(isBlur: Bool,
  47. isWait: Bool,
  48. isFastestScan: Bool,
  49. scanInterval: TimeInterval) {
  50. self.isBlur = isBlur
  51. self.isWait = isWait
  52. self.isFastestScan = isFastestScan
  53. self.scanInterval = scanInterval
  54. }
  55. }
  56. final class ImageProgressiveProvider {
  57. private let options: KingfisherParsedOptionsInfo
  58. private let refreshClosure: (Image) -> Void
  59. private let isContinueClosure: () -> Bool
  60. private let isFinishedClosure: () -> Bool
  61. private let isWait: Bool
  62. private let decoder: ImageProgressiveDecoder
  63. private let queue = ImageProgressiveSerialQueue(.main)
  64. init(_ options: KingfisherParsedOptionsInfo,
  65. isContinue: @escaping () -> Bool,
  66. isFinished: @escaping () -> Bool,
  67. refreshImage: @escaping (Image) -> Void) {
  68. self.options = options
  69. self.refreshClosure = refreshImage
  70. self.isContinueClosure = isContinue
  71. self.isFinishedClosure = isFinished
  72. self.decoder = ImageProgressiveDecoder(options)
  73. self.isWait = options.progressiveJPEG?.isWait ?? false
  74. }
  75. func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) {
  76. let interval = options.progressiveJPEG?.scanInterval ?? 0
  77. let isFastest = options.progressiveJPEG?.isFastestScan ?? true
  78. func add(decoder data: Data) {
  79. queue.add(minimum: interval) { (completion) in
  80. guard self.isContinueClosure() else {
  81. completion()
  82. return
  83. }
  84. self.decoder.decode(data, with: callbacks) { (image) in
  85. defer { completion() }
  86. guard self.isContinueClosure() else { return }
  87. guard self.isWait || !self.isFinishedClosure() else { return }
  88. guard let image = image else { return }
  89. self.refreshClosure(image)
  90. }
  91. }
  92. }
  93. if isFastest {
  94. guard let data = decoder.scanning(data) else { return }
  95. add(decoder: data)
  96. } else {
  97. for data in decoder.scanning(data) {
  98. add(decoder: data)
  99. }
  100. }
  101. }
  102. func finished(_ closure: @escaping () -> Void) {
  103. if queue.count > 0, isWait {
  104. queue.notify(closure)
  105. } else {
  106. queue.clean()
  107. closure()
  108. }
  109. }
  110. deinit {
  111. print("deinit ImageProgressiveProvider")
  112. }
  113. }
  114. final class ImageProgressiveDecoder {
  115. private let options: KingfisherParsedOptionsInfo
  116. private(set) var scannedCount: Int = 0
  117. private var scannedIndex = -1
  118. init(_ options: KingfisherParsedOptionsInfo) {
  119. self.options = options
  120. }
  121. func scanning(_ data: Data) -> [Data] {
  122. guard let _ = options.progressiveJPEG, data.kf.contains(jpeg: .SOF2) else {
  123. return []
  124. }
  125. guard (scannedIndex + 1) < data.count else {
  126. return []
  127. }
  128. var datas: [Data] = []
  129. var index = scannedIndex + 1
  130. var count = scannedCount
  131. while index < (data.count - 1) {
  132. scannedIndex = index
  133. // 0xFF, 0xDA - Start Of Scan
  134. let SOS = ImageFormat.JPEGMarker.SOS.bytes
  135. if data[index] == SOS[0], data[index + 1] == SOS[1] {
  136. datas.append(data[0 ..< index])
  137. count += 1
  138. }
  139. index += 1
  140. }
  141. // Found more scans this the previous time
  142. guard count > scannedCount else { return [] }
  143. scannedCount = count
  144. return datas
  145. }
  146. func scanning(_ data: Data) -> Data? {
  147. guard let _ = options.progressiveJPEG, data.kf.contains(jpeg: .SOF2) else {
  148. return nil
  149. }
  150. guard (scannedIndex + 1) < data.count else {
  151. return nil
  152. }
  153. var index = scannedIndex + 1
  154. var count = scannedCount
  155. var lastSOSIndex = 0
  156. while index < (data.count - 1) {
  157. scannedIndex = index
  158. // 0xFF, 0xDA - Start Of Scan
  159. let SOS = ImageFormat.JPEGMarker.SOS.bytes
  160. if data[index] == SOS[0], data[index + 1] == SOS[1] {
  161. lastSOSIndex = index
  162. count += 1
  163. }
  164. index += 1
  165. }
  166. // Found more scans this the previous time
  167. guard count > scannedCount else { return nil }
  168. scannedCount = count
  169. // `> 1` checks that we've received a first scan (SOS) and then received
  170. // and also received a second scan (SOS). This way we know that we have
  171. // at least one full scan available.
  172. guard count > 1 && lastSOSIndex > 0 else { return nil }
  173. return data[0 ..< lastSOSIndex]
  174. }
  175. func decode(_ data: Data,
  176. with callbacks: [SessionDataTask.TaskCallback],
  177. completion: @escaping (Image?) -> Void) {
  178. guard data.kf.contains(jpeg: .SOF2) else {
  179. CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
  180. return
  181. }
  182. func processing(_ data: Data) {
  183. let processor = ImageDataProcessor(
  184. data: data,
  185. callbacks: callbacks,
  186. processingQueue: options.processingQueue
  187. )
  188. processor.onImageProcessed.delegate(on: self) { (self, result) in
  189. guard let image = try? result.0.get() else {
  190. CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
  191. return
  192. }
  193. CallbackQueue.mainCurrentOrAsync.execute { completion(image) }
  194. }
  195. processor.process()
  196. }
  197. // Blur partial images.
  198. let count = scannedCount
  199. let isBlur = options.progressiveJPEG?.isBlur ?? false
  200. if isBlur, count < 5 {
  201. let queue = options.processingQueue ?? sharedProcessingQueue
  202. queue.execute {
  203. // Progressively reduce blur as we load more scans.
  204. let radius = max(2, 14 - count * 4)
  205. let image = KingfisherWrapper<Image>.image(
  206. data: data,
  207. options: self.options.imageCreatingOptions
  208. )
  209. let temp = image?.kf.blurred(withRadius: CGFloat(radius))
  210. processing(temp?.kf.data(format: .JPEG) ?? data)
  211. }
  212. } else {
  213. processing(data)
  214. }
  215. }
  216. }
  217. final class ImageProgressiveSerialQueue {
  218. typealias ClosureCallback = ((@escaping () -> Void)) -> Void
  219. private let queue: DispatchQueue
  220. private var items: [DispatchWorkItem] = []
  221. private var notify: (() -> Void)?
  222. var count: Int {
  223. return items.count
  224. }
  225. init(_ queue: DispatchQueue) {
  226. self.queue = queue
  227. }
  228. func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) {
  229. let completion = {
  230. self.queue.async {
  231. guard !self.items.isEmpty else { return }
  232. self.items.removeFirst()
  233. if let next = self.items.first {
  234. self.queue.asyncAfter(deadline: .now() + interval, execute: next)
  235. } else {
  236. self.notify?()
  237. self.notify = nil
  238. }
  239. }
  240. }
  241. let item = DispatchWorkItem {
  242. closure(completion)
  243. }
  244. if items.isEmpty {
  245. queue.asyncAfter(deadline: .now(), execute: item)
  246. }
  247. items.append(item)
  248. }
  249. func notify(_ closure: @escaping () -> Void) {
  250. self.notify = closure
  251. }
  252. func clean() {
  253. items.forEach { $0.cancel() }
  254. items.removeAll()
  255. }
  256. }