VLCThumbnailsCache.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*****************************************************************************
  2. * VLCThumbnailsCache.m
  3. * VLC for iOS
  4. *****************************************************************************
  5. * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
  6. * $Id$
  7. *
  8. * Authors: Gleb Pinigin <gpinigin # gmail.com>
  9. * Felix Paul Kühne <fkuehne # videolan.org>
  10. * Carola Nitz <caro # videolan.org>
  11. * Tobias Conradi <videolan # tobias-conradi.de>
  12. *
  13. * Refer to the COPYING file of the official project for license.
  14. *****************************************************************************/
  15. #import "VLCThumbnailsCache.h"
  16. #import <CommonCrypto/CommonDigest.h>
  17. #import "UIImage+Blur.h"
  18. #import "UIImage+Scaling.h"
  19. #import <WatchKit/WatchKit.h>
  20. #import <CoreData/CoreData.h>
  21. #import <MediaLibraryKit/MediaLibraryKit.h>
  22. @interface VLCThumbnailsCache() {
  23. NSInteger MaxCacheSize;
  24. NSCache *_thumbnailCache;
  25. NSCache *_thumbnailCacheMetadata;
  26. NSInteger _currentDeviceIdiom;
  27. }
  28. @end
  29. @implementation VLCThumbnailsCache
  30. #define MAX_CACHE_SIZE_IPHONE 21 // three times the number of items shown on iPhone 5
  31. #define MAX_CACHE_SIZE_IPAD 27 // three times the number of items shown on iPad
  32. #define MAX_CACHE_SIZE_WATCH 15 // three times the number of items shown on 42mm Watch
  33. - (instancetype)init
  34. {
  35. self = [super init];
  36. if (self) {
  37. _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
  38. MaxCacheSize = 0;
  39. switch (_currentDeviceIdiom) {
  40. case UIUserInterfaceIdiomPad:
  41. MaxCacheSize = MAX_CACHE_SIZE_IPAD;
  42. break;
  43. case UIUserInterfaceIdiomPhone:
  44. MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
  45. break;
  46. default:
  47. MaxCacheSize = MAX_CACHE_SIZE_WATCH;
  48. break;
  49. }
  50. _thumbnailCache = [[NSCache alloc] init];
  51. _thumbnailCacheMetadata = [[NSCache alloc] init];
  52. [_thumbnailCache setCountLimit: MaxCacheSize];
  53. [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
  54. }
  55. return self;
  56. }
  57. + (instancetype)sharedThumbnailCache
  58. {
  59. static dispatch_once_t onceToken;
  60. static VLCThumbnailsCache *sharedThumbnailCache;
  61. dispatch_once(&onceToken, ^{
  62. sharedThumbnailCache = [[VLCThumbnailsCache alloc] init];
  63. });
  64. return sharedThumbnailCache;
  65. }
  66. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
  67. {
  68. return [self thumbnailForManagedObject:object refreshCache:NO];
  69. }
  70. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
  71. refreshCache:(BOOL)refreshCache
  72. {
  73. UIImage *thumbnail;
  74. VLCThumbnailsCache *cache = [VLCThumbnailsCache sharedThumbnailCache];
  75. if ([object isKindOfClass:[MLShow class]]) {
  76. thumbnail = [cache thumbnailForShow:(MLShow *)object refreshCache:refreshCache];
  77. } else if ([object isKindOfClass:[MLShowEpisode class]]) {
  78. MLFile *anyFileFromEpisode = [(MLShowEpisode *)object files].anyObject;
  79. thumbnail = [cache thumbnailForMediaFile:anyFileFromEpisode refreshCache:refreshCache];
  80. } else if ([object isKindOfClass:[MLLabel class]]) {
  81. thumbnail = [cache thumbnailForLabel:(MLLabel *)object refreshCache:refreshCache];
  82. } else if ([object isKindOfClass:[MLAlbum class]]) {
  83. thumbnail = [cache thumbnailForAlbum:(MLAlbum *)object refreshCache:refreshCache];
  84. } else if ([object isKindOfClass:[MLAlbumTrack class]]) {
  85. thumbnail = [cache thumbnailForAlbumTrack:(MLAlbumTrack *)object refreshCache:refreshCache];
  86. } else {
  87. thumbnail = [cache thumbnailForMediaFile:(MLFile *)object refreshCache:refreshCache];
  88. }
  89. return thumbnail;
  90. }
  91. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object toFitRect:(CGRect)rect shouldReplaceCache:(BOOL)replaceCache
  92. {
  93. UIImage *rawThumbnail = [self thumbnailForManagedObject:object];
  94. CGSize rawSize = rawThumbnail.size;
  95. /* scaling is potentially expensive, so we should avoid re-doing it for the same size over and over again */
  96. if (rawSize.width <= rect.size.width && rawSize.height <= rect.size.height)
  97. return rawThumbnail;
  98. UIImage *scaledImage = [UIImage scaleImage:rawThumbnail toFitRect:rect];
  99. if (replaceCache)
  100. [[VLCThumbnailsCache sharedThumbnailCache] _setThumbnail:scaledImage forObjectId:object.objectID];
  101. return scaledImage;
  102. }
  103. - (void)_setThumbnail:(UIImage *)image forObjectId:(NSManagedObjectID *)objID
  104. {
  105. if (image)
  106. [_thumbnailCache setObject:image forKey:objID];
  107. }
  108. - (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile refreshCache:(BOOL)refreshCache
  109. {
  110. if (mediaFile == nil || mediaFile.objectID == nil)
  111. return nil;
  112. NSManagedObjectID *objID = mediaFile.objectID;
  113. UIImage *displayedImage;
  114. if (!refreshCache) {
  115. displayedImage = [_thumbnailCache objectForKey:objID];
  116. if (displayedImage)
  117. return displayedImage;
  118. }
  119. if (!displayedImage) {
  120. __block UIImage *computedImage = nil;
  121. void (^getThumbnailBlock)(void) = ^(){
  122. computedImage = mediaFile.computedThumbnail;
  123. };
  124. if ([NSThread isMainThread])
  125. getThumbnailBlock();
  126. else
  127. dispatch_sync(dispatch_get_main_queue(), getThumbnailBlock);
  128. displayedImage = computedImage;
  129. }
  130. if (displayedImage)
  131. [_thumbnailCache setObject:displayedImage forKey:objID];
  132. return displayedImage;
  133. }
  134. - (UIImage *)thumbnailForShow:(MLShow *)mediaShow refreshCache:(BOOL)refreshCache
  135. {
  136. NSManagedObjectID *objID = mediaShow.objectID;
  137. UIImage *displayedImage;
  138. BOOL forceRefresh = NO;
  139. NSUInteger count = [mediaShow.episodes count];
  140. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  141. if (previousCount.unsignedIntegerValue != count)
  142. forceRefresh = YES;
  143. if (refreshCache)
  144. forceRefresh = YES;
  145. if (!forceRefresh) {
  146. displayedImage = [_thumbnailCache objectForKey:objID];
  147. if (displayedImage)
  148. return displayedImage;
  149. }
  150. NSUInteger fileNumber = count > 3 ? 3 : count;
  151. NSArray *episodes = [mediaShow.episodes allObjects];
  152. NSMutableArray *files = [[NSMutableArray alloc] init];
  153. for (NSUInteger x = 0; x < count; x++) {
  154. /* this is a multi-threaded app, so the episode object might be there already,
  155. * but without an assigned file, so we need to check for its existance (#13128) */
  156. if ([episodes[x] files].anyObject != nil)
  157. [files addObject:[episodes[x] files].anyObject];
  158. }
  159. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:NO];
  160. if (displayedImage) {
  161. [_thumbnailCache setObject:displayedImage forKey:objID];
  162. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  163. }
  164. return displayedImage;
  165. }
  166. - (UIImage *)thumbnailForLabel:(MLLabel *)mediaLabel refreshCache:(BOOL)refreshCache
  167. {
  168. NSManagedObjectID *objID = mediaLabel.objectID;
  169. UIImage *displayedImage;
  170. BOOL forceRefresh = NO;
  171. NSUInteger count = [mediaLabel.files count];
  172. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  173. if (previousCount.unsignedIntegerValue != count)
  174. forceRefresh = YES;
  175. if (refreshCache)
  176. forceRefresh = YES;
  177. if (!forceRefresh) {
  178. displayedImage = [_thumbnailCache objectForKey:objID];
  179. if (displayedImage)
  180. return displayedImage;
  181. }
  182. NSUInteger fileNumber = count > 3 ? 3 : count;
  183. NSArray *files = [mediaLabel.files allObjects];
  184. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:YES];
  185. if (displayedImage) {
  186. [_thumbnailCache setObject:displayedImage forKey:objID];
  187. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  188. }
  189. return displayedImage;
  190. }
  191. - (UIImage *)thumbnailForAlbum:(MLAlbum *)album refreshCache:(BOOL)refreshCache
  192. {
  193. __block MLAlbumTrack *track = nil;
  194. void (^getFileBlock)(void) = ^(){
  195. track = [album tracks].anyObject;
  196. };
  197. if ([NSThread isMainThread])
  198. getFileBlock();
  199. else
  200. dispatch_sync(dispatch_get_main_queue(), getFileBlock);
  201. return [self thumbnailForAlbumTrack:track refreshCache:refreshCache];
  202. }
  203. - (UIImage *)thumbnailForAlbumTrack:(MLAlbumTrack *)albumTrack refreshCache:(BOOL)refreshCache
  204. {
  205. __block MLFile *anyFileFromAnyTrack = nil;
  206. void (^getFileBlock)(void) = ^(){
  207. anyFileFromAnyTrack = [albumTrack anyFileFromTrack];
  208. };
  209. if ([NSThread isMainThread])
  210. getFileBlock();
  211. else
  212. dispatch_sync(dispatch_get_main_queue(), getFileBlock);
  213. return [self thumbnailForMediaFile:anyFileFromAnyTrack refreshCache:refreshCache];
  214. }
  215. - (UIImage *)clusterThumbFromFiles:(NSArray *)files andNumber:(NSUInteger)fileNumber blur:(BOOL)blurImage
  216. {
  217. UIImage *clusterThumb;
  218. CGSize imageSize;
  219. if (_currentDeviceIdiom == UIUserInterfaceIdiomPad) {
  220. if ([UIScreen mainScreen].scale==2.0)
  221. imageSize = CGSizeMake(682., 384.);
  222. else
  223. imageSize = CGSizeMake(341., 192.);
  224. } else if (_currentDeviceIdiom == UIUserInterfaceIdiomPhone) {
  225. if ([UIScreen mainScreen].scale==2.0)
  226. imageSize = CGSizeMake(480., 270.);
  227. else
  228. imageSize = CGSizeMake(720., 405.);
  229. } else {
  230. if (SYSTEM_RUNS_IOS82_OR_LATER) {
  231. if (WKInterfaceDevice.currentDevice != nil) {
  232. CGRect screenRect = WKInterfaceDevice.currentDevice.screenBounds;
  233. imageSize = CGSizeMake(screenRect.size.width * WKInterfaceDevice.currentDevice.screenScale, 120.);
  234. }
  235. }
  236. }
  237. UIGraphicsBeginImageContext(imageSize);
  238. NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
  239. for (NSUInteger i = 0; i < iter; i++) {
  240. MLFile *file = [files objectAtIndex:i];
  241. clusterThumb = [self thumbnailForMediaFile:file refreshCache:NO];
  242. CGContextRef context = UIGraphicsGetCurrentContext();
  243. CGFloat imagePartWidth = (imageSize.width / iter);
  244. //the rect in which the image should be drawn
  245. CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
  246. CGContextSaveGState(context);
  247. CGContextClipToRect(context, clippingRect);
  248. //take the center of the clippingRect and calculate the offset from the original center
  249. CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
  250. //shift the rect to draw the middle of the image in the clippingrect
  251. CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
  252. [clusterThumb drawInRect:drawingRect];
  253. //get rid of the old clippingRect
  254. CGContextRestoreGState(context);
  255. }
  256. clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
  257. UIGraphicsEndImageContext();
  258. if (!blurImage)
  259. return clusterThumb;
  260. return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
  261. }
  262. @end