blob: dab01ba48d2f534a2c0f7677b76549cdb7ce679d [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>
Ady Abraham9243bba2023-02-10 15:31:14 -080031#include <gui/TraceUtils.h>
chaviw3277faf2021-05-19 16:45:23 -050032#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080033#include <system/window.h>
Ana Krulec3084c052018-11-21 20:27:17 +010034#include <utils/Timers.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) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500158 mVsyncSchedule = std::make_unique<VsyncSchedule>(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
Ady Abraham9243bba2023-02-10 15:31:14 -0800174 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500175 return mVsyncSchedule->getTracker().isVSyncInPhase(expectedVsyncTimestamp.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700176}
177
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500178bool Scheduler::isVsyncInPhase(TimePoint timePoint, const Fps frameRate) const {
179 return mVsyncSchedule->getTracker().isVSyncInPhase(timePoint.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700180}
181
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500182impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
183 return [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
184 return !isVsyncValid(TimePoint::fromNs(expectedVsyncTimestamp), uid);
185 };
186}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800187
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500188impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
189 return [this](uid_t uid) {
190 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().fps;
191 const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800192
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500193 const auto frameRate = getFrameRateOverride(uid);
194 if (!frameRate.has_value()) {
195 return currentPeriod;
196 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100197
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500198 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
199 if (divisor <= 1) {
200 return currentPeriod;
201 }
202 return currentPeriod * divisor;
203 };
Jorim Jaggic0086af2021-02-12 18:18:11 +0100204}
205
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500206ConnectionHandle Scheduler::createEventThread(Cycle cycle,
207 frametimeline::TokenManager* tokenManager,
208 std::chrono::nanoseconds workDuration,
209 std::chrono::nanoseconds readyDuration) {
210 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500211 *mVsyncSchedule, tokenManager,
212 makeThrottleVsyncCallback(),
213 makeGetVsyncPeriodFunction(),
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500214 workDuration, readyDuration);
215
216 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
217 handle = createConnection(std::move(eventThread));
218 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700219}
Ana Krulec98b5b242018-08-10 15:03:23 -0700220
Dominik Laskowski068173d2021-08-11 17:22:59 -0700221ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700222 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
223 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800224
Ady Abraham62f216c2020-10-13 19:07:23 -0700225 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700226
Ana Krulec6ddd2612020-09-24 13:06:33 -0700227 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700228 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
229 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700230}
231
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700232sp<EventThreadConnection> Scheduler::createConnectionInternal(
Rachel Lee2248f522023-01-27 16:45:23 -0800233 EventThread* eventThread, EventRegistrationFlags eventRegistration,
234 const sp<IBinder>& layerHandle) {
235 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
236 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
237 mLayerHistory.attachChoreographer(layerId, connection);
238 return connection;
Ana Krulec0c8cd522018-08-31 12:27:28 -0700239}
240
Ana Krulec98b5b242018-08-10 15:03:23 -0700241sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800242 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
243 const sp<IBinder>& layerHandle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700244 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700245 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Rachel Lee2248f522023-01-27 16:45:23 -0800246 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
247 layerHandle);
Ana Krulec98b5b242018-08-10 15:03:23 -0700248}
249
Dominik Laskowski98041832019-08-01 18:35:59 -0700250sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700251 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700252 RETURN_IF_INVALID_HANDLE(handle, nullptr);
253 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700254}
255
Dominik Laskowski98041832019-08-01 18:35:59 -0700256void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
257 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700258 android::EventThread* thread;
259 {
260 std::lock_guard<std::mutex> lock(mConnectionsLock);
261 RETURN_IF_INVALID_HANDLE(handle);
262 thread = mConnections[handle].thread.get();
263 }
264
265 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700266}
267
Dominik Laskowski98041832019-08-01 18:35:59 -0700268void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700269 android::EventThread* thread;
270 {
271 std::lock_guard<std::mutex> lock(mConnectionsLock);
272 RETURN_IF_INVALID_HANDLE(handle);
273 thread = mConnections[handle].thread.get();
274 }
275 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700276}
277
Dominik Laskowski98041832019-08-01 18:35:59 -0700278void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700279 android::EventThread* thread;
280 {
281 std::lock_guard<std::mutex> lock(mConnectionsLock);
282 RETURN_IF_INVALID_HANDLE(handle);
283 thread = mConnections[handle].thread.get();
284 }
285 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700286}
287
Ady Abraham62a0be22020-12-08 16:54:10 -0800288void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800289 const bool supportsFrameRateOverrideByContent =
Ady Abraham68636062022-11-16 17:07:25 -0800290 leaderSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800291
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800292 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800293 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800294
Ady Abraham62f216c2020-10-13 19:07:23 -0700295 android::EventThread* thread;
296 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800297 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700298 RETURN_IF_INVALID_HANDLE(handle);
299 thread = mConnections[handle].thread.get();
300 }
301 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
302}
303
Ady Abrahamace3d052022-11-17 16:25:05 -0800304void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800305 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700306 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100307 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700308 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700309
310 // Invalidate content based refresh rate selection so it could be calculated
311 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700312 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800313 }
Ady Abraham690f4612021-07-01 23:24:03 -0700314 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700315}
316
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100317void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700318 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800319 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100320 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700321 return;
322 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700323 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100324 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700325 return;
326 }
327
Ady Abrahamd1591702021-07-27 16:27:56 -0700328 // If the mode is not the current mode, this means that a
329 // mode change is in progress. In that case we shouldn't dispatch an event
330 // as it will be dispatched when the current mode changes.
Ady Abrahamace3d052022-11-17 16:25:05 -0800331 if (leaderSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700332 return;
333 }
334
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100335 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800336 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700337 return;
338 }
339
Ady Abrahamace3d052022-11-17 16:25:05 -0800340 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700341 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
342 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700343}
344
Ady Abrahamace3d052022-11-17 16:25:05 -0800345void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700346 android::EventThread* thread;
347 {
348 std::lock_guard<std::mutex> lock(mConnectionsLock);
349 RETURN_IF_INVALID_HANDLE(handle);
350 thread = mConnections[handle].thread.get();
351 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800352 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800353}
354
Alec Mouri717bcb62020-02-10 17:07:19 -0800355size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700356 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800357 RETURN_IF_INVALID_HANDLE(handle, 0);
358 return mConnections[handle].thread->getEventThreadConnectionCount();
359}
360
Dominik Laskowski98041832019-08-01 18:35:59 -0700361void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700362 android::EventThread* thread;
363 {
364 std::lock_guard<std::mutex> lock(mConnectionsLock);
365 RETURN_IF_INVALID_HANDLE(handle);
366 thread = mConnections.at(handle).thread.get();
367 }
368 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700369}
370
Ady Abraham9c53ee72020-07-22 21:16:18 -0700371void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
372 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700373 android::EventThread* thread;
374 {
375 std::lock_guard<std::mutex> lock(mConnectionsLock);
376 RETURN_IF_INVALID_HANDLE(handle);
377 thread = mConnections[handle].thread.get();
378 }
379 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700380}
Ana Krulece588e312018-09-18 12:32:24 -0700381
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500382void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
383 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
384}
385
386void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
387 setDuration(mAppConnectionHandle,
388 /* workDuration */ config.appWorkDuration,
389 /* readyDuration */ config.sfWorkDuration);
390 setDuration(mSfConnectionHandle,
391 /* workDuration */ vsyncPeriod,
392 /* readyDuration */ config.sfWorkDuration);
393 setDuration(config.sfWorkDuration);
394}
395
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500396void Scheduler::enableHardwareVsync() {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500397 mVsyncSchedule->enableHardwareVsync(mSchedulerCallback);
Ana Krulece588e312018-09-18 12:32:24 -0700398}
399
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500400void Scheduler::disableHardwareVsync(bool disallow) {
401 mVsyncSchedule->disableHardwareVsync(mSchedulerCallback, disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700402}
403
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500404void Scheduler::resyncToHardwareVsync(bool allowToEnable, Fps refreshRate) {
405 if (mVsyncSchedule->isHardwareVsyncAllowed(allowToEnable) && refreshRate.isValid()) {
406 mVsyncSchedule->startPeriodTransition(mSchedulerCallback, refreshRate.getPeriod());
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500407 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500408}
409
410void Scheduler::setRenderRate(Fps renderFrameRate) {
411 const auto mode = leaderSelectorPtr()->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800412
413 using fps_approx_ops::operator!=;
414 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500415 "Mismatch in render frame rates. Selector: %s, Scheduler: %s",
416 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800417
418 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
419 to_string(mode.modePtr->getFps()).c_str());
420
Ady Abrahamfdc049c2023-02-17 14:52:05 +0000421 mVsyncSchedule->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800422}
423
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700424void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700425 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800426
427 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700428 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800429
430 if (now - last > kIgnoreDelay) {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500431 const auto refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
432 resyncToHardwareVsync(false, refreshRate);
Ana Krulecc2870422019-01-29 19:00:58 -0800433 }
434}
435
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500436bool Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriodIn) {
437 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
438 return Period::fromNs(nanos);
439 });
440 return mVsyncSchedule->addResyncSample(mSchedulerCallback, TimePoint::fromNs(timestamp),
441 hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700442}
443
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500444void Scheduler::addPresentFence(std::shared_ptr<FenceTime> fence) {
445 if (mVsyncSchedule->getController().addPresentFence(std::move(fence))) {
446 enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700447 } else {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500448 disableHardwareVsync(false);
Ana Krulece588e312018-09-18 12:32:24 -0700449 }
450}
451
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700452void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200453 // If the content detection feature is off, we still keep the layer history,
454 // since we use it for other features (like Frame Rate API), so layers
455 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000456 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700457}
458
Ady Abrahambdda8f02021-04-01 16:06:11 -0700459void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700460 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700461}
462
Ady Abraham5def7332020-05-29 16:13:47 -0700463void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
464 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400465 if (leaderSelectorPtr()->canSwitch()) {
466 mLayerHistory.record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800467 }
Ana Krulec3084c052018-11-21 20:27:17 +0100468}
469
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100470void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700471 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700472}
473
Andy Labrada096227e2022-06-15 16:58:11 +0000474void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
475 mLayerHistory.setDefaultFrameRateCompatibility(layer,
476 mFeatures.test(Feature::kContentDetection));
477}
478
Dominik Laskowski49cea512019-11-12 14:13:23 -0800479void Scheduler::chooseRefreshRateForContent() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400480 const auto selectorPtr = leaderSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400481 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800482
Ady Abraham8a82ba62020-01-17 12:43:17 -0800483 ATRACE_CALL();
484
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400485 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800486 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abrahama1a49af2019-02-07 14:36:55 -0800487}
488
Ana Krulecfb772822018-11-30 10:44:07 +0100489void Scheduler::resetIdleTimer() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400490 leaderSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800491}
492
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700493void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700494 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800495 mTouchTimer->reset();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400496 leaderSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800497 }
Ady Abraham8532d012019-05-08 14:50:56 -0700498}
499
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500500void Scheduler::setDisplayPowerMode(hal::PowerMode powerMode) {
501 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700502 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700503 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700504 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500505 mVsyncSchedule->getController().setDisplayPowerMode(powerMode);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700506
507 if (mDisplayPowerTimer) {
508 mDisplayPowerTimer->reset();
509 }
510
511 // Display Power event will boost the refresh rate to performance.
512 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700513 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700514}
515
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700516void Scheduler::kernelIdleTimerCallback(TimerState state) {
517 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100518
Ady Abraham2139f732019-11-13 18:56:40 -0800519 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
520 // magic number
Ady Abrahamace3d052022-11-17 16:25:05 -0800521 const Fps refreshRate = leaderSelectorPtr()->getActiveMode().modePtr->getFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700522
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700523 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
524 using namespace fps_approx_ops;
525
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800526 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700527 // If we're not in performance mode then the kernel timer shouldn't do
528 // anything, as the refresh rate during DPU power collapse will be the
529 // same.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500530 resyncToHardwareVsync(true /* makeAvailable */, refreshRate);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800531 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700532 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
533 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700534 // need to update the VsyncController model anyway.
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500535 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700536 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800537
538 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700539}
540
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700541void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800542 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700543 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100544}
545
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700546void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700547 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700548 // Touch event will boost the refresh rate to performance.
549 // Clear layer history to get fresh FPS detection.
550 // NOTE: Instead of checking all the layers, we should be checking the layer
551 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800552 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700553 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700554 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700555 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700556}
557
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700558void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800559 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700560 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700561}
562
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400563void Scheduler::dump(utils::Dumper& dumper) const {
564 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700565
566 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400567 utils::Dumper::Section section(dumper, "Features"sv);
568
569 for (Feature feature : ftl::enum_range<Feature>()) {
570 if (const auto flagOpt = ftl::flag_name(feature)) {
571 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
572 }
573 }
574 }
575 {
576 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400577 {
578 std::scoped_lock lock(mDisplayLock);
579 ftl::FakeGuard guard(kMainThreadContext);
580 dumper.dump("leaderDisplayId"sv, mLeaderDisplayId);
581 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400582 dumper.dump("layerHistory"sv, mLayerHistory.dump());
583 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
584 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
585 }
586
587 mFrameRateOverrideMappings.dump(dumper);
588 dumper.eol();
Ana Krulecb43429d2019-01-09 14:28:51 -0800589}
590
Dominik Laskowski068173d2021-08-11 17:22:59 -0700591void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500592 mVsyncSchedule->dump(out);
Ady Abraham8735eac2020-08-12 16:35:04 -0700593}
594
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800595bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400596 if (consideredSignals.idle) return false;
597
598 const auto frameRateOverrides =
599 leaderSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
600 displayRefreshRate, consideredSignals);
601
602 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
603 // the FrameRateOverrideMappings rather than here.
604 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
605}
606
607void Scheduler::promoteLeaderDisplay(std::optional<PhysicalDisplayId> leaderIdOpt) {
608 // TODO(b/241286431): Choose the leader display.
609 mLeaderDisplayId = leaderIdOpt.value_or(mRefreshRateSelectors.begin()->first);
610 ALOGI("Display %s is the leader", to_string(*mLeaderDisplayId).c_str());
611
612 if (const auto leaderPtr = leaderSelectorPtrLocked()) {
613 leaderPtr->setIdleTimerCallbacks(
614 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
615 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
616 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
617 .onExpired =
618 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
619
620 leaderPtr->startIdleTimer();
Ady Abraham62a0be22020-12-08 16:54:10 -0800621 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400622}
623
624void Scheduler::demoteLeaderDisplay() {
625 // No need to lock for reads on kMainThreadContext.
626 if (const auto leaderPtr = FTL_FAKE_GUARD(mDisplayLock, leaderSelectorPtrLocked())) {
627 leaderPtr->stopIdleTimer();
628 leaderPtr->clearIdleTimerCallbacks();
629 }
630
631 // Clear state that depends on the leader's RefreshRateSelector.
632 std::scoped_lock lock(mPolicyLock);
633 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800634}
635
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800636template <typename S, typename T>
637auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -0800638 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400639 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800640 GlobalSignals consideredSignals;
641
Ady Abraham62a0be22020-12-08 16:54:10 -0800642 bool refreshRateChanged = false;
643 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800644
Ady Abraham8532d012019-05-08 14:50:56 -0700645 {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400646 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800647
648 auto& currentState = mPolicy.*statePtr;
649 if (currentState == newState) return {};
650 currentState = std::forward<T>(newState);
651
Dominik Laskowski596a2562022-10-28 11:26:12 -0400652 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -0800653 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400654 {
655 std::scoped_lock lock(mDisplayLock);
656 ftl::FakeGuard guard(kMainThreadContext);
657
658 modeChoices = chooseDisplayModes();
659
660 // TODO(b/240743786): The leader display's mode must change for any DisplayModeRequest
661 // to go through. Fix this by tracking per-display Scheduler::Policy and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -0800662 std::tie(modeOpt, consideredSignals) =
Dominik Laskowski596a2562022-10-28 11:26:12 -0400663 modeChoices.get(*mLeaderDisplayId)
664 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800665 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400666 })
667 .value();
668 }
ramindani69b58e82022-09-26 16:48:36 -0700669
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400670 modeRequests.reserve(modeChoices.size());
671 for (auto& [id, choice] : modeChoices) {
672 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -0800673 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400674 .emitEvent = !choice.consideredSignals.idle});
675 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800676
Ady Abrahamace3d052022-11-17 16:25:05 -0800677 frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400678
Ady Abrahamace3d052022-11-17 16:25:05 -0800679 if (mPolicy.modeOpt != modeOpt) {
680 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400681 refreshRateChanged = true;
682 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100683 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800684 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700685 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100686 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700687 }
Ady Abraham8532d012019-05-08 14:50:56 -0700688 }
Ady Abraham8532d012019-05-08 14:50:56 -0700689 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800690 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400691 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -0800692 }
693 if (frameRateOverridesChanged) {
694 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
695 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800696 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700697}
698
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400699auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800700 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -0700701
Ady Abraham68636062022-11-16 17:07:25 -0800702 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400703 display::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -0400704
705 // Tallies the score of a refresh rate across `displayCount` displays.
706 struct RefreshRateTally {
707 explicit RefreshRateTally(float score) : score(score) {}
708
709 float score;
710 size_t displayCount = 1;
711 };
712
713 // Chosen to exceed a typical number of refresh rates across displays.
714 constexpr size_t kStaticCapacity = 8;
715 ftl::SmallMap<Fps, RefreshRateTally, kStaticCapacity, FpsApproxEqual> refreshRateTallies;
716
717 const auto globalSignals = makeGlobalSignals();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800718
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400719 for (const auto& [id, selectorPtr] : mRefreshRateSelectors) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800720 auto rankedFrameRates =
Ady Abraham68636062022-11-16 17:07:25 -0800721 selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals);
ramindani69b58e82022-09-26 16:48:36 -0700722
Ady Abrahamace3d052022-11-17 16:25:05 -0800723 for (const auto& [frameRateMode, score] : rankedFrameRates.ranking) {
724 const auto [it, inserted] = refreshRateTallies.try_emplace(frameRateMode.fps, score);
Dominik Laskowski01602522022-10-07 19:02:28 -0400725
726 if (!inserted) {
727 auto& tally = it->second;
728 tally.score += score;
729 tally.displayCount++;
730 }
731 }
732
Ady Abrahamace3d052022-11-17 16:25:05 -0800733 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400734 }
ramindani69b58e82022-09-26 16:48:36 -0700735
Dominik Laskowski01602522022-10-07 19:02:28 -0400736 auto maxScoreIt = refreshRateTallies.cbegin();
ramindani69b58e82022-09-26 16:48:36 -0700737
Dominik Laskowski01602522022-10-07 19:02:28 -0400738 // Find the first refresh rate common to all displays.
739 while (maxScoreIt != refreshRateTallies.cend() &&
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400740 maxScoreIt->second.displayCount != mRefreshRateSelectors.size()) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400741 ++maxScoreIt;
742 }
743
744 if (maxScoreIt != refreshRateTallies.cend()) {
745 // Choose the highest refresh rate common to all displays, if any.
746 for (auto it = maxScoreIt + 1; it != refreshRateTallies.cend(); ++it) {
747 const auto [fps, tally] = *it;
748
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400749 if (tally.displayCount == mRefreshRateSelectors.size() &&
750 tally.score > maxScoreIt->second.score) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400751 maxScoreIt = it;
752 }
ramindani7c487282022-10-10 16:17:51 -0700753 }
754 }
ramindani69b58e82022-09-26 16:48:36 -0700755
Dominik Laskowski01602522022-10-07 19:02:28 -0400756 const std::optional<Fps> chosenFps = maxScoreIt != refreshRateTallies.cend()
757 ? std::make_optional(maxScoreIt->first)
758 : std::nullopt;
759
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400760 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -0400761
ramindani69b58e82022-09-26 16:48:36 -0700762 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -0400763
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400764 for (auto& [ranking, signals] : perDisplayRanking) {
Dominik Laskowski01602522022-10-07 19:02:28 -0400765 if (!chosenFps) {
Ady Abraham68636062022-11-16 17:07:25 -0800766 const auto& [frameRateMode, _] = ranking.front();
Ady Abrahamace3d052022-11-17 16:25:05 -0800767 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
768 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400769 continue;
770 }
771
Ady Abraham68636062022-11-16 17:07:25 -0800772 for (auto& [frameRateMode, _] : ranking) {
Ady Abrahamace3d052022-11-17 16:25:05 -0800773 if (frameRateMode.fps == *chosenFps) {
774 modeChoices.try_emplace(frameRateMode.modePtr->getPhysicalDisplayId(),
775 DisplayModeChoice{frameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -0400776 break;
777 }
778 }
779 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400780 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -0700781}
782
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400783GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +0000784 const bool powerOnImminent = mDisplayPowerTimer &&
785 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
786 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700787
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400788 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
789 .idle = mPolicy.idleTimer == TimerState::Expired,
790 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800791}
792
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500793FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700794 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500795 const auto frameRateMode =
796 leaderSelectorPtr()
797 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
798 .ranking.front()
799 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -0400800
Dominik Laskowskifc378b02022-12-02 14:56:05 -0500801 // Make sure the stored mode is up to date.
802 mPolicy.modeOpt = frameRateMode;
803
804 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700805}
806
Peiyong Line9d809e2020-04-14 13:10:48 -0700807void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800808 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
809 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
810
811 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
812 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
813 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
814 }
815}
816
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700817bool Scheduler::onPostComposition(nsecs_t presentTime) {
818 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
819 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
820 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
821 // We need to composite again as refreshTimeNanos is still in the future.
822 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700823 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700824
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700825 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800826 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -0700827 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800828}
829
Ady Abraham7825c682021-05-17 15:12:14 -0700830void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700831 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800832}
833
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800834void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
835 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
836 return;
837 }
838
839 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
840}
841
Ady Abraham62a0be22020-12-08 16:54:10 -0800842void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
843 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
844 return;
845 }
846
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800847 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -0800848}
849
Dominik Laskowski068173d2021-08-11 17:22:59 -0700850} // namespace android::scheduler