VLCThumbnailsCache.m 10.9 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
 *          Tobias Conradi <videolan # tobias-conradi.de>
12 13 14
 *
 * Refer to the COPYING file of the official project for license.
 *****************************************************************************/
15 16

#import "VLCThumbnailsCache.h"
17
#import <CommonCrypto/CommonDigest.h>
18
#import "UIImage+Blur.h"
19 20
#import <CoreData/CoreData.h>
#import <MediaLibraryKit/MediaLibraryKit.h>
21
#import <MediaLibraryKit/UIImage+MLKit.h>
22 23 24
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#endif
25

26
@interface VLCThumbnailsCache() {
27
    NSInteger MaxCacheSize;
28 29
    NSCache *_thumbnailCache;
    NSCache *_thumbnailCacheMetadata;
30
    NSInteger _currentDeviceIdiom;
31 32
}
@end
33 34 35 36 37 38

@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

39
- (instancetype)init
40
{
41 42
    self = [super init];
    if (self) {
43 44
        _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
        MaxCacheSize = 0;
45

46
        switch (_currentDeviceIdiom) {
47
            case UIUserInterfaceIdiomPad:
48
                MaxCacheSize = MAX_CACHE_SIZE_IPAD;
49 50
                break;
            case UIUserInterfaceIdiomPhone:
51
                MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
52 53 54 55
                break;
        }
        _thumbnailCache = [[NSCache alloc] init];
        _thumbnailCacheMetadata = [[NSCache alloc] init];
56 57
        [_thumbnailCache setCountLimit: MaxCacheSize];
        [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
58 59 60
    }
    return self;
}
61

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

    return sharedThumbnailCache;
}

73
+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
74 75 76 77 78 79
{
    return [self thumbnailForManagedObject:object refreshCache:NO];
}

+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
                          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 86
    } else if ([object isKindOfClass:[MLShowEpisode class]]) {
        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 98 99
    }
    return thumbnail;
}

100
+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object refreshCache:(BOOL)refreshCache toFitRect:(CGRect)rect scale:(CGFloat)scale shouldReplaceCache:(BOOL)replaceCache;
101
{
102
    UIImage *rawThumbnail = [self thumbnailForManagedObject:object refreshCache:refreshCache];
103
    CGSize rawSize = rawThumbnail.size;
104
    CGFloat rawScale = rawThumbnail.scale;
105 106

    /* scaling is potentially expensive, so we should avoid re-doing it for the same size over and over again */ 
107
    if (rawSize.width*rawScale <= rect.size.width*scale && rawSize.height*rawScale <= rect.size.height*scale)
108 109
        return rawThumbnail;

110
    UIImage *scaledImage = [UIImage scaleImage:rawThumbnail toFitRect:rect scale:scale];
111 112 113 114 115 116 117 118 119

    if (replaceCache)
        [[VLCThumbnailsCache sharedThumbnailCache] _setThumbnail:scaledImage forObjectId:object.objectID];

    return scaledImage;
}

- (void)_setThumbnail:(UIImage *)image forObjectId:(NSManagedObjectID *)objID
{
120 121
    if (image)
        [_thumbnailCache setObject:image forKey:objID];
122 123
}

124
- (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile refreshCache:(BOOL)refreshCache
125 126 127 128 129
{
    if (mediaFile == nil || mediaFile.objectID == nil)
        return nil;

    NSManagedObjectID *objID = mediaFile.objectID;
130
    UIImage *displayedImage;
131

132 133 134 135 136
    if (!refreshCache) {
        displayedImage = [_thumbnailCache objectForKey:objID];
        if (displayedImage)
            return displayedImage;
    }
137

138 139 140 141 142 143 144 145 146 147 148
    if (!displayedImage) {
        __block UIImage *computedImage = nil;
        void (^getThumbnailBlock)(void) = ^(){
            computedImage = mediaFile.computedThumbnail;
        };
        if ([NSThread isMainThread])
            getThumbnailBlock();
        else
            dispatch_sync(dispatch_get_main_queue(), getThumbnailBlock);
        displayedImage = computedImage;
    }
149

150 151 152 153 154 155 156 157 158 159
    if (!displayedImage) {
        if ([mediaFile isKindOfType:@"audio"]) {
            displayedImage = [UIImage imageNamed:@"no-artwork"];
        } else if ([mediaFile isKindOfType:@"movie"] ||
                   [mediaFile isKindOfType:@"tvShowEpisode"] ||
                   [mediaFile isKindOfType:@"clip"]) {
            displayedImage = [UIImage imageNamed:@"tvShow"];
        }
    }

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

    return displayedImage;
}

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

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

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

178 179 180
    if (refreshCache)
        forceRefresh = YES;

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

    NSUInteger fileNumber = count > 3 ? 3 : count;
    NSArray *episodes = [mediaShow.episodes allObjects];
    NSMutableArray *files = [[NSMutableArray alloc] init];
190 191 192 193 194 195
    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];
    }
