blob: 1e97f352d1a93cfef0be9f3b363919fb49355403 [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 Laskowski63f12792023-01-21 16:58:22 -050037#include <scheduler/interface/ICompositor.h>
38
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070039#include <algorithm>
40#include <cinttypes>
41#include <cstdint>
42#include <functional>
43#include <memory>
44#include <numeric>
45
46#include "../Layer.h"
Dominik Laskowski01602522022-10-07 19:02:28 -040047#include "Display/DisplayMap.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070048#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080049#include "FrameRateOverrideMappings.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070050#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090051#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080052#include "VSyncPredictor.h"
53#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070054
Dominik Laskowski98041832019-08-01 18:35:59 -070055#define RETURN_IF_INVALID_HANDLE(handle, ...) \
56 do { \
57 if (mConnections.count(handle) == 0) { \
58 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
59 return __VA_ARGS__; \
60 } \
61 } while (false)
62
Dominik Laskowski068173d2021-08-11 17:22:59 -070063namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070064
Dominik Laskowski1c99a002023-01-20 17:10:36 -050065Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
66 sp<VsyncModulator> modulatorPtr)
67 : impl::MessageQueue(compositor),
68 mFeatures(features),
69 mVsyncModulator(std::move(modulatorPtr)),
70 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070071
Dominik Laskowski83bd7712022-01-07 14:30:53 -080072Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080073 // MessageQueue depends on VsyncSchedule, so first destroy it.
74 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
75 // which will cause a use-after-free issue.
76 Impl::destroyVsync();
77
Dominik Laskowski83bd7712022-01-07 14:30:53 -080078 // Stop timers and wait for their threads to exit.
79 mDisplayPowerTimer.reset();
80 mTouchTimer.reset();
81
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040082 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowski596a2562022-10-28 11:26:12 -040083 demoteLeaderDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080084}
85
Dominik Laskowski9c93d602021-10-07 19:38:26 -070086void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070087 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070088 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070089
Dominik Laskowski98041832019-08-01 18:35:59 -070090 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070091 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070092 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080093 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070094 [this] { touchTimerCallback(TimerState::Reset); },
95 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070096 mTouchTimer->start();
97 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070098
Dominik Laskowski98041832019-08-01 18:35:59 -070099 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
100 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800101 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700102 [this] { displayPowerTimerCallback(TimerState::Reset); },
103 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700104 mDisplayPowerTimer->start();
105 }
Ana Krulece588e312018-09-18 12:32:24 -0700106}
107
Dominik Laskowski596a2562022-10-28 11:26:12 -0400108void Scheduler::setLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
109 demoteLeaderDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400110
Dominik Laskowski596a2562022-10-28 11:26:12 -0400111 std::scoped_lock lock(mDisplayLock);
112 promoteLeaderDisplay(leaderIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800113}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700114
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400115void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400116 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400117
Dominik Laskowski596a2562022-10-28 11:26:12 -0400118 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400119 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400120
121 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400122}
123
124void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400125 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400126
Dominik Laskowski596a2562022-10-28 11:26:12 -0400127 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400128 mRefreshRateSelectors.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400129
130 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400131}
132
Dominik Laskowski756b7892021-08-04 12:53:59 -0700133void Scheduler::run() {
134 while (true) {
135 waitMessage();
136 }
137}
138
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700139void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
140 TimePoint expectedVsyncTime) {
141 const TimePoint frameTime = SchedulerClock::now();
142
143 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
144 return;
145 }
146
147 compositor.composite(frameTime, vsyncId);
148 compositor.sample();
149}
150
Dominik Laskowski068173d2021-08-11 17:22:59 -0700151void Scheduler::createVsyncSchedule(FeatureFlags features) {
152 mVsyncSchedule.emplace(features);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700153}
154
Ady Abraham62a0be22020-12-08 16:54:10 -0800155std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800156 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800157 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800158 return mFrameRateOverrideMappings
159 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800160}
161
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700162bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800163 const auto frameRate = getFrameRateOverride(uid);
164 if (!frameRate.has_value()) {
165 return true;
166 }
167
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700168 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700169}
170
Ady Abraham64c2fc02020-12-29 12:07:50 -0800171impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
Ady Abraham64c2fc02020-12-29 12:07:50 -0800172 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700173 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800174 };
175}
176
Jorim Jaggic0086af2021-02-12 18:18:11 +0100177impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
178 return [this](uid_t uid) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800179 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
Dominik Laskowski5d164f22022-07-07 07:56:07 -0700180 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800181
Jorim Jaggic0086af2021-02-12 18:18:11 +0100182 const auto frameRate = getFrameRateOverride(uid);
183 if (!frameRate.has_value()) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700184 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100185 }
186
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400187 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
Ady Abrahamcc315492022-02-17 17:06:39 -0800188 if (divisor <= 1) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700189 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100190 }
Rachel Lee73fe8152022-04-11 17:23:25 -0700191 return currentPeriod * divisor;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100192 };
193}
194
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500195ConnectionHandle Scheduler::createEventThread(Cycle cycle,
196 frametimeline::TokenManager* tokenManager,
197 std::chrono::nanoseconds workDuration,
198 std::chrono::nanoseconds readyDuration) {
199 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
200 *mVsyncSchedule, tokenManager,
201 makeThrottleVsyncCallback(),
202 makeGetVsyncPeriodFunction(),
203 workDuration, readyDuration);
204
205 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
206 handle = createConnection(std::move(eventThread));
207 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700208}
Ana Krulec98b5b242018-08-10 15:03:23 -0700209
Dominik Laskowski068173d2021-08-11 17:22:59 -0700210ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700211 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
212 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800213
Ady Abraham62f216c2020-10-13 19:07:23 -0700214 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700215
Ana Krulec6ddd2612020-09-24 13:06:33 -0700216 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700217 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
218 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700219}
220
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700221sp<EventThreadConnection> Scheduler::createConnectionInternal(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700222 EventThread* eventThread, EventRegistrationFlags eventRegistration) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700223 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700224}
225
Ana Krulec98b5b242018-08-10 15:03:23 -0700226sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700227 ConnectionHandle handle, EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700228 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700229 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700230 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700231}
232
Dominik Laskowski98041832019-08-01 18:35:59 -0700233sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700234 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700235 RETURN_IF_INVALID_HANDLE(handle, nullptr);
236 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700237}
238
Dominik Laskowski98041832019-08-01 18:35:59 -0700239void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
240 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700241 android::EventThread* thread;
242 {
243 std::lock_guard<std::mutex> lock(mConnectionsLock);
244 RETURN_IF_INVALID_HANDLE(handle);
245 thread = mConnections[handle].thread.get();
246 }
247
248 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700249}
250
Dominik Laskowski98041832019-08-01 18:35:59 -0700251void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700252 android::EventThread* thread;
253 {
254 std::lock_guard<std::mutex> lock(mConnectionsLock);
255 RETURN_IF_INVALID_HANDLE(handle);
256 thread = mConnections[handle].thread.get();
257 }
258 thread->onScreenAcquired();
Ady Abraham4f960d12021-10-13 16:59:49 -0700259 mScreenAcquired = true;
Ana Krulec98b5b242018-08-10 15:03:23 -0700260}
261
Dominik Laskowski98041832019-08-01 18:35:59 -0700262void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700263 android::EventThread* thread;
264 {
265 std::lock_guard<std::mutex> lock(mConnectionsLock);
266 RETURN_IF_INVALID_HANDLE(handle);
267 thread = mConnections[handle].thread.get();
268 }
269 thread->onScreenReleased();
Ady Abraham4f960d12021-10-13 16:59:49 -0700270 mScreenAcquired = false;
Ana Krulec98b5b242018-08-10 15:03:23 -0700271}
272
Ady Abraham62a0be22020-12-08 16:54:10 -0800273void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800274 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800275 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800276
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800277 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800278 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800279
Ady Abraham62f216c2020-10-13 19:07:23 -0700280 android::EventThread* thread;
281 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800282 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700283 RETURN_IF_INVALID_HANDLE(handle);
284 thread = mConnections[handle].thread.get();
285 }
286 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
287}
288
Ady Abrahamace3d052022-11-17 16:25:05 -0800289void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800290 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700291 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100292 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700293 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700294
295 // Invalidate content based refresh rate selection so it could be calculated
296 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700297 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800298 }
Ady Abraham690f4612021-07-01 23:24:03 -0700299 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700300}
301
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100302void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700303 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800304 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100305 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700306 return;
307 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700308 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100309 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700310 return;
311 }
312
Ady Abrahamd1591702021-07-27 16:27:56 -0700313 // If the mode is not the current mode, this means that a
314 // mode change is in progress. In that case we shouldn't dispatch an event
315 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800316 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700317 return;
318 }
319
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100320 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800321 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700322 return;
323 }
324
Ady Abrahamace3d052022-11-17 16:25:05 -0800325 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700326 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
327 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700328}
329
Ady Abrahamace3d052022-11-17 16:25:05 -0800330void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700331 android::EventThread* thread;
332 {
333 std::lock_guard<std::mutex> lock(mConnectionsLock);
334 RETURN_IF_INVALID_HANDLE(handle);
335 thread = mConnections[handle].thread.get();
336 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800337 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800338}
339
Alec Mouri717bcb62020-02-10 17:07:19 -0800340size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700341 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800342 RETURN_IF_INVALID_HANDLE(handle, 0);
343 return mConnections[handle].thread->getEventThreadConnectionCount();
344}
345
Dominik Laskowski98041832019-08-01 18:35:59 -0700346void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700347 android::EventThread* thread;
348 {
349 std::lock_guard<std::mutex> lock(mConnectionsLock);
350 RETURN_IF_INVALID_HANDLE(handle);
351 thread = mConnections.at(handle).thread.get();
352 }
353 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700354}
355
Ady Abraham9c53ee72020-07-22 21:16:18 -0700356void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
357 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700358 android::EventThread* thread;
359 {
360 std::lock_guard<std::mutex> lock(mConnectionsLock);
361 RETURN_IF_INVALID_HANDLE(handle);
362 thread = mConnections[handle].thread.get();
363 }
364 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700365}
Ana Krulece588e312018-09-18 12:32:24 -0700366
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500367void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
368 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
369}
370
371void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
372 setDuration(mAppConnectionHandle,
373 /* workDuration */ config.appWorkDuration,
374 /* readyDuration */ config.sfWorkDuration);
375 setDuration(mSfConnectionHandle,
376 /* workDuration */ vsyncPeriod,
377 /* readyDuration */ config.sfWorkDuration);
378 setDuration(config.sfWorkDuration);
379}
380
Ana Krulece588e312018-09-18 12:32:24 -0700381void Scheduler::enableHardwareVsync() {
382 std::lock_guard<std::mutex> lock(mHWVsyncLock);
383 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700384 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700385 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700386 mPrimaryHWVsyncEnabled = true;
387 }
388}
389
390void Scheduler::disableHardwareVsync(bool makeUnavailable) {
391 std::lock_guard<std::mutex> lock(mHWVsyncLock);
392 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700393 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700394 mPrimaryHWVsyncEnabled = false;
395 }
396 if (makeUnavailable) {
397 mHWVsyncAvailable = false;
398 }
399}
400
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800401void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
Ana Krulecc2870422019-01-29 19:00:58 -0800402 {
403 std::lock_guard<std::mutex> lock(mHWVsyncLock);
404 if (makeAvailable) {
405 mHWVsyncAvailable = makeAvailable;
406 } else if (!mHWVsyncAvailable) {
407 // Hardware vsync is not currently available, so abort the resync
408 // attempt for now
409 return;
410 }
411 }
412
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800413 setVsyncPeriod(refreshRate.getPeriodNsecs());
Ana Krulecc2870422019-01-29 19:00:58 -0800414}
415
Ady Abrahamace3d052022-11-17 16:25:05 -0800416void Scheduler::setRenderRate(Fps renderFrameRate) {
417 const auto mode = leaderSelectorPtr()->getActiveMode();
418
419 using fps_approx_ops::operator!=;
420 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
421 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
422 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
423
424 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
425 to_string(mode.modePtr->getFps()).c_str());
426
427 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
428 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
429 to_string(mode.fps).c_str());
430
431 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
432}
433
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700434void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700435 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800436
437 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700438 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800439
440 if (now - last > kIgnoreDelay) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800441 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800442 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800443 }
444}
445
Dominik Laskowski98041832019-08-01 18:35:59 -0700446void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800447 if (period <= 0) return;
448
Ady Abraham3aff9172019-02-07 19:10:26 -0800449 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700450 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800451
452 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700453 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700454 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800455 mPrimaryHWVsyncEnabled = true;
456 }
Ana Krulece588e312018-09-18 12:32:24 -0700457}
458
Ady Abraham5dee2f12020-02-05 17:49:47 -0800459void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
460 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700461 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700462 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700463 { // Scope for the lock
464 std::lock_guard<std::mutex> lock(mHWVsyncLock);
465 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700466 needsHwVsync =
467 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
468 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700469 }
470 }
471
472 if (needsHwVsync) {
473 enableHardwareVsync();
474 } else {
475 disableHardwareVsync(false);
476 }
477}
478
Dominik Laskowski068173d2021-08-11 17:22:59 -0700479void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
480 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700481 enableHardwareVsync();
482 } else {
483 disableHardwareVsync(false);
484 }
485}
486
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700487void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200488 // If the content detection feature is off, we still keep the layer history,
489 // since we use it for other features (like Frame Rate API), so layers
490 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000491 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700492}
493
Ady Abrahambdda8f02021-04-01 16:06:11 -0700494void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700495 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700496}
497
Ady Abraham5def7332020-05-29 16:13:47 -0700498void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
499 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400500 if (leaderSelectorPtr()->canSwitch()) {
501 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800502 }
Ana Krulec3084c052018-11-21 20:27:17 +0100503}
504
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100505void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700506 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700507}
508
Andy Labrada096227e2022-06-15 16:58:11 +0000509void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
510 mLayerHistory.setDefaultFrameRateCompatibility(layer,
511 mFeatures.test(Feature::kContentDetection));
512}
513
Dominik Laskowski49cea512019-11-12 14:13:23 -0800514void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400515 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400516 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800517
Ady Abraham8a82ba62020-01-17 12:43:17 -0800518 ATRACE_CALL();
519
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400520 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800521 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800522}
523
Ana Krulecfb772822018-11-30 10:44:07 +0100524void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400525 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800526}
527
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700528void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700529 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800530 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400531 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800532 }
Ady Abraham8532d012019-05-08 14:50:56 -0700533}
534
Rachel Lee6a9731d2022-06-06 17:08:14 -0700535void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700536 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700537 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700538 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700539 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700540 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700541
542 if (mDisplayPowerTimer) {
543 mDisplayPowerTimer->reset();
544 }
545
546 // Display Power event will boost the refresh rate to performance.
547 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700548 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700549}
550
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700551void Scheduler::kernelIdleTimerCallback(TimerState state) {
552 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100553
Ady Abraham2139f732019-11-13 18:56:40 -0800554 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
555 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800556 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700557
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700558 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
559 using namespace fps_approx_ops;
560
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800561 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700562 // If we're not in performance mode then the kernel timer shouldn't do
563 // anything, as the refresh rate during DPU power collapse will be the
564 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800565 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
566 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700567 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
568 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700569 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700570 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700571 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800572
573 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700574}
575
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700576void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800577 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700578 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100579}
580
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700581void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700582 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700583 // Touch event will boost the refresh rate to performance.
584 // Clear layer history to get fresh FPS detection.
585 // NOTE: Instead of checking all the layers, we should be checking the layer
586 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800587 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700588 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700589 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700590 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700591}
592
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700593void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800594 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700595 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700596}
597
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400598void Scheduler::dump(utils::Dumper& dumper) const {
599 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700600
601 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400602 utils::Dumper::Section section(dumper, "Features"sv);
603
604 for (Feature feature : ftl::enum_range<Feature>()) {
605 if (const auto flagOpt = ftl::flag_name(feature)) {
606 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
607 }
608 }
609 }
610 {
611 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400612 {
613 std::scoped_lock lock(mDisplayLock);
614 ftl::FakeGuard guard(kMainThreadContext);
615 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
616 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400617 dumper.dump("layerHistory"sv, mLayerHistory.dump());
618 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
619 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
620 }
621
622 mFrameRateOverrideMappings.dump(dumper);
623 dumper.eol();
624
625 {
626 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
627
Ady Abraham4f960d12021-10-13 16:59:49 -0700628 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400629 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
630 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
631 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700632 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800633}
634
Dominik Laskowski068173d2021-08-11 17:22:59 -0700635void Scheduler::dumpVsync(std::string& out) const {
636 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700637}
638
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800639bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400640 if (consideredSignals.idle) return false;
641
642 const auto frameRateOverrides =
643 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
644 displayRefreshRate, consideredSignals);
645
646 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
647 // the FrameRateOverrideMappings rather than here.
648 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
649}
650
651void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
652 // TODO(b/241286431): Choose the leader display.
653 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
654 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
655
656 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
657 leaderPtr->setIdleTimerCallbacks(
658 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
659 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
660 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
661 .onExpired =
662 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
663
664 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800665 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400666}
667
668void Scheduler::demoteLeaderDisplay() {
669 // No need to lock for reads on kMainThreadContext.
670 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
671 leaderPtr->stopIdleTimer();
672 leaderPtr->clearIdleTimerCallbacks();
673 }
674
675 // Clear state that depends on the leader's RefreshRateSelector.
676 std::scoped_lock lock(mPolicyLock);
677 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800678}
679
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800680template <typename S, typename T>
681auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800682 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400683 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800684 GlobalSignals consideredSignals;
685
Ady Abraham62a0be22020-12-08 16:54:10 -0800686 bool refreshRateChanged = false;
687 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800688
Ady Abraham8532d012019-05-08 14:50:56 -0700689 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400690 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800691
692 auto& currentState = mPolicy.*statePtr;
693 if (currentState == newState) return {};
694 currentState = std::forward<T>(newState);
695
Dominik Laskowski596a2562022-10-28 11:26:12 -0400696 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800697 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400698 {
699 std::scoped_lock lock(mDisplayLock);
700 ftl::FakeGuard guard(kMainThreadContext);
701
702 modeChoices = chooseDisplayModes();
703
704 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
705 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800706 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400707 modeChoices.get(*mLeaderDisplayId)
708 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800709 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400710 })
711 .value();
712 }
ramindani69b58e82022-09-26 16:48:36 -0700713
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400714 modeRequests.reserve(modeChoices.size());
715 for (auto& [id, choice] : modeChoices) {
716 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800717 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400718 .emitEvent = !choice.consideredSignals.idle});
719 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800720
Ady Abrahamace3d052022-11-17 16:25:05 -0800721 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400722
Ady Abrahamace3d052022-11-17 16:25:05 -0800723 if (mPolicy.modeOpt != modeOpt) {
724 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400725 refreshRateChanged = true;
726 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100727 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800728 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700729 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100730 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700731 }
Ady Abraham8532d012019-05-08 14:50:56 -0700732 }
Ady Abraham8532d012019-05-08 14:50:56 -0700733 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800734 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400735 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800736 }
737 if (frameRateOverridesChanged) {
738 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
739 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800740 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700741}
742
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400743auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800744 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700745
Ady Abraham68636062022-11-16 17:07:25 -0800746 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400747 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400748
749 // Tallies the score of a refresh rate across `displayCount` displays.
750 struct RefreshRateTally {
751 explicit RefreshRateTally(float score) : score(score) {}
752
753 float score;
754 size_t displayCount = 1;
755 };
756
757 // Chosen to exceed a typical number of refresh rates across displays.
758 constexpr size_t kStaticCapacity = 8;
759 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
760
761 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800762
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400763 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800764 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800765 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700766
Ady Abrahamace3d052022-11-17 16:25:05 -0800767 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
768 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400769
770 if (!inserted) {
771 auto& tally = it->second;
772 tally.score += score;
773 tally.displayCount++;
774 }
775 }
776
Ady Abrahamace3d052022-11-17 16:25:05 -0800777 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400778 }
ramindani69b58e82022-09-26 16:48:36 -0700779
Dominik Laskowski01602522022-10-07 19:02:28 -0400780 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700781
Dominik Laskowski01602522022-10-07 19:02:28 -0400782 // Find the first refresh rate common to all displays.
783 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400784 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400785 ++maxScoreIt;
786 }
787
788 if (maxScoreIt != refreshRateTallies.cend()) {
789 // Choose the highest refresh rate common to all displays, if any.
790 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
791 const auto [fps, tally] = *it;
792
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400793 if (tally.displayCount == mRefreshRateSelectors.size() &&
794 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400795 maxScoreIt = it;
796 }
ramindani7c487282022-10-10 16:17:51 -0700797 }
798 }
ramindani69b58e82022-09-26 16:48:36 -0700799
Dominik Laskowski01602522022-10-07 19:02:28 -0400800 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
801 ? std::make_optional(maxScoreIt->first)
802 : std::nullopt;
803
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400804 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400805
ramindani69b58e82022-09-26 16:48:36 -0700806 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400807
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400808 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400809 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800810 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800811 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
812 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400813 continue;
814 }
815
Ady Abraham68636062022-11-16 17:07:25 -0800816 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800817 if (frameRateMode.fps == *chosenFps) {
818 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
819 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400820 break;
821 }
822 }
823 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400824 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700825}
826
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400827GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000828 const bool powerOnImminent = mDisplayPowerTimer &&
829 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
830 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700831
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400832 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
833 .idle = mPolicy.idleTimer == TimerState::Expired,
834 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800835}
836
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500837FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700838 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500839 const auto frameRateMode =
840 leaderSelectorPtr()
841 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
842 .ranking.front()
843 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400844
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500845 // Make sure the stored mode is up to date.
846 mPolicy.modeOpt = frameRateMode;
847
848 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700849}
850
Peiyong Line9d809e2020-04-14 13:10:48 -0700851void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800852 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
853 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
854
855 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
856 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
857 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
858 }
859}
860
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700861bool Scheduler::onPostComposition(nsecs_t presentTime) {
862 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
863 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
864 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
865 // We need to composite again as refreshTimeNanos is still in the future.
866 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700867 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700868
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700869 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800870 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700871 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800872}
873
Ady Abraham7825c682021-05-17 15:12:14 -0700874void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700875 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800876}
877
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800878void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
879 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
880 return;
881 }
882
883 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
884}
885
Ady Abraham62a0be22020-12-08 16:54:10 -0800886void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
887 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
888 return;
889 }
890
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800891 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800892}
893
Dominik Laskowski068173d2021-08-11 17:22:59 -0700894} // namespace android::scheduler