9 #include <Foundation/Foundation.h>
10 #include <UIKit/UIKit.h>
11 #include <mach/mach_time.h>
13 #include "flutter/common/task_runners.h"
14 #include "flutter/fml/logging.h"
15 #include "flutter/fml/memory/task_runner_checker.h"
16 #include "flutter/fml/trace_event.h"
22 @property(nonatomic, assign, readonly)
double refreshRate;
31 : VsyncWaiter(task_runners) {
32 auto callback = [this](std::unique_ptr<flutter::FrameTimingsRecorder> recorder) {
33 const fml::TimePoint start_time = recorder->GetVsyncStartTime();
34 const fml::TimePoint target_time = recorder->GetVsyncTargetTime();
35 FireCallback(start_time, target_time,
true);
37 client_ = [[
VSyncClient alloc] initWithTaskRunner:task_runners_.GetUITaskRunner()
51 max_refresh_rate_ = new_max_refresh_rate;
59 return client_.refreshRate;
65 flutter::VsyncWaiter::Callback _callback;
69 - (instancetype)initWithTaskRunner:(fml::RefPtr<fml::TaskRunner>)task_runner
70 callback:(
flutter::VsyncWaiter::Callback)callback {
75 _allowPauseAfterVsync = YES;
76 _callback = std::move(callback);
77 _displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)];
84 task_runner->PostTask([localDisplayLink]() {
85 [localDisplayLink addToRunLoop:NSRunLoop.currentRunLoop forMode:NSRunLoopCommonModes];
92 - (void)setMaxRefreshRate:(
double)refreshRate {
96 double maxFrameRate = fmax(refreshRate, 60);
97 double minFrameRate = fmax(maxFrameRate / 2, 60);
98 if (@available(iOS 15.0, *)) {
100 CAFrameRateRangeMake(minFrameRate, maxFrameRate, maxFrameRate);
114 - (void)onDisplayLink:(CADisplayLink*)link {
115 CFTimeInterval delay = CACurrentMediaTime() - link.timestamp;
116 fml::TimePoint frame_start_time = fml::TimePoint::Now() - fml::TimeDelta::FromSecondsF(delay);
118 CFTimeInterval duration = link.targetTimestamp - link.timestamp;
119 fml::TimePoint frame_target_time = frame_start_time + fml::TimeDelta::FromSecondsF(duration);
121 TRACE_EVENT2_INT(
"flutter",
"PlatformVsync",
"frame_start_time",
122 frame_start_time.ToEpochDelta().ToMicroseconds(),
"frame_target_time",
123 frame_target_time.ToEpochDelta().ToMicroseconds());
125 std::unique_ptr<flutter::FrameTimingsRecorder> recorder =
126 std::make_unique<flutter::FrameTimingsRecorder>();
128 _refreshRate = round(1 / (frame_target_time - frame_start_time).ToSecondsF());
130 recorder->RecordVsync(frame_start_time, frame_target_time);
131 if (_allowPauseAfterVsync) {
134 _callback(std::move(recorder));
138 [_displayLink invalidate];
142 - (CADisplayLink*)getDisplayLink {
151 CADisplayLink* displayLink = [CADisplayLink displayLinkWithTarget:[[[
self class] alloc] init]
152 selector:@selector(onDisplayLink:)];
153 displayLink.paused = YES;
154 auto preferredFPS = displayLink.preferredFramesPerSecond;
161 if (preferredFPS != 0) {
165 return UIScreen.mainScreen.maximumFramesPerSecond;
168 - (void)onDisplayLink:(CADisplayLink*)link {
173 return [[NSBundle.mainBundle objectForInfoDictionaryKey:@"CADisableMinimumFrameDurationOnPhone"]