Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

#import <React/RCTNativeAnimatedNodesManager.h>

#import <React/RCTAdaptiveFrameRate.h>
#import <React/RCTConvert.h>

#import <React/RCTAdditionAnimatedNode.h>
Expand Down Expand Up @@ -53,6 +54,7 @@ @implementation RCTNativeAnimatedNodesManager {
NSMutableDictionary<NSString *, NSMutableArray<RCTEventAnimation *> *> *_eventDrivers;
NSMutableSet<id<RCTAnimationDriver>> *_activeAnimations;
CADisplayLink *_displayLink;
RCTAdaptiveFrameRateController *_frameRateController;
}

- (instancetype)initWithSurfacePresenter:(id<RCTSurfacePresenterStub>)surfacePresenter
Expand All @@ -62,6 +64,7 @@ - (instancetype)initWithSurfacePresenter:(id<RCTSurfacePresenterStub>)surfacePre
_animationNodes = [NSMutableDictionary new];
_eventDrivers = [NSMutableDictionary new];
_activeAnimations = [NSMutableSet new];
_frameRateController = [RCTAdaptiveFrameRateController new];
}
return self;
}
Expand Down Expand Up @@ -455,6 +458,7 @@ - (void)stopAnimationLoop

- (void)stepAnimations:(CADisplayLink *)displaylink
{
CFTimeInterval workStart = CACurrentMediaTime();
NSTimeInterval time = displaylink.timestamp;
for (id<RCTAnimationDriver> animationDriver in _activeAnimations) {
[animationDriver stepAnimationWithTime:time];
Expand All @@ -469,6 +473,8 @@ - (void)stepAnimations:(CADisplayLink *)displaylink
}
}

[_frameRateController recordFrameWorkFrom:workStart to:CACurrentMediaTime() forDisplayLink:displaylink];

[self stopAnimationLoopIfNeeded];
}

Expand Down
89 changes: 89 additions & 0 deletions packages/react-native/React/Base/RCTAdaptiveFrameRate.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import <Foundation/Foundation.h>
#import <QuartzCore/QuartzCore.h>

NS_ASSUME_NONNULL_BEGIN

/**
* Chooses a frame rate range for a display link from how long its recent
* frames took to process. Frames run at the screen's maximum rate while the
* work fits the frame budget, and step down to a steady 60, 30 or 24 fps when
* it does not, rather than dropping frames unevenly.
*
* Not thread safe: use each instance from the thread its display link ticks on.
*/
@interface RCTAdaptiveFrameRate : NSObject

/**
* Returns nil when maximumFramesPerSecond is 60 or less, so callers leave
* their display link at its default rate.
*/
+ (nullable instancetype)adaptiveFrameRateForMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond;

/**
* Uses the main screen's maximum frame rate. Main thread only, because it
* reads UIScreen.
*/
+ (nullable instancetype)adaptiveFrameRateForMainScreen;

- (instancetype)initWithMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond NS_DESIGNATED_INITIALIZER;
- (instancetype)init NS_UNAVAILABLE;
+ (instancetype)new NS_UNAVAILABLE;

@property (nonatomic, readonly) CAFrameRateRange currentRange;

/**
* Records how long one frame's work took. Returns YES when this changed
* currentRange, which is when the display link needs to be updated.
*/
- (BOOL)recordFrameWorkDuration:(NSTimeInterval)seconds;

#if !TARGET_OS_OSX
- (void)applyToDisplayLink:(CADisplayLink *)displayLink;
#endif

@end

#if !TARGET_OS_OSX

/**
* Adapts the frame rate of the display links that one target ticks for. Each
* new display link, and each one that ticks again after a pause of more than
* 250 ms, starts over at the screen's maximum rate with no samples. Work
* measured for one animation then does not slow down the next.
*
* Not thread safe: use it only from the display link's tick, on the main thread.
*/
@interface RCTAdaptiveFrameRateController : NSObject

