VLCThumbnailsCache.m 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  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. // TODO: correct for watch
  38. #ifndef TARGET_OS_WATCH
  39. _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
  40. MaxCacheSize = 0;
  41. switch (_currentDeviceIdiom) {
  42. case UIUserInterfaceIdiomPad:
  43. MaxCacheSize = MAX_CACHE_SIZE_IPAD;
  44. break;
  45. case UIUserInterfaceIdiomPhone:
  46. MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
  47. break;
  48. default:
  49. MaxCacheSize = MAX_CACHE_SIZE_WATCH;
  50. break;
  51. }
  52. #else
  53. MaxCacheSize = MAX_CACHE_SIZE_WATCH;
  54. #endif
  55. _thumbnailCache = [[NSCache alloc] init];
  56. _thumbnailCacheMetadata = [[NSCache alloc] init];
  57. [_thumbnailCache setCountLimit: MaxCacheSize];
  58. [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
  59. }
  60. return self;
  61. }
  62. + (instancetype)sharedThumbnailCache
  63. {
  64. static dispatch_once_t onceToken;
  65. static VLCThumbnailsCache *sharedThumbnailCache;
  66. dispatch_once(&onceToken, ^{
  67. sharedThumbnailCache = [[VLCThumbnailsCache alloc] init];
  68. });
  69. return sharedThumbnailCache;
  70. }
  71. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
  72. {
  73. return [self thumbnailForManagedObject:object refreshCache:NO];
  74. }
  75. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
  76. refreshCache:(BOOL)refreshCache
  77. {
  78. UIImage *thumbnail;
  79. VLCThumbnailsCache *cache = [VLCThumbnailsCache sharedThumbnailCache];
  80. if ([object isKindOfClass:[MLShow class]]) {
  81. thumbnail = [cache thumbnailForShow:(MLShow *)object refreshCache:refreshCache];
  82. } else if ([object isKindOfClass:[MLShowEpisode class]]) {
  83. MLFile *anyFileFromEpisode = [(MLShowEpisode *)object files].anyObject;
  84. thumbnail = [cache thumbnailForMediaFile:anyFileFromEpisode refreshCache:refreshCache];
  85. } else if ([object isKindOfClass:[MLLabel class]]) {
  86. thumbnail = [cache thumbnailForLabel:(MLLabel *)object refreshCache:refreshCache];
  87. } else if ([object isKindOfClass:[MLAlbum class]]) {
  88. thumbnail = [cache thumbnailForAlbum:(MLAlbum *)object refreshCache:refreshCache];
  89. } else if ([object isKindOfClass:[MLAlbumTrack class]]) {
  90. thumbnail = [cache thumbnailForAlbumTrack:(MLAlbumTrack *)object refreshCache:refreshCache];
  91. } else {
  92. thumbnail = [cache thumbnailForMediaFile:(MLFile *)object refreshCache:refreshCache];
  93. }
  94. return thumbnail;
  95. }
  96. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object toFitRect:(CGRect)rect shouldReplaceCache:(BOOL)replaceCache
  97. {
  98. UIImage *rawThumbnail = [self thumbnailForManagedObject:object];
  99. CGSize rawSize = rawThumbnail.size;
  100. /* scaling is potentially expensive, so we should avoid re-doing it for the same size over and over again */
  101. if (rawSize.width <= rect.size.width && rawSize.height <= rect.size.height)
  102. return rawThumbnail;
  103. UIImage *scaledImage = [UIImage scaleImage:rawThumbnail toFitRect:rect];
  104. if (replaceCache)
  105. [[VLCThumbnailsCache sharedThumbnailCache] _setThumbnail:scaledImage forObjectId:object.objectID];
  106. return scaledImage;
  107. }
  108. - (void)_setThumbnail:(UIImage *)image forObjectId:(NSManagedObjectID *)objID
  109. {
  110. if (image)
  111. [_thumbnailCache setObject:image forKey:objID];
  112. }
  113. - (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile refreshCache:(BOOL)refreshCache
  114. {
  115. if (mediaFile == nil || mediaFile.objectID == nil)
  116. return nil;
  117. NSManagedObjectID *objID = mediaFile.objectID;
  118. UIImage *displayedImage;
  119. if (!refreshCache) {
  120. displayedImage = [_thumbnailCache objectForKey:objID];
  121. if (displayedImage)
  122. return displayedImage;
  123. }
  124. if (!displayedImage) {
  125. __block UIImage *computedImage = nil;
  126. void (^getThumbnailBlock)(void) = ^(){
  127. computedImage = mediaFile.computedThumbnail;
  128. };
  129. if ([NSThread isMainThread])
  130. getThumbnailBlock();
  131. else
  132. dispatch_sync(dispatch_get_main_queue(), getThumbnailBlock);
  133. displayedImage = computedImage;
  134. }
  135. if (displayedImage)
  136. [_thumbnailCache setObject:displayedImage forKey:objID];
  137. return displayedImage;
  138. }
  139. - (UIImage *)thumbnailForShow:(MLShow *)mediaShow refreshCache:(BOOL)refreshCache
  140. {
  141. NSManagedObjectID *objID = mediaShow.objectID;
  142. UIImage *displayedImage;
  143. BOOL forceRefresh = NO;
  144. NSUInteger count = [mediaShow.episodes count];
  145. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  146. if (previousCount.unsignedIntegerValue != count)
  147. forceRefresh = YES;
  148. if (refreshCache)
  149. forceRefresh = YES;
  150. if (!forceRefresh) {
  151. displayedImage = [_thumbnailCache objectForKey:objID];
  152. if (displayedImage)
  153. return displayedImage;
  154. }
  155. NSUInteger fileNumber = count > 3 ? 3 : count;
  156. NSArray *episodes = [mediaShow.episodes allObjects];
  157. NSMutableArray *files = [[NSMutableArray alloc] init];
  158. for (NSUInteger x = 0; x < count; x++) {
  159. /* this is a multi-threaded app, so the episode object might be there already,
  160. * but without an assigned file, so we need to check for its existance (#13128) */
  161. if ([episodes[x] files].anyObject != nil)
  162. [files addObject:[episodes[x] files].anyObject];
  163. }
  164. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:NO];
  165. if (displayedImage) {
  166. [_thumbnailCache setObject:displayedImage forKey:objID];
  167. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  168. }
  169. return displayedImage;
  170. }
  171. - (UIImage *)thumbnailForLabel:(MLLabel *)mediaLabel refreshCache:(BOOL)refreshCache
  172. {
  173. NSManagedObjectID *objID = mediaLabel.objectID;
  174. UIImage *displayedImage;
  175. BOOL forceRefresh = NO;
  176. NSUInteger count = [mediaLabel.files count];
  177. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  178. if (previousCount.unsignedIntegerValue != count)
  179. forceRefresh = YES;
  180. if (refreshCache)
  181. forceRefresh = YES;
  182. if (!forceRefresh) {
  183. displayedImage = [_thumbnailCache objectForKey:objID];
  184. if (displayedImage)
  185. return displayedImage;
  186. }
  187. NSUInteger fileNumber = count > 3 ? 3 : count;
  188. NSArray *files = [mediaLabel.files allObjects];
  189. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:YES];
  190. if (displayedImage) {
  191. [_thumbnailCache setObject:displayedImage forKey:objID];
  192. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  193. }
  194. return displayedImage;
  195. }
  196. - (UIImage *)thumbnailForAlbum:(MLAlbum *)album refreshCache:(BOOL)refreshCache
  197. {
  198. __block MLAlbumTrack *track = nil;
  199. void (^getFileBlock)(void) = ^(){
  200. track = [album tracks].anyObject;
  201. };
  202. if ([NSThread isMainThread])
  203. getFileBlock();
  204. else
  205. dispatch_sync(dispatch_get_main_queue(), getFileBlock);
  206. return [self thumbnailForAlbumTrack:track refreshCache:refreshCache];
  207. }
  208. - (UIImage *)thumbnailForAlbumTrack:(MLAlbumTrack *)albumTrack refreshCache:(BOOL)refreshCache
  209. {
  210. __block MLFile *anyFileFromAnyTrack = nil;
  211. void (^getFileBlock)(void) = ^(){
  212. anyFileFromAnyTrack = [albumTrack anyFileFromTrack];
  213. };
  214. if ([NSThread isMainThread])
  215. getFileBlock();
  216. else
  217. dispatch_sync(dispatch_get_main_queue(), getFileBlock);
  218. return [self thumbnailForMediaFile:anyFileFromAnyTrack refreshCache:refreshCache];
  219. }
  220. - (UIImage *)clusterThumbFromFiles:(NSArray *)files andNumber:(NSUInteger)fileNumber blur:(BOOL)blurImage
  221. {
  222. UIImage *clusterThumb;
  223. CGSize imageSize;
  224. // TODO: correct for watch
  225. #ifndef TARGET_OS_WATCH
  226. if (_currentDeviceIdiom == UIUserInterfaceIdiomPad) {
  227. if ([UIScreen mainScreen].scale==2.0)
  228. imageSize = CGSizeMake(682., 384.);
  229. else
  230. imageSize = CGSizeMake(341., 192.);
  231. } else if (_currentDeviceIdiom == UIUserInterfaceIdiomPhone) {
  232. if ([UIScreen mainScreen].scale==2.0)
  233. imageSize = CGSizeMake(480., 270.);
  234. else
  235. imageSize = CGSizeMake(720., 405.);
  236. } else
  237. #endif
  238. {
  239. if ([WKInterfaceDevice class]) {
  240. if (WKInterfaceDevice.currentDevice != nil) {
  241. CGRect screenRect = WKInterfaceDevice.currentDevice.screenBounds;
  242. imageSize = CGSizeMake(screenRect.size.width * WKInterfaceDevice.currentDevice.screenScale, 120.);
  243. }
  244. }
  245. }
  246. UIGraphicsBeginImageContext(imageSize);
  247. NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
  248. for (NSUInteger i = 0; i < iter; i++) {
  249. MLFile *file = [files objectAtIndex:i];
  250. clusterThumb = [self thumbnailForMediaFile:file refreshCache:NO];
  251. CGContextRef context = UIGraphicsGetCurrentContext();
  252. CGFloat imagePartWidth = (imageSize.width / iter);
  253. //the rect in which the image should be drawn
  254. CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
  255. CGContextSaveGState(context);
  256. CGContextClipToRect(context, clippingRect);
  257. //take the center of the clippingRect and calculate the offset from the original center
  258. CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
  259. //shift the rect to draw the middle of the image in the clippingrect
  260. CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
  261. [clusterThumb drawInRect:drawingRect];
  262. //get rid of the old clippingRect
  263. CGContextRestoreGState(context);
  264. }
  265. clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
  266. UIGraphicsEndImageContext();
  267. if (!blurImage)
  268. return clusterThumb;
  269. return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
  270. }
  271. @end