VLCThumbnailsCache.m 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. *
  12. * Refer to the COPYING file of the official project for license.
  13. *****************************************************************************/
  14. #import "VLC for iOS-Prefix.pch"
  15. #import "VLCThumbnailsCache.h"
  16. #import <CommonCrypto/CommonDigest.h>
  17. #import "UIImage+Blur.h"
  18. static NSInteger MaxCacheSize;
  19. static NSCache *_thumbnailCache;
  20. static NSCache *_thumbnailCacheMetadata;
  21. static NSInteger _currentDeviceIdiom;
  22. @implementation VLCThumbnailsCache
  23. #define MAX_CACHE_SIZE_IPHONE 21 // three times the number of items shown on iPhone 5
  24. #define MAX_CACHE_SIZE_IPAD 27 // three times the number of items shown on iPad
  25. #define MAX_CACHE_SIZE_WATCH 15 // three times the number of items shown on 42mm Watch
  26. -(void)initialize
  27. {
  28. _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
  29. MaxCacheSize = 0;
  30. switch (_currentDeviceIdiom) {
  31. case UIUserInterfaceIdiomPad:
  32. MaxCacheSize = MAX_CACHE_SIZE_IPAD;
  33. break;
  34. case UIUserInterfaceIdiomPhone:
  35. MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
  36. break;
  37. default:
  38. MaxCacheSize = MAX_CACHE_SIZE_WATCH;
  39. break;
  40. }
  41. _thumbnailCache = [[NSCache alloc] init];
  42. _thumbnailCacheMetadata = [[NSCache alloc] init];
  43. [_thumbnailCache setCountLimit: MaxCacheSize];
  44. [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
  45. }
  46. + (instancetype)sharedThumbnailCache
  47. {
  48. static dispatch_once_t onceToken;
  49. static VLCThumbnailsCache *sharedThumbnailCache;
  50. dispatch_once(&onceToken, ^{
  51. sharedThumbnailCache = [[VLCThumbnailsCache alloc] init];
  52. });
  53. return sharedThumbnailCache;
  54. }
  55. - (NSString *)_md5FromString:(NSString *)string
  56. {
  57. const char *ptr = [string UTF8String];
  58. unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
  59. CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
  60. NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
  61. for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
  62. [output appendFormat:@"%02x",md5Buffer[i]];
  63. return [NSString stringWithString:output];
  64. }
  65. + (UIImage *)thumbnailForMediaItemWithTitle:(NSString *)title Artist:(NSString*)artist andAlbumName:(NSString*)albumname
  66. {
  67. return [UIImage imageWithContentsOfFile:[[VLCThumbnailsCache sharedThumbnailCache] artworkPathForMediaItemWithTitle:title Artist:artist andAlbumName:albumname]];
  68. }
  69. - (NSString *)artworkPathForMediaItemWithTitle:(NSString *)title Artist:(NSString*)artist andAlbumName:(NSString*)albumname
  70. {
  71. NSString *artworkURL;
  72. NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  73. NSString *cacheDir = searchPaths[0];
  74. cacheDir = [cacheDir stringByAppendingFormat:@"/%@", [[NSBundle mainBundle] bundleIdentifier]];
  75. if (artist.length == 0 || albumname.length == 0) {
  76. /* Use generated hash to find art */
  77. artworkURL = [cacheDir stringByAppendingFormat:@"/art/arturl/%@/art.jpg", [self _md5FromString:title]];
  78. } else {
  79. /* Otherwise, it was cached by artist and album */
  80. artworkURL = [cacheDir stringByAppendingFormat:@"/art/artistalbum/%@/%@/art.jpg", artist, albumname];
  81. }
  82. return artworkURL;
  83. }
  84. - (NSString *)_getArtworkPathFromMedia:(MLFile *)file
  85. {
  86. NSString *artist, *album, *title;
  87. if (file.isAlbumTrack) {
  88. artist = file.albumTrack.artist;
  89. album = file.albumTrack.album.name;
  90. }
  91. title = file.title;
  92. return [self artworkPathForMediaItemWithTitle:title Artist:artist andAlbumName:album];
  93. }
  94. + (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
  95. {
  96. UIImage *thumbnail;
  97. VLCThumbnailsCache *cache = [VLCThumbnailsCache sharedThumbnailCache];
  98. if ([object isKindOfClass:[MLShow class]]) {
  99. thumbnail = [cache thumbnailForShow:(MLShow *)object];
  100. } else if ([object isKindOfClass:[MLShowEpisode class]]) {
  101. MLFile *anyFileFromEpisode = [(MLShowEpisode *)object files].anyObject;
  102. thumbnail = [cache thumbnailForMediaFile:anyFileFromEpisode];
  103. } else if ([object isKindOfClass:[MLLabel class]]) {
  104. thumbnail = [cache thumbnailForLabel:(MLLabel *)object];
  105. } else if ([object isKindOfClass:[MLAlbum class]]) {
  106. MLFile *anyFileFromAnyTrack = [[(MLAlbum *)object tracks].anyObject files].anyObject;
  107. thumbnail = [cache thumbnailForMediaFile:anyFileFromAnyTrack];
  108. } else if ([object isKindOfClass:[MLAlbumTrack class]]) {
  109. MLFile *anyFileFromTrack = [(MLAlbumTrack *)object files].anyObject;
  110. thumbnail = [cache thumbnailForMediaFile:anyFileFromTrack];
  111. } else {
  112. thumbnail = [cache thumbnailForMediaFile:(MLFile *)object];
  113. }
  114. return thumbnail;
  115. }
  116. - (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile
  117. {
  118. if (mediaFile == nil || mediaFile.objectID == nil)
  119. return nil;
  120. NSManagedObjectID *objID = mediaFile.objectID;
  121. UIImage *displayedImage = [_thumbnailCache objectForKey:objID];
  122. if (displayedImage)
  123. return displayedImage;
  124. if (mediaFile.isAlbumTrack || mediaFile.isShowEpisode)
  125. displayedImage = [UIImage imageWithContentsOfFile:[self _getArtworkPathFromMedia:mediaFile]];
  126. if (!displayedImage)
  127. displayedImage = mediaFile.computedThumbnail;
  128. if (displayedImage)
  129. [_thumbnailCache setObject:displayedImage forKey:objID];
  130. return displayedImage;
  131. }
  132. - (UIImage *)thumbnailForShow:(MLShow *)mediaShow
  133. {
  134. NSManagedObjectID *objID = mediaShow.objectID;
  135. UIImage *displayedImage;
  136. BOOL forceRefresh = NO;
  137. NSUInteger count = [mediaShow.episodes count];
  138. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  139. if (previousCount.unsignedIntegerValue != count)
  140. forceRefresh = YES;
  141. if (!forceRefresh) {
  142. displayedImage = [_thumbnailCache objectForKey:objID];
  143. if (displayedImage)
  144. return displayedImage;
  145. }
  146. NSUInteger fileNumber = count > 3 ? 3 : count;
  147. NSArray *episodes = [mediaShow.episodes allObjects];
  148. NSMutableArray *files = [[NSMutableArray alloc] init];
  149. for (NSUInteger x = 0; x < count; x++) {
  150. /* this is a multi-threaded app, so the episode object might be there already,
  151. * but without an assigned file, so we need to check for its existance (#13128) */
  152. if ([episodes[x] files].anyObject != nil)
  153. [files addObject:[episodes[x] files].anyObject];
  154. }
  155. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:NO];
  156. if (displayedImage) {
  157. [_thumbnailCache setObject:displayedImage forKey:objID];
  158. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  159. }
  160. return displayedImage;
  161. }
  162. - (UIImage *)thumbnailForLabel:(MLLabel *)mediaLabel
  163. {
  164. NSManagedObjectID *objID = mediaLabel.objectID;
  165. UIImage *displayedImage;
  166. BOOL forceRefresh = NO;
  167. NSUInteger count = [mediaLabel.files count];
  168. NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];
  169. if (previousCount.unsignedIntegerValue != count)
  170. forceRefresh = YES;
  171. if (!forceRefresh) {
  172. displayedImage = [_thumbnailCache objectForKey:objID];
  173. if (displayedImage)
  174. return displayedImage;
  175. }
  176. NSUInteger fileNumber = count > 3 ? 3 : count;
  177. NSArray *files = [mediaLabel.files allObjects];
  178. BOOL blur = NO;
  179. if (SYSTEM_RUNS_IOS7_OR_LATER)
  180. blur = YES;
  181. displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:blur];
  182. if (displayedImage) {
  183. [_thumbnailCache setObject:displayedImage forKey:objID];
  184. [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
  185. }
  186. return displayedImage;
  187. }
  188. - (UIImage *)clusterThumbFromFiles:(NSArray *)files andNumber:(NSUInteger)fileNumber blur:(BOOL)blurImage
  189. {
  190. UIImage *clusterThumb;
  191. CGSize imageSize;
  192. if (_currentDeviceIdiom == UIUserInterfaceIdiomPad) {
  193. if ([UIScreen mainScreen].scale==2.0)
  194. imageSize = CGSizeMake(682., 384.);
  195. else
  196. imageSize = CGSizeMake(341., 192.);
  197. } else if (_currentDeviceIdiom == UIUserInterfaceIdiomPhone) {
  198. if (SYSTEM_RUNS_IOS7_OR_LATER) {
  199. if ([UIScreen mainScreen].scale==2.0)
  200. imageSize = CGSizeMake(480., 270.);
  201. else
  202. imageSize = CGSizeMake(720., 405.);
  203. } else {
  204. if ([UIScreen mainScreen].scale==2.0)
  205. imageSize = CGSizeMake(258., 145.);
  206. else
  207. imageSize = CGSizeMake(129., 73.);
  208. }
  209. } else {
  210. imageSize = CGSizeMake(272., 120.);
  211. }
  212. UIGraphicsBeginImageContext(imageSize);
  213. NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
  214. for (NSUInteger i = 0; i < iter; i++) {
  215. MLFile *file = [files objectAtIndex:i];
  216. clusterThumb = [self thumbnailForMediaFile:file];
  217. CGContextRef context = UIGraphicsGetCurrentContext();
  218. CGFloat imagePartWidth = (imageSize.width / iter);
  219. //the rect in which the image should be drawn
  220. CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
  221. CGContextSaveGState(context);
  222. CGContextClipToRect(context, clippingRect);
  223. //take the center of the clippingRect and calculate the offset from the original center
  224. CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
  225. //shift the rect to draw the middle of the image in the clippingrect
  226. CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
  227. [clusterThumb drawInRect:drawingRect];
  228. //get rid of the old clippingRect
  229. CGContextRestoreGState(context);
  230. }
  231. clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
  232. UIGraphicsEndImageContext();
  233. if (!blurImage)
  234. return clusterThumb;
  235. return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
  236. }
  237. @end