VLCThumbnailsCache.m 11.2 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
#import <WatchKit/WatchKit.h>
20 21
#import <CoreData/CoreData.h>
#import <MediaLibraryKit/MediaLibraryKit.h>
22
#import <MediaLibraryKit/UIImage+MLKit.h>
Felix Paul Kühne's avatar
Felix Paul Kühne committed
23 24 25
#if TARGET_OS_IOS
#import <UIKit/UIKit.h>
#endif
26

27
@interface VLCThumbnailsCache() {
28
    NSInteger MaxCacheSize;
29 30
    NSCache *_thumbnailCache;
    NSCache *_thumbnailCacheMetadata;
31
    NSInteger _currentDeviceIdiom;
32 33
}
@end
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
#define MAX_CACHE_SIZE_WATCH  15  // three times the number of items shown on 42mm Watch
40

41
- (instancetype)init
42
{
43 44
    self = [super init];
    if (self) {
45
// TODO: correct for watch
Felix Paul Kühne's avatar
Felix Paul Kühne committed
46
#if TARGET_OS_IOS
47 48
        _currentDeviceIdiom = [[UIDevice currentDevice] userInterfaceIdiom];
        MaxCacheSize = 0;
49

50
        switch (_currentDeviceIdiom) {
51
            case UIUserInterfaceIdiomPad:
52
                MaxCacheSize = MAX_CACHE_SIZE_IPAD;
53 54
                break;
            case UIUserInterfaceIdiomPhone:
55
                MaxCacheSize = MAX_CACHE_SIZE_IPHONE;
56
                break;
57

58
            default:
59
                MaxCacheSize = MAX_CACHE_SIZE_WATCH;
60 61
                break;
        }
62 63
#else
        MaxCacheSize = MAX_CACHE_SIZE_WATCH;
64
#endif
65 66
        _thumbnailCache = [[NSCache alloc] init];
        _thumbnailCacheMetadata = [[NSCache alloc] init];
67 68
        [_thumbnailCache setCountLimit: MaxCacheSize];
        [_thumbnailCacheMetadata setCountLimit: MaxCacheSize];
69 70 71
    }
    return self;
}
72

73 74 75 76 77 78 79 80 81 82 83
+ (instancetype)sharedThumbnailCache
{
    static dispatch_once_t onceToken;
    static VLCThumbnailsCache *sharedThumbnailCache;
    dispatch_once(&onceToken, ^{
        sharedThumbnailCache = [[VLCThumbnailsCache alloc] init];
    });

    return sharedThumbnailCache;
}

84
+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
85 86 87 88 89 90
{
    return [self thumbnailForManagedObject:object refreshCache:NO];
}

+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object
                          refreshCache:(BOOL)refreshCache
91 92
{
    UIImage *thumbnail;
93
    VLCThumbnailsCache *cache = [VLCThumbnailsCache sharedThumbnailCache];
94
    if ([object isKindOfClass:[MLShow class]]) {
95
        thumbnail = [cache thumbnailForShow:(MLShow *)object refreshCache:refreshCache];
96 97
    } else if ([object isKindOfClass:[MLShowEpisode class]]) {
        MLFile *anyFileFromEpisode = [(MLShowEpisode *)object files].anyObject;
98
        thumbnail = [cache thumbnailForMediaFile:anyFileFromEpisode refreshCache:refreshCache];
99
    } else if ([object isKindOfClass:[MLLabel class]]) {
100
        thumbnail = [cache thumbnailForLabel:(MLLabel *)object refreshCache:refreshCache];
101
    } else if ([object isKindOfClass:[MLAlbum class]]) {
102
        thumbnail = [cache thumbnailForAlbum:(MLAlbum *)object refreshCache:refreshCache];
103
    } else if ([object isKindOfClass:[MLAlbumTrack class]]) {
104
        thumbnail = [cache thumbnailForAlbumTrack:(MLAlbumTrack *)object refreshCache:refreshCache];
105
    } else {
106
        thumbnail = [cache thumbnailForMediaFile:(MLFile *)object refreshCache:refreshCache];
107 108 109 110
    }
    return thumbnail;
}

111
+ (UIImage *)thumbnailForManagedObject:(NSManagedObject *)object refreshCache:(BOOL)refreshCache toFitRect:(CGRect)rect scale:(CGFloat)scale shouldReplaceCache:(BOOL)replaceCache;
112
{
113
    UIImage *rawThumbnail = [self thumbnailForManagedObject:object refreshCache:refreshCache];
114 115 116 117 118 119
    CGSize rawSize = rawThumbnail.size;

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

120
    UIImage *scaledImage = [UIImage scaleImage:rawThumbnail toFitRect:rect scale:scale];
121 122 123 124 125 126 127 128 129

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

    return scaledImage;
}

- (void)_setThumbnail:(UIImage *)image forObjectId:(NSManagedObjectID *)objID
{
130 131
    if (image)
        [_thumbnailCache setObject:image forKey:objID];
132 133
}

134
- (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile refreshCache:(BOOL)refreshCache
135 136 137 138 139
{
    if (mediaFile == nil || mediaFile.objectID == nil)
        return nil;

    NSManagedObjectID *objID = mediaFile.objectID;
140
    UIImage *displayedImage;
141

142 143 144 145 146
    if (!refreshCache) {
        displayedImage = [_thumbnailCache objectForKey:objID];
        if (displayedImage)
            return displayedImage;
    }
147

148 149 150 151 152 153 154 155 156 157 158
    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;
    }
159

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 281 282 283 284 285 286 287 288 289 290 291
    // TODO: correct for watch
#ifndef TARGET_OS_WATCH
    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.);
    } else
#endif
    {
        if ([WKInterfaceDevice class]) {
            if (WKInterfaceDevice.currentDevice != nil) {
                CGRect screenRect = WKInterfaceDevice.currentDevice.screenBounds;
                imageSize = CGSizeMake(screenRect.size.width * WKInterfaceDevice.currentDevice.screenScale, 120.);
            }
        }
    }
292

293
    UIGraphicsBeginImageContext(imageSize);
294 295
    NSUInteger iter = files.count < fileNumber ? files.count : fileNumber;
    for (NSUInteger i = 0; i < iter; i++) {
296
        MLFile *file =  [files objectAtIndex:i];
297
        clusterThumb = [self thumbnailForMediaFile:file refreshCache:NO];
298
        CGContextRef context = UIGraphicsGetCurrentContext();
299
        CGFloat imagePartWidth = (imageSize.width / iter);
300
        //the rect in which the image should be drawn
301
        CGRect clippingRect = CGRectMake(imagePartWidth * i, 0, imagePartWidth, imageSize.height);
302 303 304
        CGContextSaveGState(context);
        CGContextClipToRect(context, clippingRect);
        //take the center of the clippingRect and calculate the offset from the original center
305
        CGFloat centerOffset = (imagePartWidth * i + imagePartWidth / 2) - imageSize.width / 2;
306
        //shift the rect to draw the middle of the image in the clippingrect
307
        CGRect drawingRect = CGRectMake(centerOffset, 0, imageSize.width, imageSize.height);
308
        [clusterThumb drawInRect:drawingRect];
309 310 311
        //get rid of the old clippingRect
        CGContextRestoreGState(context);
    }
312
    clusterThumb = UIGraphicsGetImageFromCurrentImageContext();
313 314
    UIGraphicsEndImageContext();

315 316 317 318
    if (!blurImage)
        return clusterThumb;

    return [UIImage applyBlurOnImage:clusterThumb withRadius:0.1];
319 320
}

321
@end