196

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

    return displayedImage;
}

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

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

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

218 219 220
    if (refreshCache)
        forceRefresh = YES;

221 222 223 224 225
    if (!forceRefresh) {
        displayedImage = [_thumbnailCache objectForKey:objID];
        if (displayedImage)
            return displayedImage;
    }
226

227
    NSUInteger fileNumber = count > 3 ? 3 : count;
228
    NSArray *files = [mediaLabel.files allObjects];
Felix Paul Kühne's avatar
Felix Paul Kühne committed
229 230

    displayedImage = [self clusterThumbFromFiles:files andNumber:fileNumber blur:YES];
231
    if (displayedImage) {
232
        [_thumbnailCache setObject:displayedImage forKey:objID];
233 234
        [_thumbnailCacheMetadata setObject:@(count) forKey:objID];
    }
235 236 237

    return displayedImage;
}
238

239
- (UIImage *)thumbnailForAlbum:(MLAlbum *)album refreshCache:(BOOL)refreshCache
240 241 242 243 244 245 246 247 248 249
{
    __block MLAlbumTrack *track = nil;
    void (^getFileBlock)(void) = ^(){
        track = [album tracks].anyObject;
    };
    if ([NSThread isMainThread])
        getFileBlock();
    else
        dispatch_sync(dispatch_get_main_queue(), getFileBlock);

250
    return [self thumbnailForAlbumTrack:track refreshCache:refreshCache];
251 252
}

253
- (UIImage *)thumbnailForAlbumTrack:(MLAlbumTrack *)albumTrack refreshCache:(BOOL)refreshCache
254 255 256
{
    __block MLFile *anyFileFromAnyTrack = nil;
    void (^getFileBlock)(void) = ^(){
257
        anyFileFromAnyTrack = [albumTrack anyFileFromTrack];
258 259 260 261 262
    };
    if ([NSThread isMainThread])
        getFileBlock();
    else
        dispatch_sync(dispatch_get_main_queue(), getFileBlock);
263
    return [self thumbnailForMediaFile:anyFileFromAnyTrack refreshCache:refreshCache];
264 265
}

266
- (UIImage *)clusterThumbFromFiles:(NSArray *)files andNumber:(NSUInteger)fileNumber blur:(BOOL)blurImage
267 268
{
    UIImage *clusterThumb;
269
    CGSize imageSize = CGSizeZero;
270 271 272 273 274 275 276 277 278 279 280
    if (_currentDeviceIdiom == UIUserInterfaceIdiomPad) {
        if ([UIScreen mainScreen].scale==2.0)
            imageSize = CGSizeMake(682., 384.);
        else
            imageSize = CGSizeMake(341., 192.);
    } else if (_currentDeviceIdiom == UIUserInterfaceIdiomPhone) {
        if ([UIScreen mainScreen].scale==2.0)
            imageSize = CGSizeMake(480., 270.);
        else
            imageSize = CGSizeMake(720., 405.);
    }
281

282
    UIGraphicsBeginImageContext(imageSize);
283 284
    NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
    for (NSUInteger i = 0; i < iter; i++) {
285
        MLFile *file =  [files objectAtIndex:i];
286
        clusterThumb = [self thumbnailForMediaFile:file refreshCache:NO];
287
        CGContextRef context = UIGraphicsGetCurrentContext();
288
        CGFloat imagePartWidth = (imageSize.width / iter);
289
        //the rect in which the image should be drawn
290
        CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
291 292 293
        CGContextSaveGState(context);
        CGContextClipToRect(context, clippingRect);
        //take the center of the clippingRect and calculate the offset from the original center
294
        CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
295
        //shift the rect to draw the middle of the image in the clippingrect
296
        CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
Felix Paul Kühne's avatar
Felix Paul Kühne committed
297 298
        if (clusterThumb != nil)
            [clusterThumb drawInRect:drawingRect];
299 300 301
        //get rid of the old clippingRect
        CGContextRestoreGState(context);
    }
302
    clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
303 304
    UIGraphicsEndImageContext();

305 306 307
    if (!blurImage)
        return clusterThumb;
    return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
308 309
}

310
@end