/**
* Follows the main screen's maximum frame rate, which it reads each time a
* display link starts over.
*/
- (instancetype)init;

/**
* Uses maximumFramesPerSecond in place of the main screen's maximum.
*/
- (instancetype)initWithMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond;

/**
* Records the work that one tick of displayLink did between two
* CACurrentMediaTime() readings, and sets the display link's
* preferredFrameRateRange when the chosen range changes.
*/
- (void)recordFrameWorkFrom:(CFTimeInterval)startTime
to:(CFTimeInterval)endTime
forDisplayLink:(CADisplayLink *)displayLink;

@end

#endif

NS_ASSUME_NONNULL_END
144 changes: 144 additions & 0 deletions packages/react-native/React/Base/RCTAdaptiveFrameRate.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

#import "RCTAdaptiveFrameRate.h"

#if !TARGET_OS_OSX
#import <UIKit/UIKit.h>

#import "RCTAssert.h"
#endif

#define RCTFrameWorkSampleCount 4

@implementation RCTAdaptiveFrameRate {
NSInteger _maximumFramesPerSecond;
NSTimeInterval _samples[RCTFrameWorkSampleCount];
NSUInteger _recordedSampleCount;
}

+ (nullable instancetype)adaptiveFrameRateForMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond
{
return maximumFramesPerSecond > 60 ? [[self alloc] initWithMaximumFramesPerSecond:maximumFramesPerSecond] : nil;
}

+ (nullable instancetype)adaptiveFrameRateForMainScreen
{
#if TARGET_OS_OSX
return nil;
#else
RCTAssertMainQueue();
return [self adaptiveFrameRateForMaximumFramesPerSecond:UIScreen.mainScreen.maximumFramesPerSecond];
#endif
}

- (instancetype)initWithMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond
{
if ((self = [super init])) {
_maximumFramesPerSecond = MAX(maximumFramesPerSecond, 60);
_currentRange = [self rangeForFrameWorkDuration:0];
}
return self;
}

- (BOOL)recordFrameWorkDuration:(NSTimeInterval)seconds
{
_samples[_recordedSampleCount % RCTFrameWorkSampleCount] = seconds;
_recordedSampleCount++;
if (_recordedSampleCount < RCTFrameWorkSampleCount) {
return NO;
}

NSTimeInterval total = 0;
for (NSUInteger i = 0; i < RCTFrameWorkSampleCount; i++) {
total += _samples[i];
}
CAFrameRateRange range = [self rangeForFrameWorkDuration:total / RCTFrameWorkSampleCount];
if (CAFrameRateRangeIsEqualToRange(range, _currentRange)) {
return NO;
}
_currentRange = range;
return YES;
}

- (CAFrameRateRange)rangeForFrameWorkDuration:(NSTimeInterval)seconds
{
if (seconds < 1.0 / _maximumFramesPerSecond) {
return CAFrameRateRangeMake(60, _maximumFramesPerSecond, _maximumFramesPerSecond);
}
if (seconds < 1.0 / 60) {
return CAFrameRateRangeMake(30, 60, 60);
}
if (seconds < 1.0 / 30) {
return CAFrameRateRangeMake(24, 30, 30);
}
return CAFrameRateRangeMake(10, 24, 24);
}

#if !TARGET_OS_OSX
- (void)applyToDisplayLink:(CADisplayLink *)displayLink
{
displayLink.preferredFrameRateRange = _currentRange;
}
#endif

@end

#if !TARGET_OS_OSX

// More than twice the 100 ms between frames at the slowest range's 10 fps
// minimum, so only a pause or a stalled main thread reaches it.
static const CFTimeInterval RCTFrameWorkPauseThreshold = 0.25;

@implementation RCTAdaptiveFrameRateController {
RCTAdaptiveFrameRate *_Nullable (^_makeAdaptiveFrameRate)(void);
RCTAdaptiveFrameRate *_Nullable _adaptiveFrameRate;
__weak CADisplayLink *_displayLink;
CFTimeInterval _lastFrameWorkEnd;
}

