blob: 856fda0f6cc894f0e0fc1778a2de865989577941 [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
Dominik Laskowski98041832019-08-01 18:35:59 -070017#undef LOG_TAG
18#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Ana Krulec98b5b242018-08-10 15:03:23 -070021#include "Scheduler.h"
22
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070023#include <android-base/properties.h>
Dominik Laskowski49cea512019-11-12 14:13:23 -080024#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070025#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070027#include <configstore/Utils.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040028#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000029#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040030#include <ftl/small_map.h>
chaviw3277faf2021-05-19 16:45:23 -050031#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080032#include <system/window.h>
Ana Krulec3084c052018-11-21 20:27:17 +010033#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010034#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070035
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070036#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070037#include <algorithm>
38#include <cinttypes>
39#include <cstdint>
40#include <functional>
41#include <memory>
42#include <numeric>
43
44#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070045#include "DispSyncSource.h"
Dominik Laskowski01602522022-10-07 19:02:28 -040046#include "Display/DisplayMap.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070047#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080048#include "FrameRateOverrideMappings.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070049#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090050#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080051#include "VSyncPredictor.h"
52#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070053
Dominik Laskowski98041832019-08-01 18:35:59 -070054#define RETURN_IF_INVALID_HANDLE(handle, ...) \
55 do { \
56 if (mConnections.count(handle) == 0) { \
57 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
58 return __VA_ARGS__; \
59 } \
60 } while (false)
61
Dominik Laskowski068173d2021-08-11 17:22:59 -070062namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070063
Dominik Laskowski068173d2021-08-11 17:22:59 -070064Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features)
65 : impl::MessageQueue(compositor), mFeatures(features), mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070066
Dominik Laskowski83bd7712022-01-07 14:30:53 -080067Scheduler::~Scheduler() {
68 // Stop timers and wait for their threads to exit.
69 mDisplayPowerTimer.reset();
70 mTouchTimer.reset();
71
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040072 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowski596a2562022-10-28 11:26:12 -040073 demoteLeaderDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080074}
75
Dominik Laskowski9c93d602021-10-07 19:38:26 -070076void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070077 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070078 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070079
Dominik Laskowski98041832019-08-01 18:35:59 -070080 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070081 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070082 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080083 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070084 [this] { touchTimerCallback(TimerState::Reset); },
85 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070086 mTouchTimer->start();
87 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070088
Dominik Laskowski98041832019-08-01 18:35:59 -070089 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
90 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080091 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070092 [this] { displayPowerTimerCallback(TimerState::Reset); },
93 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -070094 mDisplayPowerTimer->start();
95 }
Ana Krulece588e312018-09-18 12:32:24 -070096}
97
Dominik Laskowski596a2562022-10-28 11:26:12 -040098void Scheduler::setLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
99 demoteLeaderDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400100
Dominik Laskowski596a2562022-10-28 11:26:12 -0400101 std::scoped_lock lock(mDisplayLock);
102 promoteLeaderDisplay(leaderIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800103}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700104
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400105void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400106 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400107
Dominik Laskowski596a2562022-10-28 11:26:12 -0400108 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400109 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400110
111 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400112}
113
114void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400115 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400116
Dominik Laskowski596a2562022-10-28 11:26:12 -0400117 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400118 mRefreshRateSelectors.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400119
120 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400121}
122
Dominik Laskowski756b7892021-08-04 12:53:59 -0700123void Scheduler::run() {
124 while (true) {
125 waitMessage();
126 }
127}
128
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700129void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
130 TimePoint expectedVsyncTime) {
131 const TimePoint frameTime = SchedulerClock::now();
132
133 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
134 return;
135 }
136
137 compositor.composite(frameTime, vsyncId);
138 compositor.sample();
139}
140
Dominik Laskowski068173d2021-08-11 17:22:59 -0700141void Scheduler::createVsyncSchedule(FeatureFlags features) {
142 mVsyncSchedule.emplace(features);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700143}
144
Ady Abraham9c53ee72020-07-22 21:16:18 -0700145std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
146 const char* name, std::chrono::nanoseconds workDuration,
147 std::chrono::nanoseconds readyDuration, bool traceVsync) {
Rachel Leeef2e21f2022-02-01 14:51:34 -0800148 return std::make_unique<scheduler::DispSyncSource>(mVsyncSchedule->getDispatch(),
149 mVsyncSchedule->getTracker(), workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700150 readyDuration, traceVsync, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700151}
152
Ady Abraham62a0be22020-12-08 16:54:10 -0800153std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800154 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800155 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800156 return mFrameRateOverrideMappings
157 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800158}
159
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700160bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800161 const auto frameRate = getFrameRateOverride(uid);
162 if (!frameRate.has_value()) {
163 return true;
164 }
165
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700166 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700167}
168
Ady Abraham64c2fc02020-12-29 12:07:50 -0800169impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
Ady Abraham64c2fc02020-12-29 12:07:50 -0800170 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700171 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800172 };
173}
174
Jorim Jaggic0086af2021-02-12 18:18:11 +0100175impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
176 return [this](uid_t uid) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800177 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
Dominik Laskowski5d164f22022-07-07 07:56:07 -0700178 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800179
Jorim Jaggic0086af2021-02-12 18:18:11 +0100180 const auto frameRate = getFrameRateOverride(uid);
181 if (!frameRate.has_value()) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700182 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100183 }
184
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400185 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
Ady Abrahamcc315492022-02-17 17:06:39 -0800186 if (divisor <= 1) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700187 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100188 }
Rachel Lee73fe8152022-04-11 17:23:25 -0700189 return currentPeriod * divisor;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100190 };
191}
192
Huihong Luoab8ffef2022-08-18 13:02:26 -0700193ConnectionHandle Scheduler::createConnection(const char* connectionName,
194 frametimeline::TokenManager* tokenManager,
195 std::chrono::nanoseconds workDuration,
196 std::chrono::nanoseconds readyDuration) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700197 auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800198 auto throttleVsync = makeThrottleVsyncCallback();
Jorim Jaggic0086af2021-02-12 18:18:11 +0100199 auto getVsyncPeriod = makeGetVsyncPeriodFunction();
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700200 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
Jorim Jaggic0086af2021-02-12 18:18:11 +0100201 std::move(throttleVsync),
202 std::move(getVsyncPeriod));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700203 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700204}
Ana Krulec98b5b242018-08-10 15:03:23 -0700205
Dominik Laskowski068173d2021-08-11 17:22:59 -0700206ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700207 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
208 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800209
Ady Abraham62f216c2020-10-13 19:07:23 -0700210 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700211
Ana Krulec6ddd2612020-09-24 13:06:33 -0700212 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700213 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
214 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700215}
216
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700217sp<EventThreadConnection> Scheduler::createConnectionInternal(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700218 EventThread* eventThread, EventRegistrationFlags eventRegistration) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700219 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700220}
221
Ana Krulec98b5b242018-08-10 15:03:23 -0700222sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700223 ConnectionHandle handle, EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700224 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700225 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700226 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700227}
228
Dominik Laskowski98041832019-08-01 18:35:59 -0700229sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700230 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700231 RETURN_IF_INVALID_HANDLE(handle, nullptr);
232 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700233}
234
Dominik Laskowski98041832019-08-01 18:35:59 -0700235void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
236 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700237 android::EventThread* thread;
238 {
239 std::lock_guard<std::mutex> lock(mConnectionsLock);
240 RETURN_IF_INVALID_HANDLE(handle);
241 thread = mConnections[handle].thread.get();
242 }
243
244 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700245}
246
Dominik Laskowski98041832019-08-01 18:35:59 -0700247void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700248 android::EventThread* thread;
249 {
250 std::lock_guard<std::mutex> lock(mConnectionsLock);
251 RETURN_IF_INVALID_HANDLE(handle);
252 thread = mConnections[handle].thread.get();
253 }
254 thread->onScreenAcquired();
Ady Abraham4f960d12021-10-13 16:59:49 -0700255 mScreenAcquired = true;
Ana Krulec98b5b242018-08-10 15:03:23 -0700256}
257
Dominik Laskowski98041832019-08-01 18:35:59 -0700258void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700259 android::EventThread* thread;
260 {
261 std::lock_guard<std::mutex> lock(mConnectionsLock);
262 RETURN_IF_INVALID_HANDLE(handle);
263 thread = mConnections[handle].thread.get();
264 }
265 thread->onScreenReleased();
Ady Abraham4f960d12021-10-13 16:59:49 -0700266 mScreenAcquired = false;
Ana Krulec98b5b242018-08-10 15:03:23 -0700267}
268
Ady Abraham62a0be22020-12-08 16:54:10 -0800269void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800270 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800271 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800272
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800273 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800274 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800275
Ady Abraham62f216c2020-10-13 19:07:23 -0700276 android::EventThread* thread;
277 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800278 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700279 RETURN_IF_INVALID_HANDLE(handle);
280 thread = mConnections[handle].thread.get();
281 }
282 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
283}
284
Ady Abrahamace3d052022-11-17 16:25:05 -0800285void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800286 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700287 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100288 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700289 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700290
291 // Invalidate content based refresh rate selection so it could be calculated
292 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700293 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800294 }
Ady Abraham690f4612021-07-01 23:24:03 -0700295 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700296}
297
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100298void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700299 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800300 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100301 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700302 return;
303 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700304 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100305 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700306 return;
307 }
308
Ady Abrahamd1591702021-07-27 16:27:56 -0700309 // If the mode is not the current mode, this means that a
310 // mode change is in progress. In that case we shouldn't dispatch an event
311 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800312 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700313 return;
314 }
315
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100316 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800317 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700318 return;
319 }
320
Ady Abrahamace3d052022-11-17 16:25:05 -0800321 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700322 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
323 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700324}
325
Ady Abrahamace3d052022-11-17 16:25:05 -0800326void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700327 android::EventThread* thread;
328 {
329 std::lock_guard<std::mutex> lock(mConnectionsLock);
330 RETURN_IF_INVALID_HANDLE(handle);
331 thread = mConnections[handle].thread.get();
332 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800333 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800334}
335
Alec Mouri717bcb62020-02-10 17:07:19 -0800336size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700337 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800338 RETURN_IF_INVALID_HANDLE(handle, 0);
339 return mConnections[handle].thread->getEventThreadConnectionCount();
340}
341
Dominik Laskowski98041832019-08-01 18:35:59 -0700342void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700343 android::EventThread* thread;
344 {
345 std::lock_guard<std::mutex> lock(mConnectionsLock);
346 RETURN_IF_INVALID_HANDLE(handle);
347 thread = mConnections.at(handle).thread.get();
348 }
349 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700350}
351
Ady Abraham9c53ee72020-07-22 21:16:18 -0700352void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
353 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700354 android::EventThread* thread;
355 {
356 std::lock_guard<std::mutex> lock(mConnectionsLock);
357 RETURN_IF_INVALID_HANDLE(handle);
358 thread = mConnections[handle].thread.get();
359 }
360 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700361}
Ana Krulece588e312018-09-18 12:32:24 -0700362
Ana Krulece588e312018-09-18 12:32:24 -0700363void Scheduler::enableHardwareVsync() {
364 std::lock_guard<std::mutex> lock(mHWVsyncLock);
365 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700366 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700367 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700368 mPrimaryHWVsyncEnabled = true;
369 }
370}
371
372void Scheduler::disableHardwareVsync(bool makeUnavailable) {
373 std::lock_guard<std::mutex> lock(mHWVsyncLock);
374 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700375 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700376 mPrimaryHWVsyncEnabled = false;
377 }
378 if (makeUnavailable) {
379 mHWVsyncAvailable = false;
380 }
381}
382
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800383void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
Ana Krulecc2870422019-01-29 19:00:58 -0800384 {
385 std::lock_guard<std::mutex> lock(mHWVsyncLock);
386 if (makeAvailable) {
387 mHWVsyncAvailable = makeAvailable;
388 } else if (!mHWVsyncAvailable) {
389 // Hardware vsync is not currently available, so abort the resync
390 // attempt for now
391 return;
392 }
393 }
394
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800395 setVsyncPeriod(refreshRate.getPeriodNsecs());
Ana Krulecc2870422019-01-29 19:00:58 -0800396}
397
Ady Abrahamace3d052022-11-17 16:25:05 -0800398void Scheduler::setRenderRate(Fps renderFrameRate) {
399 const auto mode = leaderSelectorPtr()->getActiveMode();
400
401 using fps_approx_ops::operator!=;
402 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
403 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
404 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
405
406 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
407 to_string(mode.modePtr->getFps()).c_str());
408
409 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
410 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
411 to_string(mode.fps).c_str());
412
413 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
414}
415
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700416void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700417 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800418
419 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700420 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800421
422 if (now - last > kIgnoreDelay) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800423 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800424 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800425 }
426}
427
Dominik Laskowski98041832019-08-01 18:35:59 -0700428void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800429 if (period <= 0) return;
430
Ady Abraham3aff9172019-02-07 19:10:26 -0800431 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700432 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800433
434 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700435 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700436 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800437 mPrimaryHWVsyncEnabled = true;
438 }
Ana Krulece588e312018-09-18 12:32:24 -0700439}
440
Ady Abraham5dee2f12020-02-05 17:49:47 -0800441void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
442 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700443 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700444 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700445 { // Scope for the lock
446 std::lock_guard<std::mutex> lock(mHWVsyncLock);
447 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700448 needsHwVsync =
449 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
450 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700451 }
452 }
453
454 if (needsHwVsync) {
455 enableHardwareVsync();
456 } else {
457 disableHardwareVsync(false);
458 }
459}
460
Dominik Laskowski068173d2021-08-11 17:22:59 -0700461void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
462 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700463 enableHardwareVsync();
464 } else {
465 disableHardwareVsync(false);
466 }
467}
468
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700469void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200470 // If the content detection feature is off, we still keep the layer history,
471 // since we use it for other features (like Frame Rate API), so layers
472 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000473 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700474}
475
Ady Abrahambdda8f02021-04-01 16:06:11 -0700476void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700477 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700478}
479
Ady Abraham5def7332020-05-29 16:13:47 -0700480void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
481 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400482 if (leaderSelectorPtr()->canSwitch()) {
483 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800484 }
Ana Krulec3084c052018-11-21 20:27:17 +0100485}
486
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100487void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700488 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700489}
490
Andy Labrada096227e2022-06-15 16:58:11 +0000491void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
492 mLayerHistory.setDefaultFrameRateCompatibility(layer,
493 mFeatures.test(Feature::kContentDetection));
494}
495
Dominik Laskowski49cea512019-11-12 14:13:23 -0800496void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400497 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400498 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800499
Ady Abraham8a82ba62020-01-17 12:43:17 -0800500 ATRACE_CALL();
501
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400502 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800503 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800504}
505
Ana Krulecfb772822018-11-30 10:44:07 +0100506void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400507 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800508}
509
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700510void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700511 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800512 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400513 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800514 }
Ady Abraham8532d012019-05-08 14:50:56 -0700515}
516
Rachel Lee6a9731d2022-06-06 17:08:14 -0700517void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700518 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700519 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700520 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700521 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700522 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700523
524 if (mDisplayPowerTimer) {
525 mDisplayPowerTimer->reset();
526 }
527
528 // Display Power event will boost the refresh rate to performance.
529 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700530 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700531}
532
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700533void Scheduler::kernelIdleTimerCallback(TimerState state) {
534 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100535
Ady Abraham2139f732019-11-13 18:56:40 -0800536 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
537 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800538 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700539
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700540 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
541 using namespace fps_approx_ops;
542
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800543 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700544 // If we're not in performance mode then the kernel timer shouldn't do
545 // anything, as the refresh rate during DPU power collapse will be the
546 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800547 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
548 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700549 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
550 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700551 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700552 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700553 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800554
555 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700556}
557
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700558void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800559 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700560 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100561}
562
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700563void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700564 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700565 // Touch event will boost the refresh rate to performance.
566 // Clear layer history to get fresh FPS detection.
567 // NOTE: Instead of checking all the layers, we should be checking the layer
568 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800569 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700570 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700571 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700572 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700573}
574
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700575void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800576 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700577 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700578}
579
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400580void Scheduler::dump(utils::Dumper& dumper) const {
581 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700582
583 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400584 utils::Dumper::Section section(dumper, "Features"sv);
585
586 for (Feature feature : ftl::enum_range<Feature>()) {
587 if (const auto flagOpt = ftl::flag_name(feature)) {
588 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
589 }
590 }
591 }
592 {
593 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400594 {
595 std::scoped_lock lock(mDisplayLock);
596 ftl::FakeGuard guard(kMainThreadContext);
597 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
598 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400599 dumper.dump("layerHistory"sv, mLayerHistory.dump());
600 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
601 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
602 }
603
604 mFrameRateOverrideMappings.dump(dumper);
605 dumper.eol();
606
607 {
608 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
609
Ady Abraham4f960d12021-10-13 16:59:49 -0700610 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400611 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
612 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
613 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700614 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800615}
616
Dominik Laskowski068173d2021-08-11 17:22:59 -0700617void Scheduler::dumpVsync(std::string& out) const {
618 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700619}
620
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800621bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400622 if (consideredSignals.idle) return false;
623
624 const auto frameRateOverrides =
625 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
626 displayRefreshRate, consideredSignals);
627
628 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
629 // the FrameRateOverrideMappings rather than here.
630 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
631}
632
633void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
634 // TODO(b/241286431): Choose the leader display.
635 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
636 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
637
638 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
639 leaderPtr->setIdleTimerCallbacks(
640 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
641 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
642 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
643 .onExpired =
644 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
645
646 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800647 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400648}
649
650void Scheduler::demoteLeaderDisplay() {
651 // No need to lock for reads on kMainThreadContext.
652 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
653 leaderPtr->stopIdleTimer();
654 leaderPtr->clearIdleTimerCallbacks();
655 }
656
657 // Clear state that depends on the leader's RefreshRateSelector.
658 std::scoped_lock lock(mPolicyLock);
659 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800660}
661
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800662template <typename S, typename T>
663auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400664 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800665 GlobalSignals consideredSignals;
666
Ady Abraham62a0be22020-12-08 16:54:10 -0800667 bool refreshRateChanged = false;
668 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800669
Ady Abraham8532d012019-05-08 14:50:56 -0700670 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400671 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800672
673 auto& currentState = mPolicy.*statePtr;
674 if (currentState == newState) return {};
675 currentState = std::forward<T>(newState);
676
Dominik Laskowski596a2562022-10-28 11:26:12 -0400677 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800678 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400679 {
680 std::scoped_lock lock(mDisplayLock);
681 ftl::FakeGuard guard(kMainThreadContext);
682
683 modeChoices = chooseDisplayModes();
684
685 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
686 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800687 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400688 modeChoices.get(*mLeaderDisplayId)
689 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800690 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400691 })
692 .value();
693 }
ramindani69b58e82022-09-26 16:48:36 -0700694
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400695 modeRequests.reserve(modeChoices.size());
696 for (auto& [id, choice] : modeChoices) {
697 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800698 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400699 .emitEvent = !choice.consideredSignals.idle});
700 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800701
Ady Abrahamace3d052022-11-17 16:25:05 -0800702 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400703
Ady Abrahamace3d052022-11-17 16:25:05 -0800704 if (mPolicy.modeOpt != modeOpt) {
705 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400706 refreshRateChanged = true;
707 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100708 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800709 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700710 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700712 }
Ady Abraham8532d012019-05-08 14:50:56 -0700713 }
Ady Abraham8532d012019-05-08 14:50:56 -0700714 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800715 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400716 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800717 }
718 if (frameRateOverridesChanged) {
719 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
720 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800721 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700722}
723
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400724auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800725 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700726
Ady Abraham68636062022-11-16 17:07:25 -0800727 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400728 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400729
730 // Tallies the score of a refresh rate across `displayCount` displays.
731 struct RefreshRateTally {
732 explicit RefreshRateTally(float score) : score(score) {}
733
734 float score;
735 size_t displayCount = 1;
736 };
737
738 // Chosen to exceed a typical number of refresh rates across displays.
739 constexpr size_t kStaticCapacity = 8;
740 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
741
742 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800743
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400744 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800745 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800746 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700747
Ady Abrahamace3d052022-11-17 16:25:05 -0800748 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
749 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400750
751 if (!inserted) {
752 auto& tally = it->second;
753 tally.score += score;
754 tally.displayCount++;
755 }
756 }
757
Ady Abrahamace3d052022-11-17 16:25:05 -0800758 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400759 }
ramindani69b58e82022-09-26 16:48:36 -0700760
Dominik Laskowski01602522022-10-07 19:02:28 -0400761 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700762
Dominik Laskowski01602522022-10-07 19:02:28 -0400763 // Find the first refresh rate common to all displays.
764 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400765 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400766 ++maxScoreIt;
767 }
768
769 if (maxScoreIt != refreshRateTallies.cend()) {
770 // Choose the highest refresh rate common to all displays, if any.
771 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
772 const auto [fps, tally] = *it;
773
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400774 if (tally.displayCount == mRefreshRateSelectors.size() &&
775 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400776 maxScoreIt = it;
777 }
ramindani7c487282022-10-10 16:17:51 -0700778 }
779 }
ramindani69b58e82022-09-26 16:48:36 -0700780
Dominik Laskowski01602522022-10-07 19:02:28 -0400781 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
782 ? std::make_optional(maxScoreIt->first)
783 : std::nullopt;
784
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400785 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400786
ramindani69b58e82022-09-26 16:48:36 -0700787 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400788
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400789 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400790 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800791 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800792 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
793 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400794 continue;
795 }
796
Ady Abraham68636062022-11-16 17:07:25 -0800797 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800798 if (frameRateMode.fps == *chosenFps) {
799 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
800 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400801 break;
802 }
803 }
804 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400805 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700806}
807
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400808GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000809 const bool powerOnImminent = mDisplayPowerTimer &&
810 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
811 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700812
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400813 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
814 .idle = mPolicy.idleTimer == TimerState::Expired,
815 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800816}
817
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500818FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700819 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500820 const auto frameRateMode =
821 leaderSelectorPtr()
822 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
823 .ranking.front()
824 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400825
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500826 // Make sure the stored mode is up to date.
827 mPolicy.modeOpt = frameRateMode;
828
829 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700830}
831
Peiyong Line9d809e2020-04-14 13:10:48 -0700832void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800833 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
834 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
835
836 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
837 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
838 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
839 }
840}
841
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700842bool Scheduler::onPostComposition(nsecs_t presentTime) {
843 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
844 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
845 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
846 // We need to composite again as refreshTimeNanos is still in the future.
847 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700848 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700849
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700850 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800851 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700852 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800853}
854
Ady Abraham7825c682021-05-17 15:12:14 -0700855void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700856 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800857}
858
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800859void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
860 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
861 return;
862 }
863
864 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
865}
866
Ady Abraham62a0be22020-12-08 16:54:10 -0800867void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
868 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
869 return;
870 }
871
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800872 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800873}
874
Dominik Laskowski068173d2021-08-11 17:22:59 -0700875} // namespace android::scheduler