blob: 0615b31c1072e4278c5ff7595ef72859c5f33c37 [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
Dominik Laskowski98041832019-08-01 18:35:59 -070019#include <atomic>
Dominik Laskowski62eff352021-12-06 09:59:41 -080020#include <cstdint>
Kevin DuBois413287f2019-02-25 08:46:47 -080021#include <functional>
Dominik Laskowski756b7892021-08-04 12:53:59 -070022#include <future>
Ana Krulec98b5b242018-08-10 15:03:23 -070023#include <memory>
Dominik Laskowski98041832019-08-01 18:35:59 -070024#include <mutex>
Dominik Laskowski98041832019-08-01 18:35:59 -070025#include <unordered_map>
ramindani69b58e82022-09-26 16:48:36 -070026#include <utility>
Ana Krulec98b5b242018-08-10 15:03:23 -070027
Ady Abrahamdec1a412020-01-24 10:23:50 -080028// TODO(b/129481165): remove the #pragma below and fix conversion issues
29#pragma clang diagnostic push
30#pragma clang diagnostic ignored "-Wconversion"
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010031#pragma clang diagnostic ignored "-Wextra"
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -080032#include <ui/GraphicTypes.h>
Marin Shalamanovbed7fd32020-12-21 20:02:20 +010033#pragma clang diagnostic pop // ignored "-Wconversion -Wextra"
Ana Krulec98b5b242018-08-10 15:03:23 -070034
Dominik Laskowski596a2562022-10-28 11:26:12 -040035#include <ftl/fake_guard.h>
36#include <ftl/optional.h>
Dominik Laskowski068173d2021-08-11 17:22:59 -070037#include <scheduler/Features.h>
Dominik Laskowskib418dd72023-06-13 17:31:04 -040038#include <scheduler/FrameTargeter.h>
Dominik Laskowski5d164f22022-07-07 07:56:07 -070039#include <scheduler/Time.h>
Dominik Laskowski1c99a002023-01-20 17:10:36 -050040#include <scheduler/VsyncConfig.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040041#include <ui/DisplayId.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050042#include <ui/DisplayMap.h>
Dominik Laskowski068173d2021-08-11 17:22:59 -070043
Dominik Laskowski530d6bd2022-10-10 16:55:54 -040044#include "Display/DisplayModeRequest.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070045#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080046#include "FrameRateOverrideMappings.h"
Leon Scroggins IIIc275df42023-02-07 16:40:21 -050047#include "ISchedulerCallback.h"
Ana Krulec3084c052018-11-21 20:27:17 +010048#include "LayerHistory.h"
Dominik Laskowski756b7892021-08-04 12:53:59 -070049#include "MessageQueue.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070050#include "OneShotTimer.h"
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040051#include "RefreshRateSelector.h"
Tony Huang9ac5e6e2023-08-24 09:01:44 +000052#include "SmallAreaDetectionAllowMappings.h"
Dominik Laskowski03cfce82022-11-02 12:13:29 -040053#include "Utils/Dumper.h"
Dominik Laskowski1c99a002023-01-20 17:10:36 -050054#include "VsyncModulator.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070055
Ady Abraham822ecbd2023-07-07 16:16:09 -070056#include <FrontEnd/LayerHierarchy.h>
57
Dominik Laskowski62eff352021-12-06 09:59:41 -080058namespace android::scheduler {
59
60// Opaque handle to scheduler connection.
61struct ConnectionHandle {
62 using Id = std::uintptr_t;
63 static constexpr Id INVALID_ID = static_cast<Id>(-1);
64
65 Id id = INVALID_ID;
66
67 explicit operator bool() const { return id != INVALID_ID; }
68};
69
70inline bool operator==(ConnectionHandle lhs, ConnectionHandle rhs) {
71 return lhs.id == rhs.id;
72}
73
74} // namespace android::scheduler
75
76namespace std {
77
78template <>
79struct hash<android::scheduler::ConnectionHandle> {
80 size_t operator()(android::scheduler::ConnectionHandle handle) const {
81 return hash<android::scheduler::ConnectionHandle::Id>()(handle.id);
82 }
83};
84
85} // namespace std
86
Ana Krulec98b5b242018-08-10 15:03:23 -070087namespace android {
88
Dominik Laskowski98041832019-08-01 18:35:59 -070089class FenceTime;
Ana Krulece588e312018-09-18 12:32:24 -070090
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070091namespace frametimeline {
92class TokenManager;
93} // namespace frametimeline
94
Dominik Laskowski068173d2021-08-11 17:22:59 -070095namespace scheduler {
96
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040097using GlobalSignals = RefreshRateSelector::GlobalSignals;
ramindani69b58e82022-09-26 16:48:36 -070098
Dominik Laskowskic404cb42023-03-03 19:57:53 -050099class VsyncSchedule;
100
Ady Abrahamf2851612023-09-25 17:19:00 -0700101class Scheduler : public IEventThreadCallback, android::impl::MessageQueue {
Patrick Williams83f36b22022-09-14 17:57:35 +0000102 using Impl = android::impl::MessageQueue;
Dominik Laskowski756b7892021-08-04 12:53:59 -0700103
Ana Krulec98b5b242018-08-10 15:03:23 -0700104public:
ramindanid4354a92023-10-02 15:11:09 -0700105 Scheduler(ICompositor&, ISchedulerCallback&, FeatureFlags, sp<VsyncModulator>,
106 IVsyncTrackerCallback&);
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800107 virtual ~Scheduler();
108
109 void startTimers();
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800110
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500111 // TODO(b/241285191): Remove this API by promoting pacesetter in onScreen{Acquired,Released}.
112 void setPacesetterDisplay(std::optional<PhysicalDisplayId>) REQUIRES(kMainThreadContext)
Dominik Laskowski596a2562022-10-28 11:26:12 -0400113 EXCLUDES(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400114
Dominik Laskowski596a2562022-10-28 11:26:12 -0400115 using RefreshRateSelectorPtr = std::shared_ptr<RefreshRateSelector>;
116
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500117 using ConstVsyncSchedulePtr = std::shared_ptr<const VsyncSchedule>;
118 using VsyncSchedulePtr = std::shared_ptr<VsyncSchedule>;
119
Dominik Laskowski596a2562022-10-28 11:26:12 -0400120 void registerDisplay(PhysicalDisplayId, RefreshRateSelectorPtr) REQUIRES(kMainThreadContext)
121 EXCLUDES(mDisplayLock);
122 void unregisterDisplay(PhysicalDisplayId) REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock);
Dominik Laskowski01602522022-10-07 19:02:28 -0400123
Dominik Laskowski83bd7712022-01-07 14:30:53 -0800124 void run();
Ana Krulec98b5b242018-08-10 15:03:23 -0700125
Dominik Laskowski756b7892021-08-04 12:53:59 -0700126 using Impl::initVsync;
Dominik Laskowski756b7892021-08-04 12:53:59 -0700127
128 using Impl::getScheduledFrameTime;
129 using Impl::setDuration;
130
Dominik Laskowskif11728a2022-07-28 13:07:42 -0700131 using Impl::scheduleConfigure;
Dominik Laskowski46f3e3b2021-08-10 11:44:24 -0700132 using Impl::scheduleFrame;
Dominik Laskowski756b7892021-08-04 12:53:59 -0700133
134 // Schedule an asynchronous or synchronous task on the main thread.
135 template <typename F, typename T = std::invoke_result_t<F>>
136 [[nodiscard]] std::future<T> schedule(F&& f) {
137 auto [task, future] = makeTask(std::move(f));
138 postMessage(std::move(task));
139 return std::move(future);
140 }
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700141
Chavi Weingarten076acac2023-01-19 17:20:43 +0000142 template <typename F, typename T = std::invoke_result_t<F>>
143 [[nodiscard]] std::future<T> scheduleDelayed(F&& f, nsecs_t uptimeDelay) {
144 auto [task, future] = makeTask(std::move(f));
145 postMessageDelayed(std::move(task), uptimeDelay);
146 return std::move(future);
147 }
148
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500149 enum class Cycle {
150 Render, // Surface rendering.
151 LastComposite // Ahead of display compositing by one refresh period.
152 };
153
154 ConnectionHandle createEventThread(Cycle, frametimeline::TokenManager*,
155 std::chrono::nanoseconds workDuration,
156 std::chrono::nanoseconds readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700157
Ady Abraham62f216c2020-10-13 19:07:23 -0700158 sp<IDisplayEventConnection> createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800159 ConnectionHandle, EventRegistrationFlags eventRegistration = {},
Ady Abraham822ecbd2023-07-07 16:16:09 -0700160 const sp<IBinder>& layerHandle = nullptr) EXCLUDES(mChoreographerLock);
Ana Krulece588e312018-09-18 12:32:24 -0700161
Dominik Laskowski98041832019-08-01 18:35:59 -0700162 sp<EventThreadConnection> getEventConnection(ConnectionHandle);
Kevin DuBois413287f2019-02-25 08:46:47 -0800163
Dominik Laskowski98041832019-08-01 18:35:59 -0700164 void onHotplugReceived(ConnectionHandle, PhysicalDisplayId, bool connected);
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700165 void onHotplugConnectionError(ConnectionHandle, int32_t errorCode);
166
Ady Abrahamace3d052022-11-17 16:25:05 -0800167 void onPrimaryDisplayModeChanged(ConnectionHandle, const FrameRateMode&) EXCLUDES(mPolicyLock);
168 void onNonPrimaryDisplayModeChanged(ConnectionHandle, const FrameRateMode&);
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500169
170 void enableSyntheticVsync(bool = true) REQUIRES(kMainThreadContext);
Ana Krulece588e312018-09-18 12:32:24 -0700171
Ady Abraham62a0be22020-12-08 16:54:10 -0800172 void onFrameRateOverridesChanged(ConnectionHandle, PhysicalDisplayId)
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800173 EXCLUDES(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700174
Ady Abraham9c53ee72020-07-22 21:16:18 -0700175 // Modifies work duration in the event thread.
176 void setDuration(ConnectionHandle, std::chrono::nanoseconds workDuration,
177 std::chrono::nanoseconds readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700178
Dominik Laskowski14956dc2023-02-22 13:43:57 -0500179 VsyncModulator& vsyncModulator() { return *mVsyncModulator; }
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500180
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500181 // In some cases, we should only modulate for the pacesetter display. In those
Leon Scroggins III67388622023-02-06 20:36:20 -0500182 // cases, the caller should pass in the relevant display, and the method
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500183 // will no-op if it's not the pacesetter. Other cases are not specific to a
Leon Scroggins III67388622023-02-06 20:36:20 -0500184 // display.
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500185 template <typename... Args,
186 typename Handler = std::optional<VsyncConfig> (VsyncModulator::*)(Args...)>
Leon Scroggins III67388622023-02-06 20:36:20 -0500187 void modulateVsync(std::optional<PhysicalDisplayId> id, Handler handler, Args... args) {
188 if (id) {
189 std::scoped_lock lock(mDisplayLock);
190 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500191 if (id != mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500192 return;
193 }
194 }
195
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500196 if (const auto config = (*mVsyncModulator.*handler)(args...)) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500197 setVsyncConfig(*config, getPacesetterVsyncPeriod());
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500198 }
199 }
200
201 void setVsyncConfigSet(const VsyncConfigSet&, Period vsyncPeriod);
202
Ady Abrahamace3d052022-11-17 16:25:05 -0800203 // Sets the render rate for the scheduler to run at.
Leon Scroggins III67388622023-02-06 20:36:20 -0500204 void setRenderRate(PhysicalDisplayId, Fps);
Ady Abrahamace3d052022-11-17 16:25:05 -0800205
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400206 void enableHardwareVsync(PhysicalDisplayId) REQUIRES(kMainThreadContext);
207 void disableHardwareVsync(PhysicalDisplayId, bool disallow) REQUIRES(kMainThreadContext);
Dominik Laskowski98041832019-08-01 18:35:59 -0700208
Alec Mourif8e689c2019-05-20 18:32:22 -0700209 // Resyncs the scheduler to hardware vsync.
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500210 // If allowToEnable is true, then hardware vsync will be turned on.
Alec Mourif8e689c2019-05-20 18:32:22 -0700211 // Otherwise, if hardware vsync is not already enabled then this method will
212 // no-op.
Ady Abrahamc585dba2023-11-15 18:41:35 -0800213 // If modePtr is nullopt, use the active display mode.
Leon Scroggins III67388622023-02-06 20:36:20 -0500214 void resyncToHardwareVsync(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800215 DisplayModePtr modePtr = nullptr) EXCLUDES(mDisplayLock) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500216 std::scoped_lock lock(mDisplayLock);
217 ftl::FakeGuard guard(kMainThreadContext);
Ady Abrahamc585dba2023-11-15 18:41:35 -0800218 resyncToHardwareVsyncLocked(id, allowToEnable, modePtr);
Leon Scroggins III67388622023-02-06 20:36:20 -0500219 }
Ady Abrahame9befd72022-02-24 17:24:44 -0800220 void forceNextResync() { mLastResyncTime = 0; }
Dominik Laskowski98041832019-08-01 18:35:59 -0700221
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500222 // Passes a vsync sample to VsyncController. Returns true if
223 // VsyncController detected that the vsync period changed and false
224 // otherwise.
Leon Scroggins III67388622023-02-06 20:36:20 -0500225 bool addResyncSample(PhysicalDisplayId, nsecs_t timestamp,
226 std::optional<nsecs_t> hwcVsyncPeriod);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500227 void addPresentFence(PhysicalDisplayId, std::shared_ptr<FenceTime>)
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400228 REQUIRES(kMainThreadContext);
Ady Abraham8f1ee7f2019-04-05 10:32:50 -0700229
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700230 // Layers are registered on creation, and unregistered when the weak reference expires.
231 void registerLayer(Layer*);
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000232 void recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700233 nsecs_t now, LayerHistory::LayerUpdateType) EXCLUDES(mDisplayLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100234 void setModeChangePending(bool pending);
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700235 void setDefaultFrameRateCompatibility(int32_t id, scheduler::FrameRateCompatibility);
Vishnu Nair41376b62023-11-08 05:08:58 -0800236 void setLayerProperties(int32_t id, const LayerProps&);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700237 void deregisterLayer(Layer*);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700238 void onLayerDestroyed(Layer*) EXCLUDES(mChoreographerLock);
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700239
Dominik Laskowski49cea512019-11-12 14:13:23 -0800240 // Detects content using layer history, and selects a matching refresh rate.
Ady Abraham822ecbd2023-07-07 16:16:09 -0700241 void chooseRefreshRateForContent(const surfaceflinger::frontend::LayerHierarchy*,
242 bool updateAttachedChoreographer) EXCLUDES(mDisplayLock);
Ady Abraham97d04232019-03-05 19:48:12 -0800243
Ady Abraham8532d012019-05-08 14:50:56 -0700244 void resetIdleTimer();
245
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700246 // Indicates that touch interaction is taking place.
247 void onTouchHint();
Ady Abraham8532d012019-05-08 14:50:56 -0700248
Leon Scroggins III67388622023-02-06 20:36:20 -0500249 void setDisplayPowerMode(PhysicalDisplayId, hal::PowerMode powerMode)
250 REQUIRES(kMainThreadContext);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700251
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500252 ConstVsyncSchedulePtr getVsyncSchedule(std::optional<PhysicalDisplayId> = std::nullopt) const
253 EXCLUDES(mDisplayLock);
254
255 VsyncSchedulePtr getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt = std::nullopt)
256 EXCLUDES(mDisplayLock) {
257 return std::const_pointer_cast<VsyncSchedule>(std::as_const(*this).getVsyncSchedule(idOpt));
Leon Scroggins III67388622023-02-06 20:36:20 -0500258 }
Ady Abraham55fa7272020-09-30 19:19:27 -0700259
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500260 TimePoint expectedPresentTimeForPacesetter() const EXCLUDES(mDisplayLock) {
261 std::scoped_lock lock(mDisplayLock);
262 return pacesetterDisplayLocked()
263 .transform([](const Display& display) {
264 return display.targeterPtr->target().expectedPresentTime();
265 })
266 .value_or(TimePoint());
267 }
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400268
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500269 // Returns true if a given vsync timestamp is considered valid vsync
270 // for a given uid
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400271 bool isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const;
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500272
Leon Scroggins III67388622023-02-06 20:36:20 -0500273 bool isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const;
Huihong Luo1768cb02022-10-11 11:10:34 -0700274
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400275 void dump(utils::Dumper&) const;
Dominik Laskowski98041832019-08-01 18:35:59 -0700276 void dump(ConnectionHandle, std::string&) const;
Leon Scroggins III67388622023-02-06 20:36:20 -0500277 void dumpVsync(std::string&) const EXCLUDES(mDisplayLock);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700278
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500279 // Returns the preferred refresh rate and frame rate for the pacesetter display.
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500280 FrameRateMode getPreferredDisplayMode();
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700281
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800282 // Notifies the scheduler about a refresh rate timeline change.
Peiyong Line9d809e2020-04-14 13:10:48 -0700283 void onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800284
Leon Scroggins III5b581492023-10-31 14:29:41 -0400285 // Notifies the scheduler once the composition is presented. Returns if recomposite is needed.
286 bool onCompositionPresented(nsecs_t presentTime);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800287
Ady Abraham8a82ba62020-01-17 12:43:17 -0800288 // Notifies the scheduler when the display size has changed. Called from SF's main thread
Ady Abraham7825c682021-05-17 15:12:14 -0700289 void onActiveDisplayAreaChanged(uint32_t displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800290
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 // Stores the preferred refresh rate that an app should run at.
292 // FrameRateOverride.refreshRateHz == 0 means no preference.
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800293 void setPreferredRefreshRateForUid(FrameRateOverride);
294
295 void setGameModeRefreshRateForUid(FrameRateOverride);
296
Tony Huangf3621102023-09-04 17:14:22 +0800297 void updateSmallAreaDetection(std::vector<std::pair<int32_t, float>>& uidThresholdMappings);
Tony Huang9ac5e6e2023-08-24 09:01:44 +0000298
Tony Huangf3621102023-09-04 17:14:22 +0800299 void setSmallAreaDetectionThreshold(int32_t appId, float threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +0000300
301 // Returns true if the dirty area is less than threshold.
Tony Huangf3621102023-09-04 17:14:22 +0800302 bool isSmallDirtyArea(int32_t appId, uint32_t dirtyArea);
Tony Huang9ac5e6e2023-08-24 09:01:44 +0000303
Alec Mouri7d436ec2021-01-27 20:40:50 -0800304 // Retrieves the overridden refresh rate for a given uid.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400305 std::optional<Fps> getFrameRateOverride(uid_t) const EXCLUDES(mDisplayLock);
Ady Abraham3efa3942021-06-24 19:01:25 -0700306
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500307 Period getPacesetterVsyncPeriod() const EXCLUDES(mDisplayLock) {
308 return pacesetterSelectorPtr()->getActiveMode().fps.getPeriod();
Ady Abraham3efa3942021-06-24 19:01:25 -0700309 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800310
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500311 Fps getPacesetterRefreshRate() const EXCLUDES(mDisplayLock) {
312 return pacesetterSelectorPtr()->getActiveMode().fps;
Huihong Luo1768cb02022-10-11 11:10:34 -0700313 }
314
Nathaniel Nifong1303d912021-10-06 09:41:24 -0400315 // Returns the framerate of the layer with the given sequence ID
316 float getLayerFramerate(nsecs_t now, int32_t id) const {
317 return mLayerHistory.getLayerFramerate(now, id);
318 }
319
Ady Abraham33a386b2023-07-18 15:37:11 -0700320 bool updateFrameRateOverrides(GlobalSignals, Fps displayRefreshRate) EXCLUDES(mPolicyLock);
321
Arthur Hungc70bee22023-06-02 01:35:52 +0000322 // Returns true if the small dirty detection is enabled.
323 bool supportSmallDirtyDetection() const {
324 return mFeatures.test(Feature::kSmallDirtyContentDetection);
325 }
326
Alec Mouri1c7938e2023-09-22 04:17:23 +0000327 // Injects a delay that is a fraction of the predicted frame duration for the next frame.
328 void injectPacesetterDelay(float frameDurationFraction) REQUIRES(kMainThreadContext) {
329 mPacesetterFrameDurationFractionToSkip = frameDurationFraction;
330 }
331
Ana Krulec98b5b242018-08-10 15:03:23 -0700332private:
Ana Krulecafb45842019-02-13 13:33:03 -0800333 friend class TestableScheduler;
334
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700335 enum class ContentDetectionState { Off, On };
336 enum class TimerState { Reset, Expired };
337 enum class TouchState { Inactive, Active };
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800338
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700339 // impl::MessageQueue overrides:
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500340 void onFrameSignal(ICompositor&, VsyncId, TimePoint expectedVsyncTime) override
341 REQUIRES(kMainThreadContext, mDisplayLock);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700342
Dominik Laskowski6505f792019-09-18 11:10:05 -0700343 // Create a connection on the given EventThread.
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700344 ConnectionHandle createConnection(std::unique_ptr<EventThread>);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800345
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700346 // Update feature state machine to given state when corresponding timer resets or expires.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400347 void kernelIdleTimerCallback(TimerState) EXCLUDES(mDisplayLock);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700348 void idleTimerCallback(TimerState);
349 void touchTimerCallback(TimerState);
350 void displayPowerTimerCallback(TimerState);
351
Dominik Laskowski66295432023-03-14 12:25:36 -0400352 // VsyncSchedule delegate.
353 void onHardwareVsyncRequest(PhysicalDisplayId, bool enable);
354
Leon Scroggins III67388622023-02-06 20:36:20 -0500355 void resyncToHardwareVsyncLocked(PhysicalDisplayId, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800356 DisplayModePtr modePtr = nullptr)
Leon Scroggins III67388622023-02-06 20:36:20 -0500357 REQUIRES(kMainThreadContext, mDisplayLock);
358 void resyncAllToHardwareVsync(bool allowToEnable) EXCLUDES(mDisplayLock);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500359 void setVsyncConfig(const VsyncConfig&, Period vsyncPeriod);
Dominik Laskowski98041832019-08-01 18:35:59 -0700360
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500361 // Chooses a pacesetter among the registered displays, unless `pacesetterIdOpt` is specified.
362 // The new `mPacesetterDisplayId` is never `std::nullopt`.
363 void promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt = std::nullopt)
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400364 REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock);
365
366 // Changes to the displays (e.g. registering and unregistering) must be made
367 // while mDisplayLock is locked, and the new pacesetter then must be promoted while
368 // mDisplayLock is still locked. However, a new pacesetter means that
369 // MessageQueue and EventThread need to use the new pacesetter's
370 // VsyncSchedule, and this must happen while mDisplayLock is *not* locked,
371 // or else we may deadlock with EventThread.
372 std::shared_ptr<VsyncSchedule> promotePacesetterDisplayLocked(
373 std::optional<PhysicalDisplayId> pacesetterIdOpt = std::nullopt)
Dominik Laskowski596a2562022-10-28 11:26:12 -0400374 REQUIRES(kMainThreadContext, mDisplayLock);
Leon Scroggins39d25342023-04-19 17:11:01 +0000375 void applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule>) EXCLUDES(mDisplayLock);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400376
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500377 // Blocks until the pacesetter's idle timer thread exits. `mDisplayLock` must not be locked by
378 // the caller on the main thread to avoid deadlock, since the timer thread locks it before exit.
379 void demotePacesetterDisplay() REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock, mPolicyLock);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400380
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500381 void registerDisplayInternal(PhysicalDisplayId, RefreshRateSelectorPtr, VsyncSchedulePtr)
382 REQUIRES(kMainThreadContext) EXCLUDES(mDisplayLock);
Leon Scroggins III67388622023-02-06 20:36:20 -0500383
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800384 struct Policy;
385
386 // Sets the S state of the policy to the T value under mPolicyLock, and chooses a display mode
387 // that fulfills the new policy if the state changed. Returns the signals that were considered.
388 template <typename S, typename T>
389 GlobalSignals applyPolicy(S Policy::*, T&&) EXCLUDES(mPolicyLock);
390
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400391 struct DisplayModeChoice {
Ady Abrahamace3d052022-11-17 16:25:05 -0800392 DisplayModeChoice(FrameRateMode mode, GlobalSignals consideredSignals)
393 : mode(std::move(mode)), consideredSignals(consideredSignals) {}
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400394
Ady Abrahamace3d052022-11-17 16:25:05 -0800395 FrameRateMode mode;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400396 GlobalSignals consideredSignals;
397
398 bool operator==(const DisplayModeChoice& other) const {
Ady Abrahamace3d052022-11-17 16:25:05 -0800399 return mode == other.mode && consideredSignals == other.consideredSignals;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400400 }
401
402 // For tests.
403 friend std::ostream& operator<<(std::ostream& stream, const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800404 return stream << '{' << to_string(*choice.mode.modePtr) << " considering "
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400405 << choice.consideredSignals.toString().c_str() << '}';
406 }
407 };
408
Dominik Laskowski6b049ff2023-01-29 15:46:45 -0500409 using DisplayModeChoiceMap = ui::PhysicalDisplayMap<PhysicalDisplayId, DisplayModeChoice>;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400410
411 // See mDisplayLock for thread safety.
412 DisplayModeChoiceMap chooseDisplayModes() const
413 REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext);
ramindani69b58e82022-09-26 16:48:36 -0700414
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400415 GlobalSignals makeGlobalSignals() const REQUIRES(mPolicyLock);
ramindani69b58e82022-09-26 16:48:36 -0700416
Ady Abraham33a386b2023-07-18 15:37:11 -0700417 bool updateFrameRateOverridesLocked(GlobalSignals, Fps displayRefreshRate)
418 REQUIRES(mPolicyLock);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700419 void updateAttachedChoreographers(const surfaceflinger::frontend::LayerHierarchy&,
420 Fps displayRefreshRate);
421 int updateAttachedChoreographersInternal(const surfaceflinger::frontend::LayerHierarchy&,
422 Fps displayRefreshRate, int parentDivisor);
423 void updateAttachedChoreographersFrameRate(const surfaceflinger::frontend::RequestedLayerState&,
424 Fps fps) EXCLUDES(mChoreographerLock);
Ana Krulec7ab56032018-11-02 20:51:06 +0100425
Dominik Laskowski596a2562022-10-28 11:26:12 -0400426 void dispatchCachedReportedMode() REQUIRES(mPolicyLock) EXCLUDES(mDisplayLock);
Ady Abraham62a0be22020-12-08 16:54:10 -0800427
Ady Abrahamf2851612023-09-25 17:19:00 -0700428 // IEventThreadCallback overrides
429 bool throttleVsync(TimePoint, uid_t) override;
430 Period getVsyncPeriod(uid_t) override EXCLUDES(mDisplayLock);
431 void resync() override EXCLUDES(mDisplayLock);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500432
Dominik Laskowski98041832019-08-01 18:35:59 -0700433 // Stores EventThread associated with a given VSyncSource, and an initial EventThreadConnection.
434 struct Connection {
435 sp<EventThreadConnection> connection;
436 std::unique_ptr<EventThread> thread;
437 };
Ady Abraham09bd3922019-04-08 10:44:56 -0700438
Dominik Laskowski98041832019-08-01 18:35:59 -0700439 ConnectionHandle::Id mNextConnectionHandleId = 0;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700440 mutable std::mutex mConnectionsLock;
441 std::unordered_map<ConnectionHandle, Connection> mConnections GUARDED_BY(mConnectionsLock);
Ana Krulece588e312018-09-18 12:32:24 -0700442
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500443 ConnectionHandle mAppConnectionHandle;
444 ConnectionHandle mSfConnectionHandle;
445
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700446 std::atomic<nsecs_t> mLastResyncTime = 0;
Ana Krulece588e312018-09-18 12:32:24 -0700447
Dominik Laskowski068173d2021-08-11 17:22:59 -0700448 const FeatureFlags mFeatures;
Ana Krulec7ab56032018-11-02 20:51:06 +0100449
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500450 // Shifts the VSYNC phase during certain transactions and refresh rate changes.
451 const sp<VsyncModulator> mVsyncModulator;
452
Dominik Laskowski49cea512019-11-12 14:13:23 -0800453 // Used to choose refresh rate if content detection is enabled.
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700454 LayerHistory mLayerHistory;
Ana Krulecfb772822018-11-30 10:44:07 +0100455
Ady Abraham8532d012019-05-08 14:50:56 -0700456 // Timer used to monitor touch events.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400457 ftl::Optional<OneShotTimer> mTouchTimer;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700458 // Timer used to monitor display power mode.
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400459 ftl::Optional<OneShotTimer> mDisplayPowerTimer;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700460
Alec Mouri1c7938e2023-09-22 04:17:23 +0000461 // Injected delay prior to compositing, for simulating jank.
462 float mPacesetterFrameDurationFractionToSkip GUARDED_BY(kMainThreadContext) = 0.f;
463
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800464 ISchedulerCallback& mSchedulerCallback;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800465
ramindanid4354a92023-10-02 15:11:09 -0700466 IVsyncTrackerCallback& mVsyncTrackerCallback;
467
Dominik Laskowski596a2562022-10-28 11:26:12 -0400468 // mDisplayLock may be locked while under mPolicyLock.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700469 mutable std::mutex mPolicyLock;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700470
Dominik Laskowski596a2562022-10-28 11:26:12 -0400471 // Only required for reads outside kMainThreadContext. kMainThreadContext is the only writer, so
472 // must lock for writes but not reads. See also mPolicyLock for locking order.
473 mutable std::mutex mDisplayLock;
474
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500475 using FrameTargeterPtr = std::unique_ptr<FrameTargeter>;
476
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500477 struct Display {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500478 Display(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr,
479 VsyncSchedulePtr schedulePtr, FeatureFlags features)
480 : displayId(displayId),
481 selectorPtr(std::move(selectorPtr)),
482 schedulePtr(std::move(schedulePtr)),
483 targeterPtr(std::make_unique<
484 FrameTargeter>(displayId,
485 features.test(Feature::kBackpressureGpuComposition))) {}
486
487 const PhysicalDisplayId displayId;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400488
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500489 // Effectively const except in move constructor.
490 RefreshRateSelectorPtr selectorPtr;
491 VsyncSchedulePtr schedulePtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500492 FrameTargeterPtr targeterPtr;
Dominik Laskowski66295432023-03-14 12:25:36 -0400493
494 hal::PowerMode powerMode = hal::PowerMode::OFF;
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500495 };
496
497 using DisplayRef = std::reference_wrapper<Display>;
498 using ConstDisplayRef = std::reference_wrapper<const Display>;
499
Dominik Laskowski6b049ff2023-01-29 15:46:45 -0500500 ui::PhysicalDisplayMap<PhysicalDisplayId, Display> mDisplays GUARDED_BY(mDisplayLock)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500501 GUARDED_BY(kMainThreadContext);
Leon Scroggins III67388622023-02-06 20:36:20 -0500502
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500503 ftl::Optional<PhysicalDisplayId> mPacesetterDisplayId GUARDED_BY(mDisplayLock)
Dominik Laskowski596a2562022-10-28 11:26:12 -0400504 GUARDED_BY(kMainThreadContext);
505
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500506 ftl::Optional<DisplayRef> pacesetterDisplayLocked() REQUIRES(mDisplayLock) {
507 return static_cast<const Scheduler*>(this)->pacesetterDisplayLocked().transform(
508 [](const Display& display) { return std::ref(const_cast<Display&>(display)); });
509 }
510
511 ftl::Optional<ConstDisplayRef> pacesetterDisplayLocked() const REQUIRES(mDisplayLock) {
512 ftl::FakeGuard guard(kMainThreadContext);
513 return mPacesetterDisplayId.and_then([this](PhysicalDisplayId pacesetterId)
514 REQUIRES(mDisplayLock, kMainThreadContext) {
515 return mDisplays.get(pacesetterId);
516 });
517 }
518
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500519 RefreshRateSelectorPtr pacesetterSelectorPtr() const EXCLUDES(mDisplayLock) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400520 std::scoped_lock lock(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500521 return pacesetterSelectorPtrLocked();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400522 }
523
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500524 RefreshRateSelectorPtr pacesetterSelectorPtrLocked() const REQUIRES(mDisplayLock) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400525 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500526 return pacesetterDisplayLocked()
527 .transform([](const Display& display) { return display.selectorPtr; })
528 .or_else([] { return std::optional<RefreshRateSelectorPtr>(nullptr); })
Dominik Laskowski80872bd2022-11-15 11:34:33 -0500529 .value();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400530 }
ramindani69b58e82022-09-26 16:48:36 -0700531
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500532 ConstVsyncSchedulePtr getVsyncScheduleLocked(
533 std::optional<PhysicalDisplayId> = std::nullopt) const REQUIRES(mDisplayLock);
534
535 VsyncSchedulePtr getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt = std::nullopt)
536 REQUIRES(mDisplayLock) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500537 return std::const_pointer_cast<VsyncSchedule>(
538 static_cast<const Scheduler*>(this)->getVsyncScheduleLocked(idOpt));
539 }
540
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800541 struct Policy {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700542 // Policy for choosing the display mode.
543 LayerHistory::Summary contentRequirements;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700544 TimerState idleTimer = TimerState::Reset;
545 TouchState touch = TouchState::Inactive;
546 TimerState displayPowerTimer = TimerState::Expired;
Rachel Lee6a9731d2022-06-06 17:08:14 -0700547 hal::PowerMode displayPowerMode = hal::PowerMode::ON;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700548
Dominik Laskowski068173d2021-08-11 17:22:59 -0700549 // Chosen display mode.
Ady Abrahamace3d052022-11-17 16:25:05 -0800550 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700551
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100552 struct ModeChangedParams {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700553 ConnectionHandle handle;
Ady Abrahamace3d052022-11-17 16:25:05 -0800554 FrameRateMode mode;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700555 };
556
Dominik Laskowski068173d2021-08-11 17:22:59 -0700557 // Parameters for latest dispatch of mode change event.
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100558 std::optional<ModeChangedParams> cachedModeChangedParams;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700559 } mPolicy GUARDED_BY(mPolicyLock);
Ady Abraham09bd3922019-04-08 10:44:56 -0700560
Ady Abraham822ecbd2023-07-07 16:16:09 -0700561 std::mutex mChoreographerLock;
562
563 struct AttachedChoreographers {
564 Fps frameRate;
565 std::unordered_set<wp<EventThreadConnection>, WpHash> connections;
566 };
567 // Map keyed by layer ID (sequence) to choreographer connections.
568 std::unordered_map<int32_t, AttachedChoreographers> mAttachedChoreographers
569 GUARDED_BY(mChoreographerLock);
570
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800571 std::mutex mVsyncTimelineLock;
Peiyong Line9d809e2020-04-14 13:10:48 -0700572 std::optional<hal::VsyncPeriodChangeTimeline> mLastVsyncPeriodChangeTimeline
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800573 GUARDED_BY(mVsyncTimelineLock);
574 static constexpr std::chrono::nanoseconds MAX_VSYNC_APPLIED_TIME = 200ms;
Ady Abraham8735eac2020-08-12 16:35:04 -0700575
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800576 FrameRateOverrideMappings mFrameRateOverrideMappings;
Tony Huang9ac5e6e2023-08-24 09:01:44 +0000577 SmallAreaDetectionAllowMappings mSmallAreaDetectionAllowMappings;
Ana Krulec98b5b242018-08-10 15:03:23 -0700578};
579
Dominik Laskowski068173d2021-08-11 17:22:59 -0700580} // namespace scheduler
Ana Krulec7ab56032018-11-02 20:51:06 +0100581} // namespace android