blob: b8b3f512856061fcabd2cb18b40f4369df1c3991 [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
Ady Abraham64c2fc02020-12-29 12:07:50 -0800176impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
Ady Abraham64c2fc02020-12-29 12:07:50 -0800177 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700178 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800179 };
180}
181
Jorim Jaggic0086af2021-02-12 18:18:11 +0100182impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
183 return [this](uid_t uid) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800184 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
Dominik Laskowski5d164f22022-07-07 07:56:07 -0700185 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800186
Jorim Jaggic0086af2021-02-12 18:18:11 +0100187 const auto frameRate = getFrameRateOverride(uid);
188 if (!frameRate.has_value()) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700189 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100190 }
191
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400192 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
Ady Abrahamcc315492022-02-17 17:06:39 -0800193 if (divisor <= 1) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700194 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100195 }
Rachel Lee73fe8152022-04-11 17:23:25 -0700196 return currentPeriod * divisor;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100197 };
198}
199
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500200ConnectionHandle Scheduler::createEventThread(Cycle cycle,
201 frametimeline::TokenManager* tokenManager,
202 std::chrono::nanoseconds workDuration,
203 std::chrono::nanoseconds readyDuration) {
204 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
205 *mVsyncSchedule, tokenManager,
206 makeThrottleVsyncCallback(),
207 makeGetVsyncPeriodFunction(),
208 workDuration, readyDuration);
209
210 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
211 handle = createConnection(std::move(eventThread));
212 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700213}
Ana Krulec98b5b242018-08-10 15:03:23 -0700214
Dominik Laskowski068173d2021-08-11 17:22:59 -0700215ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700216 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
217 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800218
Ady Abraham62f216c2020-10-13 19:07:23 -0700219 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700220
Ana Krulec6ddd2612020-09-24 13:06:33 -0700221 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700222 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
223 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700224}
225
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700226sp<EventThreadConnection> Scheduler::createConnectionInternal(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700227 EventThread* eventThread, EventRegistrationFlags eventRegistration) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700228 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700229}
230
Ana Krulec98b5b242018-08-10 15:03:23 -0700231sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700232 ConnectionHandle handle, EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700233 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700234 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700235 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700236}
237
Dominik Laskowski98041832019-08-01 18:35:59 -0700238sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700239 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700240 RETURN_IF_INVALID_HANDLE(handle, nullptr);
241 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700242}
243
Dominik Laskowski98041832019-08-01 18:35:59 -0700244void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
245 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700246 android::EventThread* thread;
247 {
248 std::lock_guard<std::mutex> lock(mConnectionsLock);
249 RETURN_IF_INVALID_HANDLE(handle);
250 thread = mConnections[handle].thread.get();
251 }
252
253 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700254}
255
Dominik Laskowski98041832019-08-01 18:35:59 -0700256void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700257 android::EventThread* thread;
258 {
259 std::lock_guard<std::mutex> lock(mConnectionsLock);
260 RETURN_IF_INVALID_HANDLE(handle);
261 thread = mConnections[handle].thread.get();
262 }
263 thread->onScreenAcquired();
Ady Abraham4f960d12021-10-13 16:59:49 -0700264 mScreenAcquired = true;
Ana Krulec98b5b242018-08-10 15:03:23 -0700265}
266
Dominik Laskowski98041832019-08-01 18:35:59 -0700267void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700268 android::EventThread* thread;
269 {
270 std::lock_guard<std::mutex> lock(mConnectionsLock);
271 RETURN_IF_INVALID_HANDLE(handle);
272 thread = mConnections[handle].thread.get();
273 }
274 thread->onScreenReleased();
Ady Abraham4f960d12021-10-13 16:59:49 -0700275 mScreenAcquired = false;
Ana Krulec98b5b242018-08-10 15:03:23 -0700276}
277
Ady Abraham62a0be22020-12-08 16:54:10 -0800278void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800279 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800280 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800281
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800282 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800283 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800284
Ady Abraham62f216c2020-10-13 19:07:23 -0700285 android::EventThread* thread;
286 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800287 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700288 RETURN_IF_INVALID_HANDLE(handle);
289 thread = mConnections[handle].thread.get();
290 }
291 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
292}
293
Ady Abrahamace3d052022-11-17 16:25:05 -0800294void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800295 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700296 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100297 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700298 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700299
300 // Invalidate content based refresh rate selection so it could be calculated
301 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700302 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800303 }
Ady Abraham690f4612021-07-01 23:24:03 -0700304 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700305}
306
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100307void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700308 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800309 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100310 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700311 return;
312 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700313 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100314 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700315 return;
316 }
317
Ady Abrahamd1591702021-07-27 16:27:56 -0700318 // If the mode is not the current mode, this means that a
319 // mode change is in progress. In that case we shouldn't dispatch an event
320 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800321 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700322 return;
323 }
324
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100325 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800326 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700327 return;
328 }
329
Ady Abrahamace3d052022-11-17 16:25:05 -0800330 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700331 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
332 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700333}
334
Ady Abrahamace3d052022-11-17 16:25:05 -0800335void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700336 android::EventThread* thread;
337 {
338 std::lock_guard<std::mutex> lock(mConnectionsLock);
339 RETURN_IF_INVALID_HANDLE(handle);
340 thread = mConnections[handle].thread.get();
341 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800342 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800343}
344
Alec Mouri717bcb62020-02-10 17:07:19 -0800345size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700346 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800347 RETURN_IF_INVALID_HANDLE(handle, 0);
348 return mConnections[handle].thread->getEventThreadConnectionCount();
349}
350
Dominik Laskowski98041832019-08-01 18:35:59 -0700351void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700352 android::EventThread* thread;
353 {
354 std::lock_guard<std::mutex> lock(mConnectionsLock);
355 RETURN_IF_INVALID_HANDLE(handle);
356 thread = mConnections.at(handle).thread.get();
357 }
358 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700359}
360
Ady Abraham9c53ee72020-07-22 21:16:18 -0700361void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
362 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700363 android::EventThread* thread;
364 {
365 std::lock_guard<std::mutex> lock(mConnectionsLock);
366 RETURN_IF_INVALID_HANDLE(handle);
367 thread = mConnections[handle].thread.get();
368 }
369 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700370}
Ana Krulece588e312018-09-18 12:32:24 -0700371
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500372void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
373 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
374}
375
376void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
377 setDuration(mAppConnectionHandle,
378 /* workDuration */ config.appWorkDuration,
379 /* readyDuration */ config.sfWorkDuration);
380 setDuration(mSfConnectionHandle,
381 /* workDuration */ vsyncPeriod,
382 /* readyDuration */ config.sfWorkDuration);
383 setDuration(config.sfWorkDuration);
384}
385
Ana Krulece588e312018-09-18 12:32:24 -0700386void Scheduler::enableHardwareVsync() {
387 std::lock_guard<std::mutex> lock(mHWVsyncLock);
388 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700389 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700390 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700391 mPrimaryHWVsyncEnabled = true;
392 }
393}
394
395void Scheduler::disableHardwareVsync(bool makeUnavailable) {
396 std::lock_guard<std::mutex> lock(mHWVsyncLock);
397 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700398 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700399 mPrimaryHWVsyncEnabled = false;
400 }
401 if (makeUnavailable) {
402 mHWVsyncAvailable = false;
403 }
404}
405
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800406void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
Ana Krulecc2870422019-01-29 19:00:58 -0800407 {
408 std::lock_guard<std::mutex> lock(mHWVsyncLock);
409 if (makeAvailable) {
410 mHWVsyncAvailable = makeAvailable;
411 } else if (!mHWVsyncAvailable) {
412 // Hardware vsync is not currently available, so abort the resync
413 // attempt for now
414 return;
415 }
416 }
417
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800418 setVsyncPeriod(refreshRate.getPeriodNsecs());
Ana Krulecc2870422019-01-29 19:00:58 -0800419}
420
Ady Abrahamace3d052022-11-17 16:25:05 -0800421void Scheduler::setRenderRate(Fps renderFrameRate) {
422 const auto mode = leaderSelectorPtr()->getActiveMode();
423
424 using fps_approx_ops::operator!=;
425 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
426 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
427 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
428
429 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
430 to_string(mode.modePtr->getFps()).c_str());
431
432 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
433 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
434 to_string(mode.fps).c_str());
435
436 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
437}
438
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700439void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700440 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800441
442 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700443 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800444
445 if (now - last > kIgnoreDelay) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800446 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800447 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800448 }
449}
450
Dominik Laskowski98041832019-08-01 18:35:59 -0700451void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800452 if (period <= 0) return;
453
Ady Abraham3aff9172019-02-07 19:10:26 -0800454 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700455 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800456
457 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700458 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700459 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800460 mPrimaryHWVsyncEnabled = true;
461 }
Ana Krulece588e312018-09-18 12:32:24 -0700462}
463
Ady Abraham5dee2f12020-02-05 17:49:47 -0800464void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
465 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700466 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700467 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700468 { // Scope for the lock
469 std::lock_guard<std::mutex> lock(mHWVsyncLock);
470 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700471 needsHwVsync =
472 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
473 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700474 }
475 }
476
477 if (needsHwVsync) {
478 enableHardwareVsync();
479 } else {
480 disableHardwareVsync(false);
481 }
482}
483
Dominik Laskowski068173d2021-08-11 17:22:59 -0700484void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
485 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700486 enableHardwareVsync();
487 } else {
488 disableHardwareVsync(false);
489 }
490}
491
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700492void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200493 // If the content detection feature is off, we still keep the layer history,
494 // since we use it for other features (like Frame Rate API), so layers
495 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000496 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700497}
498
Ady Abrahambdda8f02021-04-01 16:06:11 -0700499void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700500 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700501}
502
Ady Abraham5def7332020-05-29 16:13:47 -0700503void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
504 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400505 if (leaderSelectorPtr()->canSwitch()) {
506 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800507 }
Ana Krulec3084c052018-11-21 20:27:17 +0100508}
509
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100510void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700511 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700512}
513
Andy Labrada096227e2022-06-15 16:58:11 +0000514void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
515 mLayerHistory.setDefaultFrameRateCompatibility(layer,
516 mFeatures.test(Feature::kContentDetection));
517}
518
Dominik Laskowski49cea512019-11-12 14:13:23 -0800519void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400520 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400521 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800522
Ady Abraham8a82ba62020-01-17 12:43:17 -0800523 ATRACE_CALL();
524
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400525 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800526 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800527}
528
Ana Krulecfb772822018-11-30 10:44:07 +0100529void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400530 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800531}
532
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700533void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700534 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800535 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400536 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800537 }
Ady Abraham8532d012019-05-08 14:50:56 -0700538}
539
Rachel Lee6a9731d2022-06-06 17:08:14 -0700540void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700541 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700542 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700543 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700544 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700545 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700546
547 if (mDisplayPowerTimer) {
548 mDisplayPowerTimer->reset();
549 }
550
551 // Display Power event will boost the refresh rate to performance.
552 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700553 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700554}
555
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700556void Scheduler::kernelIdleTimerCallback(TimerState state) {
557 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100558
Ady Abraham2139f732019-11-13 18:56:40 -0800559 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
560 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800561 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700562
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700563 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
564 using namespace fps_approx_ops;
565
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800566 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700567 // If we're not in performance mode then the kernel timer shouldn't do
568 // anything, as the refresh rate during DPU power collapse will be the
569 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800570 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
571 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700572 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
573 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700574 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700575 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700576 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800577
578 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700579}
580
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700581void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800582 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700583 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100584}
585
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700586void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700587 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700588 // Touch event will boost the refresh rate to performance.
589 // Clear layer history to get fresh FPS detection.
590 // NOTE: Instead of checking all the layers, we should be checking the layer
591 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800592 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700593 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700594 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700595 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700596}
597
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700598void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800599 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700600 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700601}
602
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400603void Scheduler::dump(utils::Dumper& dumper) const {
604 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700605
606 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400607 utils::Dumper::Section section(dumper, "Features"sv);
608
609 for (Feature feature : ftl::enum_range<Feature>()) {
610 if (const auto flagOpt = ftl::flag_name(feature)) {
611 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
612 }
613 }
614 }
615 {
616 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400617 {
618 std::scoped_lock lock(mDisplayLock);
619 ftl::FakeGuard guard(kMainThreadContext);
620 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
621 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400622 dumper.dump("layerHistory"sv, mLayerHistory.dump());
623 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
624 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
625 }
626
627 mFrameRateOverrideMappings.dump(dumper);
628 dumper.eol();
629
630 {
631 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
632
Ady Abraham4f960d12021-10-13 16:59:49 -0700633 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400634 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
635 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
636 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700637 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800638}
639
Dominik Laskowski068173d2021-08-11 17:22:59 -0700640void Scheduler::dumpVsync(std::string& out) const {
641 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700642}
643
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800644bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400645 if (consideredSignals.idle) return false;
646
647 const auto frameRateOverrides =
648 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
649 displayRefreshRate, consideredSignals);
650
651 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
652 // the FrameRateOverrideMappings rather than here.
653 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
654}
655
656void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
657 // TODO(b/241286431): Choose the leader display.
658 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
659 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
660
661 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
662 leaderPtr->setIdleTimerCallbacks(
663 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
664 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
665 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
666 .onExpired =
667 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
668
669 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800670 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400671}
672
673void Scheduler::demoteLeaderDisplay() {
674 // No need to lock for reads on kMainThreadContext.
675 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
676 leaderPtr->stopIdleTimer();
677 leaderPtr->clearIdleTimerCallbacks();
678 }
679
680 // Clear state that depends on the leader's RefreshRateSelector.
681 std::scoped_lock lock(mPolicyLock);
682 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800683}
684
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800685template <typename S, typename T>
686auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800687 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400688 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800689 GlobalSignals consideredSignals;
690
Ady Abraham62a0be22020-12-08 16:54:10 -0800691 bool refreshRateChanged = false;
692 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800693
Ady Abraham8532d012019-05-08 14:50:56 -0700694 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400695 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800696
697 auto& currentState = mPolicy.*statePtr;
698 if (currentState == newState) return {};
699 currentState = std::forward<T>(newState);
700
Dominik Laskowski596a2562022-10-28 11:26:12 -0400701 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800702 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400703 {
704 std::scoped_lock lock(mDisplayLock);
705 ftl::FakeGuard guard(kMainThreadContext);
706
707 modeChoices = chooseDisplayModes();
708
709 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
710 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800711 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400712 modeChoices.get(*mLeaderDisplayId)
713 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800714 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400715 })
716 .value();
717 }
ramindani69b58e82022-09-26 16:48:36 -0700718
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400719 modeRequests.reserve(modeChoices.size());
720 for (auto& [id, choice] : modeChoices) {
721 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800722 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400723 .emitEvent = !choice.consideredSignals.idle});
724 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800725
Ady Abrahamace3d052022-11-17 16:25:05 -0800726 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400727
Ady Abrahamace3d052022-11-17 16:25:05 -0800728 if (mPolicy.modeOpt != modeOpt) {
729 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400730 refreshRateChanged = true;
731 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100732 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800733 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700734 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100735 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700736 }
Ady Abraham8532d012019-05-08 14:50:56 -0700737 }
Ady Abraham8532d012019-05-08 14:50:56 -0700738 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800739 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400740 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800741 }
742 if (frameRateOverridesChanged) {
743 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
744 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800745 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700746}
747
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400748auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800749 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700750
Ady Abraham68636062022-11-16 17:07:25 -0800751 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400752 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400753
754 // Tallies the score of a refresh rate across `displayCount` displays.
755 struct RefreshRateTally {
756 explicit RefreshRateTally(float score) : score(score) {}
757
758 float score;
759 size_t displayCount = 1;
760 };
761
762 // Chosen to exceed a typical number of refresh rates across displays.
763 constexpr size_t kStaticCapacity = 8;
764 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
765
766 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800767
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400768 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800769 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800770 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700771
Ady Abrahamace3d052022-11-17 16:25:05 -0800772 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
773 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400774
775 if (!inserted) {
776 auto& tally = it->second;
777 tally.score += score;
778 tally.displayCount++;
779 }
780 }
781
Ady Abrahamace3d052022-11-17 16:25:05 -0800782 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400783 }
ramindani69b58e82022-09-26 16:48:36 -0700784
Dominik Laskowski01602522022-10-07 19:02:28 -0400785 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700786
Dominik Laskowski01602522022-10-07 19:02:28 -0400787 // Find the first refresh rate common to all displays.
788 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400789 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400790 ++maxScoreIt;
791 }
792
793 if (maxScoreIt != refreshRateTallies.cend()) {
794 // Choose the highest refresh rate common to all displays, if any.
795 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
796 const auto [fps, tally] = *it;
797
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400798 if (tally.displayCount == mRefreshRateSelectors.size() &&
799 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400800 maxScoreIt = it;
801 }
ramindani7c487282022-10-10 16:17:51 -0700802 }
803 }
ramindani69b58e82022-09-26 16:48:36 -0700804
Dominik Laskowski01602522022-10-07 19:02:28 -0400805 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
806 ? std::make_optional(maxScoreIt->first)
807 : std::nullopt;
808
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400809 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400810
ramindani69b58e82022-09-26 16:48:36 -0700811 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400812
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400813 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400814 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800815 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800816 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
817 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400818 continue;
819 }
820
Ady Abraham68636062022-11-16 17:07:25 -0800821 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800822 if (frameRateMode.fps == *chosenFps) {
823 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
824 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400825 break;
826 }
827 }
828 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400829 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700830}
831
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400832GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000833 const bool powerOnImminent = mDisplayPowerTimer &&
834 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
835 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700836
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400837 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
838 .idle = mPolicy.idleTimer == TimerState::Expired,
839 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800840}
841
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500842FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700843 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500844 const auto frameRateMode =
845 leaderSelectorPtr()
846 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
847 .ranking.front()
848 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400849
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500850 // Make sure the stored mode is up to date.
851 mPolicy.modeOpt = frameRateMode;
852
853 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700854}
855
Peiyong Line9d809e2020-04-14 13:10:48 -0700856void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800857 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
858 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
859
860 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
861 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
862 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
863 }
864}
865
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700866bool Scheduler::onPostComposition(nsecs_t presentTime) {
867 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
868 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
869 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
870 // We need to composite again as refreshTimeNanos is still in the future.
871 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700872 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700873
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700874 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800875 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700876 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800877}
878
Ady Abraham7825c682021-05-17 15:12:14 -0700879void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700880 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800881}
882
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800883void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
884 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
885 return;
886 }
887
888 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
889}
890
Ady Abraham62a0be22020-12-08 16:54:10 -0800891void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
892 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
893 return;
894 }
895
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800896 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800897}
898
Dominik Laskowski068173d2021-08-11 17:22:59 -0700899} // namespace android::scheduler