SDWebImagePrefetcher.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "SDWebImagePrefetcher.h"
  9. #import "SDAsyncBlockOperation.h"
  10. #import "SDInternalMacros.h"
  11. #import <stdatomic.h>
  12. @interface SDWebImagePrefetchToken () {
  13. @public
  14. // Though current implementation, `SDWebImageManager` completion block is always on main queue. But however, there is no guarantee in docs. And we may introduce config to specify custom queue in the future.
  15. // These value are just used as incrementing counter, keep thread-safe using memory_order_relaxed for performance.
  16. atomic_ulong _skippedCount;
  17. atomic_ulong _finishedCount;
  18. atomic_flag _isAllFinished;
  19. unsigned long _totalCount;
  20. }
  21. @property (nonatomic, copy, readwrite) NSArray<NSURL *> *urls;
  22. @property (nonatomic, strong) NSPointerArray *loadOperations;
  23. @property (nonatomic, strong) NSPointerArray *prefetchOperations;
  24. @property (nonatomic, weak) SDWebImagePrefetcher *prefetcher;
  25. @property (nonatomic, copy, nullable) SDWebImagePrefetcherCompletionBlock completionBlock;
  26. @property (nonatomic, copy, nullable) SDWebImagePrefetcherProgressBlock progressBlock;
  27. @end
  28. @interface SDWebImagePrefetcher ()
  29. @property (strong, nonatomic, nonnull) SDWebImageManager *manager;
  30. @property (strong, atomic, nonnull) NSMutableSet<SDWebImagePrefetchToken *> *runningTokens;
  31. @property (strong, nonatomic, nonnull) NSOperationQueue *prefetchQueue;
  32. @end
  33. @implementation SDWebImagePrefetcher
  34. + (nonnull instancetype)sharedImagePrefetcher {
  35. static dispatch_once_t once;
  36. static id instance;
  37. dispatch_once(&once, ^{
  38. instance = [self new];
  39. });
  40. return instance;
  41. }
  42. - (nonnull instancetype)init {
  43. return [self initWithImageManager:[SDWebImageManager new]];
  44. }
  45. - (nonnull instancetype)initWithImageManager:(SDWebImageManager *)manager {
  46. if ((self = [super init])) {
  47. _manager = manager;
  48. _runningTokens = [NSMutableSet set];
  49. _options = SDWebImageLowPriority;
  50. _delegateQueue = dispatch_get_main_queue();
  51. _prefetchQueue = [NSOperationQueue new];
  52. self.maxConcurrentPrefetchCount = 3;
  53. }
  54. return self;
  55. }
  56. - (void)setMaxConcurrentPrefetchCount:(NSUInteger)maxConcurrentPrefetchCount {
  57. self.prefetchQueue.maxConcurrentOperationCount = maxConcurrentPrefetchCount;
  58. }
  59. - (NSUInteger)maxConcurrentPrefetchCount {
  60. return self.prefetchQueue.maxConcurrentOperationCount;
  61. }
  62. #pragma mark - Prefetch
  63. - (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls {
  64. return [self prefetchURLs:urls progress:nil completed:nil];
  65. }
  66. - (nullable SDWebImagePrefetchToken *)prefetchURLs:(nullable NSArray<NSURL *> *)urls
  67. progress:(nullable SDWebImagePrefetcherProgressBlock)progressBlock
  68. completed:(nullable SDWebImagePrefetcherCompletionBlock)completionBlock {
  69. if (!urls || urls.count == 0) {
  70. if (completionBlock) {
  71. completionBlock(0, 0);
  72. }
  73. return nil;
  74. }
  75. SDWebImagePrefetchToken *token = [SDWebImagePrefetchToken new];
  76. token.prefetcher = self;
  77. token.urls = urls;
  78. token->_skippedCount = 0;
  79. token->_finishedCount = 0;
  80. token->_totalCount = token.urls.count;
  81. atomic_flag_clear(&(token->_isAllFinished));
  82. token.loadOperations = [NSPointerArray weakObjectsPointerArray];
  83. token.prefetchOperations = [NSPointerArray weakObjectsPointerArray];
  84. token.progressBlock = progressBlock;
  85. token.completionBlock = completionBlock;
  86. [self addRunningToken:token];
  87. [self startPrefetchWithToken:token];
  88. return token;
  89. }
  90. - (void)startPrefetchWithToken:(SDWebImagePrefetchToken * _Nonnull)token {
  91. NSPointerArray *operations = token.loadOperations;
  92. for (NSURL *url in token.urls) {
  93. @weakify(self);
  94. SDAsyncBlockOperation *prefetchOperation = [SDAsyncBlockOperation blockOperationWithBlock:^(SDAsyncBlockOperation * _Nonnull asyncOperation) {
  95. @strongify(self);
  96. if (!self || asyncOperation.isCancelled) {
  97. return;
  98. }
  99. id<SDWebImageOperation> operation = [self.manager loadImageWithURL:url options:self.options context:self.context progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
  100. @strongify(self);
  101. if (!self) {
  102. return;
  103. }
  104. if (!finished) {
  105. return;
  106. }
  107. atomic_fetch_add_explicit(&(token->_finishedCount), 1, memory_order_relaxed);
  108. if (error) {
  109. // Add last failed
  110. atomic_fetch_add_explicit(&(token->_skippedCount), 1, memory_order_relaxed);
  111. }
  112. // Current operation finished
  113. [self callProgressBlockForToken:token imageURL:imageURL];
  114. if (atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed) == token->_totalCount) {
  115. // All finished
  116. if (!atomic_flag_test_and_set_explicit(&(token->_isAllFinished), memory_order_relaxed)) {
  117. [self callCompletionBlockForToken:token];
  118. [self removeRunningToken:token];
  119. }
  120. }
  121. [asyncOperation complete];
  122. }];
  123. NSAssert(operation != nil, @"Operation should not be nil, [SDWebImageManager loadImageWithURL:options:context:progress:completed:] break prefetch logic");
  124. @synchronized (token) {
  125. [operations addPointer:(__bridge void *)operation];
  126. }
  127. }];
  128. @synchronized (token) {
  129. [token.prefetchOperations addPointer:(__bridge void *)prefetchOperation];
  130. }
  131. [self.prefetchQueue addOperation:prefetchOperation];
  132. }
  133. }
  134. #pragma mark - Cancel
  135. - (void)cancelPrefetching {
  136. @synchronized(self.runningTokens) {
  137. NSSet<SDWebImagePrefetchToken *> *copiedTokens = [self.runningTokens copy];
  138. [copiedTokens makeObjectsPerformSelector:@selector(cancel)];
  139. [self.runningTokens removeAllObjects];
  140. }
  141. }
  142. - (void)callProgressBlockForToken:(SDWebImagePrefetchToken *)token imageURL:(NSURL *)url {
  143. if (!token) {
  144. return;
  145. }
  146. BOOL shouldCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didPrefetchURL:finishedCount:totalCount:)];
  147. NSUInteger tokenFinishedCount = [self tokenFinishedCount];
  148. NSUInteger tokenTotalCount = [self tokenTotalCount];
  149. NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
  150. NSUInteger totalCount = token->_totalCount;
  151. dispatch_async(self.delegateQueue, ^{
  152. if (shouldCallDelegate) {
  153. [self.delegate imagePrefetcher:self didPrefetchURL:url finishedCount:tokenFinishedCount totalCount:tokenTotalCount];
  154. }
  155. if (token.progressBlock) {
  156. token.progressBlock(finishedCount, totalCount);
  157. }
  158. });
  159. }
  160. - (void)callCompletionBlockForToken:(SDWebImagePrefetchToken *)token {
  161. if (!token) {
  162. return;
  163. }
  164. BOOL shoulCallDelegate = [self.delegate respondsToSelector:@selector(imagePrefetcher:didFinishWithTotalCount:skippedCount:)] && ([self countOfRunningTokens] == 1); // last one
  165. NSUInteger tokenTotalCount = [self tokenTotalCount];
  166. NSUInteger tokenSkippedCount = [self tokenSkippedCount];
  167. NSUInteger finishedCount = atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
  168. NSUInteger skippedCount = atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed);
  169. dispatch_async(self.delegateQueue, ^{
  170. if (shoulCallDelegate) {
  171. [self.delegate imagePrefetcher:self didFinishWithTotalCount:tokenTotalCount skippedCount:tokenSkippedCount];
  172. }
  173. if (token.completionBlock) {
  174. token.completionBlock(finishedCount, skippedCount);
  175. }
  176. });
  177. }
  178. #pragma mark - Helper
  179. - (NSUInteger)tokenTotalCount {
  180. NSUInteger tokenTotalCount = 0;
  181. @synchronized (self.runningTokens) {
  182. for (SDWebImagePrefetchToken *token in self.runningTokens) {
  183. tokenTotalCount += token->_totalCount;
  184. }
  185. }
  186. return tokenTotalCount;
  187. }
  188. - (NSUInteger)tokenSkippedCount {
  189. NSUInteger tokenSkippedCount = 0;
  190. @synchronized (self.runningTokens) {
  191. for (SDWebImagePrefetchToken *token in self.runningTokens) {
  192. tokenSkippedCount += atomic_load_explicit(&(token->_skippedCount), memory_order_relaxed);
  193. }
  194. }
  195. return tokenSkippedCount;
  196. }
  197. - (NSUInteger)tokenFinishedCount {
  198. NSUInteger tokenFinishedCount = 0;
  199. @synchronized (self.runningTokens) {
  200. for (SDWebImagePrefetchToken *token in self.runningTokens) {
  201. tokenFinishedCount += atomic_load_explicit(&(token->_finishedCount), memory_order_relaxed);
  202. }
  203. }
  204. return tokenFinishedCount;
  205. }
  206. - (void)addRunningToken:(SDWebImagePrefetchToken *)token {
  207. if (!token) {
  208. return;
  209. }
  210. @synchronized (self.runningTokens) {
  211. [self.runningTokens addObject:token];
  212. }
  213. }
  214. - (void)removeRunningToken:(SDWebImagePrefetchToken *)token {
  215. if (!token) {
  216. return;
  217. }
  218. @synchronized (self.runningTokens) {
  219. [self.runningTokens removeObject:token];
  220. }
  221. }
  222. - (NSUInteger)countOfRunningTokens {
  223. NSUInteger count = 0;
  224. @synchronized (self.runningTokens) {
  225. count = self.runningTokens.count;
  226. }
  227. return count;
  228. }
  229. @end
  230. @implementation SDWebImagePrefetchToken
  231. - (void)cancel {
  232. @synchronized (self) {
  233. [self.prefetchOperations compact];
  234. for (id operation in self.prefetchOperations) {
  235. if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) {
  236. [operation cancel];
  237. }
  238. }
  239. self.prefetchOperations.count = 0;
  240. [self.loadOperations compact];
  241. for (id operation in self.loadOperations) {
  242. if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) {
  243. [operation cancel];
  244. }
  245. }
  246. self.loadOperations.count = 0;
  247. }
  248. self.completionBlock = nil;
  249. self.progressBlock = nil;
  250. [self.prefetcher removeRunningToken:self];
  251. }
  252. @end