blob: 1fc15199829a08c6d231073ebe3f205e39b4982d [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dominik Laskowski98041832019-08-01 18:35:59 -070017#undef LOG_TAG
18#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Ana Krulec98b5b242018-08-10 15:03:23 -070021#include "Scheduler.h"
22
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070023#include <android-base/properties.h>
Dominik Laskowski49cea512019-11-12 14:13:23 -080024#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070025#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070027#include <configstore/Utils.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040028#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000029#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040030#include <ftl/small_map.h>
chaviw3277faf2021-05-19 16:45:23 -050031#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080032#include <system/window.h>
Ana Krulec3084c052018-11-21 20:27:17 +010033#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010034#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070035
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070036#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070037#include <algorithm>
38#include <cinttypes>
39#include <cstdint>
40#include <functional>
41#include <memory>
42#include <numeric>
43
44#include "../Layer.h"
Dominik Laskowski01602522022-10-07 19:02:28 -040045#include "Display/DisplayMap.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070046#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080047#include "FrameRateOverrideMappings.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070048#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090049#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080050#include "VSyncPredictor.h"
51#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070052
Dominik Laskowski98041832019-08-01 18:35:59 -070053#define RETURN_IF_INVALID_HANDLE(handle, ...) \
54 do { \
55 if (mConnections.count(handle) == 0) { \
56 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
57 return __VA_ARGS__; \
58 } \
59 } while (false)
60
Dominik Laskowski068173d2021-08-11 17:22:59 -070061namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070062
Dominik Laskowski1c99a002023-01-20 17:10:36 -050063Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
64 sp<VsyncModulator> modulatorPtr)
65 : impl::MessageQueue(compositor),
66 mFeatures(features),
67 mVsyncModulator(std::move(modulatorPtr)),
68 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070069
Dominik Laskowski83bd7712022-01-07 14:30:53 -080070Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080071 // MessageQueue depends on VsyncSchedule, so first destroy it.
72 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
73 // which will cause a use-after-free issue.
74 Impl::destroyVsync();
75
Dominik Laskowski83bd7712022-01-07 14:30:53 -080076 // Stop timers and wait for their threads to exit.
77 mDisplayPowerTimer.reset();
78 mTouchTimer.reset();
79
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040080 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowski596a2562022-10-28 11:26:12 -040081 demoteLeaderDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080082}
83
Dominik Laskowski9c93d602021-10-07 19:38:26 -070084void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070085 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070086 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070087
Dominik Laskowski98041832019-08-01 18:35:59 -070088 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070089 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070090 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080091 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070092 [this] { touchTimerCallback(TimerState::Reset); },
93 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070094 mTouchTimer->start();
95 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070096
Dominik Laskowski98041832019-08-01 18:35:59 -070097 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
98 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080099 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700100 [this] { displayPowerTimerCallback(TimerState::Reset); },
101 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700102 mDisplayPowerTimer->start();
103 }
Ana Krulece588e312018-09-18 12:32:24 -0700104}
105
Dominik Laskowski596a2562022-10-28 11:26:12 -0400106void Scheduler::setLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
107 demoteLeaderDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400108
Dominik Laskowski596a2562022-10-28 11:26:12 -0400109 std::scoped_lock lock(mDisplayLock);
110 promoteLeaderDisplay(leaderIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800111}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700112
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400113void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400114 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400115
Dominik Laskowski596a2562022-10-28 11:26:12 -0400116 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400117 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400118
119 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400120}
121
122void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400123 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400124
Dominik Laskowski596a2562022-10-28 11:26:12 -0400125 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400126 mRefreshRateSelectors.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400127
128 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400129}
130
Dominik Laskowski756b7892021-08-04 12:53:59 -0700131void Scheduler::run() {
132 while (true) {
133 waitMessage();
134 }
135}
136
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700137void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
138 TimePoint expectedVsyncTime) {
139 const TimePoint frameTime = SchedulerClock::now();
140
141 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
142 return;
143 }
144
145 compositor.composite(frameTime, vsyncId);
146 compositor.sample();
147}
148
Dominik Laskowski068173d2021-08-11 17:22:59 -0700149void Scheduler::createVsyncSchedule(FeatureFlags features) {
150 mVsyncSchedule.emplace(features);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700151}
152
Ady Abraham62a0be22020-12-08 16:54:10 -0800153std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800154 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800155 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800156 return mFrameRateOverrideMappings
157 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800158}
159
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700160bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800161 const auto frameRate = getFrameRateOverride(uid);
162 if (!frameRate.has_value()) {
163 return true;
164 }
165
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700166 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700167}
168
Ady Abraham64c2fc02020-12-29 12:07:50 -0800169impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
Ady Abraham64c2fc02020-12-29 12:07:50 -0800170 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700171 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
Ady Abraham64c2fc02020-12-29 12:07:50 -0800172 };
173}
174
Jorim Jaggic0086af2021-02-12 18:18:11 +0100175impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
176 return [this](uid_t uid) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800177 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
Dominik Laskowski5d164f22022-07-07 07:56:07 -0700178 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800179
Jorim Jaggic0086af2021-02-12 18:18:11 +0100180 const auto frameRate = getFrameRateOverride(uid);
181 if (!frameRate.has_value()) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700182 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100183 }
184
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400185 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
Ady Abrahamcc315492022-02-17 17:06:39 -0800186 if (divisor <= 1) {
Rachel Lee73fe8152022-04-11 17:23:25 -0700187 return currentPeriod;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100188 }
Rachel Lee73fe8152022-04-11 17:23:25 -0700189 return currentPeriod * divisor;
Jorim Jaggic0086af2021-02-12 18:18:11 +0100190 };
191}
192
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500193ConnectionHandle Scheduler::createEventThread(Cycle cycle,
194 frametimeline::TokenManager* tokenManager,
195 std::chrono::nanoseconds workDuration,
196 std::chrono::nanoseconds readyDuration) {
197 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
198 *mVsyncSchedule, tokenManager,
199 makeThrottleVsyncCallback(),
200 makeGetVsyncPeriodFunction(),
201 workDuration, readyDuration);
202
203 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
204 handle = createConnection(std::move(eventThread));
205 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700206}
Ana Krulec98b5b242018-08-10 15:03:23 -0700207
Dominik Laskowski068173d2021-08-11 17:22:59 -0700208ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700209 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
210 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800211
Ady Abraham62f216c2020-10-13 19:07:23 -0700212 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700213
Ana Krulec6ddd2612020-09-24 13:06:33 -0700214 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700215 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
216 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700217}
218
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700219sp<EventThreadConnection> Scheduler::createConnectionInternal(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700220 EventThread* eventThread, EventRegistrationFlags eventRegistration) {
Ady Abraham62f216c2020-10-13 19:07:23 -0700221 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700222}
223
Ana Krulec98b5b242018-08-10 15:03:23 -0700224sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Huihong Luo1b0c49f2022-03-15 19:18:21 -0700225 ConnectionHandle handle, EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700226 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700227 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700228 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700229}
230
Dominik Laskowski98041832019-08-01 18:35:59 -0700231sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700232 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700233 RETURN_IF_INVALID_HANDLE(handle, nullptr);
234 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700235}
236
Dominik Laskowski98041832019-08-01 18:35:59 -0700237void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
238 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700239 android::EventThread* thread;
240 {
241 std::lock_guard<std::mutex> lock(mConnectionsLock);
242 RETURN_IF_INVALID_HANDLE(handle);
243 thread = mConnections[handle].thread.get();
244 }
245
246 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700247}
248
Dominik Laskowski98041832019-08-01 18:35:59 -0700249void Scheduler::onScreenAcquired(ConnectionHandle handle) {
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 thread->onScreenAcquired();
Ady Abraham4f960d12021-10-13 16:59:49 -0700257 mScreenAcquired = true;
Ana Krulec98b5b242018-08-10 15:03:23 -0700258}
259
Dominik Laskowski98041832019-08-01 18:35:59 -0700260void Scheduler::onScreenReleased(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->onScreenReleased();
Ady Abraham4f960d12021-10-13 16:59:49 -0700268 mScreenAcquired = false;
Ana Krulec98b5b242018-08-10 15:03:23 -0700269}
270
Ady Abraham62a0be22020-12-08 16:54:10 -0800271void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800272 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800273 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800274
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800275 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800276 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800277
Ady Abraham62f216c2020-10-13 19:07:23 -0700278 android::EventThread* thread;
279 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800280 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700281 RETURN_IF_INVALID_HANDLE(handle);
282 thread = mConnections[handle].thread.get();
283 }
284 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
285}
286
Ady Abrahamace3d052022-11-17 16:25:05 -0800287void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800288 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700289 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100290 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700291 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700292
293 // Invalidate content based refresh rate selection so it could be calculated
294 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700295 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800296 }
Ady Abraham690f4612021-07-01 23:24:03 -0700297 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700298}
299
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100300void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700301 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800302 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100303 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700304 return;
305 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700306 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100307 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700308 return;
309 }
310
Ady Abrahamd1591702021-07-27 16:27:56 -0700311 // If the mode is not the current mode, this means that a
312 // mode change is in progress. In that case we shouldn't dispatch an event
313 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800314 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700315 return;
316 }
317
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100318 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800319 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700320 return;
321 }
322
Ady Abrahamace3d052022-11-17 16:25:05 -0800323 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700324 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
325 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700326}
327
Ady Abrahamace3d052022-11-17 16:25:05 -0800328void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700329 android::EventThread* thread;
330 {
331 std::lock_guard<std::mutex> lock(mConnectionsLock);
332 RETURN_IF_INVALID_HANDLE(handle);
333 thread = mConnections[handle].thread.get();
334 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800335 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800336}
337
Alec Mouri717bcb62020-02-10 17:07:19 -0800338size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700339 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800340 RETURN_IF_INVALID_HANDLE(handle, 0);
341 return mConnections[handle].thread->getEventThreadConnectionCount();
342}
343
Dominik Laskowski98041832019-08-01 18:35:59 -0700344void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700345 android::EventThread* thread;
346 {
347 std::lock_guard<std::mutex> lock(mConnectionsLock);
348 RETURN_IF_INVALID_HANDLE(handle);
349 thread = mConnections.at(handle).thread.get();
350 }
351 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700352}
353
Ady Abraham9c53ee72020-07-22 21:16:18 -0700354void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
355 std::chrono::nanoseconds readyDuration) {
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[handle].thread.get();
361 }
362 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700363}
Ana Krulece588e312018-09-18 12:32:24 -0700364
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500365void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
366 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
367}
368
369void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
370 setDuration(mAppConnectionHandle,
371 /* workDuration */ config.appWorkDuration,
372 /* readyDuration */ config.sfWorkDuration);
373 setDuration(mSfConnectionHandle,
374 /* workDuration */ vsyncPeriod,
375 /* readyDuration */ config.sfWorkDuration);
376 setDuration(config.sfWorkDuration);
377}
378
Ana Krulece588e312018-09-18 12:32:24 -0700379void Scheduler::enableHardwareVsync() {
380 std::lock_guard<std::mutex> lock(mHWVsyncLock);
381 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700382 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700383 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700384 mPrimaryHWVsyncEnabled = true;
385 }
386}
387
388void Scheduler::disableHardwareVsync(bool makeUnavailable) {
389 std::lock_guard<std::mutex> lock(mHWVsyncLock);
390 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700391 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700392 mPrimaryHWVsyncEnabled = false;
393 }
394 if (makeUnavailable) {
395 mHWVsyncAvailable = false;
396 }
397}
398
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800399void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
Ana Krulecc2870422019-01-29 19:00:58 -0800400 {
401 std::lock_guard<std::mutex> lock(mHWVsyncLock);
402 if (makeAvailable) {
403 mHWVsyncAvailable = makeAvailable;
404 } else if (!mHWVsyncAvailable) {
405 // Hardware vsync is not currently available, so abort the resync
406 // attempt for now
407 return;
408 }
409 }
410
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800411 setVsyncPeriod(refreshRate.getPeriodNsecs());
Ana Krulecc2870422019-01-29 19:00:58 -0800412}
413
Ady Abrahamace3d052022-11-17 16:25:05 -0800414void Scheduler::setRenderRate(Fps renderFrameRate) {
415 const auto mode = leaderSelectorPtr()->getActiveMode();
416
417 using fps_approx_ops::operator!=;
418 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
419 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
420 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
421
422 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
423 to_string(mode.modePtr->getFps()).c_str());
424
425 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
426 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
427 to_string(mode.fps).c_str());
428
429 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
430}
431
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700432void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700433 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800434
435 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700436 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800437
438 if (now - last > kIgnoreDelay) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800439 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800440 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800441 }
442}
443
Dominik Laskowski98041832019-08-01 18:35:59 -0700444void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800445 if (period <= 0) return;
446
Ady Abraham3aff9172019-02-07 19:10:26 -0800447 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Dominik Laskowski068173d2021-08-11 17:22:59 -0700448 mVsyncSchedule->getController().startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800449
450 if (!mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700451 mVsyncSchedule->getTracker().resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700452 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800453 mPrimaryHWVsyncEnabled = true;
454 }
Ana Krulece588e312018-09-18 12:32:24 -0700455}
456
Ady Abraham5dee2f12020-02-05 17:49:47 -0800457void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
458 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700459 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700460 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700461 { // Scope for the lock
462 std::lock_guard<std::mutex> lock(mHWVsyncLock);
463 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700464 needsHwVsync =
465 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
466 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700467 }
468 }
469
470 if (needsHwVsync) {
471 enableHardwareVsync();
472 } else {
473 disableHardwareVsync(false);
474 }
475}
476
Dominik Laskowski068173d2021-08-11 17:22:59 -0700477void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
478 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
Ana Krulece588e312018-09-18 12:32:24 -0700479 enableHardwareVsync();
480 } else {
481 disableHardwareVsync(false);
482 }
483}
484
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700485void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200486 // If the content detection feature is off, we still keep the layer history,
487 // since we use it for other features (like Frame Rate API), so layers
488 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000489 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700490}
491
Ady Abrahambdda8f02021-04-01 16:06:11 -0700492void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700493 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700494}
495
Ady Abraham5def7332020-05-29 16:13:47 -0700496void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
497 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400498 if (leaderSelectorPtr()->canSwitch()) {
499 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800500 }
Ana Krulec3084c052018-11-21 20:27:17 +0100501}
502
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100503void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700504 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700505}
506
Andy Labrada096227e2022-06-15 16:58:11 +0000507void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
508 mLayerHistory.setDefaultFrameRateCompatibility(layer,
509 mFeatures.test(Feature::kContentDetection));
510}
511
Dominik Laskowski49cea512019-11-12 14:13:23 -0800512void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400513 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400514 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800515
Ady Abraham8a82ba62020-01-17 12:43:17 -0800516 ATRACE_CALL();
517
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400518 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800519 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800520}
521
Ana Krulecfb772822018-11-30 10:44:07 +0100522void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400523 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800524}
525
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700526void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700527 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800528 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400529 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800530 }
Ady Abraham8532d012019-05-08 14:50:56 -0700531}
532
Rachel Lee6a9731d2022-06-06 17:08:14 -0700533void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700534 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700535 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700536 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700537 }
Rachel Lee6a9731d2022-06-06 17:08:14 -0700538 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700539
540 if (mDisplayPowerTimer) {
541 mDisplayPowerTimer->reset();
542 }
543
544 // Display Power event will boost the refresh rate to performance.
545 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700546 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700547}
548
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700549void Scheduler::kernelIdleTimerCallback(TimerState state) {
550 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100551
Ady Abraham2139f732019-11-13 18:56:40 -0800552 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
553 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800554 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700555
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700556 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
557 using namespace fps_approx_ops;
558
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800559 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700560 // If we're not in performance mode then the kernel timer shouldn't do
561 // anything, as the refresh rate during DPU power collapse will be the
562 // same.
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800563 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
564 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700565 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
566 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700567 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700568 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700569 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800570
571 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700572}
573
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700574void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800575 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700576 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100577}
578
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700579void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700580 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700581 // Touch event will boost the refresh rate to performance.
582 // Clear layer history to get fresh FPS detection.
583 // NOTE: Instead of checking all the layers, we should be checking the layer
584 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800585 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700586 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700587 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700588 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700589}
590
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700591void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800592 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700593 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700594}
595
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400596void Scheduler::dump(utils::Dumper& dumper) const {
597 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700598
599 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400600 utils::Dumper::Section section(dumper, "Features"sv);
601
602 for (Feature feature : ftl::enum_range<Feature>()) {
603 if (const auto flagOpt = ftl::flag_name(feature)) {
604 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
605 }
606 }
607 }
608 {
609 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400610 {
611 std::scoped_lock lock(mDisplayLock);
612 ftl::FakeGuard guard(kMainThreadContext);
613 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
614 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400615 dumper.dump("layerHistory"sv, mLayerHistory.dump());
616 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
617 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
618 }
619
620 mFrameRateOverrideMappings.dump(dumper);
621 dumper.eol();
622
623 {
624 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
625
Ady Abraham4f960d12021-10-13 16:59:49 -0700626 std::lock_guard lock(mHWVsyncLock);
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400627 dumper.dump("screenAcquired"sv, mScreenAcquired.load());
628 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
629 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
Ady Abraham4f960d12021-10-13 16:59:49 -0700630 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800631}
632
Dominik Laskowski068173d2021-08-11 17:22:59 -0700633void Scheduler::dumpVsync(std::string& out) const {
634 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700635}
636
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800637bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400638 if (consideredSignals.idle) return false;
639
640 const auto frameRateOverrides =
641 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
642 displayRefreshRate, consideredSignals);
643
644 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
645 // the FrameRateOverrideMappings rather than here.
646 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
647}
648
649void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
650 // TODO(b/241286431): Choose the leader display.
651 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
652 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
653
654 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
655 leaderPtr->setIdleTimerCallbacks(
656 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
657 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
658 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
659 .onExpired =
660 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
661
662 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800663 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400664}
665
666void Scheduler::demoteLeaderDisplay() {
667 // No need to lock for reads on kMainThreadContext.
668 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
669 leaderPtr->stopIdleTimer();
670 leaderPtr->clearIdleTimerCallbacks();
671 }
672
673 // Clear state that depends on the leader's RefreshRateSelector.
674 std::scoped_lock lock(mPolicyLock);
675 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800676}
677
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800678template <typename S, typename T>
679auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800680 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400681 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800682 GlobalSignals consideredSignals;
683
Ady Abraham62a0be22020-12-08 16:54:10 -0800684 bool refreshRateChanged = false;
685 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800686
Ady Abraham8532d012019-05-08 14:50:56 -0700687 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400688 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800689
690 auto& currentState = mPolicy.*statePtr;
691 if (currentState == newState) return {};
692 currentState = std::forward<T>(newState);
693
Dominik Laskowski596a2562022-10-28 11:26:12 -0400694 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800695 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400696 {
697 std::scoped_lock lock(mDisplayLock);
698 ftl::FakeGuard guard(kMainThreadContext);
699
700 modeChoices = chooseDisplayModes();
701
702 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
703 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800704 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400705 modeChoices.get(*mLeaderDisplayId)
706 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800707 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400708 })
709 .value();
710 }
ramindani69b58e82022-09-26 16:48:36 -0700711
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400712 modeRequests.reserve(modeChoices.size());
713 for (auto& [id, choice] : modeChoices) {
714 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800715 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400716 .emitEvent = !choice.consideredSignals.idle});
717 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800718
Ady Abrahamace3d052022-11-17 16:25:05 -0800719 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400720
Ady Abrahamace3d052022-11-17 16:25:05 -0800721 if (mPolicy.modeOpt != modeOpt) {
722 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400723 refreshRateChanged = true;
724 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100725 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800726 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700727 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100728 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700729 }
Ady Abraham8532d012019-05-08 14:50:56 -0700730 }
Ady Abraham8532d012019-05-08 14:50:56 -0700731 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800732 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400733 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800734 }
735 if (frameRateOverridesChanged) {
736 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
737 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800738 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700739}
740
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400741auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800742 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700743
Ady Abraham68636062022-11-16 17:07:25 -0800744 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400745 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400746
747 // Tallies the score of a refresh rate across `displayCount` displays.
748 struct RefreshRateTally {
749 explicit RefreshRateTally(float score) : score(score) {}
750
751 float score;
752 size_t displayCount = 1;
753 };
754
755 // Chosen to exceed a typical number of refresh rates across displays.
756 constexpr size_t kStaticCapacity = 8;
757 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
758
759 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800760
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400761 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800762 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800763 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700764
Ady Abrahamace3d052022-11-17 16:25:05 -0800765 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
766 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400767
768 if (!inserted) {
769 auto& tally = it->second;
770 tally.score += score;
771 tally.displayCount++;
772 }
773 }
774
Ady Abrahamace3d052022-11-17 16:25:05 -0800775 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400776 }
ramindani69b58e82022-09-26 16:48:36 -0700777
Dominik Laskowski01602522022-10-07 19:02:28 -0400778 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700779
Dominik Laskowski01602522022-10-07 19:02:28 -0400780 // Find the first refresh rate common to all displays.
781 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400782 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400783 ++maxScoreIt;
784 }
785
786 if (maxScoreIt != refreshRateTallies.cend()) {
787 // Choose the highest refresh rate common to all displays, if any.
788 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
789 const auto [fps, tally] = *it;
790
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400791 if (tally.displayCount == mRefreshRateSelectors.size() &&
792 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400793 maxScoreIt = it;
794 }
ramindani7c487282022-10-10 16:17:51 -0700795 }
796 }
ramindani69b58e82022-09-26 16:48:36 -0700797
Dominik Laskowski01602522022-10-07 19:02:28 -0400798 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
799 ? std::make_optional(maxScoreIt->first)
800 : std::nullopt;
801
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400802 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400803
ramindani69b58e82022-09-26 16:48:36 -0700804 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400805
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400806 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400807 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800808 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800809 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
810 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400811 continue;
812 }
813
Ady Abraham68636062022-11-16 17:07:25 -0800814 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800815 if (frameRateMode.fps == *chosenFps) {
816 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
817 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400818 break;
819 }
820 }
821 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400822 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700823}
824
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400825GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000826 const bool powerOnImminent = mDisplayPowerTimer &&
827 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
828 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700829
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400830 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
831 .idle = mPolicy.idleTimer == TimerState::Expired,
832 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800833}
834
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500835FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700836 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500837 const auto frameRateMode =
838 leaderSelectorPtr()
839 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
840 .ranking.front()
841 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400842
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500843 // Make sure the stored mode is up to date.
844 mPolicy.modeOpt = frameRateMode;
845
846 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700847}
848
Peiyong Line9d809e2020-04-14 13:10:48 -0700849void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800850 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
851 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
852
853 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
854 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
855 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
856 }
857}
858
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700859bool Scheduler::onPostComposition(nsecs_t presentTime) {
860 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
861 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
862 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
863 // We need to composite again as refreshTimeNanos is still in the future.
864 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700865 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700866
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700867 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800868 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700869 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800870}
871
Ady Abraham7825c682021-05-17 15:12:14 -0700872void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700873 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800874}
875
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800876void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
877 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
878 return;
879 }
880
881 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
882}
883
Ady Abraham62a0be22020-12-08 16:54:10 -0800884void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
885 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
886 return;
887 }
888
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800889 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800890}
891
Dominik Laskowski068173d2021-08-11 17:22:59 -0700892} // namespace android::scheduler