ImageProgressive.swift 13 KB

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