ImageProgressive.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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. /// The updating strategy when an intermediate progressive image is generated and about to be set to the hosting view.
  32. ///
  33. /// - keep: Do not change the received intermediate progressive image. Just use as it is.
  34. /// - replace: Replace the image to a new one. If the progressive loading is initialized by a view extension in
  35. /// Kingfisher, the replacing image will be used to update the view.
  36. public enum UpdatingStrategy {
  37. case keep
  38. case replace(KFCrossPlatformImage?)
  39. }
  40. /// A default `ImageProgressive` could be used across. It blurs the progressive loading with the fastest
  41. /// scan enabled and scan interval as 0.
  42. public static let `default` = ImageProgressive(
  43. isBlur: true,
  44. isFastestScan: true,
  45. scanInterval: 0
  46. )
  47. /// Whether to enable blur effect processing
  48. let isBlur: Bool
  49. /// Whether to enable the fastest scan
  50. let isFastestScan: Bool
  51. /// Minimum time interval for each scan
  52. let scanInterval: TimeInterval
  53. /// Called when an intermediate image is prepared and about to be set to the image view. The return value of this
  54. /// delegate will be used to update the hosting view, if any. Otherwise, if there is no hosting view (a.k.a the
  55. /// image retrieving is not happening from a view extension method), the returned `UpdatingStrategy` is ignored.
  56. public let onImageUpdated = Delegate<KFCrossPlatformImage, UpdatingStrategy>()
  57. public init(isBlur: Bool,
  58. isFastestScan: Bool,
  59. scanInterval: TimeInterval
  60. )
  61. {
  62. self.isBlur = isBlur
  63. self.isFastestScan = isFastestScan
  64. self.scanInterval = scanInterval
  65. }
  66. }
  67. protocol ImageSettable: AnyObject {
  68. var image: KFCrossPlatformImage? { get set }
  69. }
  70. final class ImageProgressiveProvider: DataReceivingSideEffect {
  71. var onShouldApply: () -> Bool = { return true }
  72. func onDataReceived(_ session: URLSession, task: SessionDataTask, data: Data) {
  73. DispatchQueue.main.async {
  74. guard self.onShouldApply() else { return }
  75. self.update(data: task.mutableData, with: task.callbacks)
  76. }
  77. }
  78. private let option: ImageProgressive
  79. private let refresh: (KFCrossPlatformImage) -> Void
  80. private let decoder: ImageProgressiveDecoder
  81. private let queue = ImageProgressiveSerialQueue()
  82. init?(_ options: KingfisherParsedOptionsInfo,
  83. refresh: @escaping (KFCrossPlatformImage) -> Void) {
  84. guard let option = options.progressiveJPEG else { return nil }
  85. self.option = option
  86. self.refresh = refresh
  87. self.decoder = ImageProgressiveDecoder(
  88. option,
  89. processingQueue: options.processingQueue ?? sharedProcessingQueue,
  90. creatingOptions: options.imageCreatingOptions
  91. )
  92. }
  93. func update(data: Data, with callbacks: [SessionDataTask.TaskCallback]) {
  94. guard !data.isEmpty else { return }
  95. queue.add(minimum: option.scanInterval) { completion in
  96. func decode(_ data: Data) {
  97. self.decoder.decode(data, with: callbacks) { image in
  98. defer { completion() }
  99. guard self.onShouldApply() else { return }
  100. guard let image = image else { return }
  101. self.refresh(image)
  102. }
  103. }
  104. let semaphore = DispatchSemaphore(value: 0)
  105. var onShouldApply: Bool = false
  106. CallbackQueue.mainAsync.execute {
  107. onShouldApply = self.onShouldApply()
  108. semaphore.signal()
  109. }
  110. semaphore.wait()
  111. guard onShouldApply else {
  112. self.queue.clean()
  113. completion()
  114. return
  115. }
  116. if self.option.isFastestScan {
  117. decode(self.decoder.scanning(data) ?? Data())
  118. } else {
  119. self.decoder.scanning(data).forEach { decode($0) }
  120. }
  121. }
  122. }
  123. }
  124. private final class ImageProgressiveDecoder {
  125. private let option: ImageProgressive
  126. private let processingQueue: CallbackQueue
  127. private let creatingOptions: ImageCreatingOptions
  128. private(set) var scannedCount = 0
  129. private(set) var scannedIndex = -1
  130. init(_ option: ImageProgressive,
  131. processingQueue: CallbackQueue,
  132. creatingOptions: ImageCreatingOptions) {
  133. self.option = option
  134. self.processingQueue = processingQueue
  135. self.creatingOptions = creatingOptions
  136. }
  137. func scanning(_ data: Data) -> [Data] {
  138. guard data.kf.contains(jpeg: .SOF2) else {
  139. return []
  140. }
  141. guard scannedIndex + 1 < data.count else {
  142. return []
  143. }
  144. var datas: [Data] = []
  145. var index = scannedIndex + 1
  146. var count = scannedCount
  147. while index < data.count - 1 {
  148. scannedIndex = index
  149. // 0xFF, 0xDA - Start Of Scan
  150. let SOS = ImageFormat.JPEGMarker.SOS.bytes
  151. if data[index] == SOS[0], data[index + 1] == SOS[1] {
  152. if count > 0 {
  153. datas.append(data[0 ..< index])
  154. }
  155. count += 1
  156. }
  157. index += 1
  158. }
  159. // Found more scans this the previous time
  160. guard count > scannedCount else { return [] }
  161. scannedCount = count
  162. // `> 1` checks that we've received a first scan (SOS) and then received
  163. // and also received a second scan (SOS). This way we know that we have
  164. // at least one full scan available.
  165. guard count > 1 else { return [] }
  166. return datas
  167. }
  168. func scanning(_ data: Data) -> Data? {
  169. guard data.kf.contains(jpeg: .SOF2) else {
  170. return nil
  171. }
  172. guard scannedIndex + 1 < data.count else {
  173. return nil
  174. }
  175. var index = scannedIndex + 1
  176. var count = scannedCount
  177. var lastSOSIndex = 0
  178. while index < data.count - 1 {
  179. scannedIndex = index
  180. // 0xFF, 0xDA - Start Of Scan
  181. let SOS = ImageFormat.JPEGMarker.SOS.bytes
  182. if data[index] == SOS[0], data[index + 1] == SOS[1] {
  183. lastSOSIndex = index
  184. count += 1
  185. }
  186. index += 1
  187. }
  188. // Found more scans this the previous time
  189. guard count > scannedCount else { return nil }
  190. scannedCount = count
  191. // `> 1` checks that we've received a first scan (SOS) and then received
  192. // and also received a second scan (SOS). This way we know that we have
  193. // at least one full scan available.
  194. guard count > 1 && lastSOSIndex > 0 else { return nil }
  195. return data[0 ..< lastSOSIndex]
  196. }
  197. func decode(_ data: Data,
  198. with callbacks: [SessionDataTask.TaskCallback],
  199. completion: @escaping (KFCrossPlatformImage?) -> Void) {
  200. guard data.kf.contains(jpeg: .SOF2) else {
  201. CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
  202. return
  203. }
  204. func processing(_ data: Data) {
  205. let processor = ImageDataProcessor(
  206. data: data,
  207. callbacks: callbacks,
  208. processingQueue: processingQueue
  209. )
  210. processor.onImageProcessed.delegate(on: self) { (self, result) in
  211. guard let image = try? result.0.get() else {
  212. CallbackQueue.mainCurrentOrAsync.execute { completion(nil) }
  213. return
  214. }
  215. CallbackQueue.mainCurrentOrAsync.execute { completion(image) }
  216. }
  217. processor.process()
  218. }
  219. // Blur partial images.
  220. let count = scannedCount
  221. if option.isBlur, count < 6 {
  222. processingQueue.execute {
  223. // Progressively reduce blur as we load more scans.
  224. let image = KingfisherWrapper<KFCrossPlatformImage>.image(
  225. data: data,
  226. options: self.creatingOptions
  227. )
  228. let radius = max(2, 14 - count * 4)
  229. let temp = image?.kf.blurred(withRadius: CGFloat(radius))
  230. processing(temp?.kf.data(format: .JPEG) ?? data)
  231. }
  232. } else {
  233. processing(data)
  234. }
  235. }
  236. }
  237. private final class ImageProgressiveSerialQueue {
  238. typealias ClosureCallback = ((@escaping () -> Void)) -> Void
  239. private let queue: DispatchQueue
  240. private var items: [DispatchWorkItem] = []
  241. private var notify: (() -> Void)?
  242. private var lastTime: TimeInterval?
  243. var count: Int { return items.count }
  244. init() {
  245. self.queue = DispatchQueue(label: "com.onevcat.Kingfisher.ImageProgressive.SerialQueue")
  246. }
  247. func add(minimum interval: TimeInterval, closure: @escaping ClosureCallback) {
  248. let completion = { [weak self] in
  249. guard let self = self else { return }
  250. self.queue.async { [weak self] in
  251. guard let self = self else { return }
  252. guard !self.items.isEmpty else { return }
  253. self.items.removeFirst()
  254. if let next = self.items.first {
  255. self.queue.asyncAfter(
  256. deadline: .now() + interval,
  257. execute: next
  258. )
  259. } else {
  260. self.lastTime = Date().timeIntervalSince1970
  261. self.notify?()
  262. self.notify = nil
  263. }
  264. }
  265. }
  266. queue.async { [weak self] in
  267. guard let self = self else { return }
  268. let item = DispatchWorkItem {
  269. closure(completion)
  270. }
  271. if self.items.isEmpty {
  272. let difference = Date().timeIntervalSince1970 - (self.lastTime ?? 0)
  273. let delay = difference < interval ? interval - difference : 0
  274. self.queue.asyncAfter(deadline: .now() + delay, execute: item)
  275. }
  276. self.items.append(item)
  277. }
  278. }
  279. func notify(_ closure: @escaping () -> Void) {
  280. self.notify = closure
  281. }
  282. func clean() {
  283. queue.async { [weak self] in
  284. guard let self = self else { return }
  285. self.items.forEach { $0.cancel() }
  286. self.items.removeAll()
  287. }
  288. }
  289. }