- (instancetype)init
{
return [self initWithAdaptiveFrameRateFactory:^{
return [RCTAdaptiveFrameRate adaptiveFrameRateForMainScreen];
}];
}

- (instancetype)initWithMaximumFramesPerSecond:(NSInteger)maximumFramesPerSecond
{
return [self initWithAdaptiveFrameRateFactory:^{
return [RCTAdaptiveFrameRate adaptiveFrameRateForMaximumFramesPerSecond:maximumFramesPerSecond];
}];
}

- (instancetype)initWithAdaptiveFrameRateFactory:(RCTAdaptiveFrameRate *_Nullable (^)(void))factory
{
if ((self = [super init])) {
_makeAdaptiveFrameRate = factory;
}
return self;
}

- (void)recordFrameWorkFrom:(CFTimeInterval)startTime
to:(CFTimeInterval)endTime
forDisplayLink:(CADisplayLink *)displayLink
{
if (displayLink != _displayLink || startTime - _lastFrameWorkEnd > RCTFrameWorkPauseThreshold) {
_displayLink = displayLink;
_adaptiveFrameRate = _makeAdaptiveFrameRate();
[_adaptiveFrameRate applyToDisplayLink:displayLink];
}
_lastFrameWorkEnd = endTime;

if ([_adaptiveFrameRate recordFrameWorkDuration:endTime - startTime]) {
[_adaptiveFrameRate applyToDisplayLink:displayLink];
}
}

@end

#endif
16 changes: 15 additions & 1 deletion packages/react-native/React/Fabric/RCTScheduler.mm
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#import "RCTScheduler.h"

#import <QuartzCore/CADisplayLink.h>
#import <React/RCTAdaptiveFrameRate.h>
#import <React/RCTAssert.h>
#import <cxxreact/TraceSection.h>
#import <react/featureflags/ReactNativeFeatureFlags.h>
Expand Down Expand Up @@ -144,11 +145,24 @@ @interface RCTAnimationChoreographerDisplayLinkTarget : NSObject
- (void)displayLinkTick:(CADisplayLink *)sender;
@end

@implementation RCTAnimationChoreographerDisplayLinkTarget
@implementation RCTAnimationChoreographerDisplayLinkTarget {
RCTAdaptiveFrameRateController *_frameRateController;
}

- (instancetype)init
{
if (self = [super init]) {
_frameRateController = [RCTAdaptiveFrameRateController new];
}
return self;
}

- (void)displayLinkTick:(CADisplayLink *)sender
{
if (_choreographer != nullptr) {
CFTimeInterval workStart = CACurrentMediaTime();
_choreographer->onAnimationFrame(std::chrono::duration<double>(sender.targetTimestamp));
[_frameRateController recordFrameWorkFrom:workStart to:CACurrentMediaTime() forDisplayLink:sender];
}
}
@end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#import <React/RCTPlatformDisplayLink.h>
#else
#import <QuartzCore/CADisplayLink.h>
#import <React/RCTAdaptiveFrameRate.h>
#import <UIKit/UIKit.h>
#endif

Expand All @@ -27,6 +28,7 @@ @implementation RCTAnimatedModuleProvider {
RCTPlatformDisplayLink *_displayLink;
#else
CADisplayLink *_displayLink;
RCTAdaptiveFrameRateController *_frameRateController;
#endif
std::function<void()> _onRender;

Expand All @@ -44,6 +46,9 @@ - (instancetype)initWithSkipFramesDuringForegroundTransition:(BOOL)skipFramesDur
{
if (self = [super init]) {
_skipFramesDuringForegroundTransition = skipFramesDuringForegroundTransition;
#if !TARGET_OS_OSX
_frameRateController = [RCTAdaptiveFrameRateController new];
#endif
}
return self;
}
Expand Down Expand Up @@ -90,7 +95,15 @@ - (void)_onDisplayLinkTick

auto strongProvider = _nativeAnimatedNodesManagerProvider.lock();
if (strongProvider != nullptr && _displayLink != nullptr && _onRender != nullptr) {
#if TARGET_OS_OSX
_onRender();
#else
// _onRender can stop rendering synchronously, which clears _displayLink.
CADisplayLink *displayLink = _displayLink;
CFTimeInterval workStart = CACurrentMediaTime();
_onRender();
[_frameRateController recordFrameWorkFrom:workStart to:CACurrentMediaTime() forDisplayLink:displayLink];
#endif
}
}

