1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
|
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <atomic>
#include <cstdint>
#include <functional>
#include <future>
#include <memory>
#include <mutex>
#include <unordered_map>
#include <utility>
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#pragma clang diagnostic ignored "-Wextra"
#include <ui/GraphicTypes.h>
#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"
#include <ftl/fake_guard.h>
#include <ftl/non_null.h>
#include <ftl/optional.h>
#include <scheduler/Features.h>
#include <scheduler/FrameRateMode.h>
#include <scheduler/FrameTargeter.h>
#include <scheduler/Time.h>
#include <scheduler/VsyncConfig.h>
#include <ui/DisplayId.h>
#include <ui/DisplayMap.h>
#include "DisplayHardware/DisplayMode.h"
#include "EventThread.h"
#include "FrameRateOverrideMappings.h"
#include "ISchedulerCallback.h"
#include "LayerHistory.h"
#include "MessageQueue.h"
#include "OneShotTimer.h"
#include "RefreshRateSelector.h"
#include "SmallAreaDetectionAllowMappings.h"
#include "Utils/Dumper.h"
#include "VsyncConfiguration.h"
#include "VsyncModulator.h"
#include <FrontEnd/LayerHierarchy.h>
namespace android {
class FenceTime;
class TimeStats;
namespace frametimeline {
class TokenManager;
} // namespace frametimeline
namespace surfaceflinger {
class Factory;
} // namespace surfaceflinger
namespace scheduler {
using GlobalSignals = RefreshRateSelector::GlobalSignals;
class RefreshRateStats;
class VsyncConfiguration;
class VsyncSchedule;
enum class Cycle {
Render, // Surface rendering.
LastComposite // Ahead of display compositing by one refresh period.
};
class Scheduler : public IEventThreadCallback, android::impl::MessageQueue {
using Impl = android::impl::MessageQueue;
public:
Scheduler(ICompositor&, ISchedulerCallback&, FeatureFlags, surfaceflinger::Factory&,
Fps activeRefreshRate, TimeStats&);
virtual ~Scheduler();
void startTimers();
// TODO: b/241285191 - Remove this API by promoting pacesetter in onScreen{Acquired,Released}.
void setPacesetterDisplay(PhysicalDisplayId) REQUIRES(kMainThreadContext)
EXCLUDES(mDisplayLock, mVsyncConfigLock);
using RefreshRateSelectorPtr = std::shared_ptr<RefreshRateSelector>;
using ConstVsyncSchedulePtr = std::shared_ptr<const VsyncSchedule>;
using VsyncSchedulePtr = std::shared_ptr<VsyncSchedule>;
// After registration/unregistration, `activeDisplayId` is promoted to pacesetter. Note that the
// active display is never unregistered, since hotplug disconnect never happens for activatable
// displays, i.e. a foldable's internal displays or otherwise the (internal or external) primary
// display.
// TODO: b/255635821 - Remove active display parameters.
void registerDisplay(PhysicalDisplayId, RefreshRateSelectorPtr,
PhysicalDisplayId activeDisplayId) REQUIRES(kMainThreadContext)
EXCLUDES(mDisplayLock);
void unregisterDisplay(PhysicalDisplayId, PhysicalDisplayId activeDisplayId)
REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock);
void run();
void initVsync(frametimeline::TokenManager&, std::chrono::nanoseconds workDuration);
using Impl::setDuration;
using Impl::getScheduledFrameResult;
using Impl::scheduleConfigure;
using Impl::scheduleFrame;
// Schedule an asynchronous or synchronous task on the main thread.
template <typename F, typename T = std::invoke_result_t<F>>
[[nodiscard]] std::future<T> schedule(F&& f) {
auto [task, future] = makeTask(std::move(f));
postMessage(std::move(task));
return std::move(future);
}
template <typename F, typename T = std::invoke_result_t<F>>
[[nodiscard]] std::future<T> scheduleDelayed(F&& f, nsecs_t uptimeDelay) {
auto [task, future] = makeTask(std::move(f));
postMessageDelayed(std::move(task), uptimeDelay);
return std::move(future);
}
void createEventThread(Cycle, frametimeline::TokenManager*,
std::chrono::nanoseconds workDuration,
std::chrono::nanoseconds readyDuration);
sp<IDisplayEventConnection> createDisplayEventConnection(
Cycle, EventRegistrationFlags eventRegistration = {},
const sp<IBinder>& layerHandle = nullptr) EXCLUDES(mChoreographerLock);
enum class Hotplug { Connected, Disconnected };
void dispatchHotplug(PhysicalDisplayId, Hotplug);
void dispatchHotplugError(int32_t errorCode);
// Returns true if the PhysicalDisplayId is the pacesetter.
bool onDisplayModeChanged(PhysicalDisplayId, const FrameRateMode&,
bool clearContentRequirements) EXCLUDES(mPolicyLock);
void onDisplayModeRejected(PhysicalDisplayId, DisplayModeId);
void enableSyntheticVsync(bool = true) REQUIRES(kMainThreadContext);
void omitVsyncDispatching(bool) REQUIRES(kMainThreadContext);
void onHdcpLevelsChanged(Cycle, PhysicalDisplayId, int32_t, int32_t);
// Modifies work duration in the event thread.
void setDuration(Cycle, std::chrono::nanoseconds workDuration,
std::chrono::nanoseconds readyDuration);
VsyncModulator& vsyncModulator() { return *mVsyncModulator; }
// In some cases, we should only modulate for the pacesetter display. In those
// cases, the caller should pass in the relevant display, and the method
// will no-op if it's not the pacesetter. Other cases are not specific to a
// display.
template <typename... Args,
typename Handler = std::optional<VsyncConfig> (VsyncModulator::*)(Args...)>
void modulateVsync(std::optional<PhysicalDisplayId> id, Handler handler, Args... args) {
if (id) {
std::scoped_lock lock(mDisplayLock);
ftl::FakeGuard guard(kMainThreadContext);
if (id != mPacesetterDisplayId) {
return;
}
}
if (const auto config = (*mVsyncModulator.*handler)(args...)) {
setVsyncConfig(*config, getPacesetterVsyncPeriod());
}
}
void updatePhaseConfiguration(PhysicalDisplayId, Fps) EXCLUDES(mVsyncConfigLock);
void reloadPhaseConfiguration(Fps, Duration minSfDuration, Duration maxSfDuration,
Duration appDuration) EXCLUDES(mVsyncConfigLock);
VsyncConfigSet getCurrentVsyncConfigs() const EXCLUDES(mVsyncConfigLock) {
std::scoped_lock lock{mVsyncConfigLock};
return mVsyncConfiguration->getCurrentConfigs();
}
VsyncConfigSet getVsyncConfigsForRefreshRate(Fps refreshRate) const EXCLUDES(mVsyncConfigLock) {
std::scoped_lock lock{mVsyncConfigLock};
return mVsyncConfiguration->getConfigsForRefreshRate(refreshRate);
}
// Sets the render rate for the scheduler to run at.
void setRenderRate(PhysicalDisplayId, Fps, bool applyImmediately);
void enableHardwareVsync(PhysicalDisplayId) REQUIRES(kMainThreadContext);
void disableHardwareVsync(PhysicalDisplayId, bool disallow) REQUIRES(kMainThreadContext);
// Resyncs the scheduler to hardware vsync.
// If allowToEnable is true, then hardware vsync will be turned on.
// Otherwise, if hardware vsync is not already enabled then this method will
// no-op.
// If modePtr is nullopt, use the active display mode.
void resyncToHardwareVsync(PhysicalDisplayId id, bool allowToEnable,
DisplayModePtr modePtr = nullptr) EXCLUDES(mDisplayLock) {
std::scoped_lock lock(mDisplayLock);
ftl::FakeGuard guard(kMainThreadContext);
resyncToHardwareVsyncLocked(id, allowToEnable, modePtr);
}
void forceNextResync() { mLastResyncTime = 0; }
// Passes a vsync sample to VsyncController. Returns true if
// VsyncController detected that the vsync period changed and false
// otherwise.
bool addResyncSample(PhysicalDisplayId, nsecs_t timestamp,
std::optional<nsecs_t> hwcVsyncPeriod);
void addPresentFence(PhysicalDisplayId, std::shared_ptr<FenceTime>)
REQUIRES(kMainThreadContext);
// Layers are registered on creation, and unregistered when the weak reference expires.
void registerLayer(Layer*, FrameRateCompatibility);
void recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
nsecs_t now, LayerHistory::LayerUpdateType) EXCLUDES(mDisplayLock);
void setModeChangePending(bool pending);
void setDefaultFrameRateCompatibility(int32_t id, scheduler::FrameRateCompatibility);
void setLayerProperties(int32_t id, const LayerProps&);
void deregisterLayer(Layer*);
void onLayerDestroyed(Layer*) EXCLUDES(mChoreographerLock);
// Detects content using layer history, and selects a matching refresh rate.
void chooseRefreshRateForContent(const surfaceflinger::frontend::LayerHierarchy*,
bool updateAttachedChoreographer) EXCLUDES(mDisplayLock);
void resetIdleTimer();
// Indicates that touch interaction is taking place.
void onTouchHint();
void setDisplayPowerMode(PhysicalDisplayId, hal::PowerMode) REQUIRES(kMainThreadContext);
// TODO(b/255635821): Track this per display.
void setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode) REQUIRES(kMainThreadContext);
ConstVsyncSchedulePtr getVsyncSchedule(std::optional<PhysicalDisplayId> = std::nullopt) const
EXCLUDES(mDisplayLock);
VsyncSchedulePtr getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt = std::nullopt)
EXCLUDES(mDisplayLock) {
return std::const_pointer_cast<VsyncSchedule>(std::as_const(*this).getVsyncSchedule(idOpt));
}
TimePoint expectedPresentTimeForPacesetter() const EXCLUDES(mDisplayLock) {
std::scoped_lock lock(mDisplayLock);
return pacesetterDisplayLocked()
.transform([](const Display& display) {
return display.targeterPtr->target().expectedPresentTime();
})
.value_or(TimePoint());
}
// Returns true if a given vsync timestamp is considered valid vsync
// for a given uid
bool isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const;
bool isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const;
void dump(utils::Dumper&) const EXCLUDES(mVsyncConfigLock);
void dump(Cycle, std::string&) const;
void dumpVsync(std::string&) const EXCLUDES(mDisplayLock);
// Returns the preferred refresh rate and frame rate for the pacesetter display.
FrameRateMode getPreferredDisplayMode();
// Notifies the scheduler about a refresh rate timeline change.
void onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline);
// Notifies the scheduler once the composition is presented. Returns if recomposite is needed.
bool onCompositionPresented(nsecs_t presentTime);
// Notifies the scheduler when the display size has changed. Called from SF's main thread
void onActiveDisplayAreaChanged(uint32_t displayArea);
// Stores the preferred refresh rate that an app should run at.
// FrameRateOverride.refreshRateHz == 0 means no preference.
void setPreferredRefreshRateForUid(FrameRateOverride);
// Stores the frame rate override that a game should run at set by game interventions.
// FrameRateOverride.refreshRateHz == 0 means no preference.
void setGameModeFrameRateForUid(FrameRateOverride) EXCLUDES(mDisplayLock);
// Stores the frame rate override that a game should run rat set by default game frame rate.
// FrameRateOverride.refreshRateHz == 0 means no preference, game default game frame rate is not
// enabled.
//
// "ro.surface_flinger.game_default_frame_rate_override" sets the frame rate value,
// "persist.graphics.game_default_frame_rate.enabled" controls whether this feature is enabled.
void setGameDefaultFrameRateForUid(FrameRateOverride) EXCLUDES(mDisplayLock);
void updateSmallAreaDetection(std::vector<std::pair<int32_t, float>>& uidThresholdMappings);
void setSmallAreaDetectionThreshold(int32_t appId, float threshold);
// Returns true if the dirty area is less than threshold.
bool isSmallDirtyArea(int32_t appId, uint32_t dirtyArea);
// Retrieves the overridden refresh rate for a given uid.
std::optional<Fps> getFrameRateOverride(uid_t) const EXCLUDES(mDisplayLock);
Period getPacesetterVsyncPeriod() const EXCLUDES(mDisplayLock) {
return pacesetterSelectorPtr()->getActiveMode().fps.getPeriod();
}
Fps getPacesetterRefreshRate() const EXCLUDES(mDisplayLock) {
return pacesetterSelectorPtr()->getActiveMode().fps;
}
Fps getNextFrameInterval(PhysicalDisplayId, TimePoint currentExpectedPresentTime) const
EXCLUDES(mDisplayLock);
// Returns the framerate of the layer with the given sequence ID
float getLayerFramerate(nsecs_t now, int32_t id) const {
return mLayerHistory.getLayerFramerate(now, id);
}
void updateFrameRateOverrides(GlobalSignals, Fps displayRefreshRate) EXCLUDES(mPolicyLock);
// Returns true if the small dirty detection is enabled for the appId.
bool supportSmallDirtyDetection(int32_t appId) {
return mFeatures.test(Feature::kSmallDirtyContentDetection) &&
mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId).has_value();
}
// Injects a delay that is a fraction of the predicted frame duration for the next frame.
void injectPacesetterDelay(float frameDurationFraction) REQUIRES(kMainThreadContext) {
mPacesetterFrameDurationFractionToSkip = frameDurationFraction;
}
void setDebugPresentDelay(TimePoint delay) { mDebugPresentDelay = delay; }
private:
friend class TestableScheduler;
enum class ContentDetectionState { Off, On };
enum class TimerState { Reset, Expired };
enum class TouchState { Inactive, Active };
// impl::MessageQueue overrides:
void onFrameSignal(ICompositor&, VsyncId, TimePoint expectedVsyncTime) override
REQUIRES(kMainThreadContext, mDisplayLock) EXCLUDES(mVsyncConfigLock);
// Used to skip event dispatch before EventThread creation during boot.
// TODO: b/241285191 - Reorder Scheduler initialization to avoid this.
bool hasEventThreads() const {
return CC_LIKELY(
mRenderEventThread &&
(FlagManager::getInstance().deprecate_vsync_sf() || mLastCompositeEventThread));
}
EventThread& eventThreadFor(Cycle cycle) const {
return *(cycle == Cycle::Render ? mRenderEventThread : mLastCompositeEventThread);
}
// Update feature state machine to given state when corresponding timer resets or expires.
void kernelIdleTimerCallback(TimerState) EXCLUDES(mDisplayLock);
void idleTimerCallback(TimerState);
void touchTimerCallback(TimerState);
void displayPowerTimerCallback(TimerState);
// VsyncSchedule delegate.
void onHardwareVsyncRequest(PhysicalDisplayId, bool enable);
void resyncToHardwareVsyncLocked(PhysicalDisplayId, bool allowToEnable,
DisplayModePtr modePtr = nullptr)
REQUIRES(kMainThreadContext, mDisplayLock);
void resyncAllToHardwareVsync(bool allowToEnable) EXCLUDES(mDisplayLock);
void setVsyncConfig(const VsyncConfig&, Period vsyncPeriod);
// TODO: b/241286431 - Remove this option, which assumes that the pacesetter does not change
// when a (secondary) display is registered or unregistered. In the short term, this avoids
// a deadlock where the main thread joins with the timer thread as the timer thread waits to
// lock a mutex held by the main thread.
struct PromotionParams {
// Whether to stop and start the idle timer.
bool toggleIdleTimer;
};
void promotePacesetterDisplay(PhysicalDisplayId pacesetterId, PromotionParams)
REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock);
// Changes to the displays (e.g. registering and unregistering) must be made
// while mDisplayLock is locked, and the new pacesetter then must be promoted while
// mDisplayLock is still locked. However, a new pacesetter means that
// MessageQueue and EventThread need to use the new pacesetter's
// VsyncSchedule, and this must happen while mDisplayLock is *not* locked,
// or else we may deadlock with EventThread.
std::shared_ptr<VsyncSchedule> promotePacesetterDisplayLocked(PhysicalDisplayId pacesetterId,
PromotionParams)
REQUIRES(kMainThreadContext, mDisplayLock);
void applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule>) EXCLUDES(mDisplayLock);
// If toggleIdleTimer is true, the calling thread blocks until the pacesetter's idle timer
// thread exits, in which case mDisplayLock must not be locked by the caller to avoid deadlock,
// since the timer thread locks it before exit.
void demotePacesetterDisplay(PromotionParams) REQUIRES(kMainThreadContext)
EXCLUDES(mDisplayLock, mPolicyLock);
void registerDisplayInternal(PhysicalDisplayId, RefreshRateSelectorPtr, VsyncSchedulePtr,
PhysicalDisplayId activeDisplayId) REQUIRES(kMainThreadContext)
EXCLUDES(mDisplayLock);
struct Policy;
// Sets the S state of the policy to the T value under mPolicyLock, and chooses a display mode
// that fulfills the new policy if the state changed. Returns the signals that were considered.
template <typename S, typename T>
GlobalSignals applyPolicy(S Policy::*, T&&) EXCLUDES(mPolicyLock);
struct DisplayModeChoice {
DisplayModeChoice(FrameRateMode mode, GlobalSignals consideredSignals)
: mode(std::move(mode)), consideredSignals(consideredSignals) {}
static DisplayModeChoice from(RefreshRateSelector::RankedFrameRates rankedFrameRates) {
return {rankedFrameRates.ranking.front().frameRateMode,
rankedFrameRates.consideredSignals};
}
FrameRateMode mode;
GlobalSignals consideredSignals;
bool operator==(const DisplayModeChoice& other) const {
return mode == other.mode && consideredSignals == other.consideredSignals;
}
// For tests.
friend std::ostream& operator<<(std::ostream& stream, const DisplayModeChoice& choice) {
return stream << '{' << to_string(*choice.mode.modePtr) << " considering "
<< choice.consideredSignals.toString().c_str() << '}';
}
};
using DisplayModeChoiceMap = ui::PhysicalDisplayMap<PhysicalDisplayId, DisplayModeChoice>;
// See mDisplayLock for thread safety.
DisplayModeChoiceMap chooseDisplayModes() const
REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext);
GlobalSignals makeGlobalSignals() const REQUIRES(mPolicyLock);
bool updateFrameRateOverridesLocked(GlobalSignals, Fps displayRefreshRate)
REQUIRES(mPolicyLock);
void onFrameRateOverridesChanged();
void updateAttachedChoreographers(const surfaceflinger::frontend::LayerHierarchy&,
Fps displayRefreshRate);
int updateAttachedChoreographersInternal(const surfaceflinger::frontend::LayerHierarchy&,
Fps displayRefreshRate, int parentDivisor);
void updateAttachedChoreographersFrameRate(const surfaceflinger::frontend::RequestedLayerState&,
Fps fps) EXCLUDES(mChoreographerLock);
void emitModeChangeIfNeeded() REQUIRES(mPolicyLock) EXCLUDES(mDisplayLock);
// IEventThreadCallback overrides
bool throttleVsync(TimePoint, uid_t) override;
// Get frame interval
Period getVsyncPeriod(uid_t) override EXCLUDES(mDisplayLock);
void resync() override EXCLUDES(mDisplayLock);
void onExpectedPresentTimePosted(TimePoint expectedPresentTime) override EXCLUDES(mDisplayLock);
std::unique_ptr<EventThread> mRenderEventThread;
std::unique_ptr<EventThread> mLastCompositeEventThread;
std::atomic<nsecs_t> mLastResyncTime = 0;
const FeatureFlags mFeatures;
mutable std::mutex mVsyncConfigLock;
// Stores phase offsets configured per refresh rate.
std::unique_ptr<VsyncConfiguration> mVsyncConfiguration GUARDED_BY(mVsyncConfigLock);
// Shifts the VSYNC phase during certain transactions and refresh rate changes.
const sp<VsyncModulator> mVsyncModulator;
const std::unique_ptr<RefreshRateStats> mRefreshRateStats;
// Used to choose refresh rate if content detection is enabled.
LayerHistory mLayerHistory;
// Timer used to monitor touch events.
ftl::Optional<OneShotTimer> mTouchTimer;
// Timer used to monitor display power mode.
ftl::Optional<OneShotTimer> mDisplayPowerTimer;
// Injected delay prior to compositing, for simulating jank.
float mPacesetterFrameDurationFractionToSkip GUARDED_BY(kMainThreadContext) = 0.f;
ISchedulerCallback& mSchedulerCallback;
// mDisplayLock may be locked while under mPolicyLock.
mutable std::mutex mPolicyLock;
// Only required for reads outside kMainThreadContext. kMainThreadContext is the only writer, so
// must lock for writes but not reads. See also mPolicyLock for locking order.
mutable std::mutex mDisplayLock;
using FrameTargeterPtr = std::unique_ptr<FrameTargeter>;
struct Display {
Display(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr,
VsyncSchedulePtr schedulePtr, FeatureFlags features)
: displayId(displayId),
selectorPtr(std::move(selectorPtr)),
schedulePtr(std::move(schedulePtr)),
targeterPtr(std::make_unique<FrameTargeter>(displayId, features)) {}
const PhysicalDisplayId displayId;
// Effectively const except in move constructor.
RefreshRateSelectorPtr selectorPtr;
VsyncSchedulePtr schedulePtr;
FrameTargeterPtr targeterPtr;
hal::PowerMode powerMode = hal::PowerMode::OFF;
};
using DisplayRef = std::reference_wrapper<Display>;
using ConstDisplayRef = std::reference_wrapper<const Display>;
ui::PhysicalDisplayMap<PhysicalDisplayId, Display> mDisplays GUARDED_BY(mDisplayLock)
GUARDED_BY(kMainThreadContext);
ftl::Optional<PhysicalDisplayId> mPacesetterDisplayId GUARDED_BY(mDisplayLock)
GUARDED_BY(kMainThreadContext);
ftl::Optional<DisplayRef> pacesetterDisplayLocked() REQUIRES(mDisplayLock) {
return static_cast<const Scheduler*>(this)->pacesetterDisplayLocked().transform(
[](const Display& display) { return std::ref(const_cast<Display&>(display)); });
}
ftl::Optional<ConstDisplayRef> pacesetterDisplayLocked() const REQUIRES(mDisplayLock) {
ftl::FakeGuard guard(kMainThreadContext);
return mPacesetterDisplayId.and_then([this](PhysicalDisplayId pacesetterId)
REQUIRES(mDisplayLock, kMainThreadContext) {
return mDisplays.get(pacesetterId);
});
}
// The pacesetter must exist as a precondition.
ftl::NonNull<const Display*> pacesetterPtrLocked() const REQUIRES(mDisplayLock) {
return ftl::as_non_null(&pacesetterDisplayLocked()->get());
}
RefreshRateSelectorPtr pacesetterSelectorPtr() const EXCLUDES(mDisplayLock) {
std::scoped_lock lock(mDisplayLock);
return pacesetterSelectorPtrLocked();
}
RefreshRateSelectorPtr pacesetterSelectorPtrLocked() const REQUIRES(mDisplayLock) {
return pacesetterDisplayLocked()
.transform([](const Display& display) { return display.selectorPtr; })
.or_else([] { return std::optional<RefreshRateSelectorPtr>(nullptr); })
.value();
}
ConstVsyncSchedulePtr getVsyncScheduleLocked(
std::optional<PhysicalDisplayId> = std::nullopt) const REQUIRES(mDisplayLock);
VsyncSchedulePtr getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt = std::nullopt)
REQUIRES(mDisplayLock) {
return std::const_pointer_cast<VsyncSchedule>(
static_cast<const Scheduler*>(this)->getVsyncScheduleLocked(idOpt));
}
struct Policy {
// Policy for choosing the display mode.
LayerHistory::Summary contentRequirements;
TimerState idleTimer = TimerState::Reset;
TouchState touch = TouchState::Inactive;
TimerState displayPowerTimer = TimerState::Expired;
hal::PowerMode displayPowerMode = hal::PowerMode::ON;
// Chosen display mode.
ftl::Optional<FrameRateMode> modeOpt;
// Display mode of latest emitted event.
std::optional<FrameRateMode> emittedModeOpt;
} mPolicy GUARDED_BY(mPolicyLock);
std::mutex mChoreographerLock;
struct AttachedChoreographers {
Fps frameRate;
std::unordered_set<wp<EventThreadConnection>, WpHash> connections;
};
// Map keyed by layer ID (sequence) to choreographer connections.
std::unordered_map<int32_t, AttachedChoreographers> mAttachedChoreographers
GUARDED_BY(mChoreographerLock);
std::mutex mVsyncTimelineLock;
std::optional<hal::VsyncPeriodChangeTimeline> mLastVsyncPeriodChangeTimeline
GUARDED_BY(mVsyncTimelineLock);
static constexpr std::chrono::nanoseconds MAX_VSYNC_APPLIED_TIME = 200ms;
FrameRateOverrideMappings mFrameRateOverrideMappings;
SmallAreaDetectionAllowMappings mSmallAreaDetectionAllowMappings;
std::atomic<std::optional<TimePoint>> mDebugPresentDelay;
};
} // namespace scheduler
} // namespace android
|