ImageProgressive.swift 11 KB

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