Refactory the `SDAnimatedImageView` implementation. Put all animation calculation logic into `SDAnimatedPlayer`. Refactory the animated progressive implementation to directly get the coder

This commit is contained in:
DreamPiggy 2019-11-04 02:52:27 +08:00
parent c8b84c7575
commit 1fe5fb28af
4 changed files with 497 additions and 372 deletions

View File

@ -0,0 +1,59 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import <Foundation/Foundation.h>
#import "SDWebImageCompat.h"
#import "SDImageCoder.h"
@interface SDAnimatedImagePlayer : NSObject
/// Current playing frame image. This value is KVO Compliance.
@property (nonatomic, readonly, nullable) UIImage *currentFrame;
/// Current frame index, zero based. This value is KVO Compliance.
@property (nonatomic, readonly) NSUInteger currentFrameIndex;
/// Current loop count since its latest animating. This value is KVO Compliance.
@property (nonatomic, readonly) NSUInteger currentLoopCount;
/// Total frame count for niamted image rendering. Defaults is animated image's frame count.
@property (nonatomic, assign) NSUInteger totalFrameCount;
/// Total loop count for animated image rendering. Default is animated image's loop count.
@property (nonatomic, assign) NSUInteger totalLoopCount;
/**
Provide a max buffer size by bytes. This is used to adjust frame buffer count and can be useful when the decoding cost is expensive (such as Animated WebP software decoding). Default is 0.
`0` means automatically adjust by calculating current memory usage.
`1` means without any buffer cache, each of frames will be decoded and then be freed after rendering. (Lowest Memory and Highest CPU)
`NSUIntegerMax` means cache all the buffer. (Lowest CPU and Highest Memory)
*/
@property (nonatomic, assign) NSUInteger maxBufferSize;
/**
You can specify a runloop mode to let it rendering.
Default is NSRunLoopCommonModes on multi-core iOS device, NSDefaultRunLoopMode on single-core iOS device
*/
@property (nonatomic, copy, nonnull) NSRunLoopMode runLoopMode;
- (nullable instancetype)initWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
+ (nullable instancetype)playerWithProvider:(nonnull id<SDAnimatedImageProvider>)provider;
@property (nonatomic, copy, nullable) void (^animationFrameHandler)(NSUInteger index, UIImage * _Nonnull frame);
@property (nonatomic, copy, nullable) void (^animationLoopHandler)(NSUInteger loopCount);
@property (readonly) BOOL isPlaying;
- (void)startPlaying;
- (void)pausePlaying;
- (void)stopPlaying;
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount;
- (void)clearFrameBuffer;
@end

View File

