blob: 76f1af9f568fa33a6dfa84cb1768d16cd6a08771 [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 Laskowskiec0eac22023-01-28 16:16:19 -050028#include <ftl/concat.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040029#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000030#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040031#include <ftl/small_map.h>
Ady Abraham9243bba2023-02-10 15:31:14 -080032#include <gui/TraceUtils.h>
chaviw3277faf2021-05-19 16:45:23 -050033#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080034#include <system/window.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050035#include <ui/DisplayMap.h>
Ana Krulec3084c052018-11-21 20:27:17 +010036#include <utils/Timers.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070037
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070038#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowski63f12792023-01-21 16:58:22 -050039#include <scheduler/interface/ICompositor.h>
40
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070041#include <algorithm>
42#include <cinttypes>
43#include <cstdint>
44#include <functional>
45#include <memory>
46#include <numeric>
47
48#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070049#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080050#include "FrameRateOverrideMappings.h"
Rachel Lee2248f522023-01-27 16:45:23 -080051#include "FrontEnd/LayerHandle.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070052#include "OneShotTimer.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090053#include "SurfaceFlingerProperties.h"
Dominik Laskowskic404cb42023-03-03 19:57:53 -050054#include "VSyncTracker.h"
55#include "VsyncController.h"
56#include "VsyncSchedule.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070057
Dominik Laskowski98041832019-08-01 18:35:59 -070058#define RETURN_IF_INVALID_HANDLE(handle, ...) \
59 do { \
60 if (mConnections.count(handle) == 0) { \
61 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
62 return __VA_ARGS__; \
63 } \
64 } while (false)
65
Dominik Laskowski068173d2021-08-11 17:22:59 -070066namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070067
Dominik Laskowski1c99a002023-01-20 17:10:36 -050068Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
69 sp<VsyncModulator> modulatorPtr)
70 : impl::MessageQueue(compositor),
71 mFeatures(features),
72 mVsyncModulator(std::move(modulatorPtr)),
73 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070074
Dominik Laskowski83bd7712022-01-07 14:30:53 -080075Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080076 // MessageQueue depends on VsyncSchedule, so first destroy it.
77 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
78 // which will cause a use-after-free issue.
79 Impl::destroyVsync();
80
Dominik Laskowski83bd7712022-01-07 14:30:53 -080081 // Stop timers and wait for their threads to exit.
82 mDisplayPowerTimer.reset();
83 mTouchTimer.reset();
84
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040085 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -050086 demotePacesetterDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080087}
88
Dominik Laskowski9c93d602021-10-07 19:38:26 -070089void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070090 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070091 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070092
Dominik Laskowski98041832019-08-01 18:35:59 -070093 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070094 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070095 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080096 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070097 [this] { touchTimerCallback(TimerState::Reset); },
98 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070099 mTouchTimer->start();
100 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700101
Dominik Laskowski98041832019-08-01 18:35:59 -0700102 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
103 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800104 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700105 [this] { displayPowerTimerCallback(TimerState::Reset); },
106 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700107 mDisplayPowerTimer->start();
108 }
Ana Krulece588e312018-09-18 12:32:24 -0700109}
110
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500111void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
112 demotePacesetterDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400113
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500114 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800115}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700116
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400117void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400118 auto schedulePtr = std::make_shared<VsyncSchedule>(displayId, mFeatures,
119 [this](PhysicalDisplayId id, bool enable) {
120 onHardwareVsyncRequest(id, enable);
121 });
122
123 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr));
Leon Scroggins III67388622023-02-06 20:36:20 -0500124}
125
126void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
127 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500128 VsyncSchedulePtr schedulePtr) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500129 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400130
Dominik Laskowski008bec02023-03-14 12:04:58 -0400131 auto [pacesetterVsyncSchedule, isNew] = [&]() FTL_FAKE_GUARD(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400132 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400133 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500134 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
135 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400136 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400137
Dominik Laskowski008bec02023-03-14 12:04:58 -0400138 return std::make_pair(promotePacesetterDisplayLocked(), isNew);
139 }();
140
Leon Scroggins39d25342023-04-19 17:11:01 +0000141 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400142
143 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
144 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400145 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400146 }
Dominik Laskowski01602522022-10-07 19:02:28 -0400147}
148
149void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500150 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400151
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400152 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
153 {
154 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500155 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400156
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400157 // Do not allow removing the final display. Code in the scheduler expects
158 // there to be at least one display. (This may be relaxed in the future with
159 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500160 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500161
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400162 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
163 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000164 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400165}
166
Dominik Laskowski756b7892021-08-04 12:53:59 -0700167void Scheduler::run() {
168 while (true) {
169 waitMessage();
170 }
171}
172
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700173void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
174 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500175 const FrameTargeter::BeginFrameArgs beginFrameArgs =
176 {.frameBeginTime = SchedulerClock::now(),
177 .vsyncId = vsyncId,
178 // TODO(b/255601557): Calculate per display.
179 .expectedVsyncTime = expectedVsyncTime,
180 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700181
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500182 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId);
183 const auto pacesetterId = *mPacesetterDisplayId;
184 const auto pacesetterOpt = mDisplays.get(pacesetterId);
185
186 FrameTargeter& pacesetterTargeter = *pacesetterOpt->get().targeterPtr;
187 pacesetterTargeter.beginFrame(beginFrameArgs, *pacesetterOpt->get().schedulePtr);
188
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400189 FrameTargets targets;
190 targets.try_emplace(pacesetterId, &pacesetterTargeter.target());
191
192 for (const auto& [id, display] : mDisplays) {
193 if (id == pacesetterId) continue;
194
195 const FrameTargeter& targeter = *display.targeterPtr;
196 targets.try_emplace(id, &targeter.target());
197 }
198
199 if (!compositor.commit(pacesetterId, targets)) return;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500200
201 // TODO(b/256196556): Choose the frontrunner display.
202 FrameTargeters targeters;
203 targeters.try_emplace(pacesetterId, &pacesetterTargeter);
204
205 for (auto& [id, display] : mDisplays) {
206 if (id == pacesetterId) continue;
207
208 FrameTargeter& targeter = *display.targeterPtr;
209 targeter.beginFrame(beginFrameArgs, *display.schedulePtr);
210
211 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700212 }
213
Alec Mouri1c7938e2023-09-22 04:17:23 +0000214 if (flagutils::vrrConfigEnabled() &&
215 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
216 const auto period = pacesetterTargeter.target().expectedFrameDuration();
217 const auto skipDuration = Duration::fromNs(
218 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
219 ATRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
220 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
221 std::this_thread::sleep_for(skipDuration);
222 mPacesetterFrameDurationFractionToSkip = 0.f;
223 }
224
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500225 const auto resultsPerDisplay = compositor.composite(pacesetterId, targeters);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700226 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400227
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500228 for (const auto& [id, targeter] : targeters) {
229 const auto resultOpt = resultsPerDisplay.get(id);
230 LOG_ALWAYS_FATAL_IF(!resultOpt);
231 targeter->endFrame(*resultOpt);
232 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700233}
234
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500235std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800236 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500237 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800238 return mFrameRateOverrideMappings
239 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800240}
241
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400242bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800243 const auto frameRate = getFrameRateOverride(uid);
244 if (!frameRate.has_value()) {
245 return true;
246 }
247
Ady Abraham9243bba2023-02-10 15:31:14 -0800248 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400249 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700250}
251
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400252bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
253 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700254}
255
Ady Abrahamf2851612023-09-25 17:19:00 -0700256bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
257 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500258}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800259
Ady Abrahamf2851612023-09-25 17:19:00 -0700260Period Scheduler::getVsyncPeriod(uid_t uid) {
261 const auto [refreshRate, period] = [this] {
262 std::scoped_lock lock(mDisplayLock);
263 const auto pacesetterOpt = pacesetterDisplayLocked();
264 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
265 const Display& pacesetter = *pacesetterOpt;
266 return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
267 pacesetter.schedulePtr->period());
268 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500269
Ady Abrahamf2851612023-09-25 17:19:00 -0700270 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800271
Ady Abrahamf2851612023-09-25 17:19:00 -0700272 const auto frameRate = getFrameRateOverride(uid);
273 if (!frameRate.has_value()) {
274 return currentPeriod;
275 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100276
Ady Abrahamf2851612023-09-25 17:19:00 -0700277 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
278 if (divisor <= 1) {
279 return currentPeriod;
280 }
281
282 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
283 // behaviour.
284 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100285}
286
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500287ConnectionHandle Scheduler::createEventThread(Cycle cycle,
288 frametimeline::TokenManager* tokenManager,
289 std::chrono::nanoseconds workDuration,
290 std::chrono::nanoseconds readyDuration) {
291 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Ady Abrahamf2851612023-09-25 17:19:00 -0700292 getVsyncSchedule(), tokenManager, *this,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500293 workDuration, readyDuration);
294
295 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
296 handle = createConnection(std::move(eventThread));
297 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700298}
Ana Krulec98b5b242018-08-10 15:03:23 -0700299
Dominik Laskowski068173d2021-08-11 17:22:59 -0700300ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700301 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
302 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800303
Ady Abrahamf2851612023-09-25 17:19:00 -0700304 auto connection = eventThread->createEventConnection();
Dominik Laskowski98041832019-08-01 18:35:59 -0700305
Ana Krulec6ddd2612020-09-24 13:06:33 -0700306 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700307 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
308 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700309}
310
311sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800312 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
313 const sp<IBinder>& layerHandle) {
Ady Abraham822ecbd2023-07-07 16:16:09 -0700314 const auto connection = [&]() -> sp<EventThreadConnection> {
315 std::scoped_lock lock(mConnectionsLock);
316 RETURN_IF_INVALID_HANDLE(handle, nullptr);
317
Ady Abrahamf2851612023-09-25 17:19:00 -0700318 return mConnections[handle].thread->createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700319 }();
320 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
321
322 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
323 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
324 // processed on the main thread.
325 mSchedulerCallback.onChoreographerAttached();
326
327 std::scoped_lock lock(mChoreographerLock);
328 const auto [iter, emplaced] =
329 mAttachedChoreographers.emplace(layerId,
330 AttachedChoreographers{Fps(), {connection}});
331 if (!emplaced) {
332 iter->second.connections.emplace(connection);
333 connection->frameRate = iter->second.frameRate;
334 }
335 }
336 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700337}
338
Dominik Laskowski98041832019-08-01 18:35:59 -0700339sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700340 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700341 RETURN_IF_INVALID_HANDLE(handle, nullptr);
342 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700343}
344
Dominik Laskowski98041832019-08-01 18:35:59 -0700345void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
346 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700347 android::EventThread* thread;
348 {
349 std::lock_guard<std::mutex> lock(mConnectionsLock);
350 RETURN_IF_INVALID_HANDLE(handle);
351 thread = mConnections[handle].thread.get();
352 }
353
354 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700355}
356
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700357void Scheduler::onHotplugConnectionError(ConnectionHandle handle, int32_t errorCode) {
358 android::EventThread* thread;
359 {
360 std::lock_guard<std::mutex> lock(mConnectionsLock);
361 RETURN_IF_INVALID_HANDLE(handle);
362 thread = mConnections[handle].thread.get();
363 }
364
365 thread->onHotplugConnectionError(errorCode);
366}
367
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500368void Scheduler::enableSyntheticVsync(bool enable) {
369 // TODO(b/241285945): Remove connection handles.
370 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700371 android::EventThread* thread;
372 {
373 std::lock_guard<std::mutex> lock(mConnectionsLock);
374 RETURN_IF_INVALID_HANDLE(handle);
375 thread = mConnections[handle].thread.get();
376 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500377 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700378}
379
Ady Abraham62a0be22020-12-08 16:54:10 -0800380void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800381 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500382 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800383
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800384 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800385 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800386
Ady Abraham62f216c2020-10-13 19:07:23 -0700387 android::EventThread* thread;
388 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800389 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700390 RETURN_IF_INVALID_HANDLE(handle);
391 thread = mConnections[handle].thread.get();
392 }
393 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
394}
395
Ady Abrahamace3d052022-11-17 16:25:05 -0800396void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800397 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700398 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100399 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700400 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700401
402 // Invalidate content based refresh rate selection so it could be calculated
403 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700404 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800405 }
Ady Abraham690f4612021-07-01 23:24:03 -0700406 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700407}
408
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100409void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700410 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800411 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100412 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700413 return;
414 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700415 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100416 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700417 return;
418 }
419
Ady Abrahamd1591702021-07-27 16:27:56 -0700420 // If the mode is not the current mode, this means that a
421 // mode change is in progress. In that case we shouldn't dispatch an event
422 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500423 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700424 return;
425 }
426
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100427 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800428 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700429 return;
430 }
431
Ady Abrahamace3d052022-11-17 16:25:05 -0800432 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700433 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
434 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700435}
436
Ady Abrahamace3d052022-11-17 16:25:05 -0800437void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700438 android::EventThread* thread;
439 {
440 std::lock_guard<std::mutex> lock(mConnectionsLock);
441 RETURN_IF_INVALID_HANDLE(handle);
442 thread = mConnections[handle].thread.get();
443 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800444 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800445}
446
Dominik Laskowski98041832019-08-01 18:35:59 -0700447void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700448 android::EventThread* thread;
449 {
450 std::lock_guard<std::mutex> lock(mConnectionsLock);
451 RETURN_IF_INVALID_HANDLE(handle);
452 thread = mConnections.at(handle).thread.get();
453 }
454 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700455}
456
Ady Abraham9c53ee72020-07-22 21:16:18 -0700457void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
458 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700459 android::EventThread* thread;
460 {
461 std::lock_guard<std::mutex> lock(mConnectionsLock);
462 RETURN_IF_INVALID_HANDLE(handle);
463 thread = mConnections[handle].thread.get();
464 }
465 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700466}
Ana Krulece588e312018-09-18 12:32:24 -0700467
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500468void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
469 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
470}
471
472void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
473 setDuration(mAppConnectionHandle,
474 /* workDuration */ config.appWorkDuration,
475 /* readyDuration */ config.sfWorkDuration);
476 setDuration(mSfConnectionHandle,
477 /* workDuration */ vsyncPeriod,
478 /* readyDuration */ config.sfWorkDuration);
479 setDuration(config.sfWorkDuration);
480}
481
Leon Scroggins III67388622023-02-06 20:36:20 -0500482void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
483 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400484 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400485 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700486}
487
Leon Scroggins III67388622023-02-06 20:36:20 -0500488void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
489 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400490 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400491 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700492}
493
Leon Scroggins III67388622023-02-06 20:36:20 -0500494void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800495 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500496 std::scoped_lock lock(mDisplayLock);
497 ftl::FakeGuard guard(kMainThreadContext);
498
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500499 for (const auto& [id, _] : mDisplays) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500500 resyncToHardwareVsyncLocked(id, allowToEnable);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500501 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500502}
503
Leon Scroggins III67388622023-02-06 20:36:20 -0500504void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
505 std::optional<Fps> refreshRate) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500506 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400507 if (!displayOpt) {
508 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
509 return;
510 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500511 const Display& display = *displayOpt;
512
513 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500514 if (!refreshRate) {
ramindania04b8a52023-08-07 18:49:47 -0700515 refreshRate = display.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Leon Scroggins III67388622023-02-06 20:36:20 -0500516 }
517 if (refreshRate->isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400518 constexpr bool kForce = false;
519 display.schedulePtr->startPeriodTransition(refreshRate->getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500520 }
521 }
522}
523
Dominik Laskowski66295432023-03-14 12:25:36 -0400524void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
525 static const auto& whence = __func__;
526 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
527
528 // On main thread to serialize reads/writes of pending hardware VSYNC state.
529 static_cast<void>(
530 schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
531 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
532
533 if (const auto displayOpt = mDisplays.get(id)) {
534 auto& display = displayOpt->get();
535 display.schedulePtr->setPendingHardwareVsyncState(enabled);
536
537 if (display.powerMode != hal::PowerMode::OFF) {
538 mSchedulerCallback.requestHardwareVsync(id, enabled);
539 }
540 }
541 }));
542}
543
Leon Scroggins III67388622023-02-06 20:36:20 -0500544void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
545 std::scoped_lock lock(mDisplayLock);
546 ftl::FakeGuard guard(kMainThreadContext);
547
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500548 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400549 if (!displayOpt) {
550 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
551 return;
552 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500553 const Display& display = *displayOpt;
554 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800555
556 using fps_approx_ops::operator!=;
557 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500558 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
559 "%" PRIu64,
560 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800561
562 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700563 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800564
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500565 display.schedulePtr->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800566}
567
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700568void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700569 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800570
571 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700572 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800573
574 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500575 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800576 }
577}
578
Leon Scroggins III67388622023-02-06 20:36:20 -0500579bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
580 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500581 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
582 return Period::fromNs(nanos);
583 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400584 auto schedule = getVsyncSchedule(id);
585 if (!schedule) {
586 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
587 return false;
588 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400589 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700590}
591
Leon Scroggins III67388622023-02-06 20:36:20 -0500592void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500593 const auto scheduleOpt =
594 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
595 return display.powerMode == hal::PowerMode::OFF
596 ? std::nullopt
597 : std::make_optional(display.schedulePtr);
598 });
599
600 if (!scheduleOpt) return;
601 const auto& schedule = scheduleOpt->get();
602
Dominik Laskowski66295432023-03-14 12:25:36 -0400603 if (const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence))) {
604 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700605 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400606 constexpr bool kDisallow = false;
607 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700608 }
609}
610
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700611void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200612 // If the content detection feature is off, we still keep the layer history,
613 // since we use it for other features (like Frame Rate API), so layers
614 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000615 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700616}
617
Ady Abrahambdda8f02021-04-01 16:06:11 -0700618void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700619 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700620}
621
Ady Abraham822ecbd2023-07-07 16:16:09 -0700622void Scheduler::onLayerDestroyed(Layer* layer) {
623 std::scoped_lock lock(mChoreographerLock);
624 mAttachedChoreographers.erase(layer->getSequence());
625}
626
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000627void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700628 LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500629 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000630 mLayerHistory.record(id, layerProps, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800631 }
Ana Krulec3084c052018-11-21 20:27:17 +0100632}
633
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100634void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700635 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700636}
637
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700638void Scheduler::setDefaultFrameRateCompatibility(
639 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
640 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000641 mFeatures.test(Feature::kContentDetection));
642}
643
Ady Abraham822ecbd2023-07-07 16:16:09 -0700644void Scheduler::chooseRefreshRateForContent(
645 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
646 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500647 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400648 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800649
Ady Abraham8a82ba62020-01-17 12:43:17 -0800650 ATRACE_CALL();
651
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400652 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800653 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700654
655 if (updateAttachedChoreographer) {
656 LOG_ALWAYS_FATAL_IF(!hierarchy);
657
658 // update the attached choreographers after we selected the render rate.
659 const ftl::Optional<FrameRateMode> modeOpt = [&] {
660 std::scoped_lock lock(mPolicyLock);
661 return mPolicy.modeOpt;
662 }();
663
664 if (modeOpt) {
665 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
666 }
667 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800668}
669
Ana Krulecfb772822018-11-30 10:44:07 +0100670void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500671 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800672}
673
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700674void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700675 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800676 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500677 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800678 }
Ady Abraham8532d012019-05-08 14:50:56 -0700679}
680
Leon Scroggins III67388622023-02-06 20:36:20 -0500681void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500682 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500683 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500684 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500685 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500686 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500687 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700688 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700689 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700690 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500691 {
692 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400693
694 const auto displayOpt = mDisplays.get(id);
695 LOG_ALWAYS_FATAL_IF(!displayOpt);
696 auto& display = displayOpt->get();
697
698 display.powerMode = powerMode;
699 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500700 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500701 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700702
703 if (mDisplayPowerTimer) {
704 mDisplayPowerTimer->reset();
705 }
706
707 // Display Power event will boost the refresh rate to performance.
708 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700709 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700710}
711
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500712auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
713 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500714 std::scoped_lock lock(mDisplayLock);
715 return getVsyncScheduleLocked(idOpt);
716}
717
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500718auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
719 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500720 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500721
Leon Scroggins III67388622023-02-06 20:36:20 -0500722 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500723 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
724 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500725 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500726
727 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400728 if (!displayOpt) {
729 return nullptr;
730 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500731 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500732}
733
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700734void Scheduler::kernelIdleTimerCallback(TimerState state) {
735 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100736
Ady Abraham2139f732019-11-13 18:56:40 -0800737 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
738 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700739 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700740
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700741 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
742 using namespace fps_approx_ops;
743
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800744 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700745 // If we're not in performance mode then the kernel timer shouldn't do
746 // anything, as the refresh rate during DPU power collapse will be the
747 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500748 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800749 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700750 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
751 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700752 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500753 std::scoped_lock lock(mDisplayLock);
754 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500755 for (const auto& [_, display] : mDisplays) {
756 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400757 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500758 }
Alec Mouridc28b372019-04-18 21:17:13 -0700759 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800760
761 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700762}
763
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700764void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800765 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700766 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100767}
768
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700769void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700770 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700771 // Touch event will boost the refresh rate to performance.
772 // Clear layer history to get fresh FPS detection.
773 // NOTE: Instead of checking all the layers, we should be checking the layer
774 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800775 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700776 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700777 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700778 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700779}
780
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700781void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800782 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700783 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700784}
785
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400786void Scheduler::dump(utils::Dumper& dumper) const {
787 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700788
789 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400790 utils::Dumper::Section section(dumper, "Features"sv);
791
792 for (Feature feature : ftl::enum_range<Feature>()) {
793 if (const auto flagOpt = ftl::flag_name(feature)) {
794 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
795 }
796 }
797 }
798 {
799 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400800 {
801 std::scoped_lock lock(mDisplayLock);
802 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500803 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400804 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400805 dumper.dump("layerHistory"sv, mLayerHistory.dump());
806 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
807 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
808 }
809
810 mFrameRateOverrideMappings.dump(dumper);
811 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400812
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500813 {
814 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
815
816 std::scoped_lock lock(mDisplayLock);
817 ftl::FakeGuard guard(kMainThreadContext);
818
819 for (const auto& [id, display] : mDisplays) {
820 utils::Dumper::Section
821 section(dumper,
822 id == mPacesetterDisplayId
823 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
824 : ftl::Concat("Follower Display ", id.value).c_str());
825
826 display.targeterPtr->dump(dumper);
827 dumper.eol();
828 }
829 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800830}
831
Dominik Laskowski068173d2021-08-11 17:22:59 -0700832void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500833 std::scoped_lock lock(mDisplayLock);
834 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500835 if (mPacesetterDisplayId) {
836 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
837 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500838 getVsyncScheduleLocked()->dump(out);
839 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500840 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500841 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500842 continue;
843 }
844 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500845 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500846 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700847}
848
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800849bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700850 std::scoped_lock lock(mPolicyLock);
851 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
852}
853
854bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
855 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400856 if (consideredSignals.idle) return false;
857
858 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500859 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
860 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400861
862 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
863 // the FrameRateOverrideMappings rather than here.
864 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
865}
866
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500867void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400868 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
869
870 {
871 std::scoped_lock lock(mDisplayLock);
872 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
873 }
874
Leon Scroggins39d25342023-04-19 17:11:01 +0000875 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400876}
877
878std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
879 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500880 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500881 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500882 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400883
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500884 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
885 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
886 const Display& pacesetter = *pacesetterOpt;
887
888 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400889 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
890 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
891 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
892 .onExpired =
893 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
894
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500895 pacesetter.selectorPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500896
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500897 newVsyncSchedulePtr = pacesetter.schedulePtr;
898
ramindania04b8a52023-08-07 18:49:47 -0700899 const Fps refreshRate = pacesetter.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Dominik Laskowski66295432023-03-14 12:25:36 -0400900 constexpr bool kForce = true;
901 newVsyncSchedulePtr->startPeriodTransition(refreshRate.getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500902 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500903 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400904}
Leon Scroggins III67388622023-02-06 20:36:20 -0500905
Leon Scroggins39d25342023-04-19 17:11:01 +0000906void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
907 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400908 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500909 {
910 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400911 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -0500912 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400913 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -0500914 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800915 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400916 for (auto* thread : threads) {
Leon Scroggins39d25342023-04-19 17:11:01 +0000917 thread->onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400918 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400919}
920
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500921void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400922 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500923 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
924 pacesetterPtr->stopIdleTimer();
925 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400926 }
927
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500928 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400929 std::scoped_lock lock(mPolicyLock);
930 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800931}
932
Ady Abraham822ecbd2023-07-07 16:16:09 -0700933void Scheduler::updateAttachedChoreographersFrameRate(
934 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
935 std::scoped_lock lock(mChoreographerLock);
936
937 const auto layerId = static_cast<int32_t>(layer.id);
938 const auto choreographers = mAttachedChoreographers.find(layerId);
939 if (choreographers == mAttachedChoreographers.end()) {
940 return;
941 }
942
943 auto& layerChoreographers = choreographers->second;
944
945 layerChoreographers.frameRate = fps;
946 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
947 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
948
949 auto it = layerChoreographers.connections.begin();
950 while (it != layerChoreographers.connections.end()) {
951 sp<EventThreadConnection> choreographerConnection = it->promote();
952 if (choreographerConnection) {
953 choreographerConnection->frameRate = fps;
954 it++;
955 } else {
956 it = choreographers->second.connections.erase(it);
957 }
958 }
959
960 if (layerChoreographers.connections.empty()) {
961 mAttachedChoreographers.erase(choreographers);
962 }
963}
964
965int Scheduler::updateAttachedChoreographersInternal(
966 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
967 int parentDivisor) {
968 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
969
970 int divisor = 0;
971 if (layerHierarchy.getLayer()) {
972 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
973 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
974 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
975 parentDivisor);
976
977 if (frameRate.isValid()) {
978 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
979 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
980 // Since this layer wants an exact match, we would only set a frame rate if the
981 // desired rate is a divisor of the display refresh rate.
982 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
983 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
984 // find the closest frame rate divisor for the desired frame rate.
985 divisor = static_cast<int>(
986 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
987 }
988 }
989 }
990
991 // We start by traversing the children, updating their choreographers, and getting back the
992 // aggregated frame rate.
993 int childrenDivisor = 0;
994 for (const auto& [child, _] : layerHierarchy.mChildren) {
995 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
996
997 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
998
999 const int childDivisor =
1000 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1001 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1002 if (childDivisor > 0) {
1003 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1004 }
1005 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1006 }
1007
1008 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1009
1010 // If there is no explicit vote for this layer. Use the children's vote if exists
1011 divisor = (divisor == 0) ? childrenDivisor : divisor;
1012 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1013
1014 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1015 divisor = (divisor == 0) ? parentDivisor : divisor;
1016 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1017
1018 if (layerHierarchy.getLayer()) {
1019 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1020 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1021 }
1022
1023 return divisor;
1024}
1025
1026void Scheduler::updateAttachedChoreographers(
1027 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1028 ATRACE_CALL();
1029 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1030}
1031
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001032template <typename S, typename T>
1033auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001034 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001035 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001036 GlobalSignals consideredSignals;
1037
Ady Abraham62a0be22020-12-08 16:54:10 -08001038 bool refreshRateChanged = false;
1039 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001040
Ady Abraham8532d012019-05-08 14:50:56 -07001041 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001042 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001043
1044 auto& currentState = mPolicy.*statePtr;
1045 if (currentState == newState) return {};
1046 currentState = std::forward<T>(newState);
1047
Dominik Laskowski596a2562022-10-28 11:26:12 -04001048 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001049 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001050 {
1051 std::scoped_lock lock(mDisplayLock);
1052 ftl::FakeGuard guard(kMainThreadContext);
1053
1054 modeChoices = chooseDisplayModes();
1055
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001056 // TODO(b/240743786): The pacesetter display's mode must change for any
1057 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1058 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001059 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001060 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001061 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001062 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001063 })
1064 .value();
1065 }
ramindani69b58e82022-09-26 16:48:36 -07001066
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001067 modeRequests.reserve(modeChoices.size());
1068 for (auto& [id, choice] : modeChoices) {
1069 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001070 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001071 .emitEvent = !choice.consideredSignals.idle});
1072 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001073
Ady Abraham33a386b2023-07-18 15:37:11 -07001074 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001075
Ady Abrahamace3d052022-11-17 16:25:05 -08001076 if (mPolicy.modeOpt != modeOpt) {
1077 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001078 refreshRateChanged = true;
1079 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001080 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001081 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001082 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001083 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001084 }
Ady Abraham8532d012019-05-08 14:50:56 -07001085 }
Ady Abraham8532d012019-05-08 14:50:56 -07001086 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001087 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001088 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001089 }
1090 if (frameRateOverridesChanged) {
1091 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1092 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001093 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001094}
1095
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001096auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001097 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001098
Ady Abraham68636062022-11-16 17:07:25 -08001099 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski6b049ff2023-01-29 15:46:45 -05001100 ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -04001101 const auto globalSignals = makeGlobalSignals();
ramindani22f2ead2023-04-21 10:27:11 -07001102 Fps pacesetterFps;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001103
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001104 for (const auto& [id, display] : mDisplays) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001105 auto rankedFrameRates =
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001106 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
1107 globalSignals);
ramindani22f2ead2023-04-21 10:27:11 -07001108 if (id == *mPacesetterDisplayId) {
1109 pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
Dominik Laskowski01602522022-10-07 19:02:28 -04001110 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001111 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001112 }
ramindani69b58e82022-09-26 16:48:36 -07001113
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001114 DisplayModeChoiceMap modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001115 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -04001116
ramindani22f2ead2023-04-21 10:27:11 -07001117 for (auto& [rankings, signals] : perDisplayRanking) {
1118 const auto chosenFrameRateMode =
1119 ftl::find_if(rankings,
1120 [&](const auto& ranking) {
1121 return ranking.frameRateMode.fps == pacesetterFps;
1122 })
1123 .transform([](const auto& scoredFrameRate) {
1124 return scoredFrameRate.get().frameRateMode;
1125 })
1126 .value_or(rankings.front().frameRateMode);
Dominik Laskowski01602522022-10-07 19:02:28 -04001127
ramindani22f2ead2023-04-21 10:27:11 -07001128 modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
1129 DisplayModeChoice{chosenFrameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -04001130 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001131 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001132}
1133
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001134GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001135 const bool powerOnImminent = mDisplayPowerTimer &&
1136 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1137 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001138
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001139 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1140 .idle = mPolicy.idleTimer == TimerState::Expired,
1141 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001142}
1143
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001144FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001145 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001146 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001147 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001148 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1149 .ranking.front()
1150 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001151
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001152 // Make sure the stored mode is up to date.
1153 mPolicy.modeOpt = frameRateMode;
1154
1155 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001156}
1157
Peiyong Line9d809e2020-04-14 13:10:48 -07001158void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001159 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1160 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1161
1162 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1163 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1164 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1165 }
1166}
1167
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001168bool Scheduler::onPostComposition(nsecs_t presentTime) {
1169 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1170 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1171 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1172 // We need to composite again as refreshTimeNanos is still in the future.
1173 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001174 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001175
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001176 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001177 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001178 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001179}
1180
Ady Abraham7825c682021-05-17 15:12:14 -07001181void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001182 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001183}
1184
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001185void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
1186 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1187 return;
1188 }
1189
1190 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1191}
1192
Ady Abraham62a0be22020-12-08 16:54:10 -08001193void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1194 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1195 return;
1196 }
1197
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001198 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001199}
1200
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001201void Scheduler::updateSmallAreaDetection(
1202 std::vector<std::pair<uid_t, float>>& uidThresholdMappings) {
1203 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1204}
1205
1206void Scheduler::setSmallAreaDetectionThreshold(uid_t uid, float threshold) {
1207 mSmallAreaDetectionAllowMappings.setThesholdForUid(uid, threshold);
1208}
1209
1210bool Scheduler::isSmallDirtyArea(uid_t uid, uint32_t dirtyArea) {
1211 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForUid(uid);
1212 if (oThreshold) return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1213
1214 return false;
1215}
1216
Dominik Laskowski068173d2021-08-11 17:22:59 -07001217} // namespace android::scheduler