blob: d72ae1f03e427ec90817ba9851f2132664b00913 [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
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500214 const auto resultsPerDisplay = compositor.composite(pacesetterId, targeters);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700215 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400216
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500217 for (const auto& [id, targeter] : targeters) {
218 const auto resultOpt = resultsPerDisplay.get(id);
219 LOG_ALWAYS_FATAL_IF(!resultOpt);
220 targeter->endFrame(*resultOpt);
221 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700222}
223
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500224std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800225 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500226 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800227 return mFrameRateOverrideMappings
228 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800229}
230
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400231bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800232 const auto frameRate = getFrameRateOverride(uid);
233 if (!frameRate.has_value()) {
234 return true;
235 }
236
Ady Abraham9243bba2023-02-10 15:31:14 -0800237 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400238 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700239}
240
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400241bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
242 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700243}
244
Ady Abrahamf2851612023-09-25 17:19:00 -0700245bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
246 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500247}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800248
Ady Abrahamf2851612023-09-25 17:19:00 -0700249Period Scheduler::getVsyncPeriod(uid_t uid) {
250 const auto [refreshRate, period] = [this] {
251 std::scoped_lock lock(mDisplayLock);
252 const auto pacesetterOpt = pacesetterDisplayLocked();
253 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
254 const Display& pacesetter = *pacesetterOpt;
255 return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
256 pacesetter.schedulePtr->period());
257 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500258
Ady Abrahamf2851612023-09-25 17:19:00 -0700259 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800260
Ady Abrahamf2851612023-09-25 17:19:00 -0700261 const auto frameRate = getFrameRateOverride(uid);
262 if (!frameRate.has_value()) {
263 return currentPeriod;
264 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100265
Ady Abrahamf2851612023-09-25 17:19:00 -0700266 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
267 if (divisor <= 1) {
268 return currentPeriod;
269 }
270
271 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
272 // behaviour.
273 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100274}
275
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500276ConnectionHandle Scheduler::createEventThread(Cycle cycle,
277 frametimeline::TokenManager* tokenManager,
278 std::chrono::nanoseconds workDuration,
279 std::chrono::nanoseconds readyDuration) {
280 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Ady Abrahamf2851612023-09-25 17:19:00 -0700281 getVsyncSchedule(), tokenManager, *this,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500282 workDuration, readyDuration);
283
284 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
285 handle = createConnection(std::move(eventThread));
286 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700287}
Ana Krulec98b5b242018-08-10 15:03:23 -0700288
Dominik Laskowski068173d2021-08-11 17:22:59 -0700289ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700290 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
291 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800292
Ady Abrahamf2851612023-09-25 17:19:00 -0700293 auto connection = eventThread->createEventConnection();
Dominik Laskowski98041832019-08-01 18:35:59 -0700294
Ana Krulec6ddd2612020-09-24 13:06:33 -0700295 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700296 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
297 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700298}
299
300sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800301 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
302 const sp<IBinder>& layerHandle) {
Ady Abraham822ecbd2023-07-07 16:16:09 -0700303 const auto connection = [&]() -> sp<EventThreadConnection> {
304 std::scoped_lock lock(mConnectionsLock);
305 RETURN_IF_INVALID_HANDLE(handle, nullptr);
306
Ady Abrahamf2851612023-09-25 17:19:00 -0700307 return mConnections[handle].thread->createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700308 }();
309 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
310
311 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
312 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
313 // processed on the main thread.
314 mSchedulerCallback.onChoreographerAttached();
315
316 std::scoped_lock lock(mChoreographerLock);
317 const auto [iter, emplaced] =
318 mAttachedChoreographers.emplace(layerId,
319 AttachedChoreographers{Fps(), {connection}});
320 if (!emplaced) {
321 iter->second.connections.emplace(connection);
322 connection->frameRate = iter->second.frameRate;
323 }
324 }
325 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700326}
327
Dominik Laskowski98041832019-08-01 18:35:59 -0700328sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700329 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700330 RETURN_IF_INVALID_HANDLE(handle, nullptr);
331 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700332}
333
Dominik Laskowski98041832019-08-01 18:35:59 -0700334void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
335 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700336 android::EventThread* thread;
337 {
338 std::lock_guard<std::mutex> lock(mConnectionsLock);
339 RETURN_IF_INVALID_HANDLE(handle);
340 thread = mConnections[handle].thread.get();
341 }
342
343 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700344}
345
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700346void Scheduler::onHotplugConnectionError(ConnectionHandle handle, int32_t errorCode) {
347 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->onHotplugConnectionError(errorCode);
355}
356
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500357void Scheduler::enableSyntheticVsync(bool enable) {
358 // TODO(b/241285945): Remove connection handles.
359 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700360 android::EventThread* thread;
361 {
362 std::lock_guard<std::mutex> lock(mConnectionsLock);
363 RETURN_IF_INVALID_HANDLE(handle);
364 thread = mConnections[handle].thread.get();
365 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500366 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700367}
368
Ady Abraham62a0be22020-12-08 16:54:10 -0800369void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800370 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500371 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800372
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800373 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800374 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800375
Ady Abraham62f216c2020-10-13 19:07:23 -0700376 android::EventThread* thread;
377 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800378 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700379 RETURN_IF_INVALID_HANDLE(handle);
380 thread = mConnections[handle].thread.get();
381 }
382 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
383}
384
Ady Abrahamace3d052022-11-17 16:25:05 -0800385void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800386 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700387 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100388 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700389 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700390
391 // Invalidate content based refresh rate selection so it could be calculated
392 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700393 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800394 }
Ady Abraham690f4612021-07-01 23:24:03 -0700395 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700396}
397
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100398void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700399 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800400 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100401 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700402 return;
403 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700404 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100405 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700406 return;
407 }
408
Ady Abrahamd1591702021-07-27 16:27:56 -0700409 // If the mode is not the current mode, this means that a
410 // mode change is in progress. In that case we shouldn't dispatch an event
411 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500412 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700413 return;
414 }
415
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100416 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800417 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700418 return;
419 }
420
Ady Abrahamace3d052022-11-17 16:25:05 -0800421 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700422 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
423 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700424}
425
Ady Abrahamace3d052022-11-17 16:25:05 -0800426void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700427 android::EventThread* thread;
428 {
429 std::lock_guard<std::mutex> lock(mConnectionsLock);
430 RETURN_IF_INVALID_HANDLE(handle);
431 thread = mConnections[handle].thread.get();
432 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800433 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800434}
435
Dominik Laskowski98041832019-08-01 18:35:59 -0700436void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700437 android::EventThread* thread;
438 {
439 std::lock_guard<std::mutex> lock(mConnectionsLock);
440 RETURN_IF_INVALID_HANDLE(handle);
441 thread = mConnections.at(handle).thread.get();
442 }
443 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700444}
445
Ady Abraham9c53ee72020-07-22 21:16:18 -0700446void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
447 std::chrono::nanoseconds readyDuration) {
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[handle].thread.get();
453 }
454 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700455}
Ana Krulece588e312018-09-18 12:32:24 -0700456
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500457void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
458 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
459}
460
461void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
462 setDuration(mAppConnectionHandle,
463 /* workDuration */ config.appWorkDuration,
464 /* readyDuration */ config.sfWorkDuration);
465 setDuration(mSfConnectionHandle,
466 /* workDuration */ vsyncPeriod,
467 /* readyDuration */ config.sfWorkDuration);
468 setDuration(config.sfWorkDuration);
469}
470
Leon Scroggins III67388622023-02-06 20:36:20 -0500471void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
472 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400473 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400474 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700475}
476
Leon Scroggins III67388622023-02-06 20:36:20 -0500477void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
478 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400479 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400480 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700481}
482
Leon Scroggins III67388622023-02-06 20:36:20 -0500483void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800484 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500485 std::scoped_lock lock(mDisplayLock);
486 ftl::FakeGuard guard(kMainThreadContext);
487
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500488 for (const auto& [id, _] : mDisplays) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500489 resyncToHardwareVsyncLocked(id, allowToEnable);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500490 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500491}
492
Leon Scroggins III67388622023-02-06 20:36:20 -0500493void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
494 std::optional<Fps> refreshRate) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500495 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400496 if (!displayOpt) {
497 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
498 return;
499 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500500 const Display& display = *displayOpt;
501
502 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500503 if (!refreshRate) {
ramindania04b8a52023-08-07 18:49:47 -0700504 refreshRate = display.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Leon Scroggins III67388622023-02-06 20:36:20 -0500505 }
506 if (refreshRate->isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400507 constexpr bool kForce = false;
508 display.schedulePtr->startPeriodTransition(refreshRate->getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500509 }
510 }
511}
512
Dominik Laskowski66295432023-03-14 12:25:36 -0400513void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
514 static const auto& whence = __func__;
515 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
516
517 // On main thread to serialize reads/writes of pending hardware VSYNC state.
518 static_cast<void>(
519 schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
520 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
521
522 if (const auto displayOpt = mDisplays.get(id)) {
523 auto& display = displayOpt->get();
524 display.schedulePtr->setPendingHardwareVsyncState(enabled);
525
526 if (display.powerMode != hal::PowerMode::OFF) {
527 mSchedulerCallback.requestHardwareVsync(id, enabled);
528 }
529 }
530 }));
531}
532
Leon Scroggins III67388622023-02-06 20:36:20 -0500533void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
534 std::scoped_lock lock(mDisplayLock);
535 ftl::FakeGuard guard(kMainThreadContext);
536
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500537 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400538 if (!displayOpt) {
539 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
540 return;
541 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500542 const Display& display = *displayOpt;
543 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800544
545 using fps_approx_ops::operator!=;
546 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500547 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
548 "%" PRIu64,
549 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800550
551 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700552 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800553
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500554 display.schedulePtr->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800555}
556
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700557void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700558 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800559
560 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700561 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800562
563 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500564 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800565 }
566}
567
Leon Scroggins III67388622023-02-06 20:36:20 -0500568bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
569 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500570 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
571 return Period::fromNs(nanos);
572 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400573 auto schedule = getVsyncSchedule(id);
574 if (!schedule) {
575 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
576 return false;
577 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400578 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700579}
580
Leon Scroggins III67388622023-02-06 20:36:20 -0500581void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500582 const auto scheduleOpt =
583 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
584 return display.powerMode == hal::PowerMode::OFF
585 ? std::nullopt
586 : std::make_optional(display.schedulePtr);
587 });
588
589 if (!scheduleOpt) return;
590 const auto& schedule = scheduleOpt->get();
591
Dominik Laskowski66295432023-03-14 12:25:36 -0400592 if (const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence))) {
593 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700594 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400595 constexpr bool kDisallow = false;
596 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700597 }
598}
599
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700600void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200601 // If the content detection feature is off, we still keep the layer history,
602 // since we use it for other features (like Frame Rate API), so layers
603 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000604 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700605}
606
Ady Abrahambdda8f02021-04-01 16:06:11 -0700607void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700608 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700609}
610
Ady Abraham822ecbd2023-07-07 16:16:09 -0700611void Scheduler::onLayerDestroyed(Layer* layer) {
612 std::scoped_lock lock(mChoreographerLock);
613 mAttachedChoreographers.erase(layer->getSequence());
614}
615
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000616void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Ady Abraham5def7332020-05-29 16:13:47 -0700617 LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500618 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000619 mLayerHistory.record(id, layerProps, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800620 }
Ana Krulec3084c052018-11-21 20:27:17 +0100621}
622
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100623void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700624 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700625}
626
Andy Labrada096227e2022-06-15 16:58:11 +0000627void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
628 mLayerHistory.setDefaultFrameRateCompatibility(layer,
629 mFeatures.test(Feature::kContentDetection));
630}
631
Ady Abraham822ecbd2023-07-07 16:16:09 -0700632void Scheduler::chooseRefreshRateForContent(
633 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
634 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500635 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400636 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800637
Ady Abraham8a82ba62020-01-17 12:43:17 -0800638 ATRACE_CALL();
639
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400640 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800641 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700642
643 if (updateAttachedChoreographer) {
644 LOG_ALWAYS_FATAL_IF(!hierarchy);
645
646 // update the attached choreographers after we selected the render rate.
647 const ftl::Optional<FrameRateMode> modeOpt = [&] {
648 std::scoped_lock lock(mPolicyLock);
649 return mPolicy.modeOpt;
650 }();
651
652 if (modeOpt) {
653 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
654 }
655 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800656}
657
Ana Krulecfb772822018-11-30 10:44:07 +0100658void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500659 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800660}
661
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700662void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700663 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800664 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500665 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800666 }
Ady Abraham8532d012019-05-08 14:50:56 -0700667}
668
Leon Scroggins III67388622023-02-06 20:36:20 -0500669void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500670 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500671 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500672 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500673 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500674 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500675 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700676 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700677 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700678 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500679 {
680 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400681
682 const auto displayOpt = mDisplays.get(id);
683 LOG_ALWAYS_FATAL_IF(!displayOpt);
684 auto& display = displayOpt->get();
685
686 display.powerMode = powerMode;
687 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500688 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500689 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700690
691 if (mDisplayPowerTimer) {
692 mDisplayPowerTimer->reset();
693 }
694
695 // Display Power event will boost the refresh rate to performance.
696 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700697 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700698}
699
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500700auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
701 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500702 std::scoped_lock lock(mDisplayLock);
703 return getVsyncScheduleLocked(idOpt);
704}
705
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500706auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
707 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500708 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500709
Leon Scroggins III67388622023-02-06 20:36:20 -0500710 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500711 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
712 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500713 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500714
715 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400716 if (!displayOpt) {
717 return nullptr;
718 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500719 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500720}
721
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700722void Scheduler::kernelIdleTimerCallback(TimerState state) {
723 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100724
Ady Abraham2139f732019-11-13 18:56:40 -0800725 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
726 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700727 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700728
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700729 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
730 using namespace fps_approx_ops;
731
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800732 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700733 // If we're not in performance mode then the kernel timer shouldn't do
734 // anything, as the refresh rate during DPU power collapse will be the
735 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500736 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800737 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700738 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
739 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700740 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500741 std::scoped_lock lock(mDisplayLock);
742 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500743 for (const auto& [_, display] : mDisplays) {
744 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400745 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500746 }
Alec Mouridc28b372019-04-18 21:17:13 -0700747 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800748
749 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700750}
751
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700752void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800753 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700754 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100755}
756
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700757void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700758 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700759 // Touch event will boost the refresh rate to performance.
760 // Clear layer history to get fresh FPS detection.
761 // NOTE: Instead of checking all the layers, we should be checking the layer
762 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800763 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700764 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700765 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700766 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700767}
768
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700769void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800770 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700771 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700772}
773
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400774void Scheduler::dump(utils::Dumper& dumper) const {
775 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700776
777 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400778 utils::Dumper::Section section(dumper, "Features"sv);
779
780 for (Feature feature : ftl::enum_range<Feature>()) {
781 if (const auto flagOpt = ftl::flag_name(feature)) {
782 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
783 }
784 }
785 }
786 {
787 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400788 {
789 std::scoped_lock lock(mDisplayLock);
790 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500791 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400792 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400793 dumper.dump("layerHistory"sv, mLayerHistory.dump());
794 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
795 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
796 }
797
798 mFrameRateOverrideMappings.dump(dumper);
799 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400800
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500801 {
802 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
803
804 std::scoped_lock lock(mDisplayLock);
805 ftl::FakeGuard guard(kMainThreadContext);
806
807 for (const auto& [id, display] : mDisplays) {
808 utils::Dumper::Section
809 section(dumper,
810 id == mPacesetterDisplayId
811 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
812 : ftl::Concat("Follower Display ", id.value).c_str());
813
814 display.targeterPtr->dump(dumper);
815 dumper.eol();
816 }
817 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800818}
819
Dominik Laskowski068173d2021-08-11 17:22:59 -0700820void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500821 std::scoped_lock lock(mDisplayLock);
822 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500823 if (mPacesetterDisplayId) {
824 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
825 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500826 getVsyncScheduleLocked()->dump(out);
827 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500828 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500829 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500830 continue;
831 }
832 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500833 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500834 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700835}
836
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800837bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700838 std::scoped_lock lock(mPolicyLock);
839 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
840}
841
842bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
843 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400844 if (consideredSignals.idle) return false;
845
846 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500847 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
848 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400849
850 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
851 // the FrameRateOverrideMappings rather than here.
852 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
853}
854
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500855void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400856 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
857
858 {
859 std::scoped_lock lock(mDisplayLock);
860 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
861 }
862
Leon Scroggins39d25342023-04-19 17:11:01 +0000863 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400864}
865
866std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
867 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500868 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500869 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500870 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400871
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500872 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
873 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
874 const Display& pacesetter = *pacesetterOpt;
875
876 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400877 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
878 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
879 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
880 .onExpired =
881 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
882
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500883 pacesetter.selectorPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500884
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500885 newVsyncSchedulePtr = pacesetter.schedulePtr;
886
ramindania04b8a52023-08-07 18:49:47 -0700887 const Fps refreshRate = pacesetter.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Dominik Laskowski66295432023-03-14 12:25:36 -0400888 constexpr bool kForce = true;
889 newVsyncSchedulePtr->startPeriodTransition(refreshRate.getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500890 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500891 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400892}
Leon Scroggins III67388622023-02-06 20:36:20 -0500893
Leon Scroggins39d25342023-04-19 17:11:01 +0000894void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
895 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400896 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500897 {
898 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400899 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -0500900 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400901 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -0500902 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800903 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400904 for (auto* thread : threads) {
Leon Scroggins39d25342023-04-19 17:11:01 +0000905 thread->onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400906 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400907}
908
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500909void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400910 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500911 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
912 pacesetterPtr->stopIdleTimer();
913 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400914 }
915
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500916 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400917 std::scoped_lock lock(mPolicyLock);
918 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800919}
920
Ady Abraham822ecbd2023-07-07 16:16:09 -0700921void Scheduler::updateAttachedChoreographersFrameRate(
922 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
923 std::scoped_lock lock(mChoreographerLock);
924
925 const auto layerId = static_cast<int32_t>(layer.id);
926 const auto choreographers = mAttachedChoreographers.find(layerId);
927 if (choreographers == mAttachedChoreographers.end()) {
928 return;
929 }
930
931 auto& layerChoreographers = choreographers->second;
932
933 layerChoreographers.frameRate = fps;
934 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
935 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
936
937 auto it = layerChoreographers.connections.begin();
938 while (it != layerChoreographers.connections.end()) {
939 sp<EventThreadConnection> choreographerConnection = it->promote();
940 if (choreographerConnection) {
941 choreographerConnection->frameRate = fps;
942 it++;
943 } else {
944 it = choreographers->second.connections.erase(it);
945 }
946 }
947
948 if (layerChoreographers.connections.empty()) {
949 mAttachedChoreographers.erase(choreographers);
950 }
951}
952
953int Scheduler::updateAttachedChoreographersInternal(
954 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
955 int parentDivisor) {
956 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
957
958 int divisor = 0;
959 if (layerHierarchy.getLayer()) {
960 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
961 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
962 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
963 parentDivisor);
964
965 if (frameRate.isValid()) {
966 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
967 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
968 // Since this layer wants an exact match, we would only set a frame rate if the
969 // desired rate is a divisor of the display refresh rate.
970 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
971 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
972 // find the closest frame rate divisor for the desired frame rate.
973 divisor = static_cast<int>(
974 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
975 }
976 }
977 }
978
979 // We start by traversing the children, updating their choreographers, and getting back the
980 // aggregated frame rate.
981 int childrenDivisor = 0;
982 for (const auto& [child, _] : layerHierarchy.mChildren) {
983 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
984
985 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
986
987 const int childDivisor =
988 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
989 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
990 if (childDivisor > 0) {
991 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
992 }
993 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
994 }
995
996 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
997
998 // If there is no explicit vote for this layer. Use the children's vote if exists
999 divisor = (divisor == 0) ? childrenDivisor : divisor;
1000 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1001
1002 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1003 divisor = (divisor == 0) ? parentDivisor : divisor;
1004 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1005
1006 if (layerHierarchy.getLayer()) {
1007 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1008 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1009 }
1010
1011 return divisor;
1012}
1013
1014void Scheduler::updateAttachedChoreographers(
1015 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1016 ATRACE_CALL();
1017 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1018}
1019
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001020template <typename S, typename T>
1021auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001022 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001023 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001024 GlobalSignals consideredSignals;
1025
Ady Abraham62a0be22020-12-08 16:54:10 -08001026 bool refreshRateChanged = false;
1027 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001028
Ady Abraham8532d012019-05-08 14:50:56 -07001029 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001030 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001031
1032 auto& currentState = mPolicy.*statePtr;
1033 if (currentState == newState) return {};
1034 currentState = std::forward<T>(newState);
1035
Dominik Laskowski596a2562022-10-28 11:26:12 -04001036 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001037 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001038 {
1039 std::scoped_lock lock(mDisplayLock);
1040 ftl::FakeGuard guard(kMainThreadContext);
1041
1042 modeChoices = chooseDisplayModes();
1043
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001044 // TODO(b/240743786): The pacesetter display's mode must change for any
1045 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1046 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001047 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001048 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001049 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001050 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001051 })
1052 .value();
1053 }
ramindani69b58e82022-09-26 16:48:36 -07001054
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001055 modeRequests.reserve(modeChoices.size());
1056 for (auto& [id, choice] : modeChoices) {
1057 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001058 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001059 .emitEvent = !choice.consideredSignals.idle});
1060 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001061
Ady Abraham33a386b2023-07-18 15:37:11 -07001062 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001063
Ady Abrahamace3d052022-11-17 16:25:05 -08001064 if (mPolicy.modeOpt != modeOpt) {
1065 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001066 refreshRateChanged = true;
1067 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001068 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001069 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001070 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001071 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001072 }
Ady Abraham8532d012019-05-08 14:50:56 -07001073 }
Ady Abraham8532d012019-05-08 14:50:56 -07001074 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001075 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001076 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001077 }
1078 if (frameRateOverridesChanged) {
1079 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1080 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001081 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001082}
1083
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001084auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001085 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001086
Ady Abraham68636062022-11-16 17:07:25 -08001087 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski6b049ff2023-01-29 15:46:45 -05001088 ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -04001089 const auto globalSignals = makeGlobalSignals();
ramindani22f2ead2023-04-21 10:27:11 -07001090 Fps pacesetterFps;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001091
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001092 for (const auto& [id, display] : mDisplays) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001093 auto rankedFrameRates =
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001094 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
1095 globalSignals);
ramindani22f2ead2023-04-21 10:27:11 -07001096 if (id == *mPacesetterDisplayId) {
1097 pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
Dominik Laskowski01602522022-10-07 19:02:28 -04001098 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001099 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001100 }
ramindani69b58e82022-09-26 16:48:36 -07001101
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001102 DisplayModeChoiceMap modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001103 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -04001104
ramindani22f2ead2023-04-21 10:27:11 -07001105 for (auto& [rankings, signals] : perDisplayRanking) {
1106 const auto chosenFrameRateMode =
1107 ftl::find_if(rankings,
1108 [&](const auto& ranking) {
1109 return ranking.frameRateMode.fps == pacesetterFps;
1110 })
1111 .transform([](const auto& scoredFrameRate) {
1112 return scoredFrameRate.get().frameRateMode;
1113 })
1114 .value_or(rankings.front().frameRateMode);
Dominik Laskowski01602522022-10-07 19:02:28 -04001115
ramindani22f2ead2023-04-21 10:27:11 -07001116 modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
1117 DisplayModeChoice{chosenFrameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -04001118 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001119 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001120}
1121
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001122GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001123 const bool powerOnImminent = mDisplayPowerTimer &&
1124 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1125 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001126
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001127 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1128 .idle = mPolicy.idleTimer == TimerState::Expired,
1129 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001130}
1131
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001132FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001133 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001134 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001135 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001136 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1137 .ranking.front()
1138 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001139
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001140 // Make sure the stored mode is up to date.
1141 mPolicy.modeOpt = frameRateMode;
1142
1143 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001144}
1145
Peiyong Line9d809e2020-04-14 13:10:48 -07001146void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001147 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1148 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1149
1150 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1151 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1152 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1153 }
1154}
1155
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001156bool Scheduler::onPostComposition(nsecs_t presentTime) {
1157 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1158 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1159 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1160 // We need to composite again as refreshTimeNanos is still in the future.
1161 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001162 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001163
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001164 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001165 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001166 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001167}
1168
Ady Abraham7825c682021-05-17 15:12:14 -07001169void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001170 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001171}
1172
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001173void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
1174 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1175 return;
1176 }
1177
1178 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1179}
1180
Ady Abraham62a0be22020-12-08 16:54:10 -08001181void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1182 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1183 return;
1184 }
1185
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001186 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001187}
1188
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001189void Scheduler::updateSmallAreaDetection(
1190 std::vector<std::pair<uid_t, float>>& uidThresholdMappings) {
1191 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1192}
1193
1194void Scheduler::setSmallAreaDetectionThreshold(uid_t uid, float threshold) {
1195 mSmallAreaDetectionAllowMappings.setThesholdForUid(uid, threshold);
1196}
1197
1198bool Scheduler::isSmallDirtyArea(uid_t uid, uint32_t dirtyArea) {
1199 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForUid(uid);
1200 if (oThreshold) return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1201
1202 return false;
1203}
1204
Dominik Laskowski068173d2021-08-11 17:22:59 -07001205} // namespace android::scheduler