VLCThumbnailsCache.m 10.6 KB
Newer Older
1
2
3
4
/*****************************************************************************
 * VLCThumbnailsCache.m
 * VLC for iOS
 *****************************************************************************
5
 * Copyright (c) 2013-2015 VideoLAN. All rights reserved.
6
7
8
9
 * $Id$
 *
 * Authors: Gleb Pinigin <gpinigin # gmail.com>
 *          Felix Paul Kühne <fkuehne # videolan.org>
10
 *          Carola Nitz <caro # videolan.org>
11
12
13
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
14

15
#import "VLC for iOS-Prefix.pch"
16
#import "VLCThumbnailsCache.h"
17
#import <CommonCrypto/CommonDigest.h>
18
#import "UIImage+Blur.h"
19
20
#import <WatchKit/WatchKit.h>

21
22
23
24
25
26
27
@interface VLCThumbnailsCache() {
    NSInteger MaxCacheSize;
    NSCache *_thumbnailCache;
    NSCache *_thumbnailCacheMetadata;
    NSInteger _currentDeviceIdiom;
}
@end
28
29
30
31
32

@implementation VLCThumbnailsCache

#define MAX_CACHE_SIZE_IPHONE 21  // three times the number of items shown on iPhone 5
#define MAX_CACHE_SIZE_IPAD   27  // three times the number of items shown on iPad
33
#define MAX_CACHE_SIZE_WATCH  15  // three times the number of items shown on 42mm Watch
34

35
- (instancetype)init
36
{
37
38
39
40
    self = [super init];
    if (self) {
        _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
        MaxCacheSize = 0;
41

42
43
44
45
46
47
48
        switch (_currentDeviceIdiom) {
            case UIUserInterfaceIdiomPad:
                MaxCacheSize = MAX_CACHE_SIZE_IPAD;
                break;
            case UIUserInterfaceIdiomPhone:
                MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
                break;
49

50
51
52
53
            default:
                MaxCacheSize = MAX_CACHE_SIZE_WATCH;
                break;
        }
54

55
56
57
58
59
60
61
        _thumbnailCache = [[NSCache alloc] init];
        _thumbnailCacheMetadata = [[NSCache alloc] init];
        [_thumbnailCache setCountLimit: MaxCacheSize];
        [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
    }
    return self;
}
62

63
64
65
66
67
68
69
70
71
72
73
+ (instancetype)sharedThumbnailCache
{
    static dispatch_once_t onceToken;
    static VLCThumbnailsCache *sharedThumbnailCache;
    dispatch_once(&onceToken, ^{
        sharedThumbnailCache = [[VLCThumbnailsCache alloc] init];
    });

    return sharedThumbnailCache;
}

74
- (NSString *)_md5FromString:(NSString *)string
75
76
77
{
    const char *ptr = [string UTF8String];
    unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
78
    CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
79
80
81
82
83
84
85
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x",md5Buffer[i]];

    return [NSString stringWithString:output];
}

86
+ (UIImage *)thumbnailForMediaItemWithTitle:(NSString *)title Artist:(NSString*)artist andAlbumName:(NSString*)albumname
87
{
88
    return [UIImage imageWithContentsOfFile:[[VLCThumbnailsCache sharedThumbnailCache] artworkPathForMediaItemWithTitle:title Artist:artist andAlbumName:albumname]];
89
}
90

91
- (NSString *)artworkPathForMediaItemWithTitle:(NSString *)title Artist:(NSString*)artist andAlbumName:(NSString*)albumname
92
93
{
    NSString *artworkURL;
94
95
96
97
    NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cacheDir = searchPaths[0];
    cacheDir = [cacheDir stringByAppendingFormat:@"/%@", [[NSBundle mainBundle] bundleIdentifier]];

98
    if (artist.length == 0 || albumname.length == 0) {
99
100
101
102
        /* Use generated hash to find art */
        artworkURL = [cacheDir stringByAppendingFormat:@"/art/arturl/%@/art.jpg", [self _md5FromString:title]];
    } else {
        /* Otherwise, it was cached by artist and album */
103
        artworkURL = [cacheDir stringByAppendingFormat:@"/art/artistalbum/%@/%@/art.jpg", artist, albumname];
104
105
106
107
108
    }

    return artworkURL;
}

