Flutter macOS Embedder
FlutterVSyncWaiter.mm
Go to the documentation of this file.
1 // Copyright 2013 The Flutter Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 
6 #include <optional>
7 #include <vector>
8 
9 #include "flutter/fml/logging.h"
10 #import "flutter/shell/platform/darwin/common/InternalFlutterSwiftCommon/InternalFlutterSwiftCommon.h"
11 #import "flutter/shell/platform/darwin/macos/InternalFlutterSwift/InternalFlutterSwift.h"
13 
14 #if (FLUTTER_RUNTIME_MODE == FLUTTER_RUNTIME_MODE_PROFILE)
15 #define VSYNC_TRACING_ENABLED 1
16 #endif
17 
18 #if VSYNC_TRACING_ENABLED
19 #include <OSLog/OSLog.h>
20 
21 // Trace vsync events using os_signpost so that they can be seen in Instruments "Points of
22 // Interest".
23 #define TRACE_VSYNC(event_type, baton) \
24  do { \
25  static os_log_t log = os_log_create("FlutterVSync", "PointsOfInterest"); \
26  _Pragma("GCC diagnostic push") _Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \
27  os_signpost_event_emit(log, OS_SIGNPOST_ID_EXCLUSIVE, event_type, "baton %lx", baton); \
28  _Pragma("GCC diagnostic pop") \
29  } while (0)
30 #else
31 #define TRACE_VSYNC(event_type, baton) \
32  do { \
33  } while (0)
34 #endif
35 
37 @end
38 
39 // It's preferable to fire the timers slightly early than too late due to scheduling latency.
40 // 1ms before vsync should be late enough for all events to be processed.
41 static const CFTimeInterval kTimerLatencyCompensation = 0.001;
42 
43 @implementation FlutterVSyncWaiter {
44  std::optional<std::uintptr_t> _pendingBaton;
46  void (^_block)(CFTimeInterval, CFTimeInterval, uintptr_t);
47  CFTimeInterval _lastTargetTimestamp;
49 }
50 
51 - (instancetype)initWithDisplayLink:(FlutterDisplayLink*)displayLink
52  block:(void (^)(CFTimeInterval timestamp,
53  CFTimeInterval targetTimestamp,
54  uintptr_t baton))block {
55  FML_DCHECK([NSThread isMainThread]);
56  if (self = [super init]) {
57  _block = block;
58 
59  _displayLink = displayLink;
60  _displayLink.delegate = self;
61  // Get at least one callback to initialize _lastTargetTimestamp.
62  _displayLink.paused = NO;
63  _warmUpFrame = YES;
64  }
65  return self;
66 }
67 
68 // Called from display link thread.
69 - (void)onDisplayLink:(CFTimeInterval)timestamp targetTimestamp:(CFTimeInterval)targetTimestamp {
70  if (_lastTargetTimestamp == 0) {
71  // Initial vsync - timestamp will be used to determine vsync phase.
72  _lastTargetTimestamp = targetTimestamp;
73  _displayLink.paused = YES;
74  } else {
75  _lastTargetTimestamp = targetTimestamp;
76 
77  // CVDisplayLink callback is called one and a half frame before the target
78  // timestamp. That can cause frame-pacing issues if the frame is rendered too early,
79  // it may also trigger frame start before events are processed.
80  CFTimeInterval minStart = targetTimestamp - _displayLink.nominalOutputRefreshPeriod;
81  CFTimeInterval current = CACurrentMediaTime();
82  CFTimeInterval remaining = std::max(minStart - current - kTimerLatencyCompensation, 0.0);
83 
84  TRACE_VSYNC("DisplayLinkCallback-Original", _pendingBaton.value_or(0));
85 
86  [FlutterRunLoop.mainRunLoop
87  performAfterDelay:remaining
88  block:^{
89  if (!_pendingBaton.has_value()) {
90  TRACE_VSYNC("DisplayLinkPaused", size_t(0));
91  _displayLink.paused = YES;
92  return;
93  }
94  TRACE_VSYNC("DisplayLinkCallback-Delayed", _pendingBaton.value_or(0));
95  _block(minStart, targetTimestamp, *_pendingBaton);
96  _pendingBaton = std::nullopt;
97  }];
98  }
99 }
100 
101 // Called from UI thread.
102 - (void)waitForVSync:(uintptr_t)baton {
103  FML_DCHECK([NSThread isMainThread]);
104  // CVDisplayLink start -> callback latency is two frames, there is
105  // no need to delay the warm-up frame.
106  if (_warmUpFrame) {
107  _warmUpFrame = NO;
108  TRACE_VSYNC("WarmUpFrame", baton);
109  CFTimeInterval now = CACurrentMediaTime();
110  _block(now, now, baton);
111  return;
112  }
113 
114  if (_pendingBaton.has_value()) {
115  [FlutterLogger logWarning:@"Engine requested vsync while another was pending"];
116  _block(0, 0, *_pendingBaton);
117  _pendingBaton = std::nullopt;
118  }
119 
120  TRACE_VSYNC("VSyncRequest", _pendingBaton.value_or(0));
121 
122  CFTimeInterval tick_interval = _displayLink.nominalOutputRefreshPeriod;
123  if (_displayLink.paused || tick_interval == 0 || _lastTargetTimestamp == 0) {
124  // When starting display link the first notification will come in the middle
125  // of next frame, which would incur a whole frame period of latency.
126  // To avoid that, first vsync notification will be fired using a timer
127  // scheduled to fire where the next frame is expected to start.
128  // Also use a timer if display link does not belong to any display
129  // (nominalOutputRefreshPeriod being 0)
130 
131  // Start of the vsync interval.
132  CFTimeInterval start = CACurrentMediaTime();
133 
134  // Timer delay is calculated as the time to the next frame start.
135  CFTimeInterval delay = 0;
136 
137  if (tick_interval != 0 && _lastTargetTimestamp != 0) {
138  CFTimeInterval phase = fmod(_lastTargetTimestamp, tick_interval);
139  CFTimeInterval now = start;
140  start = now - (fmod(now, tick_interval)) + phase;
141  if (start < now) {
142  start += tick_interval;
143  }
144  delay = std::max(start - now - kTimerLatencyCompensation, 0.0);
145  }
146 
147  [FlutterRunLoop.mainRunLoop performAfterDelay:delay
148  block:^{
149  CFTimeInterval targetTime = start + tick_interval;
150  TRACE_VSYNC("SynthesizedInitialVSync", baton);
151  _block(start, targetTime, baton);
152  }];
153  _displayLink.paused = NO;
154  } else {
155  _pendingBaton = baton;
156  }
157 }
158 
159 - (void)invalidate {
160  // It is possible that there is pending vsync request while the view for which
161  // this waiter belongs is being destroyed. In that case trigger the vsync
162  // immediately to avoid deadlock.
163  if (_pendingBaton.has_value()) {
164  CFTimeInterval now = CACurrentMediaTime();
165  _block(now, now, _pendingBaton.value());
166  _pendingBaton = std::nullopt;
167  }
168 
169  [_displayLink invalidate];
170  _displayLink = nil;
171 }
172 
173 - (void)dealloc {
174  FML_DCHECK(_displayLink == nil);
175 }
176 
177 @end
FlutterDisplayLink * _displayLink
static const CFTimeInterval kTimerLatencyCompensation
#define TRACE_VSYNC(event_type, baton)
CFTimeInterval _lastTargetTimestamp
void(^ _block)(CFTimeInterval, CFTimeInterval, uintptr_t)
BOOL _warmUpFrame