VLCThumbnailsCache.m 12 KB

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