109
- (NSString *)_getArtworkPathFromMedia:(MLFile *)file
110
111
112
113
114
115
116
117
118
119
120
121
{
    NSString *artist, *album, *title;

    if (file.isAlbumTrack) {
        artist = file.albumTrack.artist;
        album = file.albumTrack.album.name;
    }
    title = file.title;

    return [self artworkPathForMediaItemWithTitle:title Artist:artist andAlbumName:album];
}

122
123
124
+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
{
    UIImage *thumbnail;
125
    VLCThumbnailsCache *cache = [VLCThumbnailsCache sharedThumbnailCache];
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    if ([object isKindOfClass:[MLShow class]]) {
        thumbnail = [cache thumbnailForShow:(MLShow *)object];
    } else if ([object isKindOfClass:[MLShowEpisode class]]) {
        MLFile *anyFileFromEpisode = [(MLShowEpisode *)object files].anyObject;
        thumbnail = [cache thumbnailForMediaFile:anyFileFromEpisode];
    } else if ([object isKindOfClass:[MLLabel class]]) {
        thumbnail = [cache thumbnailForLabel:(MLLabel *)object];
    } else if ([object isKindOfClass:[MLAlbum class]]) {
        MLFile *anyFileFromAnyTrack = [[(MLAlbum *)object tracks].anyObject files].anyObject;
        thumbnail = [cache thumbnailForMediaFile:anyFileFromAnyTrack];
    } else if ([object isKindOfClass:[MLAlbumTrack class]]) {
        MLFile *anyFileFromTrack = [(MLAlbumTrack *)object files].anyObject;
        thumbnail = [cache thumbnailForMediaFile:anyFileFromTrack];
    } else {
        thumbnail = [cache thumbnailForMediaFile:(MLFile *)object];
    }
    return thumbnail;
}

- (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile
146
147
148
149
150
{
    if (mediaFile == nil || mediaFile.objectID == nil)
        return nil;

    NSManagedObjectID *objID = mediaFile.objectID;
151
152
153
154
155
    UIImage *displayedImage = [_thumbnailCache objectForKey:objID];

    if (displayedImage)
        return displayedImage;

156
157
158
159
160
161
    if (mediaFile.isAlbumTrack || mediaFile.isShowEpisode)
        displayedImage = [UIImage imageWithContentsOfFile:[self _getArtworkPathFromMedia:mediaFile]];

    if (!displayedImage)
        displayedImage = mediaFile.computedThumbnail;

162
163
    if (displayedImage)
        [_thumbnailCache setObject:displayedImage forKey:objID];
164
165
166
167

    return displayedImage;
}

168
- (UIImage *)thumbnailForShow:(MLShow *)mediaShow
169
170
{
    NSManagedObjectID *objID = mediaShow.objectID;
171
    UIImage *displayedImage;
172
173
174
175
176
177
178
    BOOL forceRefresh = NO;

    NSUInteger count = [mediaShow.episodes count];
    NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];

    if (previousCount.unsignedIntegerValue != count)
        forceRefresh = YES;
179

180
181
182
183
184
    if (!forceRefresh) {
        displayedImage = [_thumbnailCache objectForKey:objID];
        if (displayedImage)
            return displayedImage;
    }
185
186
187
188

    NSUInteger fileNumber = count > 3 ? 3 : count;
    NSArray *episodes = [mediaShow.episodes allObjects];
    NSMutableArray *files = [[NSMutableArray alloc] init];
189
190
191
192
193
194
    for (NSUInteger x = 0; x < count; x++) {
        /* this is a multi-threaded app, so the episode object might be there already,
         * but without an assigned file, so we need to check for its existance (#13128) */
        if ([episodes[x] files].anyObject != nil)
            [files addObject:[episodes[x] files].anyObject];
    }
195

196
    displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:NO];
