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