blob: 33c98ff6d57d16a9514d6c86ba929765111d2f61 [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
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500130 // Do not allow removing the final display. Code in the scheduler expects
131 // there to be at least one display. (This may be relaxed in the future with
132 // headless virtual display.)
133 LOG_ALWAYS_FATAL_IF(mRefreshRateSelectors.empty(), "Cannot unregister all displays!");
134
Dominik Laskowski596a2562022-10-28 11:26:12 -0400135 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400136}
137
Dominik Laskowski756b7892021-08-04 12:53:59 -0700138void Scheduler::run() {
139 while (true) {
140 waitMessage();
141 }
142}
143
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700144void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
145 TimePoint expectedVsyncTime) {
146 const TimePoint frameTime = SchedulerClock::now();
147
148 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
149 return;
150 }
151
152 compositor.composite(frameTime, vsyncId);
153 compositor.sample();
154}
155
Dominik Laskowski068173d2021-08-11 17:22:59 -0700156void Scheduler::createVsyncSchedule(FeatureFlags features) {
157 mVsyncSchedule.emplace(features);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700158}
159
Ady Abraham62a0be22020-12-08 16:54:10 -0800160std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800161 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800162 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800163 return mFrameRateOverrideMappings
164 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800165}
166
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700167bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800168 const auto frameRate = getFrameRateOverride(uid);
169 if (!frameRate.has_value()) {
170 return true;
171 }
172
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700173 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700174}
175
Huihong Luo1768cb02022-10-11 11:10:34 -0700176bool Scheduler::isVsyncInPhase(TimePoint timePoint, const Fps frameRate) const {
177 return mVsyncSchedule->getTracker().isVSyncInPhase(timePoint.ns(), frameRate);
178}
179
Ady Abraham64c2fc02020-12-29 12:07:50 -0800180impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
Ady Abraham64c2fc02020-12-29 12:07:50 -0800181 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700182 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800183 };
184}
185
Jorim Jaggic0086af2021-02-12 18:18:11 +0100186impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
187 return [this](uid_t uid) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800188 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
Dominik Laskowski5d164f22022-07-07 07:56:07 -0700189 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800190
Jorim Jaggic0086af2021-02-12 18:18:11 +0100191 const auto frameRate = getFrameRateOverride(uid);
192 if (!frameRate.has_value()) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700193 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100194 }
195
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400196 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
Ady Abrahamcc315492022-02-17 17:06:39 -0800197 if (divisor <= 1) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700198 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100199 }
Rachel Lee73fe8152022-04-11 17:23:25 -0700200 return currentPeriod * divisor;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100201 };
202}
203
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500204ConnectionHandle Scheduler::createEventThread(Cycle cycle,
205 frametimeline::TokenManager* tokenManager,
206 std::chrono::nanoseconds workDuration,
207 std::chrono::nanoseconds readyDuration) {
208 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
209 *mVsyncSchedule, tokenManager,
210 makeThrottleVsyncCallback(),
211 makeGetVsyncPeriodFunction(),
212 workDuration, readyDuration);
213
214 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
215 handle = createConnection(std::move(eventThread));
216 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700217}
Ana Krulec98b5b242018-08-10 15:03:23 -0700218
Dominik Laskowski068173d2021-08-11 17:22:59 -0700219ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700220 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
221 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800222
Ady Abraham62f216c2020-10-13 19:07:23 -0700223 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700224
Ana Krulec6ddd2612020-09-24 13:06:33 -0700225 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700226 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
227 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700228}
229
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700230sp<EventThreadConnection> Scheduler::createConnectionInternal(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700231 EventThread* eventThread, EventRegistrationFlags eventRegistration) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700232 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700233}
234
Ana Krulec98b5b242018-08-10 15:03:23 -0700235sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700236 ConnectionHandle handle, EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700237 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700238 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700239 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700240}
241
Dominik Laskowski98041832019-08-01 18:35:59 -0700242sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700243 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700244 RETURN_IF_INVALID_HANDLE(handle, nullptr);
245 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700246}
247
Dominik Laskowski98041832019-08-01 18:35:59 -0700248void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
249 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700250 android::EventThread* thread;
251 {
252 std::lock_guard<std::mutex> lock(mConnectionsLock);
253 RETURN_IF_INVALID_HANDLE(handle);
254 thread = mConnections[handle].thread.get();
255 }
256
257 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700258}
259
Dominik Laskowski98041832019-08-01 18:35:59 -0700260void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700261 android::EventThread* thread;
262 {
263 std::lock_guard<std::mutex> lock(mConnectionsLock);
264 RETURN_IF_INVALID_HANDLE(handle);
265 thread = mConnections[handle].thread.get();
266 }
267 thread->onScreenAcquired();
Ady Abraham4f960d12021-10-13 16:59:49 -0700268 mScreenAcquired = true;
Ana Krulec98b5b242018-08-10 15:03:23 -0700269}
270
Dominik Laskowski98041832019-08-01 18:35:59 -0700271void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700272 android::EventThread* thread;
273 {
274 std::lock_guard<std::mutex> lock(mConnectionsLock);
275 RETURN_IF_INVALID_HANDLE(handle);
276 thread = mConnections[handle].thread.get();
277 }
278 thread->onScreenReleased();
Ady Abraham4f960d12021-10-13 16:59:49 -0700279 mScreenAcquired = false;
Ana Krulec98b5b242018-08-10 15:03:23 -0700280}
281
Ady Abraham62a0be22020-12-08 16:54:10 -0800282void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800283 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800284 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800285
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800286 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800287 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800288
Ady Abraham62f216c2020-10-13 19:07:23 -0700289 android::EventThread* thread;
290 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800291 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700292 RETURN_IF_INVALID_HANDLE(handle);
293 thread = mConnections[handle].thread.get();
294 }
295 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
296}
297
Ady Abrahamace3d052022-11-17 16:25:05 -0800298void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800299 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700300 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100301 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700302 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700303
304 // Invalidate content based refresh rate selection so it could be calculated
305 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700306 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800307 }
Ady Abraham690f4612021-07-01 23:24:03 -0700308 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700309}
310
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100311void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700312 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800313 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100314 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700315 return;
316 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700317 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100318 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700319 return;
320 }
321
Ady Abrahamd1591702021-07-27 16:27:56 -0700322 // If the mode is not the current mode, this means that a
323 // mode change is in progress. In that case we shouldn't dispatch an event
324 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800325 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700326 return;
327 }
328
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100329 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800330 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700331 return;
332 }
333
Ady Abrahamace3d052022-11-17 16:25:05 -0800334 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700335 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
336 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700337}
338
Ady Abrahamace3d052022-11-17 16:25:05 -0800339void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700340 android::EventThread* thread;
341 {
342 std::lock_guard<std::mutex> lock(mConnectionsLock);
343 RETURN_IF_INVALID_HANDLE(handle);
344 thread = mConnections[handle].thread.get();
345 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800346 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800347}
348
Alec Mouri717bcb62020-02-10 17:07:19 -0800349size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700350 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800351 RETURN_IF_INVALID_HANDLE(handle, 0);
352 return mConnections[handle].thread->getEventThreadConnectionCount();
353}
354
Dominik Laskowski98041832019-08-01 18:35:59 -0700355void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700356 android::EventThread* thread;
357 {
358 std::lock_guard<std::mutex> lock(mConnectionsLock);
359 RETURN_IF_INVALID_HANDLE(handle);
360 thread = mConnections.at(handle).thread.get();
361 }
362 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700363}
364
Ady Abraham9c53ee72020-07-22 21:16:18 -0700365void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
366 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700367 android::EventThread* thread;
368 {
369 std::lock_guard<std::mutex> lock(mConnectionsLock);
370 RETURN_IF_INVALID_HANDLE(handle);
371 thread = mConnections[handle].thread.get();
372 }
373 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700374}
Ana Krulece588e312018-09-18 12:32:24 -0700375
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500376void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
377 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
378}
379
380void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
381 setDuration(mAppConnectionHandle,
382 /* workDuration */ config.appWorkDuration,
383 /* readyDuration */ config.sfWorkDuration);
384 setDuration(mSfConnectionHandle,
385 /* workDuration */ vsyncPeriod,
386 /* readyDuration */ config.sfWorkDuration);
387 setDuration(config.sfWorkDuration);
388}
389
Ana Krulece588e312018-09-18 12:32:24 -0700390void Scheduler::enableHardwareVsync() {
391 std::lock_guard<std::mutex> lock(mHWVsyncLock);
392 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700393 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700394 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700395 mPrimaryHWVsyncEnabled = true;
396 }
397}
398
399void Scheduler::disableHardwareVsync(bool makeUnavailable) {
400 std::lock_guard<std::mutex> lock(mHWVsyncLock);
401 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700402 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700403 mPrimaryHWVsyncEnabled = false;
404 }
405 if (makeUnavailable) {
406 mHWVsyncAvailable = false;
407 }
408}
409
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800410void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
Ana Krulecc2870422019-01-29 19:00:58 -0800411 {
412 std::lock_guard<std::mutex> lock(mHWVsyncLock);
413 if (makeAvailable) {
414 mHWVsyncAvailable = makeAvailable;
415 } else if (!mHWVsyncAvailable) {
416 // Hardware vsync is not currently available, so abort the resync
417 // attempt for now
418 return;
419 }
420 }
421
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800422 setVsyncPeriod(refreshRate.getPeriodNsecs());
Ana Krulecc2870422019-01-29 19:00:58 -0800423}
424
Ady Abrahamace3d052022-11-17 16:25:05 -0800425void Scheduler::setRenderRate(Fps renderFrameRate) {
426 const auto mode = leaderSelectorPtr()->getActiveMode();
427
428 using fps_approx_ops::operator!=;
429 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
430 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
431 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
432
433 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
434 to_string(mode.modePtr->getFps()).c_str());
435
436 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
437 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
438 to_string(mode.fps).c_str());
439
440 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
441}
442
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700443void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700444 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800445
446 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700447 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800448
449 if (now - last > kIgnoreDelay) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800450 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800451 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800452 }
453}
454
Dominik Laskowski98041832019-08-01 18:35:59 -0700455void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800456 if (period <= 0) return;
457
Ady Abraham3aff9172019-02-07 19:10:26 -0800458 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700459 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800460
461 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700462 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700463 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800464 mPrimaryHWVsyncEnabled = true;
465 }
Ana Krulece588e312018-09-18 12:32:24 -0700466}
467
Ady Abraham5dee2f12020-02-05 17:49:47 -0800468void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
469 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700470 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700471 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700472 { // Scope for the lock
473 std::lock_guard<std::mutex> lock(mHWVsyncLock);
474 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700475 needsHwVsync =
476 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
477 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700478 }
479 }
480
481 if (needsHwVsync) {
482 enableHardwareVsync();
483 } else {
484 disableHardwareVsync(false);
485 }
486}
487
Dominik Laskowski068173d2021-08-11 17:22:59 -0700488void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
489 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700490 enableHardwareVsync();
491 } else {
492 disableHardwareVsync(false);
493 }
494}
495
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700496void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200497 // If the content detection feature is off, we still keep the layer history,
498 // since we use it for other features (like Frame Rate API), so layers
499 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000500 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700501}
502
Ady Abrahambdda8f02021-04-01 16:06:11 -0700503void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700504 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700505}
506
Ady Abraham5def7332020-05-29 16:13:47 -0700507void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
508 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400509 if (leaderSelectorPtr()->canSwitch()) {
510 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800511 }
Ana Krulec3084c052018-11-21 20:27:17 +0100512}
513
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100514void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700515 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700516}
517
Andy Labrada096227e2022-06-15 16:58:11 +0000518void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
519 mLayerHistory.setDefaultFrameRateCompatibility(layer,
520 mFeatures.test(Feature::kContentDetection));
521}
522
Dominik Laskowski49cea512019-11-12 14:13:23 -0800523void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400524 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400525 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800526
Ady Abraham8a82ba62020-01-17 12:43:17 -0800527 ATRACE_CALL();
528
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400529 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800530 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800531}
532
Ana Krulecfb772822018-11-30 10:44:07 +0100533void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400534 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800535}
536
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700537void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700538 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800539 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400540 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800541 }
Ady Abraham8532d012019-05-08 14:50:56 -0700542}
543
Rachel Lee6a9731d2022-06-06 17:08:14 -0700544void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700545 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700546 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700547 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700548 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700549 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700550
551 if (mDisplayPowerTimer) {
552 mDisplayPowerTimer->reset();
553 }
554
555 // Display Power event will boost the refresh rate to performance.
556 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700557 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700558}
559
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700560void Scheduler::kernelIdleTimerCallback(TimerState state) {
561 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100562
Ady Abraham2139f732019-11-13 18:56:40 -0800563 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
564 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800565 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700566
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700567 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
568 using namespace fps_approx_ops;
569
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800570 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700571 // If we're not in performance mode then the kernel timer shouldn't do
572 // anything, as the refresh rate during DPU power collapse will be the
573 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800574 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
575 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700576 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
577 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700578 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700579 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700580 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800581
582 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700583}
584
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700585void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800586 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700587 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100588}
589
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700590void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700591 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700592 // Touch event will boost the refresh rate to performance.
593 // Clear layer history to get fresh FPS detection.
594 // NOTE: Instead of checking all the layers, we should be checking the layer
595 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800596 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700597 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700598 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700599 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700600}
601
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700602void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800603 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700604 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700605}
606
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400607void Scheduler::dump(utils::Dumper& dumper) const {
608 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700609
610 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400611 utils::Dumper::Section section(dumper, "Features"sv);
612
613 for (Feature feature : ftl::enum_range<Feature>()) {
614 if (const auto flagOpt = ftl::flag_name(feature)) {
615 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
616 }
617 }
618 }
619 {
620 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400621 {
622 std::scoped_lock lock(mDisplayLock);
623 ftl::FakeGuard guard(kMainThreadContext);
624 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
625 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400626 dumper.dump("layerHistory"sv, mLayerHistory.dump());
627 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
628 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
629 }
630
631 mFrameRateOverrideMappings.dump(dumper);
632 dumper.eol();
633
634 {
635 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
636
Ady Abraham4f960d12021-10-13 16:59:49 -0700637 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400638 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
639 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
640 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700641 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800642}
643
Dominik Laskowski068173d2021-08-11 17:22:59 -0700644void Scheduler::dumpVsync(std::string& out) const {
645 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700646}
647
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800648bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400649 if (consideredSignals.idle) return false;
650
651 const auto frameRateOverrides =
652 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
653 displayRefreshRate, consideredSignals);
654
655 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
656 // the FrameRateOverrideMappings rather than here.
657 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
658}
659
660void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
661 // TODO(b/241286431): Choose the leader display.
662 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
663 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
664
665 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
666 leaderPtr->setIdleTimerCallbacks(
667 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
668 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
669 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
670 .onExpired =
671 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
672
673 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800674 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400675}
676
677void Scheduler::demoteLeaderDisplay() {
678 // No need to lock for reads on kMainThreadContext.
679 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
680 leaderPtr->stopIdleTimer();
681 leaderPtr->clearIdleTimerCallbacks();
682 }
683
684 // Clear state that depends on the leader's RefreshRateSelector.
685 std::scoped_lock lock(mPolicyLock);
686 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800687}
688
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800689template <typename S, typename T>
690auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800691 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400692 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800693 GlobalSignals consideredSignals;
694
Ady Abraham62a0be22020-12-08 16:54:10 -0800695 bool refreshRateChanged = false;
696 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800697
Ady Abraham8532d012019-05-08 14:50:56 -0700698 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400699 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800700
701 auto& currentState = mPolicy.*statePtr;
702 if (currentState == newState) return {};
703 currentState = std::forward<T>(newState);
704
Dominik Laskowski596a2562022-10-28 11:26:12 -0400705 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800706 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400707 {
708 std::scoped_lock lock(mDisplayLock);
709 ftl::FakeGuard guard(kMainThreadContext);
710
711 modeChoices = chooseDisplayModes();
712
713 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
714 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800715 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400716 modeChoices.get(*mLeaderDisplayId)
717 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800718 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400719 })
720 .value();
721 }
ramindani69b58e82022-09-26 16:48:36 -0700722
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400723 modeRequests.reserve(modeChoices.size());
724 for (auto& [id, choice] : modeChoices) {
725 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800726 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400727 .emitEvent = !choice.consideredSignals.idle});
728 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800729
Ady Abrahamace3d052022-11-17 16:25:05 -0800730 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400731
Ady Abrahamace3d052022-11-17 16:25:05 -0800732 if (mPolicy.modeOpt != modeOpt) {
733 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400734 refreshRateChanged = true;
735 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100736 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800737 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700738 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100739 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700740 }
Ady Abraham8532d012019-05-08 14:50:56 -0700741 }
Ady Abraham8532d012019-05-08 14:50:56 -0700742 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800743 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400744 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800745 }
746 if (frameRateOverridesChanged) {
747 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
748 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800749 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700750}
751
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400752auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800753 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700754
Ady Abraham68636062022-11-16 17:07:25 -0800755 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400756 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400757
758 // Tallies the score of a refresh rate across `displayCount` displays.
759 struct RefreshRateTally {
760 explicit RefreshRateTally(float score) : score(score) {}
761
762 float score;
763 size_t displayCount = 1;
764 };
765
766 // Chosen to exceed a typical number of refresh rates across displays.
767 constexpr size_t kStaticCapacity = 8;
768 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
769
770 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800771
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400772 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800773 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800774 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700775
Ady Abrahamace3d052022-11-17 16:25:05 -0800776 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
777 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400778
779 if (!inserted) {
780 auto& tally = it->second;
781 tally.score += score;
782 tally.displayCount++;
783 }
784 }
785
Ady Abrahamace3d052022-11-17 16:25:05 -0800786 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400787 }
ramindani69b58e82022-09-26 16:48:36 -0700788
Dominik Laskowski01602522022-10-07 19:02:28 -0400789 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700790
Dominik Laskowski01602522022-10-07 19:02:28 -0400791 // Find the first refresh rate common to all displays.
792 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400793 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400794 ++maxScoreIt;
795 }
796
797 if (maxScoreIt != refreshRateTallies.cend()) {
798 // Choose the highest refresh rate common to all displays, if any.
799 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
800 const auto [fps, tally] = *it;
801
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400802 if (tally.displayCount == mRefreshRateSelectors.size() &&
803 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400804 maxScoreIt = it;
805 }
ramindani7c487282022-10-10 16:17:51 -0700806 }
807 }
ramindani69b58e82022-09-26 16:48:36 -0700808
Dominik Laskowski01602522022-10-07 19:02:28 -0400809 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
810 ? std::make_optional(maxScoreIt->first)
811 : std::nullopt;
812
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400813 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400814
ramindani69b58e82022-09-26 16:48:36 -0700815 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400816
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400817 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400818 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800819 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800820 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
821 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400822 continue;
823 }
824
Ady Abraham68636062022-11-16 17:07:25 -0800825 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800826 if (frameRateMode.fps == *chosenFps) {
827 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
828 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400829 break;
830 }
831 }
832 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400833 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700834}
835
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400836GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000837 const bool powerOnImminent = mDisplayPowerTimer &&
838 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
839 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700840
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400841 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
842 .idle = mPolicy.idleTimer == TimerState::Expired,
843 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800844}
845
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500846FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700847 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500848 const auto frameRateMode =
849 leaderSelectorPtr()
850 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
851 .ranking.front()
852 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400853
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500854 // Make sure the stored mode is up to date.
855 mPolicy.modeOpt = frameRateMode;
856
857 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700858}
859
Peiyong Line9d809e2020-04-14 13:10:48 -0700860void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800861 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
862 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
863
864 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
865 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
866 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
867 }
868}
869
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700870bool Scheduler::onPostComposition(nsecs_t presentTime) {
871 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
872 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
873 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
874 // We need to composite again as refreshTimeNanos is still in the future.
875 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700876 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700877
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700878 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800879 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700880 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800881}
882
Ady Abraham7825c682021-05-17 15:12:14 -0700883void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700884 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800885}
886
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800887void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
888 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
889 return;
890 }
891
892 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
893}
894
Ady Abraham62a0be22020-12-08 16:54:10 -0800895void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
896 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
897 return;
898 }
899
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800900 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800901}
902
Dominik Laskowski068173d2021-08-11 17:22:59 -0700903} // namespace android::scheduler