blob: f1fcc884e5ca30b1b825bb9c70a2b80188adfc8e [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 =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400155 leaderSelectorPtr()->supportsFrameRateOverrideByContent();
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) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400177 const Fps refreshRate = leaderSelectorPtr()->getActiveModePtr()->getFps();
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 =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400271 leaderSelectorPtr()->supportsFrameRateOverrideByContent();
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 Abraham690f4612021-07-01 23:24:03 -0700285void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, DisplayModePtr 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.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700300 if (!mPolicy.mode) {
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.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400312 if (leaderSelectorPtr()->getActiveModePtr() != mPolicy.mode) {
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
Dominik Laskowski068173d2021-08-11 17:22:59 -0700317 if (mPolicy.mode == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700318 return;
319 }
320
Dominik Laskowski068173d2021-08-11 17:22:59 -0700321 mPolicy.cachedModeChangedParams->mode = mPolicy.mode;
322 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
323 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700324}
325
Ady Abraham690f4612021-07-01 23:24:03 -0700326void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, DisplayModePtr 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 Abraham690f4612021-07-01 23:24:03 -0700333 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
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700398void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700399 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800400
401 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700402 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800403
404 if (now - last > kIgnoreDelay) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400405 const auto refreshRate = leaderSelectorPtr()->getActiveModePtr()->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800406 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800407 }
408}
409
Dominik Laskowski98041832019-08-01 18:35:59 -0700410void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800411 if (period <= 0) return;
412
Ady Abraham3aff9172019-02-07 19:10:26 -0800413 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700414 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800415
416 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700417 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700418 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800419 mPrimaryHWVsyncEnabled = true;
420 }
Ana Krulece588e312018-09-18 12:32:24 -0700421}
422
Ady Abraham5dee2f12020-02-05 17:49:47 -0800423void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
424 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700425 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700426 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700427 { // Scope for the lock
428 std::lock_guard<std::mutex> lock(mHWVsyncLock);
429 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700430 needsHwVsync =
431 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
432 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700433 }
434 }
435
436 if (needsHwVsync) {
437 enableHardwareVsync();
438 } else {
439 disableHardwareVsync(false);
440 }
441}
442
Dominik Laskowski068173d2021-08-11 17:22:59 -0700443void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
444 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700445 enableHardwareVsync();
446 } else {
447 disableHardwareVsync(false);
448 }
449}
450
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700451void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200452 // If the content detection feature is off, we still keep the layer history,
453 // since we use it for other features (like Frame Rate API), so layers
454 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000455 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700456}
457
Ady Abrahambdda8f02021-04-01 16:06:11 -0700458void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700459 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700460}
461
Ady Abraham5def7332020-05-29 16:13:47 -0700462void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
463 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400464 if (leaderSelectorPtr()->canSwitch()) {
465 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800466 }
Ana Krulec3084c052018-11-21 20:27:17 +0100467}
468
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100469void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700470 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700471}
472
Andy Labrada096227e2022-06-15 16:58:11 +0000473void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
474 mLayerHistory.setDefaultFrameRateCompatibility(layer,
475 mFeatures.test(Feature::kContentDetection));
476}
477
Dominik Laskowski49cea512019-11-12 14:13:23 -0800478void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400479 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400480 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800481
Ady Abraham8a82ba62020-01-17 12:43:17 -0800482 ATRACE_CALL();
483
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400484 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800485 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800486}
487
Ana Krulecfb772822018-11-30 10:44:07 +0100488void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400489 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800490}
491
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700492void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700493 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800494 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400495 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800496 }
Ady Abraham8532d012019-05-08 14:50:56 -0700497}
498
Rachel Lee6a9731d2022-06-06 17:08:14 -0700499void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700500 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700501 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700502 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700503 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700504 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700505
506 if (mDisplayPowerTimer) {
507 mDisplayPowerTimer->reset();
508 }
509
510 // Display Power event will boost the refresh rate to performance.
511 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700512 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700513}
514
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700515void Scheduler::kernelIdleTimerCallback(TimerState state) {
516 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100517
Ady Abraham2139f732019-11-13 18:56:40 -0800518 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
519 // magic number
Dominik Laskowski596a2562022-10-28 11:26:12 -0400520 const Fps refreshRate = leaderSelectorPtr()->getActiveModePtr()->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700521
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700522 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
523 using namespace fps_approx_ops;
524
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800525 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700526 // If we're not in performance mode then the kernel timer shouldn't do
527 // anything, as the refresh rate during DPU power collapse will be the
528 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800529 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
530 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700531 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
532 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700533 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700534 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700535 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800536
537 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700538}
539
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700540void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800541 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700542 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100543}
544
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700545void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700546 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700547 // Touch event will boost the refresh rate to performance.
548 // Clear layer history to get fresh FPS detection.
549 // NOTE: Instead of checking all the layers, we should be checking the layer
550 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800551 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700552 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700553 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700554 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700555}
556
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700557void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800558 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700559 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700560}
561
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400562void Scheduler::dump(utils::Dumper& dumper) const {
563 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700564
565 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400566 utils::Dumper::Section section(dumper, "Features"sv);
567
568 for (Feature feature : ftl::enum_range<Feature>()) {
569 if (const auto flagOpt = ftl::flag_name(feature)) {
570 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
571 }
572 }
573 }
574 {
575 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400576 {
577 std::scoped_lock lock(mDisplayLock);
578 ftl::FakeGuard guard(kMainThreadContext);
579 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
580 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400581 dumper.dump("layerHistory"sv, mLayerHistory.dump());
582 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
583 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
584 }
585
586 mFrameRateOverrideMappings.dump(dumper);
587 dumper.eol();
588
589 {
590 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
591
Ady Abraham4f960d12021-10-13 16:59:49 -0700592 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400593 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
594 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
595 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700596 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800597}
598
Dominik Laskowski068173d2021-08-11 17:22:59 -0700599void Scheduler::dumpVsync(std::string& out) const {
600 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700601}
602
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800603bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400604 if (consideredSignals.idle) return false;
605
606 const auto frameRateOverrides =
607 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
608 displayRefreshRate, consideredSignals);
609
610 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
611 // the FrameRateOverrideMappings rather than here.
612 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
613}
614
615void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
616 // TODO(b/241286431): Choose the leader display.
617 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
618 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
619
620 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
621 leaderPtr->setIdleTimerCallbacks(
622 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
623 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
624 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
625 .onExpired =
626 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
627
628 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800629 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400630}
631
632void Scheduler::demoteLeaderDisplay() {
633 // No need to lock for reads on kMainThreadContext.
634 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
635 leaderPtr->stopIdleTimer();
636 leaderPtr->clearIdleTimerCallbacks();
637 }
638
639 // Clear state that depends on the leader's RefreshRateSelector.
640 std::scoped_lock lock(mPolicyLock);
641 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800642}
643
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800644template <typename S, typename T>
645auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400646 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800647 GlobalSignals consideredSignals;
648
Ady Abraham62a0be22020-12-08 16:54:10 -0800649 bool refreshRateChanged = false;
650 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800651
Ady Abraham8532d012019-05-08 14:50:56 -0700652 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400653 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800654
655 auto& currentState = mPolicy.*statePtr;
656 if (currentState == newState) return {};
657 currentState = std::forward<T>(newState);
658
Dominik Laskowski596a2562022-10-28 11:26:12 -0400659 DisplayModeChoiceMap modeChoices;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400660 DisplayModePtr modePtr;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400661 {
662 std::scoped_lock lock(mDisplayLock);
663 ftl::FakeGuard guard(kMainThreadContext);
664
665 modeChoices = chooseDisplayModes();
666
667 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
668 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
669 std::tie(modePtr, consideredSignals) =
670 modeChoices.get(*mLeaderDisplayId)
671 .transform([](const DisplayModeChoice& choice) {
672 return std::make_pair(choice.modePtr, choice.consideredSignals);
673 })
674 .value();
675 }
ramindani69b58e82022-09-26 16:48:36 -0700676
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400677 modeRequests.reserve(modeChoices.size());
678 for (auto& [id, choice] : modeChoices) {
679 modeRequests.emplace_back(
680 display::DisplayModeRequest{.modePtr =
681 ftl::as_non_null(std::move(choice.modePtr)),
682 .emitEvent = !choice.consideredSignals.idle});
683 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800684
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400685 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modePtr->getFps());
686
687 if (mPolicy.mode != modePtr) {
688 mPolicy.mode = modePtr;
689 refreshRateChanged = true;
690 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100691 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800692 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700693 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100694 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700695 }
Ady Abraham8532d012019-05-08 14:50:56 -0700696 }
Ady Abraham8532d012019-05-08 14:50:56 -0700697 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800698 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400699 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800700 }
701 if (frameRateOverridesChanged) {
702 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
703 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800704 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700705}
706
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400707auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800708 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700709
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400710 using RankedRefreshRates = RefreshRateSelector::RankedRefreshRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400711 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400712
713 // Tallies the score of a refresh rate across `displayCount` displays.
714 struct RefreshRateTally {
715 explicit RefreshRateTally(float score) : score(score) {}
716
717 float score;
718 size_t displayCount = 1;
719 };
720
721 // Chosen to exceed a typical number of refresh rates across displays.
722 constexpr size_t kStaticCapacity = 8;
723 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
724
725 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800726
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400727 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400728 auto rankedRefreshRates =
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400729 selectorPtr->getRankedRefreshRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700730
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400731 for (const auto& [modePtr, score] : rankedRefreshRates.ranking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400732 const auto [it, inserted] = refreshRateTallies.try_emplace(modePtr->getFps(), score);
733
734 if (!inserted) {
735 auto& tally = it->second;
736 tally.score += score;
737 tally.displayCount++;
738 }
739 }
740
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400741 perDisplayRanking.push_back(std::move(rankedRefreshRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400742 }
ramindani69b58e82022-09-26 16:48:36 -0700743
Dominik Laskowski01602522022-10-07 19:02:28 -0400744 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700745
Dominik Laskowski01602522022-10-07 19:02:28 -0400746 // Find the first refresh rate common to all displays.
747 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400748 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400749 ++maxScoreIt;
750 }
751
752 if (maxScoreIt != refreshRateTallies.cend()) {
753 // Choose the highest refresh rate common to all displays, if any.
754 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
755 const auto [fps, tally] = *it;
756
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400757 if (tally.displayCount == mRefreshRateSelectors.size() &&
758 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400759 maxScoreIt = it;
760 }
ramindani7c487282022-10-10 16:17:51 -0700761 }
762 }
ramindani69b58e82022-09-26 16:48:36 -0700763
Dominik Laskowski01602522022-10-07 19:02:28 -0400764 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
765 ? std::make_optional(maxScoreIt->first)
766 : std::nullopt;
767
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400768 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400769
ramindani69b58e82022-09-26 16:48:36 -0700770 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400771
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400772 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400773 if (!chosenFps) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400774 auto& [modePtr, _] = ranking.front();
775 modeChoices.try_emplace(modePtr->getPhysicalDisplayId(),
776 DisplayModeChoice{std::move(modePtr), signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400777 continue;
778 }
779
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400780 for (auto& [modePtr, _] : ranking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400781 if (modePtr->getFps() == *chosenFps) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400782 modeChoices.try_emplace(modePtr->getPhysicalDisplayId(),
783 DisplayModeChoice{std::move(modePtr), signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400784 break;
785 }
786 }
787 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400788 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700789}
790
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400791GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000792 const bool powerOnImminent = mDisplayPowerTimer &&
793 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
794 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700795
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400796 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
797 .idle = mPolicy.idleTimer == TimerState::Expired,
798 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800799}
800
Ady Abraham690f4612021-07-01 23:24:03 -0700801DisplayModePtr Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700802 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800803 // Make sure the stored mode is up to date.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700804 if (mPolicy.mode) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400805 const auto ranking =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400806 leaderSelectorPtr()
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400807 ->getRankedRefreshRates(mPolicy.contentRequirements, makeGlobalSignals())
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400808 .ranking;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400809
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400810 mPolicy.mode = ranking.front().modePtr;
Ana Krulec3f6a2062020-01-23 15:48:01 -0800811 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700812 return mPolicy.mode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700813}
814
Peiyong Line9d809e2020-04-14 13:10:48 -0700815void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800816 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
817 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
818
819 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
820 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
821 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
822 }
823}
824
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700825bool Scheduler::onPostComposition(nsecs_t presentTime) {
826 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
827 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
828 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
829 // We need to composite again as refreshTimeNanos is still in the future.
830 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700831 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700832
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700833 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800834 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700835 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800836}
837
Ady Abraham7825c682021-05-17 15:12:14 -0700838void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700839 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800840}
841
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800842void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
843 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
844 return;
845 }
846
847 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
848}
849
Ady Abraham62a0be22020-12-08 16:54:10 -0800850void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
851 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
852 return;
853 }
854
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800855 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800856}
857
Dominik Laskowski068173d2021-08-11 17:22:59 -0700858} // namespace android::scheduler