197
    if (displayedImage) {
198
        [_thumbnailCache setObject:displayedImage forKey:objID];
199
200
        [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
    }
201
202
203
204

    return displayedImage;
}

205
- (UIImage *)thumbnailForLabel:(MLLabel *)mediaLabel
206
207
{
    NSManagedObjectID *objID = mediaLabel.objectID;
208
    UIImage *displayedImage;
209
210
211
212
213
214
215
    BOOL forceRefresh = NO;

    NSUInteger count = [mediaLabel.files count];
    NSNumber *previousCount = [_thumbnailCacheMetadata objectForKey:objID];

    if (previousCount.unsignedIntegerValue != count)
        forceRefresh = YES;
216

217
218
219
220
221
    if (!forceRefresh) {
        displayedImage = [_thumbnailCache objectForKey:objID];
        if (displayedImage)
            return displayedImage;
    }
222

223
    NSUInteger fileNumber = count > 3 ? 3 : count;
224
    NSArray *files = [mediaLabel.files allObjects];
225
226
227
228
    BOOL blur = NO;
    if (SYSTEM_RUNS_IOS7_OR_LATER)
        blur = YES;
    displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:blur];
229
    if (displayedImage) {
230
        [_thumbnailCache setObject:displayedImage forKey:objID];
231
232
        [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
    }
233
234
235

    return displayedImage;
}
236

237
- (UIImage *)clusterThumbFromFiles:(NSArray *)files andNumber:(NSUInteger)fileNumber blur:(BOOL)blurImage
238
239
{
    UIImage *clusterThumb;
240
    CGSize imageSize;
241
    if (_currentDeviceIdiom == UIUserInterfaceIdiomPad) {
242
        if ([UIScreen mainScreen].scale==2.0)
243
            imageSize = CGSizeMake(682., 384.);
244
        else
245
            imageSize = CGSizeMake(341., 192.);
246
    } else if (_currentDeviceIdiom == UIUserInterfaceIdiomPhone) {
247
248
249
250
251
252
        if (SYSTEM_RUNS_IOS7_OR_LATER) {
            if ([UIScreen mainScreen].scale==2.0)
                imageSize = CGSizeMake(480., 270.);
            else
                imageSize = CGSizeMake(720., 405.);
        } else {
253
            if ([UIScreen mainScreen].scale==2.0)
254
                imageSize = CGSizeMake(258., 145.);
255
            else
256
                imageSize = CGSizeMake(129., 73.);
257
        }
258
    } else {
259
260
261
262
263
264
        if (SYSTEM_RUNS_IOS82_OR_LATER) {
            if (WKInterfaceDevice.currentDevice != nil) {
                CGRect screenRect = WKInterfaceDevice.currentDevice.screenBounds;
                imageSize = CGSizeMake(screenRect.size.width * WKInterfaceDevice.currentDevice.screenScale, 120.);
            }
        }
265
    }
266
267

    UIGraphicsBeginImageContext(imageSize);
268
269
    NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
    for (NSUInteger i = 0; i < iter; i++) {
270
        MLFile *file =  [files objectAtIndex:i];
271
        clusterThumb = [self thumbnailForMediaFile:file];
272
        CGContextRef context = UIGraphicsGetCurrentContext();
273
        CGFloat imagePartWidth = (imageSize.width / iter);
274
275
276
277
278
279
280
281
        //the rect in which the image should be drawn
        CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
        CGContextSaveGState(context);
        CGContextClipToRect(context, clippingRect);
        //take the center of the clippingRect and calculate the offset from the original center
        CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
        //shift the rect to draw the middle of the image in the clippingrect
        CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
282
        [clusterThumb drawInRect:drawingRect];
283
284
285
        //get rid of the old clippingRect
        CGContextRestoreGState(context);
    }
286
    clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
287
288
    UIGraphicsEndImageContext();

289
290
291
292
    if (!blurImage)
        return clusterThumb;

    return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
293
294
}

295
@end