blob: 5fc250bd9fe57a6019b75c530ceb810c998e4e74 [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"
Rachel Lee2248f522023-01-27 16:45:23 -080050#include "FrontEnd/LayerHandle.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070051#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090052#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080053#include "VSyncPredictor.h"
54#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070055
Dominik Laskowski98041832019-08-01 18:35:59 -070056#define RETURN_IF_INVALID_HANDLE(handle, ...) \
57 do { \
58 if (mConnections.count(handle) == 0) { \
59 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
60 return __VA_ARGS__; \
61 } \
62 } while (false)
63
Dominik Laskowski068173d2021-08-11 17:22:59 -070064namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070065
Dominik Laskowski1c99a002023-01-20 17:10:36 -050066Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
67 sp<VsyncModulator> modulatorPtr)
68 : impl::MessageQueue(compositor),
69 mFeatures(features),
70 mVsyncModulator(std::move(modulatorPtr)),
71 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070072
Dominik Laskowski83bd7712022-01-07 14:30:53 -080073Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080074 // MessageQueue depends on VsyncSchedule, so first destroy it.
75 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
76 // which will cause a use-after-free issue.
77 Impl::destroyVsync();
78
Dominik Laskowski83bd7712022-01-07 14:30:53 -080079 // Stop timers and wait for their threads to exit.
80 mDisplayPowerTimer.reset();
81 mTouchTimer.reset();
82
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040083 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowski596a2562022-10-28 11:26:12 -040084 demoteLeaderDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080085}
86
Dominik Laskowski9c93d602021-10-07 19:38:26 -070087void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070088 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070089 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070090
Dominik Laskowski98041832019-08-01 18:35:59 -070091 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070092 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070093 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080094 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070095 [this] { touchTimerCallback(TimerState::Reset); },
96 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070097 mTouchTimer->start();
98 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070099
Dominik Laskowski98041832019-08-01 18:35:59 -0700100 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
101 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800102 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700103 [this] { displayPowerTimerCallback(TimerState::Reset); },
104 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700105 mDisplayPowerTimer->start();
106 }
Ana Krulece588e312018-09-18 12:32:24 -0700107}
108
Dominik Laskowski596a2562022-10-28 11:26:12 -0400109void Scheduler::setLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
110 demoteLeaderDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400111
Dominik Laskowski596a2562022-10-28 11:26:12 -0400112 std::scoped_lock lock(mDisplayLock);
113 promoteLeaderDisplay(leaderIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800114}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700115
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400116void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400117 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400118
Dominik Laskowski596a2562022-10-28 11:26:12 -0400119 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400120 mRefreshRateSelectors.emplace_or_replace(displayId, std::move(selectorPtr));
Dominik Laskowski596a2562022-10-28 11:26:12 -0400121
122 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400123}
124
125void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400126 demoteLeaderDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400127
Dominik Laskowski596a2562022-10-28 11:26:12 -0400128 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400129 mRefreshRateSelectors.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400130
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500131 // Do not allow removing the final display. Code in the scheduler expects
132 // there to be at least one display. (This may be relaxed in the future with
133 // headless virtual display.)
134 LOG_ALWAYS_FATAL_IF(mRefreshRateSelectors.empty(), "Cannot unregister all displays!");
135
Dominik Laskowski596a2562022-10-28 11:26:12 -0400136 promoteLeaderDisplay();
Dominik Laskowski01602522022-10-07 19:02:28 -0400137}
138
Dominik Laskowski756b7892021-08-04 12:53:59 -0700139void Scheduler::run() {
140 while (true) {
141 waitMessage();
142 }
143}
144
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700145void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
146 TimePoint expectedVsyncTime) {
147 const TimePoint frameTime = SchedulerClock::now();
148
149 if (!compositor.commit(frameTime, vsyncId, expectedVsyncTime)) {
150 return;
151 }
152
153 compositor.composite(frameTime, vsyncId);
154 compositor.sample();
155}
156
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500157void Scheduler::createVsyncSchedule(FeatureFlags features) {
158 mVsyncSchedule.emplace(features);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700159}
160
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500161std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800162 const bool supportsFrameRateOverrideByContent =
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500163 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800164 return mFrameRateOverrideMappings
165 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800166}
167
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500168bool Scheduler::isVsyncValid(TimePoint expectedVsyncTimestamp, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800169 const auto frameRate = getFrameRateOverride(uid);
170 if (!frameRate.has_value()) {
171 return true;
172 }
173
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500174 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700175}
176
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500177bool Scheduler::isVsyncInPhase(TimePoint timePoint, const Fps frameRate) const {
178 return mVsyncSchedule->getTracker().isVSyncInPhase(timePoint.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700179}
180
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500181impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
182 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
183 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
184 };
185}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800186
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500187impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
188 return [this](uid_t uid) {
189 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
190 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800191
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500192 const auto frameRate = getFrameRateOverride(uid);
193 if (!frameRate.has_value()) {
194 return currentPeriod;
195 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100196
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500197 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
198 if (divisor <= 1) {
199 return currentPeriod;
200 }
201 return currentPeriod * divisor;
202 };
Jorim Jaggic0086af2021-02-12 18:18:11 +0100203}
204
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500205ConnectionHandle Scheduler::createEventThread(Cycle cycle,
206 frametimeline::TokenManager* tokenManager,
207 std::chrono::nanoseconds workDuration,
208 std::chrono::nanoseconds readyDuration) {
209 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500210 *mVsyncSchedule, tokenManager,
211 makeThrottleVsyncCallback(),
212 makeGetVsyncPeriodFunction(),
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500213 workDuration, readyDuration);
214
215 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
216 handle = createConnection(std::move(eventThread));
217 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700218}
Ana Krulec98b5b242018-08-10 15:03:23 -0700219
Dominik Laskowski068173d2021-08-11 17:22:59 -0700220ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700221 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
222 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800223
Ady Abraham62f216c2020-10-13 19:07:23 -0700224 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700225
Ana Krulec6ddd2612020-09-24 13:06:33 -0700226 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700227 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
228 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700229}
230
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700231sp<EventThreadConnection> Scheduler::createConnectionInternal(
Rachel Lee2248f522023-01-27 16:45:23 -0800232 EventThread* eventThread, EventRegistrationFlags eventRegistration,
233 const sp<IBinder>& layerHandle) {
234 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
235 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
236 mLayerHistory.attachChoreographer(layerId, connection);
237 return connection;
Ana Krulec0c8cd522018-08-31 12:27:28 -0700238}
239
Ana Krulec98b5b242018-08-10 15:03:23 -0700240sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800241 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
242 const sp<IBinder>& layerHandle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700243 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700244 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Rachel Lee2248f522023-01-27 16:45:23 -0800245 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
246 layerHandle);
Ana Krulec98b5b242018-08-10 15:03:23 -0700247}
248
Dominik Laskowski98041832019-08-01 18:35:59 -0700249sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700250 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700251 RETURN_IF_INVALID_HANDLE(handle, nullptr);
252 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700253}
254
Dominik Laskowski98041832019-08-01 18:35:59 -0700255void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
256 bool connected) {
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
264 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700265}
266
Dominik Laskowski98041832019-08-01 18:35:59 -0700267void Scheduler::onScreenAcquired(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->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700275}
276
Dominik Laskowski98041832019-08-01 18:35:59 -0700277void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700278 android::EventThread* thread;
279 {
280 std::lock_guard<std::mutex> lock(mConnectionsLock);
281 RETURN_IF_INVALID_HANDLE(handle);
282 thread = mConnections[handle].thread.get();
283 }
284 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700285}
286
Ady Abraham62a0be22020-12-08 16:54:10 -0800287void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800288 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800289 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800290
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800291 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800292 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800293
Ady Abraham62f216c2020-10-13 19:07:23 -0700294 android::EventThread* thread;
295 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800296 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700297 RETURN_IF_INVALID_HANDLE(handle);
298 thread = mConnections[handle].thread.get();
299 }
300 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
301}
302
Ady Abrahamace3d052022-11-17 16:25:05 -0800303void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800304 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700305 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100306 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700307 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700308
309 // Invalidate content based refresh rate selection so it could be calculated
310 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700311 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800312 }
Ady Abraham690f4612021-07-01 23:24:03 -0700313 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700314}
315
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100316void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700317 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800318 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100319 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700320 return;
321 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700322 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100323 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700324 return;
325 }
326
Ady Abrahamd1591702021-07-27 16:27:56 -0700327 // If the mode is not the current mode, this means that a
328 // mode change is in progress. In that case we shouldn't dispatch an event
329 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800330 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700331 return;
332 }
333
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100334 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800335 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700336 return;
337 }
338
Ady Abrahamace3d052022-11-17 16:25:05 -0800339 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700340 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
341 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700342}
343
Ady Abrahamace3d052022-11-17 16:25:05 -0800344void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
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[handle].thread.get();
350 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800351 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800352}
353
Alec Mouri717bcb62020-02-10 17:07:19 -0800354size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700355 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800356 RETURN_IF_INVALID_HANDLE(handle, 0);
357 return mConnections[handle].thread->getEventThreadConnectionCount();
358}
359
Dominik Laskowski98041832019-08-01 18:35:59 -0700360void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700361 android::EventThread* thread;
362 {
363 std::lock_guard<std::mutex> lock(mConnectionsLock);
364 RETURN_IF_INVALID_HANDLE(handle);
365 thread = mConnections.at(handle).thread.get();
366 }
367 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700368}
369
Ady Abraham9c53ee72020-07-22 21:16:18 -0700370void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
371 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700372 android::EventThread* thread;
373 {
374 std::lock_guard<std::mutex> lock(mConnectionsLock);
375 RETURN_IF_INVALID_HANDLE(handle);
376 thread = mConnections[handle].thread.get();
377 }
378 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700379}
Ana Krulece588e312018-09-18 12:32:24 -0700380
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500381void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
382 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
383}
384
385void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
386 setDuration(mAppConnectionHandle,
387 /* workDuration */ config.appWorkDuration,
388 /* readyDuration */ config.sfWorkDuration);
389 setDuration(mSfConnectionHandle,
390 /* workDuration */ vsyncPeriod,
391 /* readyDuration */ config.sfWorkDuration);
392 setDuration(config.sfWorkDuration);
393}
394
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500395void Scheduler::enableHardwareVsync() {
396 std::lock_guard<std::mutex> lock(mHWVsyncLock);
397 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
398 mVsyncSchedule->getTracker().resetModel();
399 mSchedulerCallback.setVsyncEnabled(true);
400 mPrimaryHWVsyncEnabled = true;
Ana Krulece588e312018-09-18 12:32:24 -0700401 }
402}
403
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500404void Scheduler::disableHardwareVsync(bool makeUnavailable) {
405 std::lock_guard<std::mutex> lock(mHWVsyncLock);
406 if (mPrimaryHWVsyncEnabled) {
407 mSchedulerCallback.setVsyncEnabled(false);
408 mPrimaryHWVsyncEnabled = false;
Ana Krulece588e312018-09-18 12:32:24 -0700409 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500410 if (makeUnavailable) {
411 mHWVsyncAvailable = false;
Ana Krulece588e312018-09-18 12:32:24 -0700412 }
413}
414
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500415void Scheduler::resyncToHardwareVsync(bool makeAvailable, Fps refreshRate) {
416 {
417 std::lock_guard<std::mutex> lock(mHWVsyncLock);
418 if (makeAvailable) {
419 mHWVsyncAvailable = makeAvailable;
420 } else if (!mHWVsyncAvailable) {
421 // Hardware vsync is not currently available, so abort the resync
422 // attempt for now
423 return;
424 }
425 }
Ana Krulecc2870422019-01-29 19:00:58 -0800426
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500427 setVsyncPeriod(refreshRate.getPeriodNsecs());
428}
429
430void Scheduler::setRenderRate(Fps renderFrameRate) {
431 const auto mode = leaderSelectorPtr()->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800432
433 using fps_approx_ops::operator!=;
434 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500435 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
436 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800437
438 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
439 to_string(mode.modePtr->getFps()).c_str());
440
441 const auto divisor = RefreshRateSelector::getFrameRateDivisor(mode.modePtr->getFps(), mode.fps);
442 LOG_ALWAYS_FATAL_IF(divisor == 0, "%s <> %s -- not divisors", to_string(mode.fps).c_str(),
443 to_string(mode.fps).c_str());
444
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500445 mVsyncSchedule->getTracker().setDivisor(static_cast<unsigned>(divisor));
Ady Abrahamace3d052022-11-17 16:25:05 -0800446}
447
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700448void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700449 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800450
451 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700452 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800453
454 if (now - last > kIgnoreDelay) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500455 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
456 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800457 }
458}
459
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500460void Scheduler::setVsyncPeriod(nsecs_t period) {
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800461 if (period <= 0) return;
462
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500463 std::lock_guard<std::mutex> lock(mHWVsyncLock);
464 mVsyncSchedule->getController().startPeriodTransition(period);
465
466 if (!mPrimaryHWVsyncEnabled) {
467 mVsyncSchedule->getTracker().resetModel();
468 mSchedulerCallback.setVsyncEnabled(true);
469 mPrimaryHWVsyncEnabled = true;
470 }
Ana Krulece588e312018-09-18 12:32:24 -0700471}
472
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500473void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
474 bool* periodFlushed) {
475 bool needsHwVsync = false;
476 *periodFlushed = false;
477 { // Scope for the lock
478 std::lock_guard<std::mutex> lock(mHWVsyncLock);
479 if (mPrimaryHWVsyncEnabled) {
480 needsHwVsync =
481 mVsyncSchedule->getController().addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
482 periodFlushed);
483 }
Ana Krulece588e312018-09-18 12:32:24 -0700484 }
485
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500486 if (needsHwVsync) {
487 enableHardwareVsync();
488 } else {
489 disableHardwareVsync(false);
490 }
Ana Krulece588e312018-09-18 12:32:24 -0700491}
492
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500493void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
494 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
495 enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700496 } else {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500497 disableHardwareVsync(false);
Ana Krulece588e312018-09-18 12:32:24 -0700498 }
499}
500
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700501void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200502 // If the content detection feature is off, we still keep the layer history,
503 // since we use it for other features (like Frame Rate API), so layers
504 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000505 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700506}
507
Ady Abrahambdda8f02021-04-01 16:06:11 -0700508void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700509 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700510}
511
Ady Abraham5def7332020-05-29 16:13:47 -0700512void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
513 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400514 if (leaderSelectorPtr()->canSwitch()) {
515 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800516 }
Ana Krulec3084c052018-11-21 20:27:17 +0100517}
518
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100519void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700520 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700521}
522
Andy Labrada096227e2022-06-15 16:58:11 +0000523void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
524 mLayerHistory.setDefaultFrameRateCompatibility(layer,
525 mFeatures.test(Feature::kContentDetection));
526}
527
Dominik Laskowski49cea512019-11-12 14:13:23 -0800528void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400529 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400530 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800531
Ady Abraham8a82ba62020-01-17 12:43:17 -0800532 ATRACE_CALL();
533
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400534 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800535 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800536}
537
Ana Krulecfb772822018-11-30 10:44:07 +0100538void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400539 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800540}
541
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700542void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700543 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800544 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400545 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800546 }
Ady Abraham8532d012019-05-08 14:50:56 -0700547}
548
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500549void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
550 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700551 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700552 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700553 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500554 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700555
556 if (mDisplayPowerTimer) {
557 mDisplayPowerTimer->reset();
558 }
559
560 // Display Power event will boost the refresh rate to performance.
561 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700562 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700563}
564
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700565void Scheduler::kernelIdleTimerCallback(TimerState state) {
566 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100567
Ady Abraham2139f732019-11-13 18:56:40 -0800568 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
569 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800570 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700571
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700572 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
573 using namespace fps_approx_ops;
574
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800575 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700576 // If we're not in performance mode then the kernel timer shouldn't do
577 // anything, as the refresh rate during DPU power collapse will be the
578 // same.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500579 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800580 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700581 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
582 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700583 // need to update the VsyncController model anyway.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500584 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700585 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800586
587 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700588}
589
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700590void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800591 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700592 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100593}
594
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700595void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700596 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700597 // Touch event will boost the refresh rate to performance.
598 // Clear layer history to get fresh FPS detection.
599 // NOTE: Instead of checking all the layers, we should be checking the layer
600 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800601 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700602 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700603 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700604 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700605}
606
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700607void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800608 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700609 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700610}
611
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400612void Scheduler::dump(utils::Dumper& dumper) const {
613 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700614
615 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400616 utils::Dumper::Section section(dumper, "Features"sv);
617
618 for (Feature feature : ftl::enum_range<Feature>()) {
619 if (const auto flagOpt = ftl::flag_name(feature)) {
620 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
621 }
622 }
623 }
624 {
625 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400626 {
627 std::scoped_lock lock(mDisplayLock);
628 ftl::FakeGuard guard(kMainThreadContext);
629 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
630 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400631 dumper.dump("layerHistory"sv, mLayerHistory.dump());
632 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
633 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
634 }
635
636 mFrameRateOverrideMappings.dump(dumper);
637 dumper.eol();
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500638
639 {
640 utils::Dumper::Section section(dumper, "Hardware VSYNC"sv);
641
642 std::lock_guard lock(mHWVsyncLock);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500643 dumper.dump("hwVsyncAvailable"sv, mHWVsyncAvailable);
644 dumper.dump("hwVsyncEnabled"sv, mPrimaryHWVsyncEnabled);
645 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800646}
647
Dominik Laskowski068173d2021-08-11 17:22:59 -0700648void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500649 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700650}
651
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800652bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400653 if (consideredSignals.idle) return false;
654
655 const auto frameRateOverrides =
656 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
657 displayRefreshRate, consideredSignals);
658
659 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
660 // the FrameRateOverrideMappings rather than here.
661 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
662}
663
664void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
665 // TODO(b/241286431): Choose the leader display.
666 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
667 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
668
669 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
670 leaderPtr->setIdleTimerCallbacks(
671 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
672 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
673 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
674 .onExpired =
675 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
676
677 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800678 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400679}
680
681void Scheduler::demoteLeaderDisplay() {
682 // No need to lock for reads on kMainThreadContext.
683 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
684 leaderPtr->stopIdleTimer();
685 leaderPtr->clearIdleTimerCallbacks();
686 }
687
688 // Clear state that depends on the leader's RefreshRateSelector.
689 std::scoped_lock lock(mPolicyLock);
690 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800691}
692
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800693template <typename S, typename T>
694auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800695 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400696 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800697 GlobalSignals consideredSignals;
698
Ady Abraham62a0be22020-12-08 16:54:10 -0800699 bool refreshRateChanged = false;
700 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800701
Ady Abraham8532d012019-05-08 14:50:56 -0700702 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400703 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800704
705 auto& currentState = mPolicy.*statePtr;
706 if (currentState == newState) return {};
707 currentState = std::forward<T>(newState);
708
Dominik Laskowski596a2562022-10-28 11:26:12 -0400709 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800710 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400711 {
712 std::scoped_lock lock(mDisplayLock);
713 ftl::FakeGuard guard(kMainThreadContext);
714
715 modeChoices = chooseDisplayModes();
716
717 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
718 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800719 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400720 modeChoices.get(*mLeaderDisplayId)
721 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800722 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400723 })
724 .value();
725 }
ramindani69b58e82022-09-26 16:48:36 -0700726
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400727 modeRequests.reserve(modeChoices.size());
728 for (auto& [id, choice] : modeChoices) {
729 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800730 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400731 .emitEvent = !choice.consideredSignals.idle});
732 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800733
Ady Abrahamace3d052022-11-17 16:25:05 -0800734 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400735
Ady Abrahamace3d052022-11-17 16:25:05 -0800736 if (mPolicy.modeOpt != modeOpt) {
737 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400738 refreshRateChanged = true;
739 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100740 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800741 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700742 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100743 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700744 }
Ady Abraham8532d012019-05-08 14:50:56 -0700745 }
Ady Abraham8532d012019-05-08 14:50:56 -0700746 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800747 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400748 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800749 }
750 if (frameRateOverridesChanged) {
751 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
752 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800753 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700754}
755
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400756auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800757 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700758
Ady Abraham68636062022-11-16 17:07:25 -0800759 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400760 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400761
762 // Tallies the score of a refresh rate across `displayCount` displays.
763 struct RefreshRateTally {
764 explicit RefreshRateTally(float score) : score(score) {}
765
766 float score;
767 size_t displayCount = 1;
768 };
769
770 // Chosen to exceed a typical number of refresh rates across displays.
771 constexpr size_t kStaticCapacity = 8;
772 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
773
774 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800775
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400776 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800777 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800778 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700779
Ady Abrahamace3d052022-11-17 16:25:05 -0800780 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
781 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400782
783 if (!inserted) {
784 auto& tally = it->second;
785 tally.score += score;
786 tally.displayCount++;
787 }
788 }
789
Ady Abrahamace3d052022-11-17 16:25:05 -0800790 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400791 }
ramindani69b58e82022-09-26 16:48:36 -0700792
Dominik Laskowski01602522022-10-07 19:02:28 -0400793 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700794
Dominik Laskowski01602522022-10-07 19:02:28 -0400795 // Find the first refresh rate common to all displays.
796 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400797 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400798 ++maxScoreIt;
799 }
800
801 if (maxScoreIt != refreshRateTallies.cend()) {
802 // Choose the highest refresh rate common to all displays, if any.
803 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
804 const auto [fps, tally] = *it;
805
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400806 if (tally.displayCount == mRefreshRateSelectors.size() &&
807 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400808 maxScoreIt = it;
809 }
ramindani7c487282022-10-10 16:17:51 -0700810 }
811 }
ramindani69b58e82022-09-26 16:48:36 -0700812
Dominik Laskowski01602522022-10-07 19:02:28 -0400813 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
814 ? std::make_optional(maxScoreIt->first)
815 : std::nullopt;
816
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400817 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400818
ramindani69b58e82022-09-26 16:48:36 -0700819 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400820
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400821 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400822 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800823 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800824 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
825 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400826 continue;
827 }
828
Ady Abraham68636062022-11-16 17:07:25 -0800829 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800830 if (frameRateMode.fps == *chosenFps) {
831 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
832 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400833 break;
834 }
835 }
836 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400837 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700838}
839
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400840GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000841 const bool powerOnImminent = mDisplayPowerTimer &&
842 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
843 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700844
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400845 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
846 .idle = mPolicy.idleTimer == TimerState::Expired,
847 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800848}
849
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500850FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700851 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500852 const auto frameRateMode =
853 leaderSelectorPtr()
854 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
855 .ranking.front()
856 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400857
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500858 // Make sure the stored mode is up to date.
859 mPolicy.modeOpt = frameRateMode;
860
861 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700862}
863
Peiyong Line9d809e2020-04-14 13:10:48 -0700864void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800865 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
866 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
867
868 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
869 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
870 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
871 }
872}
873
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700874bool Scheduler::onPostComposition(nsecs_t presentTime) {
875 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
876 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
877 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
878 // We need to composite again as refreshTimeNanos is still in the future.
879 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700880 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700881
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700882 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800883 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700884 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800885}
886
Ady Abraham7825c682021-05-17 15:12:14 -0700887void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700888 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800889}
890
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800891void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
892 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
893 return;
894 }
895
896 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
897}
898
Ady Abraham62a0be22020-12-08 16:54:10 -0800899void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
900 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
901 return;
902 }
903
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800904 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800905}
906
Dominik Laskowski068173d2021-08-11 17:22:59 -0700907} // namespace android::scheduler