Expand Down
2 changes: 2 additions & 0 deletions packages/rn-tester/RNTester/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CADisableMinimumFrameDurationOnPhone</key>
<true/>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
Expand Down
4 changes: 4 additions & 0 deletions packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
79B29C2E2E607A99007612A5 /* SceneDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 79B29C2D2E607A99007612A5 /* SceneDelegate.mm */; };
7F806D4D4D97AD6403558B35 /* RCTStatusBarAppearanceTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = 67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */; };
A8717727467541429C262C63 /* RCTTimingClockChangeTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */; };
A1F0C3D2E4B5968778695A4B /* RCTAdaptiveFrameRateTests.m in Sources */ = {isa = PBXBuildFile; fileRef = B2E1D4C3F5A6079889706B5C /* RCTAdaptiveFrameRateTests.m */; };
8145AE06241172D900A3F8DA /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 8145AE05241172D900A3F8DA /* LaunchScreen.storyboard */; };
832F45BB2A8A6E1F0097B4E6 /* SwiftTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 832F45BA2A8A6E1F0097B4E6 /* SwiftTest.swift */; };
A975CA6C2C05EADF0043F72A /* RCTNetworkTaskTests.m in Sources */ = {isa = PBXBuildFile; fileRef = A975CA6B2C05EADE0043F72A /* RCTNetworkTaskTests.m */; };
Expand Down Expand Up @@ -92,6 +93,7 @@
5C60EB1B226440DB0018C04F /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = RNTester/AppDelegate.mm; sourceTree = "<group>"; };
67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTStatusBarAppearanceTests.mm; sourceTree = "<group>"; };
A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTimingClockChangeTests.mm; sourceTree = "<group>"; };
B2E1D4C3F5A6079889706B5C /* RCTAdaptiveFrameRateTests.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = RCTAdaptiveFrameRateTests.m; sourceTree = "<group>"; };
79B29C2C2E607A99007612A5 /* SceneDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = SceneDelegate.h; path = RNTester/SceneDelegate.h; sourceTree = "<group>"; };
79B29C2D2E607A99007612A5 /* SceneDelegate.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; name = SceneDelegate.mm; path = RNTester/SceneDelegate.mm; sourceTree = "<group>"; };
8145AE05241172D900A3F8DA /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = RNTester/LaunchScreen.storyboard; sourceTree = "<group>"; };
Expand Down Expand Up @@ -324,6 +326,7 @@
E7DB20B322B2BAA4005AC45F /* RNTesterUnitTestsBundle.js */,
67B0814814F7C07E196BC295 /* RCTStatusBarAppearanceTests.mm */,
A8717727467541429C262C64 /* RCTTimingClockChangeTests.mm */,
B2E1D4C3F5A6079889706B5C /* RCTAdaptiveFrameRateTests.m */,
);
path = RNTesterUnitTests;
sourceTree = "<group>";
Expand Down Expand Up @@ -645,6 +648,7 @@
602160B9478DAFF2BAB56595 /* RCTUtilsTests.m in Sources */,
7F806D4D4D97AD6403558B35 /* RCTStatusBarAppearanceTests.mm in Sources */,
A8717727467541429C262C63 /* RCTTimingClockChangeTests.mm in Sources */,
A1F0C3D2E4B5968778695A4B /* RCTAdaptiveFrameRateTests.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
Loading
Loading