ImageProgressive.swift 13 KB

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