@ -0,0 +1,348 @@
/*
* This file is part of the SDWebImage package.
* (c) Olivier Poitrey <rs@dailymotion.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#import "SDAnimatedImagePlayer.h"
#import "NSImage+Compatibility.h"
#import "SDDisplayLink.h"
#import "SDDeviceHelper.h"
#import "SDInternalMacros.h"
@interface SDAnimatedImagePlayer () {
NSRunLoopMode _runLoopMode;
}
@property (nonatomic, strong, readwrite) UIImage *currentFrame;
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
@property (nonatomic, strong) id<SDAnimatedImageProvider> animatedProvider;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIImage *> *frameBuffer;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, assign) BOOL bufferMiss;
@property (nonatomic, assign) NSUInteger maxBufferCount;
@property (nonatomic, strong) NSOperationQueue *fetchQueue;
@property (nonatomic, strong) dispatch_semaphore_t lock;
@property (nonatomic, strong) SDDisplayLink *displayLink;
@end
@implementation SDAnimatedImagePlayer
- (instancetype)initWithProvider:(id<SDAnimatedImageProvider>)provider {
self = [super init];
if (self) {
NSUInteger animatedImageFrameCount = provider.animatedImageFrameCount;
// Check the frame count
if (animatedImageFrameCount <= 1) {
return nil;
}
self.totalFrameCount = animatedImageFrameCount;
// Get the current frame and loop count.
self.totalLoopCount = provider.animatedImageLoopCount;
self.animatedProvider = provider;
[self setupCurrentFrame];
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
return self;
}
+ (instancetype)playerWithProvider:(id<SDAnimatedImageProvider>)provider {
SDAnimatedImagePlayer *player = [[SDAnimatedImagePlayer alloc] initWithProvider:provider];
return player;
}
#pragma mark - Life Cycle
- (void)dealloc {
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
[_fetchQueue cancelAllOperations];
[_fetchQueue addOperationWithBlock:^{
NSNumber *currentFrameIndex = @(self.currentFrameIndex);
SD_LOCK(self.lock);
NSArray *keys = self.frameBuffer.allKeys;
// only keep the next frame for later rendering
for (NSNumber * key in keys) {
if (![key isEqualToNumber:currentFrameIndex]) {
[self.frameBuffer removeObjectForKey:key];
}
}
SD_UNLOCK(self.lock);
}];
}
#pragma mark - Private
- (NSOperationQueue *)fetchQueue {
if (!_fetchQueue) {
_fetchQueue = [[NSOperationQueue alloc] init];
_fetchQueue.maxConcurrentOperationCount = 1;
}
return _fetchQueue;
}
- (NSMutableDictionary<NSNumber *,UIImage *> *)frameBuffer {
if (!_frameBuffer) {
_frameBuffer = [NSMutableDictionary dictionary];
}
return _frameBuffer;
}
- (dispatch_semaphore_t)lock {
if (!_lock) {
_lock = dispatch_semaphore_create(1);
}
return _lock;
}
- (SDDisplayLink *)displayLink {
if (!_displayLink) {
_displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)];
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
}
return _displayLink;
}
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode
{
if ([_runLoopMode isEqual:runLoopMode]) {
return;
}
if (_displayLink) {
if (_runLoopMode) {
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode];
}
if (runLoopMode.length > 0) {
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode];
}
}
_runLoopMode = [runLoopMode copy];
}
- (NSRunLoopMode)runLoopMode
{
if (!_runLoopMode) {
_runLoopMode = [[self class] defaultRunLoopMode];
}
return _runLoopMode;
}
#pragma mark - State Control
- (void)setupCurrentFrame {
if ([self.animatedProvider isKindOfClass:[UIImage class]]) {
UIImage *image = (UIImage *)self.animatedProvider;
// Use the poster image if available
#if SD_MAC
UIImage *posterFrame = [[NSImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:kCGImagePropertyOrientationUp];
#else
UIImage *posterFrame = [[UIImage alloc] initWithCGImage:image.CGImage scale:image.scale orientation:image.imageOrientation];
#endif
if (posterFrame) {
self.currentFrame = posterFrame;
self.frameBuffer[@(self.currentFrameIndex)] = self.currentFrame;
}
}
}
- (void)resetCurrentFrameIndex {
self.currentFrame = nil;
self.currentFrameIndex = 0;
self.currentLoopCount = 0;
self.currentTime = 0;
self.bufferMiss = NO;
}
- (void)clearFrameBuffer {
SD_LOCK(self.lock);
[_frameBuffer removeAllObjects];
SD_UNLOCK(self.lock);
}
#pragma mark - Animation Control
- (void)startPlaying {
[self.displayLink start];
// Calculate max buffer size
[self calculateMaxBufferCount];
}
- (void)stopPlaying {
[_fetchQueue cancelAllOperations];
// Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method.
[_displayLink stop];
[self resetCurrentFrameIndex];
}
- (void)pausePlaying {
[_fetchQueue cancelAllOperations];
[_displayLink stop];
}
- (BOOL)isPlaying {
return self.displayLink.isRunning;
}
- (void)seekToFrameAtIndex:(NSUInteger)index loopCount:(NSUInteger)loopCount {
self.currentFrameIndex = index;
self.currentLoopCount = loopCount;
}
#pragma mark - Core Render
- (void)displayDidRefresh:(SDDisplayLink *)displayLink {
// If for some reason a wild call makes it through when we shouldn't be animating, bail.
// Early return!
if (!self.isPlaying) {
return;
}
// Calculate refresh duration
NSTimeInterval duration = self.displayLink.duration;
NSUInteger totalFrameCount = self.totalFrameCount;
NSUInteger currentFrameIndex = self.currentFrameIndex;
NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount;
// Check if we have the frame buffer firstly to improve performance
if (!self.bufferMiss) {
// Then check if timestamp is reached
self.currentTime += duration;
NSTimeInterval currentDuration = [self.animatedProvider animatedImageDurationAtIndex:currentFrameIndex];
if (self.currentTime < currentDuration) {
// Current frame timestamp not reached, return
return;
}
self.currentTime -= currentDuration;
NSTimeInterval nextDuration = [self.animatedProvider animatedImageDurationAtIndex:nextFrameIndex];
if (self.currentTime > nextDuration) {
// Do not skip frame
self.currentTime = nextDuration;
}
}
// Update the current frame
UIImage *currentFrame;
UIImage *fetchFrame;
SD_LOCK(self.lock);
currentFrame = self.frameBuffer[@(currentFrameIndex)];
fetchFrame = currentFrame ? self.frameBuffer[@(nextFrameIndex)] : nil;
SD_UNLOCK(self.lock);
BOOL bufferFull = NO;
if (currentFrame) {
SD_LOCK(self.lock);
// Remove the frame buffer if need
if (self.frameBuffer.count > self.maxBufferCount) {
self.frameBuffer[@(currentFrameIndex)] = nil;
}
// Check whether we can stop fetch
if (self.frameBuffer.count == totalFrameCount) {
bufferFull = YES;
}
SD_UNLOCK(self.lock);
self.currentFrame = currentFrame;
[self handleFrameChange];
self.currentFrameIndex = nextFrameIndex;
self.bufferMiss = NO;
} else {
self.bufferMiss = YES;
}
// Update the loop count when last frame rendered
if (nextFrameIndex == 0 && !self.bufferMiss) {
// Update the loop count
self.currentLoopCount++;
[self handleLoopChnage];
// if reached the max loop count, stop animating, 0 means loop indefinitely
NSUInteger maxLoopCount = self.totalLoopCount;
if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) {
[self stopPlaying];
return;
}
}
// Since we support handler, check animating state again
if (!self.isPlaying) {
return;
}
// Check if we should prefetch next frame or current frame
NSUInteger fetchFrameIndex;
if (self.bufferMiss) {
// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame
fetchFrameIndex = currentFrameIndex;
} else {
// Or, most cases, the decode speed is faster than render speed, we fetch next frame
fetchFrameIndex = nextFrameIndex;
}
if (!fetchFrame && !bufferFull && self.fetchQueue.operationCount == 0) {
// Prefetch next frame in background queue
id<SDAnimatedImageProvider> animatedProvider = self.animatedProvider;
@weakify(self);
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
@strongify(self);
if (!self) {
return;
}
UIImage *frame = [animatedProvider animatedImageFrameAtIndex:fetchFrameIndex];
BOOL isAnimating = self.displayLink.isRunning;
if (isAnimating) {
SD_LOCK(self.lock);
self.frameBuffer[@(fetchFrameIndex)] = frame;
SD_UNLOCK(self.lock);
}
}];
[self.fetchQueue addOperation:operation];
}
}
- (void)handleFrameChange {
if (self.animationFrameHandler) {
self.animationFrameHandler(self.currentFrameIndex, self.currentFrame);
}
}
- (void)handleLoopChnage {
if (self.animationLoopHandler) {
self.animationLoopHandler(self.currentLoopCount);
}
}
#pragma mark - Util
- (void)calculateMaxBufferCount {
NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage);
if (bytes == 0) bytes = 1024;
NSUInteger max = 0;
if (self.maxBufferSize > 0) {
max = self.maxBufferSize;
} else {
// Calculate based on current memory, these factors are by experience
NSUInteger total = [SDDeviceHelper totalMemory];
NSUInteger free = [SDDeviceHelper freeMemory];
max = MIN(total * 0.2, free * 0.6);
}
NSUInteger maxBufferCount = (double)max / (double)bytes;
if (!maxBufferCount) {
// At least 1 frame
maxBufferCount = 1;
}
self.maxBufferCount = maxBufferCount;
}
+ (NSString *)defaultRunLoopMode {
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
}
@end

View File

@ -21,7 +21,7 @@
@interface SDAnimatedImageView : UIImageView @interface SDAnimatedImageView : UIImageView
/** /**
Current display frame image. Current display frame image. This value is KVO Compliance.
*/ */
@property (nonatomic, strong, readonly, nullable) UIImage *currentFrame; @property (nonatomic, strong, readonly, nullable) UIImage *currentFrame;
/** /**

View File

@ -10,52 +10,22 @@
#if SD_UIKIT || SD_MAC #if SD_UIKIT || SD_MAC
#import "SDAnimatedImagePlayer.h"
#import "UIImage+Metadata.h" #import "UIImage+Metadata.h"
#import "NSImage+Compatibility.h" #import "NSImage+Compatibility.h"
#import "SDDisplayLink.h"
#import "SDInternalMacros.h" #import "SDInternalMacros.h"
#import <mach/mach.h> #import "objc/runtime.h"
#import <objc/runtime.h>
static NSUInteger SDDeviceTotalMemory() {
return (NSUInteger)[[NSProcessInfo processInfo] physicalMemory];
}
static NSUInteger SDDeviceFreeMemory() {
mach_port_t host_port = mach_host_self();
mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t);
vm_size_t page_size;
vm_statistics_data_t vm_stat;
kern_return_t kern;
kern = host_page_size(host_port, &page_size);
if (kern != KERN_SUCCESS) return 0;
kern = host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size);
if (kern != KERN_SUCCESS) return 0;
return vm_stat.free_count * page_size;
}
@interface SDAnimatedImageView () <CALayerDelegate> { @interface SDAnimatedImageView () <CALayerDelegate> {
NSRunLoopMode _runLoopMode;
BOOL _initFinished; // Extra flag to mark the `commonInit` is called BOOL _initFinished; // Extra flag to mark the `commonInit` is called
} }
@property (nonatomic, strong, readwrite) UIImage *currentFrame; @property (nonatomic, strong, readwrite) UIImage *currentFrame;
@property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex; @property (nonatomic, assign, readwrite) NSUInteger currentFrameIndex;
@property (nonatomic, assign, readwrite) NSUInteger currentLoopCount; @property (nonatomic, assign, readwrite) NSUInteger currentLoopCount;
@property (nonatomic, assign) NSUInteger totalFrameCount;
@property (nonatomic, assign) NSUInteger totalLoopCount;
@property (nonatomic, strong) UIImage<SDAnimatedImage> *animatedImage;
@property (nonatomic, strong) NSMutableDictionary<NSNumber *, UIImage *> *frameBuffer;
@property (nonatomic, assign) NSTimeInterval currentTime;
@property (nonatomic, assign) BOOL bufferMiss;
@property (nonatomic, assign) BOOL shouldAnimate; @property (nonatomic, assign) BOOL shouldAnimate;
@property (nonatomic, assign) BOOL isProgressive; @property (nonatomic, assign) BOOL isProgressive;
@property (nonatomic, assign) NSUInteger maxBufferCount; @property (nonatomic,strong) SDAnimatedImagePlayer *player; // The animation player.
@property (nonatomic, strong) NSOperationQueue *fetchQueue;
@property (nonatomic, strong) dispatch_semaphore_t lock;
@property (nonatomic, assign) CGFloat animatedImageScale;
@property (nonatomic, strong) SDDisplayLink *displayLink;
@property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer. @property (nonatomic) CALayer *imageViewLayer; // The actual rendering layer.
@end @end
@ -124,59 +94,11 @@ static NSUInteger SDDeviceFreeMemory() {
self.shouldIncrementalLoad = YES; self.shouldIncrementalLoad = YES;
#if SD_MAC #if SD_MAC
self.wantsLayer = YES; self.wantsLayer = YES;
#endif
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveMemoryWarning:) name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif #endif
// Mark commonInit finished // Mark commonInit finished
_initFinished = YES; _initFinished = YES;
} }
- (void)resetAnimatedImage
{
self.animatedImage = nil;
self.totalFrameCount = 0;
self.totalLoopCount = 0;
// reset current state
[self resetCurrentFrameIndex];
self.shouldAnimate = NO;
self.isProgressive = NO;
self.maxBufferCount = 0;
self.animatedImageScale = 1;
[_fetchQueue cancelAllOperations];
// clear buffer cache
[self clearFrameBuffer];
}
- (void)resetProgressiveImage
{
self.animatedImage = nil;
self.totalFrameCount = 0;
self.totalLoopCount = 0;
// preserve current state
self.shouldAnimate = NO;
self.isProgressive = YES;
self.maxBufferCount = 0;
self.animatedImageScale = 1;
// preserve buffer cache
}
- (void)resetCurrentFrameIndex
{
self.currentFrame = nil;
self.currentFrameIndex = 0;
self.currentLoopCount = 0;
self.currentTime = 0;
self.bufferMiss = NO;
}
- (void)clearFrameBuffer
{
SD_LOCK(self.lock);
[_frameBuffer removeAllObjects];
SD_UNLOCK(self.lock);
}
#pragma mark - Accessors #pragma mark - Accessors
#pragma mark Public #pragma mark Public
@ -189,46 +111,64 @@ static NSUInteger SDDeviceFreeMemory() {
// Check Progressive rendering // Check Progressive rendering
[self updateIsProgressiveWithImage:image]; [self updateIsProgressiveWithImage:image];
if (self.isProgressive) { if (!self.isProgressive) {
// Reset all value, but keep current state
[self resetProgressiveImage];
} else {
// Stop animating // Stop animating
[self stopAnimating]; self.player = nil;
// Reset all value self.currentFrame = nil;
[self resetAnimatedImage]; self.currentFrameIndex = 0;
self.currentLoopCount = 0;
} }
// We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end. // We need call super method to keep function. This will impliedly call `setNeedsDisplay`. But we have no way to avoid this when using animated image. So we call `setNeedsDisplay` again at the end.
super.image = image; super.image = image;
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) { if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)]) {
NSUInteger animatedImageFrameCount = ((UIImage<SDAnimatedImage> *)image).animatedImageFrameCount; if (!self.player) {
// Check the frame count id<SDAnimatedImageProvider> provider;
if (animatedImageFrameCount <= 1) { // Check progressive loading
if (self.isProgressive) {
provider = [self progressiveAnimatedCoderForImage:image];
} else {
provider = (id<SDAnimatedImage>)image;
}
// Create animted player
self.player = [SDAnimatedImagePlayer playerWithProvider:provider];
} else {
// Update Frame Count
self.player.totalFrameCount = [(id<SDAnimatedImage>)image animatedImageFrameCount];
}
if (!self.player) {
// animated player nil means the image format is not supported, or frame count <= 1
return; return;
} }
// If progressive rendering is disabled but animated image is incremental. Only show poster image
if (!self.isProgressive && image.sd_isIncremental) { // Custom Loop Count
return; if (self.shouldCustomLoopCount) {
} self.player.totalLoopCount = self.animationRepeatCount;
self.animatedImage = (UIImage<SDAnimatedImage> *)image;
self.totalFrameCount = animatedImageFrameCount;
// Get the current frame and loop count.
self.totalLoopCount = self.animatedImage.animatedImageLoopCount;
// Get the scale
self.animatedImageScale = image.scale;
if (!self.isProgressive) {
self.currentFrame = image;
SD_LOCK(self.lock);
self.frameBuffer[@(self.currentFrameIndex)] = self.currentFrame;
SD_UNLOCK(self.lock);
} }
// Setup handler
@weakify(self);
self.player.animationFrameHandler = ^(NSUInteger index, UIImage * frame) {
@strongify(self);
self.currentFrameIndex = index;
self.currentFrame = frame;
[self.imageViewLayer setNeedsDisplay];
};
self.player.animationLoopHandler = ^(NSUInteger loopCount) {
@strongify(self);
self.currentLoopCount = loopCount;
// Progressive image reach the current last frame index. Keep the state and pause animating. Wait for later restart
if (self.isProgressive) {
NSUInteger lastFrameIndex = self.player.totalFrameCount;
[self.player seekToFrameAtIndex:lastFrameIndex loopCount:0];
[self.player pausePlaying];
}
};
// Ensure disabled highlighting; it's not supported (see `-setHighlighted:`). // Ensure disabled highlighting; it's not supported (see `-setHighlighted:`).
super.highlighted = NO; super.highlighted = NO;
// Calculate max buffer size
[self calculateMaxBufferCount];
// Update should animate // Update should animate
[self updateShouldAnimate]; [self updateShouldAnimate];
if (self.shouldAnimate) { if (self.shouldAnimate) {
@ -239,95 +179,26 @@ static NSUInteger SDDeviceFreeMemory() {
} }
} }
#pragma mark - Configuration
- (void)setRunLoopMode:(NSRunLoopMode)runLoopMode - (void)setRunLoopMode:(NSRunLoopMode)runLoopMode
{ {
if ([_runLoopMode isEqual:runLoopMode]) { self.player.runLoopMode = runLoopMode;
return;
}
if (_displayLink) {
if (_runLoopMode) {
[_displayLink removeFromRunLoop:[NSRunLoop mainRunLoop] forMode:_runLoopMode];
}
if (runLoopMode.length > 0) {
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:runLoopMode];
}
}
_runLoopMode = [runLoopMode copy];
} }
- (NSRunLoopMode)runLoopMode - (NSRunLoopMode)runLoopMode
{ {
if (!_runLoopMode) { return self.player.runLoopMode;
_runLoopMode = [[self class] defaultRunLoopMode];
}
return _runLoopMode;
} }
- (BOOL)shouldIncrementalLoad { - (BOOL)shouldIncrementalLoad
{
if (!_initFinished) { if (!_initFinished) {
return YES; // Defaults to YES return YES; // Defaults to YES
} }
return _initFinished; return _initFinished;
} }
#pragma mark - Private
- (NSOperationQueue *)fetchQueue
{
if (!_fetchQueue) {
_fetchQueue = [[NSOperationQueue alloc] init];
_fetchQueue.maxConcurrentOperationCount = 1;
}
return _fetchQueue;
}
- (NSMutableDictionary<NSNumber *,UIImage *> *)frameBuffer
{
if (!_frameBuffer) {
_frameBuffer = [NSMutableDictionary dictionary];
}
return _frameBuffer;
}
- (dispatch_semaphore_t)lock {
if (!_lock) {
_lock = dispatch_semaphore_create(1);
}
return _lock;
}
- (SDDisplayLink *)displayLink {
if (!_displayLink) {
_displayLink = [SDDisplayLink displayLinkWithTarget:self selector:@selector(displayDidRefresh:)];
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:self.runLoopMode];
}
return _displayLink;
}
#pragma mark - Life Cycle
- (void)dealloc
{
#if SD_UIKIT
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidReceiveMemoryWarningNotification object:nil];
#endif
}
- (void)didReceiveMemoryWarning:(NSNotification *)notification {
[_fetchQueue cancelAllOperations];
[_fetchQueue addOperationWithBlock:^{
NSNumber *currentFrameIndex = @(self.currentFrameIndex);
SD_LOCK(self.lock);
NSArray *keys = self.frameBuffer.allKeys;
// only keep the next frame for later rendering
for (NSNumber * key in keys) {
if (![key isEqualToNumber:currentFrameIndex]) {
[self.frameBuffer removeObjectForKey:key];
}
}
SD_UNLOCK(self.lock);
}];
}
#pragma mark - UIView Method Overrides #pragma mark - UIView Method Overrides
#pragma mark Observing View-Related Changes #pragma mark Observing View-Related Changes
@ -408,8 +279,8 @@ static NSUInteger SDDeviceFreeMemory() {
- (void)startAnimating - (void)startAnimating
{ {
if (self.animatedImage) { if (self.player) {
[self.displayLink start]; [self.player startPlaying];
} else { } else {
#if SD_UIKIT #if SD_UIKIT
[super startAnimating]; [super startAnimating];
@ -419,15 +290,14 @@ static NSUInteger SDDeviceFreeMemory() {
- (void)stopAnimating - (void)stopAnimating
{ {
if (self.animatedImage) { if (self.player) {
[_fetchQueue cancelAllOperations];
// Using `_displayLink` here because when UIImageView dealloc, it may trigger `[self stopAnimating]`, we already release the display link in SDAnimatedImageView's dealloc method.
[_displayLink stop];
if (self.resetFrameIndexWhenStopped) { if (self.resetFrameIndexWhenStopped) {
[self resetCurrentFrameIndex]; [self.player stopPlaying];
} else {
[self.player pausePlaying];
} }
if (self.clearBufferWhenStopped) { if (self.clearBufferWhenStopped) {
[self clearFrameBuffer]; [self.player clearFrameBuffer];
} }
} else { } else {
#if SD_UIKIT #if SD_UIKIT
@ -436,18 +306,16 @@ static NSUInteger SDDeviceFreeMemory() {
} }
} }
#if SD_UIKIT
- (BOOL)isAnimating - (BOOL)isAnimating
{ {
BOOL isAnimating = NO; if (self.player) {
if (self.animatedImage) { return self.player.isPlaying;
isAnimating = self.displayLink.isRunning;
} else { } else {
#if SD_UIKIT return [super isAnimating];
isAnimating = [super isAnimating];
#endif
} }
return isAnimating;
} }
#endif
#if SD_MAC #if SD_MAC
- (void)setAnimates:(BOOL)animates - (void)setAnimates:(BOOL)animates
@ -466,7 +334,7 @@ static NSUInteger SDDeviceFreeMemory() {
- (void)setHighlighted:(BOOL)highlighted - (void)setHighlighted:(BOOL)highlighted
{ {
// Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell. // Highlighted image is unsupported for animated images, but implementing it breaks the image view when embedded in a UICollectionViewCell.
if (!self.animatedImage) { if (!self.player) {
[super setHighlighted:highlighted]; [super setHighlighted:highlighted];
} }
} }
@ -484,7 +352,7 @@ static NSUInteger SDDeviceFreeMemory() {
#else #else
BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0; BOOL isVisible = self.window && self.superview && ![self isHidden] && self.alpha > 0.0;
#endif #endif
self.shouldAnimate = self.animatedImage && self.totalFrameCount > 1 && isVisible; self.shouldAnimate = self.player && isVisible;
} }
// Update progressive status only after `setImage:` call. // Update progressive status only after `setImage:` call.
@ -497,157 +365,31 @@ static NSUInteger SDDeviceFreeMemory() {
} }
// We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here // We must use `image.class conformsToProtocol:` instead of `image conformsToProtocol:` here
// Because UIKit on macOS, using internal hard-coded override method, which returns NO // Because UIKit on macOS, using internal hard-coded override method, which returns NO
if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental) { id<SDAnimatedImageCoder> currentAnimatedCoder = [self progressiveAnimatedCoderForImage:image];
if (currentAnimatedCoder) {
UIImage *previousImage = self.image; UIImage *previousImage = self.image;
if ([previousImage.class conformsToProtocol:@protocol(SDAnimatedImage)] && previousImage.sd_isIncremental) { if (!previousImage) {
NSData *previousData = [((UIImage<SDAnimatedImage> *)previousImage) animatedImageData]; // If current animated coder supports progressive, and no previous image to check, start progressive loading
NSData *currentData = [((UIImage<SDAnimatedImage> *)image) animatedImageData];
// Check whether to use progressive rendering or not
if (!previousData || !currentData) {
// Early return
return;
}
// Warning: normally the `previousData` is same instance as `currentData` because our `SDAnimatedImage` class share the same `coder` instance internally. But there may be a race condition, that later retrived `currentData` is already been updated and it's not the same instance as `previousData`.
// And for protocol extensible design, we should not assume `SDAnimatedImage` protocol implementations always share same instance. So both of two reasons, we need that `rangeOfData` check.
if ([currentData isEqualToData:previousData]) {
// If current data is the same data (or instance) as previous data
self.isProgressive = YES;
} else if (currentData.length > previousData.length) {
// If current data is appended by previous data, use `NSDataSearchAnchored`, search is limited to start of currentData
NSRange range = [currentData rangeOfData:previousData options:NSDataSearchAnchored range:NSMakeRange(0, previousData.length)];
if (range.location != NSNotFound) {
// Contains hole previous data and they start with the same beginning
self.isProgressive = YES;
}
}
} else {
// Previous image is not progressive, so start progressive rendering
self.isProgressive = YES; self.isProgressive = YES;
} else {
id<SDAnimatedImageCoder> previousAnimatedCoder = [self progressiveAnimatedCoderForImage:previousImage];
if (previousAnimatedCoder == currentAnimatedCoder) {
// If current animated coder is the same as previous, start progressive loading
self.isProgressive = YES;
}
} }
} }
} }
- (void)displayDidRefresh:(SDDisplayLink *)displayLink // Check if image can represent a `Progressive Animated Image` during loading
{ - (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)progressiveAnimatedCoderForImage:(UIImage *)image {
// If for some reason a wild call makes it through when we shouldn't be animating, bail. if ([image.class conformsToProtocol:@protocol(SDAnimatedImage)] && image.sd_isIncremental && [image respondsToSelector:@selector(animatedCoder)]) {
// Early return! id<SDAnimatedImageCoder> animatedCoder = [(id<SDAnimatedImage>)image animatedCoder];
if (!self.shouldAnimate) { if ([animatedCoder conformsToProtocol:@protocol(SDProgressiveImageCoder)]) {
return; return (id<SDAnimatedImageCoder, SDProgressiveImageCoder>)animatedCoder;
}
// Calculate refresh duration
NSTimeInterval duration = self.displayLink.duration;
NSUInteger totalFrameCount = self.totalFrameCount;
NSUInteger currentFrameIndex = self.currentFrameIndex;
NSUInteger nextFrameIndex = (currentFrameIndex + 1) % totalFrameCount;
// Check if we have the frame buffer firstly to improve performance
if (!self.bufferMiss) {
// Then check if timestamp is reached
self.currentTime += duration;
NSTimeInterval currentDuration = [self.animatedImage animatedImageDurationAtIndex:currentFrameIndex];
if (self.currentTime < currentDuration) {
// Current frame timestamp not reached, return
return;
}
self.currentTime -= currentDuration;
NSTimeInterval nextDuration = [self.animatedImage animatedImageDurationAtIndex:nextFrameIndex];
if (self.currentTime > nextDuration) {
// Do not skip frame
self.currentTime = nextDuration;
} }
} }
return nil;
// Update the current frame
UIImage *currentFrame;
UIImage *fetchFrame;
SD_LOCK(self.lock);
currentFrame = self.frameBuffer[@(currentFrameIndex)];
fetchFrame = currentFrame ? self.frameBuffer[@(nextFrameIndex)] : nil;
SD_UNLOCK(self.lock);
BOOL bufferFull = NO;
if (currentFrame) {
SD_LOCK(self.lock);
// Remove the frame buffer if need
if (self.frameBuffer.count > self.maxBufferCount) {
self.frameBuffer[@(currentFrameIndex)] = nil;
}
// Check whether we can stop fetch
if (self.frameBuffer.count == totalFrameCount) {
bufferFull = YES;
}
SD_UNLOCK(self.lock);
self.currentFrame = currentFrame;
self.currentFrameIndex = nextFrameIndex;
self.bufferMiss = NO;
[self.imageViewLayer setNeedsDisplay];
} else {
self.bufferMiss = YES;
}
// Update the loop count when last frame rendered
if (nextFrameIndex == 0 && !self.bufferMiss) {
// Progressive image reach the current last frame index. Keep the state and stop animating. Wait for later restart
if (self.isProgressive) {
// Recovery the current frame index and removed frame buffer (See above)
self.currentFrameIndex = currentFrameIndex;
SD_LOCK(self.lock);
self.frameBuffer[@(currentFrameIndex)] = self.currentFrame;
SD_UNLOCK(self.lock);
[self stopAnimating];
return;
}
// Update the loop count
self.currentLoopCount++;
// if reached the max loop count, stop animating, 0 means loop indefinitely
NSUInteger maxLoopCount = self.shouldCustomLoopCount ? self.animationRepeatCount : self.totalLoopCount;
if (maxLoopCount != 0 && (self.currentLoopCount >= maxLoopCount)) {
[self stopAnimating];
return;
}
}
// Check if we should prefetch next frame or current frame
NSUInteger fetchFrameIndex;
if (self.bufferMiss) {
// When buffer miss, means the decode speed is slower than render speed, we fetch current miss frame
fetchFrameIndex = currentFrameIndex;
} else {
// Or, most cases, the decode speed is faster than render speed, we fetch next frame
fetchFrameIndex = nextFrameIndex;
}
if (!fetchFrame && !bufferFull && self.fetchQueue.operationCount == 0) {
// Prefetch next frame in background queue
UIImage<SDAnimatedImage> *animatedImage = self.animatedImage;
@weakify(self);
NSOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
@strongify(self);
if (!self) {
return;
}
UIImage *frame = [animatedImage animatedImageFrameAtIndex:fetchFrameIndex];
BOOL isAnimating = self.displayLink.isRunning;
if (isAnimating) {
SD_LOCK(self.lock);
self.frameBuffer[@(fetchFrameIndex)] = frame;
SD_UNLOCK(self.lock);
}
// Ensure when self dealloc, it dealloced on the main queue (UIKit/AppKit rule)
dispatch_async(dispatch_get_main_queue(), ^{
[self class];
});
}];
[self.fetchQueue addOperation:operation];
}
}
+ (NSString *)defaultRunLoopMode
{
// Key off `activeProcessorCount` (as opposed to `processorCount`) since the system could shut down cores in certain situations.
return [NSProcessInfo processInfo].activeProcessorCount > 1 ? NSRunLoopCommonModes : NSDefaultRunLoopMode;
} }
@ -656,9 +398,10 @@ static NSUInteger SDDeviceFreeMemory() {
- (void)displayLayer:(CALayer *)layer - (void)displayLayer:(CALayer *)layer
{ {
if (self.currentFrame) { UIImage *currentFrame = self.currentFrame;
layer.contentsScale = self.animatedImageScale; if (currentFrame) {
layer.contents = (__bridge id)self.currentFrame.CGImage; layer.contentsScale = currentFrame.scale;
layer.contents = (__bridge id)currentFrame.CGImage;
} }
} }
@ -696,31 +439,6 @@ static NSUInteger SDDeviceFreeMemory() {
#endif #endif
#pragma mark - Util
- (void)calculateMaxBufferCount {
NSUInteger bytes = CGImageGetBytesPerRow(self.currentFrame.CGImage) * CGImageGetHeight(self.currentFrame.CGImage);
if (bytes == 0) bytes = 1024;
NSUInteger max = 0;
if (self.maxBufferSize > 0) {
max = self.maxBufferSize;
} else {
// Calculate based on current memory, these factors are by experience
NSUInteger total = SDDeviceTotalMemory();
NSUInteger free = SDDeviceFreeMemory();
max = MIN(total * 0.2, free * 0.6);
}
NSUInteger maxBufferCount = (double)max / (double)bytes;
if (!maxBufferCount) {
// At least 1 frame
maxBufferCount = 1;
}
self.maxBufferCount = maxBufferCount;
}
@end @end
#endif #endif