blob: 2875650ed09fa2847340db071474a48fd903fd95 [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>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000027#include <common/trace.h>
Ana Krulece588e312018-09-18 12:32:24 -070028#include <configstore/Utils.h>
Dominik Laskowskiec0eac22023-01-28 16:16:19 -050029#include <ftl/concat.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040030#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000031#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040032#include <ftl/small_map.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 <cinttypes>
42#include <cstdint>
43#include <functional>
44#include <memory>
45#include <numeric>
46
Alec Mouri9b133ca2023-11-14 19:00:01 +000047#include <common/FlagManager.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070048#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080049#include "FrameRateOverrideMappings.h"
Rachel Lee2248f522023-01-27 16:45:23 -080050#include "FrontEnd/LayerHandle.h"
Lloyd Pique6f240172024-09-16 15:51:45 -070051#include "Layer.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070052#include "OneShotTimer.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050053#include "RefreshRateStats.h"
54#include "SurfaceFlingerFactory.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090055#include "SurfaceFlingerProperties.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050056#include "TimeStats/TimeStats.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050057#include "VsyncConfiguration.h"
Dominik Laskowskic404cb42023-03-03 19:57:53 -050058#include "VsyncController.h"
59#include "VsyncSchedule.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070060
Dominik Laskowski068173d2021-08-11 17:22:59 -070061namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070062
Dominik Laskowski1c99a002023-01-20 17:10:36 -050063Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
ramindaniae645822024-01-11 10:57:29 -080064 surfaceflinger::Factory& factory, Fps activeRefreshRate, TimeStats& timeStats)
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050065 : android::impl::MessageQueue(compositor),
Dominik Laskowski1c99a002023-01-20 17:10:36 -050066 mFeatures(features),
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050067 mVsyncConfiguration(factory.createVsyncConfiguration(activeRefreshRate)),
68 mVsyncModulator(sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs())),
Leon Scroggins IIIde8d9a12024-01-23 12:05:49 -050069 mRefreshRateStats(std::make_unique<RefreshRateStats>(timeStats, activeRefreshRate)),
ramindaniae645822024-01-11 10:57:29 -080070 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070071
Dominik Laskowski83bd7712022-01-07 14:30:53 -080072Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080073 // MessageQueue depends on VsyncSchedule, so first destroy it.
74 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
75 // which will cause a use-after-free issue.
76 Impl::destroyVsync();
77
Dominik Laskowski83bd7712022-01-07 14:30:53 -080078 // Stop timers and wait for their threads to exit.
79 mDisplayPowerTimer.reset();
80 mTouchTimer.reset();
81
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040082 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowskib9724192024-07-12 15:55:28 -040083 demotePacesetterDisplay({.toggleIdleTimer = true});
Dominik Laskowski83bd7712022-01-07 14:30:53 -080084}
85
Leon Scroggins IIIa7be94e2024-01-23 12:24:30 -050086void Scheduler::initVsync(frametimeline::TokenManager& tokenManager,
87 std::chrono::nanoseconds workDuration) {
88 Impl::initVsyncInternal(getVsyncSchedule()->getDispatch(), tokenManager, workDuration);
89}
90
Dominik Laskowski9c93d602021-10-07 19:38:26 -070091void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070092 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070093 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070094
Ady Abrahamc496b432023-12-01 21:35:05 +000095 const int32_t defaultTouchTimerValue =
Ady Abraham3f84c502023-11-30 18:18:06 -080096 FlagManager::getInstance().enable_fro_dependent_features() &&
97 sysprop::enable_frame_rate_override(true)
98 ? 200
99 : 0;
Ady Abrahamc496b432023-12-01 21:35:05 +0000100 if (const int32_t millis = set_touch_timer_ms(defaultTouchTimerValue); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700101 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700102 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800103 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700104 [this] { touchTimerCallback(TimerState::Reset); },
105 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700106 mTouchTimer->start();
107 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700108
Dominik Laskowski98041832019-08-01 18:35:59 -0700109 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
110 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800111 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700112 [this] { displayPowerTimerCallback(TimerState::Reset); },
113 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700114 mDisplayPowerTimer->start();
115 }
Ana Krulece588e312018-09-18 12:32:24 -0700116}
117
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400118void Scheduler::setPacesetterDisplay(PhysicalDisplayId pacesetterId) {
Dominik Laskowskib9724192024-07-12 15:55:28 -0400119 constexpr PromotionParams kPromotionParams = {.toggleIdleTimer = true};
Dominik Laskowski59db9562022-10-27 16:18:53 -0400120
Dominik Laskowskib9724192024-07-12 15:55:28 -0400121 demotePacesetterDisplay(kPromotionParams);
122 promotePacesetterDisplay(pacesetterId, kPromotionParams);
Dominik Laskowskie0bc94b2024-08-04 15:39:25 -0400123
124 // Cancel the pending refresh rate change, if any, before updating the phase configuration.
125 mVsyncModulator->cancelRefreshRateChange();
126
127 mVsyncConfiguration->reset();
Dominik Laskowskie37c04e2024-08-04 15:48:00 -0400128 updatePhaseConfiguration(pacesetterId, pacesetterSelectorPtr()->getActiveMode().fps);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800129}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700130
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400131void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr,
132 PhysicalDisplayId activeDisplayId) {
ramindaniae645822024-01-11 10:57:29 -0800133 auto schedulePtr =
134 std::make_shared<VsyncSchedule>(selectorPtr->getActiveMode().modePtr, mFeatures,
135 [this](PhysicalDisplayId id, bool enable) {
136 onHardwareVsyncRequest(id, enable);
137 });
Dominik Laskowski66295432023-03-14 12:25:36 -0400138
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400139 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr),
140 activeDisplayId);
Leon Scroggins III67388622023-02-06 20:36:20 -0500141}
142
143void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
144 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400145 VsyncSchedulePtr schedulePtr,
146 PhysicalDisplayId activeDisplayId) {
Dominik Laskowskib9724192024-07-12 15:55:28 -0400147 const bool isPrimary = (ftl::FakeGuard(mDisplayLock), !mPacesetterDisplayId);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400148
Dominik Laskowskib9724192024-07-12 15:55:28 -0400149 // Start the idle timer for the first registered (i.e. primary) display.
150 const PromotionParams promotionParams = {.toggleIdleTimer = isPrimary};
151
152 demotePacesetterDisplay(promotionParams);
153
154 auto [pacesetterVsyncSchedule, isNew] = [&]() REQUIRES(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400155 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400156 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500157 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
158 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400159 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400160
Dominik Laskowskib9724192024-07-12 15:55:28 -0400161 return std::make_pair(promotePacesetterDisplayLocked(activeDisplayId, promotionParams),
162 isNew);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400163 }();
164
Leon Scroggins39d25342023-04-19 17:11:01 +0000165 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400166
167 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
168 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400169 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400170 }
Dominik Laskowski091129a2024-02-21 14:26:03 -0500171
172 dispatchHotplug(displayId, Hotplug::Connected);
Dominik Laskowski01602522022-10-07 19:02:28 -0400173}
174
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400175void Scheduler::unregisterDisplay(PhysicalDisplayId displayId, PhysicalDisplayId activeDisplayId) {
176 LOG_ALWAYS_FATAL_IF(displayId == activeDisplayId, "Cannot unregister the active display!");
177
Dominik Laskowski091129a2024-02-21 14:26:03 -0500178 dispatchHotplug(displayId, Hotplug::Disconnected);
179
Dominik Laskowskib9724192024-07-12 15:55:28 -0400180 constexpr PromotionParams kPromotionParams = {.toggleIdleTimer = false};
181 demotePacesetterDisplay(kPromotionParams);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400182
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400183 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
184 {
185 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500186 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400187
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400188 // Do not allow removing the final display. Code in the scheduler expects
189 // there to be at least one display. (This may be relaxed in the future with
190 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500191 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500192
Dominik Laskowskib9724192024-07-12 15:55:28 -0400193 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(activeDisplayId, kPromotionParams);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400194 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000195 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400196}
197
Dominik Laskowski756b7892021-08-04 12:53:59 -0700198void Scheduler::run() {
199 while (true) {
200 waitMessage();
201 }
202}
203
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700204void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
205 TimePoint expectedVsyncTime) {
Ady Abraham708ebfb2024-11-14 14:42:49 -0800206 const auto debugPresentDelay = mDebugPresentDelay.load();
207 mDebugPresentDelay.store(std::nullopt);
208
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500209 const FrameTargeter::BeginFrameArgs beginFrameArgs =
210 {.frameBeginTime = SchedulerClock::now(),
211 .vsyncId = vsyncId,
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500212 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500213 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
Ady Abraham708ebfb2024-11-14 14:42:49 -0800214 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration,
215 .debugPresentTimeDelay = debugPresentDelay};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700216
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500217 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
218 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500219
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500220 {
221 FrameTargets targets;
222 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500223
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500224 // TODO (b/256196556): Followers should use the next VSYNC after the frontrunner, not the
225 // pacesetter.
226 // Update expectedVsyncTime, which may have been adjusted by beginFrame.
227 expectedVsyncTime = pacesetterPtr->targeterPtr->target().expectedPresentTime();
228
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500229 for (const auto& [id, display] : mDisplays) {
230 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400231
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500232 auto followerBeginFrameArgs = beginFrameArgs;
233 followerBeginFrameArgs.expectedVsyncTime =
234 display.schedulePtr->vsyncDeadlineAfter(expectedVsyncTime);
235
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500236 FrameTargeter& targeter = *display.targeterPtr;
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500237 targeter.beginFrame(followerBeginFrameArgs, *display.schedulePtr);
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500238 targets.try_emplace(id, &targeter.target());
239 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400240
ramindaniae645822024-01-11 10:57:29 -0800241 if (!compositor.commit(pacesetterPtr->displayId, targets)) {
242 if (FlagManager::getInstance().vrr_config()) {
243 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
244 }
Ady Abraham14beed72024-05-15 17:16:45 -0700245 mSchedulerCallback.onCommitNotComposited(pacesetterPtr->displayId);
ramindaniae645822024-01-11 10:57:29 -0800246 return;
247 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400248 }
249
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500250 // The pacesetter may have changed or been registered anew during commit.
251 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500252
253 // TODO(b/256196556): Choose the frontrunner display.
254 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500255 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500256
257 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500258 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500259
260 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500261 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700262 }
263
Ady Abrahamd6d80162023-10-23 12:57:41 -0700264 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000265 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500266 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000267 const auto skipDuration = Duration::fromNs(
268 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000269 SFTRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
270 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
Alec Mouri1c7938e2023-09-22 04:17:23 +0000271 std::this_thread::sleep_for(skipDuration);
272 mPacesetterFrameDurationFractionToSkip = 0.f;
273 }
274
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500275 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
ramindaniae645822024-01-11 10:57:29 -0800276 if (FlagManager::getInstance().vrr_config()) {
277 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
278 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700279 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400280
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500281 for (const auto& [id, targeter] : targeters) {
282 const auto resultOpt = resultsPerDisplay.get(id);
283 LOG_ALWAYS_FATAL_IF(!resultOpt);
284 targeter->endFrame(*resultOpt);
285 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700286}
287
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500288std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800289 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500290 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800291 return mFrameRateOverrideMappings
292 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800293}
294
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400295bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800296 const auto frameRate = getFrameRateOverride(uid);
297 if (!frameRate.has_value()) {
298 return true;
299 }
300
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000301 SFTRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400302 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700303}
304
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400305bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
306 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700307}
308
Ady Abrahamf2851612023-09-25 17:19:00 -0700309bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
310 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500311}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800312
Ady Abrahamf2851612023-09-25 17:19:00 -0700313Period Scheduler::getVsyncPeriod(uid_t uid) {
314 const auto [refreshRate, period] = [this] {
315 std::scoped_lock lock(mDisplayLock);
316 const auto pacesetterOpt = pacesetterDisplayLocked();
317 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
318 const Display& pacesetter = *pacesetterOpt;
Ying Weiaf854ad2024-03-16 05:24:39 +0000319 const FrameRateMode& frameRateMode = pacesetter.selectorPtr->getActiveMode();
320 const auto refreshRate = frameRateMode.fps;
321 const auto displayVsync = frameRateMode.modePtr->getVsyncRate();
322 const auto numPeriod = RefreshRateSelector::getFrameRateDivisor(displayVsync, refreshRate);
323 return std::make_pair(refreshRate, numPeriod * pacesetter.schedulePtr->period());
Ady Abrahamf2851612023-09-25 17:19:00 -0700324 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500325
Ady Abrahamf2851612023-09-25 17:19:00 -0700326 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800327
Ady Abrahamf2851612023-09-25 17:19:00 -0700328 const auto frameRate = getFrameRateOverride(uid);
329 if (!frameRate.has_value()) {
330 return currentPeriod;
331 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100332
Ady Abrahamf2851612023-09-25 17:19:00 -0700333 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
334 if (divisor <= 1) {
335 return currentPeriod;
336 }
337
338 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
339 // behaviour.
340 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100341}
ramindaniae645822024-01-11 10:57:29 -0800342void Scheduler::onExpectedPresentTimePosted(TimePoint expectedPresentTime) {
343 const auto frameRateMode = [this] {
344 std::scoped_lock lock(mDisplayLock);
345 const auto pacesetterOpt = pacesetterDisplayLocked();
346 const Display& pacesetter = *pacesetterOpt;
347 return pacesetter.selectorPtr->getActiveMode();
348 }();
349
350 if (frameRateMode.modePtr->getVrrConfig()) {
351 mSchedulerCallback.onExpectedPresentTimePosted(expectedPresentTime, frameRateMode.modePtr,
352 frameRateMode.fps);
353 }
354}
Jorim Jaggic0086af2021-02-12 18:18:11 +0100355
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500356void Scheduler::createEventThread(Cycle cycle, frametimeline::TokenManager* tokenManager,
357 std::chrono::nanoseconds workDuration,
358 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500359 auto eventThread =
360 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
361 getVsyncSchedule(), tokenManager, *this,
362 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500363
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500364 if (cycle == Cycle::Render) {
365 mRenderEventThread = std::move(eventThread);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500366 } else {
367 mLastCompositeEventThread = std::move(eventThread);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500368 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700369}
370
371sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500372 Cycle cycle, EventRegistrationFlags eventRegistration, const sp<IBinder>& layerHandle) {
373 const auto connection = eventThreadFor(cycle).createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700374 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
375
376 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
377 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
378 // processed on the main thread.
379 mSchedulerCallback.onChoreographerAttached();
380
381 std::scoped_lock lock(mChoreographerLock);
382 const auto [iter, emplaced] =
383 mAttachedChoreographers.emplace(layerId,
384 AttachedChoreographers{Fps(), {connection}});
385 if (!emplaced) {
386 iter->second.connections.emplace(connection);
387 connection->frameRate = iter->second.frameRate;
388 }
389 }
390 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700391}
392
Dominik Laskowski091129a2024-02-21 14:26:03 -0500393void Scheduler::dispatchHotplug(PhysicalDisplayId displayId, Hotplug hotplug) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500394 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500395 const bool connected = hotplug == Hotplug::Connected;
396 eventThreadFor(Cycle::Render).onHotplugReceived(displayId, connected);
397 eventThreadFor(Cycle::LastComposite).onHotplugReceived(displayId, connected);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500398 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700399}
400
Dominik Laskowski091129a2024-02-21 14:26:03 -0500401void Scheduler::dispatchHotplugError(int32_t errorCode) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500402 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500403 eventThreadFor(Cycle::Render).onHotplugConnectionError(errorCode);
404 eventThreadFor(Cycle::LastComposite).onHotplugConnectionError(errorCode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700405 }
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700406}
407
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500408void Scheduler::enableSyntheticVsync(bool enable) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500409 eventThreadFor(Cycle::Render).enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700410}
411
Ady Abraham8e3e2ea2024-10-31 15:52:31 -0700412void Scheduler::omitVsyncDispatching(bool omitted) {
413 eventThreadFor(Cycle::Render).omitVsyncDispatching(omitted);
414 // Note: If we don't couple Cycle::LastComposite event thread, there is a black screen
415 // after boot. This is most likely sysui or system_server dependency on sf instance
416 // Choreographer
417 eventThreadFor(Cycle::LastComposite).omitVsyncDispatching(omitted);
418}
419
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400420void Scheduler::onFrameRateOverridesChanged() {
421 const auto [pacesetterId, supportsFrameRateOverrideByContent] = [this] {
422 std::scoped_lock lock(mDisplayLock);
423 const auto pacesetterOpt = pacesetterDisplayLocked();
424 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
425 const Display& pacesetter = *pacesetterOpt;
426 return std::make_pair(FTL_FAKE_GUARD(kMainThreadContext, *mPacesetterDisplayId),
427 pacesetter.selectorPtr->supportsAppFrameRateOverrideByContent());
428 }();
Andy Yud6a36202022-01-26 04:08:22 -0800429
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800430 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800431 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800432
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400433 eventThreadFor(Cycle::Render).onFrameRateOverridesChanged(pacesetterId, std::move(overrides));
Ady Abraham62f216c2020-10-13 19:07:23 -0700434}
435
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500436void Scheduler::onHdcpLevelsChanged(Cycle cycle, PhysicalDisplayId displayId,
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700437 int32_t connectedLevel, int32_t maxLevel) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500438 eventThreadFor(cycle).onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700439}
440
Aditya Kumar91b33f12024-10-09 20:21:46 +0000441#pragma clang diagnostic push
442#pragma clang diagnostic ignored "-Wunused-value" // b/369277774
Ady Abrahamfc48edc2024-11-05 19:29:49 -0800443bool Scheduler::onDisplayModeChanged(PhysicalDisplayId displayId, const FrameRateMode& mode,
444 bool clearContentRequirements) {
Dominik Laskowskibda52362024-08-04 00:41:46 -0400445 const bool isPacesetter =
446 FTL_FAKE_GUARD(kMainThreadContext,
447 (std::scoped_lock(mDisplayLock), displayId == mPacesetterDisplayId));
448
449 if (isPacesetter) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700450 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400451 mPolicy.emittedModeOpt = mode;
Ady Abraham5cc2e262021-03-25 13:09:17 -0700452
Ady Abrahamfc48edc2024-11-05 19:29:49 -0800453 if (clearContentRequirements) {
454 // Invalidate content based refresh rate selection so it could be calculated
455 // again for the new refresh rate.
456 mPolicy.contentRequirements.clear();
457 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800458 }
Dominik Laskowskibda52362024-08-04 00:41:46 -0400459
460 if (hasEventThreads()) {
461 eventThreadFor(Cycle::Render).onModeChanged(mode);
462 }
463
464 return isPacesetter;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700465}
Aditya Kumar91b33f12024-10-09 20:21:46 +0000466#pragma clang diagnostic pop
Ady Abrahamdfd62162020-06-10 16:11:56 -0700467
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400468void Scheduler::emitModeChangeIfNeeded() {
469 if (!mPolicy.modeOpt || !mPolicy.emittedModeOpt) {
470 ALOGW("No mode change to emit");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700471 return;
472 }
473
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400474 const auto& mode = *mPolicy.modeOpt;
475
476 if (mode != pacesetterSelectorPtr()->getActiveMode()) {
477 // A mode change is pending. The event will be emitted when the mode becomes active.
Ady Abrahamd1591702021-07-27 16:27:56 -0700478 return;
479 }
480
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400481 if (mode == *mPolicy.emittedModeOpt) {
482 // The event was already emitted.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700483 return;
484 }
485
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400486 mPolicy.emittedModeOpt = mode;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700487
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500488 if (hasEventThreads()) {
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400489 eventThreadFor(Cycle::Render).onModeChanged(mode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700490 }
Ady Abraham447052e2019-02-13 16:07:27 -0800491}
492
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500493void Scheduler::dump(Cycle cycle, std::string& result) const {
494 eventThreadFor(cycle).dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700495}
496
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500497void Scheduler::setDuration(Cycle cycle, std::chrono::nanoseconds workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700498 std::chrono::nanoseconds readyDuration) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500499 if (hasEventThreads()) {
500 eventThreadFor(cycle).setDuration(workDuration, readyDuration);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700501 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700502}
Ana Krulece588e312018-09-18 12:32:24 -0700503
Aditya Kumar860ef882024-10-10 13:47:44 -0700504#pragma clang diagnostic push
505#pragma clang diagnostic ignored "-Wunused-value" // b/369277774
Dominik Laskowskie37c04e2024-08-04 15:48:00 -0400506void Scheduler::updatePhaseConfiguration(PhysicalDisplayId displayId, Fps refreshRate) {
507 const bool isPacesetter =
508 FTL_FAKE_GUARD(kMainThreadContext,
509 (std::scoped_lock(mDisplayLock), displayId == mPacesetterDisplayId));
510 if (!isPacesetter) return;
511
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500512 mRefreshRateStats->setRefreshRate(refreshRate);
513 mVsyncConfiguration->setRefreshRateFps(refreshRate);
514 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
515 refreshRate.getPeriod());
516}
Aditya Kumar860ef882024-10-10 13:47:44 -0700517#pragma clang diagnostic pop
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500518
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500519void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
520 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500521}
522
523void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500524 setDuration(Cycle::Render,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500525 /* workDuration */ config.appWorkDuration,
526 /* readyDuration */ config.sfWorkDuration);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500527 setDuration(Cycle::LastComposite,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500528 /* workDuration */ vsyncPeriod,
529 /* readyDuration */ config.sfWorkDuration);
530 setDuration(config.sfWorkDuration);
531}
532
Leon Scroggins III67388622023-02-06 20:36:20 -0500533void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
534 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400535 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400536 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700537}
538
Leon Scroggins III67388622023-02-06 20:36:20 -0500539void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
540 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400541 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400542 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700543}
544
Leon Scroggins III67388622023-02-06 20:36:20 -0500545void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000546 SFTRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500547 std::scoped_lock lock(mDisplayLock);
548 ftl::FakeGuard guard(kMainThreadContext);
549
Leon Scroggins III792ea802023-11-27 17:32:51 -0500550 for (const auto& [id, display] : mDisplays) {
551 if (display.powerMode != hal::PowerMode::OFF ||
552 !FlagManager::getInstance().multithreaded_present()) {
553 resyncToHardwareVsyncLocked(id, allowToEnable);
554 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500555 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500556}
557
Leon Scroggins III67388622023-02-06 20:36:20 -0500558void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800559 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500560 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400561 if (!displayOpt) {
562 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
563 return;
564 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500565 const Display& display = *displayOpt;
566
567 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800568 if (!modePtr) {
569 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500570 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800571 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400572 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800573 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500574 }
575 }
576}
577
Dominik Laskowski66295432023-03-14 12:25:36 -0400578void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
579 static const auto& whence = __func__;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000580 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400581
582 // On main thread to serialize reads/writes of pending hardware VSYNC state.
583 static_cast<void>(
Leon Scroggins III53ca9562023-12-27 16:32:12 -0500584 schedule([=, this]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000585 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400586
587 if (const auto displayOpt = mDisplays.get(id)) {
588 auto& display = displayOpt->get();
589 display.schedulePtr->setPendingHardwareVsyncState(enabled);
590
591 if (display.powerMode != hal::PowerMode::OFF) {
592 mSchedulerCallback.requestHardwareVsync(id, enabled);
593 }
594 }
595 }));
596}
597
Ady Abrahamee6365b2024-03-06 14:31:45 -0800598void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate, bool applyImmediately) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500599 std::scoped_lock lock(mDisplayLock);
600 ftl::FakeGuard guard(kMainThreadContext);
601
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500602 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400603 if (!displayOpt) {
604 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
605 return;
606 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500607 const Display& display = *displayOpt;
608 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800609
610 using fps_approx_ops::operator!=;
611 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500612 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
613 "%" PRIu64,
614 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800615
616 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700617 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800618
Ady Abrahamee6365b2024-03-06 14:31:45 -0800619 display.schedulePtr->getTracker().setRenderRate(renderFrameRate, applyImmediately);
Ady Abrahamace3d052022-11-17 16:25:05 -0800620}
621
ramindani0491e642023-11-16 17:42:14 -0800622Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
623 TimePoint currentExpectedPresentTime) const {
624 std::scoped_lock lock(mDisplayLock);
625 ftl::FakeGuard guard(kMainThreadContext);
626
627 const auto displayOpt = mDisplays.get(id);
628 if (!displayOpt) {
629 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
630 return Fps{};
631 }
632 const Display& display = *displayOpt;
Leon Scroggins IIIa0785012024-01-23 16:05:59 -0500633 const Duration threshold =
634 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriod() / 2;
635 const TimePoint nextVsyncTime =
636 display.schedulePtr->vsyncDeadlineAfter(currentExpectedPresentTime + threshold,
637 currentExpectedPresentTime);
638 const Duration frameInterval = nextVsyncTime - currentExpectedPresentTime;
639 return Fps::fromPeriodNsecs(frameInterval.ns());
ramindani0491e642023-11-16 17:42:14 -0800640}
641
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700642void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700643 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800644
645 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700646 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800647
648 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500649 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800650 }
651}
652
Leon Scroggins III67388622023-02-06 20:36:20 -0500653bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
654 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500655 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
656 return Period::fromNs(nanos);
657 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400658 auto schedule = getVsyncSchedule(id);
659 if (!schedule) {
660 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
661 return false;
662 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400663 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700664}
665
Leon Scroggins III67388622023-02-06 20:36:20 -0500666void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000667 SFTRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500668 const auto scheduleOpt =
669 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
670 return display.powerMode == hal::PowerMode::OFF
671 ? std::nullopt
672 : std::make_optional(display.schedulePtr);
673 });
674
675 if (!scheduleOpt) return;
676 const auto& schedule = scheduleOpt->get();
677
Yi Kong08d7c812023-12-12 16:40:22 +0900678 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
679 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400680 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700681 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400682 constexpr bool kDisallow = false;
683 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700684 }
685}
686
Vishnu Nair5c61a012024-08-05 21:14:39 -0700687void Scheduler::registerLayer(Layer* layer, FrameRateCompatibility frameRateCompatibility) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200688 // If the content detection feature is off, we still keep the layer history,
689 // since we use it for other features (like Frame Rate API), so layers
690 // still need to be registered.
Vishnu Nair5c61a012024-08-05 21:14:39 -0700691 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection),
692 frameRateCompatibility);
Ady Abraham09bd3922019-04-08 10:44:56 -0700693}
694
Ady Abrahambdda8f02021-04-01 16:06:11 -0700695void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700696 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700697}
698
Ady Abraham822ecbd2023-07-07 16:16:09 -0700699void Scheduler::onLayerDestroyed(Layer* layer) {
700 std::scoped_lock lock(mChoreographerLock);
701 mAttachedChoreographers.erase(layer->getSequence());
702}
703
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000704void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700705 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Ady Abrahamf8fdc452024-04-05 16:22:55 +0000706 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700707 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800708 }
Ana Krulec3084c052018-11-21 20:27:17 +0100709}
710
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100711void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700712 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700713}
714
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700715void Scheduler::setDefaultFrameRateCompatibility(
716 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
717 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000718 mFeatures.test(Feature::kContentDetection));
719}
720
Vishnu Nair41376b62023-11-08 05:08:58 -0800721void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
722 mLayerHistory.setLayerProperties(id, properties);
723}
724
Ady Abraham822ecbd2023-07-07 16:16:09 -0700725void Scheduler::chooseRefreshRateForContent(
726 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
727 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500728 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400729 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800730
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000731 SFTRACE_CALL();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800732
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400733 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800734 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700735
736 if (updateAttachedChoreographer) {
737 LOG_ALWAYS_FATAL_IF(!hierarchy);
738
739 // update the attached choreographers after we selected the render rate.
740 const ftl::Optional<FrameRateMode> modeOpt = [&] {
741 std::scoped_lock lock(mPolicyLock);
742 return mPolicy.modeOpt;
743 }();
744
745 if (modeOpt) {
746 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
747 }
748 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800749}
750
Ana Krulecfb772822018-11-30 10:44:07 +0100751void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500752 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800753}
754
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700755void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700756 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800757 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500758 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800759 }
Ady Abraham8532d012019-05-08 14:50:56 -0700760}
761
Leon Scroggins III67388622023-02-06 20:36:20 -0500762void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500763 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500764 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500765 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500766 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500767 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500768 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700769 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700770 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700771 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500772 {
773 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400774
775 const auto displayOpt = mDisplays.get(id);
776 LOG_ALWAYS_FATAL_IF(!displayOpt);
777 auto& display = displayOpt->get();
778
779 display.powerMode = powerMode;
780 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500781 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500782 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700783
784 if (mDisplayPowerTimer) {
785 mDisplayPowerTimer->reset();
786 }
787
788 // Display Power event will boost the refresh rate to performance.
789 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700790 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700791}
792
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500793auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
794 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500795 std::scoped_lock lock(mDisplayLock);
796 return getVsyncScheduleLocked(idOpt);
797}
798
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500799auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
800 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500801 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500802
Leon Scroggins III67388622023-02-06 20:36:20 -0500803 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500804 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
805 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500806 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500807
808 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400809 if (!displayOpt) {
810 return nullptr;
811 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500812 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500813}
814
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700815void Scheduler::kernelIdleTimerCallback(TimerState state) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000816 SFTRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100817
Ady Abraham2139f732019-11-13 18:56:40 -0800818 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
819 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700820 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700821
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700822 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
823 using namespace fps_approx_ops;
824
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800825 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700826 // If we're not in performance mode then the kernel timer shouldn't do
827 // anything, as the refresh rate during DPU power collapse will be the
828 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500829 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800830 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700831 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
832 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700833 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500834 std::scoped_lock lock(mDisplayLock);
835 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500836 for (const auto& [_, display] : mDisplays) {
837 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400838 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500839 }
Alec Mouridc28b372019-04-18 21:17:13 -0700840 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800841
842 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700843}
844
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700845void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800846 applyPolicy(&Policy::idleTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000847 SFTRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100848}
849
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700850void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700851 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700852 // Touch event will boost the refresh rate to performance.
853 // Clear layer history to get fresh FPS detection.
854 // NOTE: Instead of checking all the layers, we should be checking the layer
855 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800856 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700857 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700858 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000859 SFTRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700860}
861
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700862void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800863 applyPolicy(&Policy::displayPowerTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000864 SFTRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700865}
866
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400867void Scheduler::dump(utils::Dumper& dumper) const {
868 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700869
870 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400871 utils::Dumper::Section section(dumper, "Features"sv);
872
873 for (Feature feature : ftl::enum_range<Feature>()) {
874 if (const auto flagOpt = ftl::flag_name(feature)) {
875 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
876 }
877 }
878 }
879 {
880 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400881 {
882 std::scoped_lock lock(mDisplayLock);
883 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500884 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400885 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400886 dumper.dump("layerHistory"sv, mLayerHistory.dump());
887 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
888 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
889 }
890
891 mFrameRateOverrideMappings.dump(dumper);
892 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400893
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500894 mVsyncConfiguration->dump(dumper.out());
895 dumper.eol();
896
897 mRefreshRateStats->dump(dumper.out());
898 dumper.eol();
899
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400900 std::scoped_lock lock(mDisplayLock);
901 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500902
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400903 for (const auto& [id, display] : mDisplays) {
904 utils::Dumper::Section
905 section(dumper,
906 id == mPacesetterDisplayId
907 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
908 : ftl::Concat("Follower Display ", id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500909
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400910 display.selectorPtr->dump(dumper);
911 display.targeterPtr->dump(dumper);
912 dumper.eol();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500913 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800914}
915
Dominik Laskowski068173d2021-08-11 17:22:59 -0700916void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500917 std::scoped_lock lock(mDisplayLock);
918 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500919 if (mPacesetterDisplayId) {
920 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
921 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500922 getVsyncScheduleLocked()->dump(out);
923 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500924 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500925 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500926 continue;
927 }
928 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500929 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500930 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700931}
932
Aditya Kumar860ef882024-10-10 13:47:44 -0700933#pragma clang diagnostic push
934#pragma clang diagnostic ignored "-Wunused-value" // b/369277774
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400935void Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
936 const bool changed = (std::scoped_lock(mPolicyLock),
937 updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate));
938
939 if (changed) {
940 onFrameRateOverridesChanged();
941 }
Ady Abraham33a386b2023-07-18 15:37:11 -0700942}
Aditya Kumar860ef882024-10-10 13:47:44 -0700943#pragma clang diagnostic pop
Ady Abraham33a386b2023-07-18 15:37:11 -0700944
945bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
946 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400947 if (consideredSignals.idle) return false;
948
949 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500950 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
951 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400952
953 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
954 // the FrameRateOverrideMappings rather than here.
955 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
956}
957
Melody Hsue524dd92024-08-27 22:27:29 +0000958void Scheduler::addBufferStuffedUids(BufferStuffingMap bufferStuffedUids) {
959 if (!mRenderEventThread) return;
960 mRenderEventThread->addBufferStuffedUids(std::move(bufferStuffedUids));
961}
962
Dominik Laskowskib9724192024-07-12 15:55:28 -0400963void Scheduler::promotePacesetterDisplay(PhysicalDisplayId pacesetterId, PromotionParams params) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400964 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400965 {
966 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib9724192024-07-12 15:55:28 -0400967 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterId, params);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400968 }
969
Leon Scroggins39d25342023-04-19 17:11:01 +0000970 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400971}
972
973std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
Dominik Laskowskib9724192024-07-12 15:55:28 -0400974 PhysicalDisplayId pacesetterId, PromotionParams params) {
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400975 // TODO: b/241286431 - Choose the pacesetter among mDisplays.
976 mPacesetterDisplayId = pacesetterId;
977 ALOGI("Display %s is the pacesetter", to_string(pacesetterId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400978
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500979 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
980 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
981 const Display& pacesetter = *pacesetterOpt;
982
Dominik Laskowskib9724192024-07-12 15:55:28 -0400983 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
984 pacesetter.selectorPtr->setIdleTimerCallbacks(
985 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
986 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
987 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
988 .onExpired =
989 [this] { kernelIdleTimerCallback(TimerState::Expired); }},
990 .vrr = {.onReset = [this] { mSchedulerCallback.vrrDisplayIdle(false); },
991 .onExpired = [this] { mSchedulerCallback.vrrDisplayIdle(true); }}});
Dominik Laskowski596a2562022-10-28 11:26:12 -0400992
Dominik Laskowskib9724192024-07-12 15:55:28 -0400993 pacesetter.selectorPtr->startIdleTimer();
994 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500995
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500996 newVsyncSchedulePtr = pacesetter.schedulePtr;
997
Dominik Laskowski66295432023-03-14 12:25:36 -0400998 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800999 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
1000 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -05001001 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001002 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001003}
Leon Scroggins III67388622023-02-06 20:36:20 -05001004
Leon Scroggins39d25342023-04-19 17:11:01 +00001005void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
1006 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Dominik Laskowski4babfc42024-02-16 12:28:40 -05001007
1008 if (hasEventThreads()) {
1009 eventThreadFor(Cycle::Render).onNewVsyncSchedule(vsyncSchedule);
1010 eventThreadFor(Cycle::LastComposite).onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001011 }
Dominik Laskowski596a2562022-10-28 11:26:12 -04001012}
1013
Dominik Laskowskib9724192024-07-12 15:55:28 -04001014void Scheduler::demotePacesetterDisplay(PromotionParams params) {
1015 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
1016 // No need to lock for reads on kMainThreadContext.
1017 if (const auto pacesetterPtr =
1018 FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
1019 pacesetterPtr->stopIdleTimer();
1020 pacesetterPtr->clearIdleTimerCallbacks();
1021 }
Dominik Laskowski596a2562022-10-28 11:26:12 -04001022 }
1023
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001024 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -04001025 std::scoped_lock lock(mPolicyLock);
1026 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -08001027}
1028
Ady Abraham822ecbd2023-07-07 16:16:09 -07001029void Scheduler::updateAttachedChoreographersFrameRate(
1030 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
1031 std::scoped_lock lock(mChoreographerLock);
1032
1033 const auto layerId = static_cast<int32_t>(layer.id);
1034 const auto choreographers = mAttachedChoreographers.find(layerId);
1035 if (choreographers == mAttachedChoreographers.end()) {
1036 return;
1037 }
1038
1039 auto& layerChoreographers = choreographers->second;
1040
1041 layerChoreographers.frameRate = fps;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001042 SFTRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
Ady Abraham822ecbd2023-07-07 16:16:09 -07001043 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1044
1045 auto it = layerChoreographers.connections.begin();
1046 while (it != layerChoreographers.connections.end()) {
1047 sp<EventThreadConnection> choreographerConnection = it->promote();
1048 if (choreographerConnection) {
1049 choreographerConnection->frameRate = fps;
1050 it++;
1051 } else {
1052 it = choreographers->second.connections.erase(it);
1053 }
1054 }
1055
1056 if (layerChoreographers.connections.empty()) {
1057 mAttachedChoreographers.erase(choreographers);
1058 }
1059}
1060
1061int Scheduler::updateAttachedChoreographersInternal(
1062 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1063 int parentDivisor) {
1064 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1065
1066 int divisor = 0;
1067 if (layerHierarchy.getLayer()) {
1068 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1069 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1070 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1071 parentDivisor);
1072
1073 if (frameRate.isValid()) {
1074 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1075 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1076 // Since this layer wants an exact match, we would only set a frame rate if the
1077 // desired rate is a divisor of the display refresh rate.
1078 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1079 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1080 // find the closest frame rate divisor for the desired frame rate.
1081 divisor = static_cast<int>(
1082 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1083 }
1084 }
1085 }
1086
1087 // We start by traversing the children, updating their choreographers, and getting back the
1088 // aggregated frame rate.
1089 int childrenDivisor = 0;
1090 for (const auto& [child, _] : layerHierarchy.mChildren) {
1091 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1092
1093 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1094
1095 const int childDivisor =
1096 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1097 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1098 if (childDivisor > 0) {
1099 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1100 }
1101 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1102 }
1103
1104 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1105
1106 // If there is no explicit vote for this layer. Use the children's vote if exists
1107 divisor = (divisor == 0) ? childrenDivisor : divisor;
1108 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1109
1110 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1111 divisor = (divisor == 0) ? parentDivisor : divisor;
1112 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1113
1114 if (layerHierarchy.getLayer()) {
1115 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1116 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1117 }
1118
1119 return divisor;
1120}
1121
1122void Scheduler::updateAttachedChoreographers(
1123 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001124 SFTRACE_CALL();
Ady Abraham822ecbd2023-07-07 16:16:09 -07001125 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1126}
1127
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001128template <typename S, typename T>
1129auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001130 SFTRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001131 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001132 GlobalSignals consideredSignals;
1133
Ady Abraham62a0be22020-12-08 16:54:10 -08001134 bool refreshRateChanged = false;
1135 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001136
Ady Abraham8532d012019-05-08 14:50:56 -07001137 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001138 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001139
1140 auto& currentState = mPolicy.*statePtr;
1141 if (currentState == newState) return {};
1142 currentState = std::forward<T>(newState);
1143
Dominik Laskowski596a2562022-10-28 11:26:12 -04001144 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001145 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001146 {
1147 std::scoped_lock lock(mDisplayLock);
1148 ftl::FakeGuard guard(kMainThreadContext);
1149
1150 modeChoices = chooseDisplayModes();
1151
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001152 // TODO(b/240743786): The pacesetter display's mode must change for any
1153 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1154 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001155 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001156 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001157 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001158 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001159 })
1160 .value();
1161 }
ramindani69b58e82022-09-26 16:48:36 -07001162
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001163 modeRequests.reserve(modeChoices.size());
1164 for (auto& [id, choice] : modeChoices) {
1165 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001166 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001167 .emitEvent = choice.consideredSignals
1168 .shouldEmitEvent()});
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001169 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001170
ramindanif2f40f42024-06-18 16:48:28 -07001171 if (!FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1172 frameRateOverridesChanged =
1173 updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
1174 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001175 if (mPolicy.modeOpt != modeOpt) {
1176 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001177 refreshRateChanged = true;
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001178 } else if (consideredSignals.shouldEmitEvent()) {
1179 // The mode did not change, but we may need to emit if DisplayModeRequest::emitEvent was
1180 // previously false.
1181 emitModeChangeIfNeeded();
Ady Abraham8532d012019-05-08 14:50:56 -07001182 }
Ady Abraham8532d012019-05-08 14:50:56 -07001183 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001184 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001185 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001186 }
ramindanif2f40f42024-06-18 16:48:28 -07001187
1188 if (FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1189 std::scoped_lock lock(mPolicyLock);
1190 frameRateOverridesChanged =
1191 updateFrameRateOverridesLocked(consideredSignals, mPolicy.modeOpt->fps);
1192 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001193 if (frameRateOverridesChanged) {
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001194 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001195 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001196 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001197}
1198
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001199auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001200 SFTRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001201
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001202 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -04001203 const auto globalSignals = makeGlobalSignals();
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001204
1205 const Fps pacesetterFps = [&]() REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext) {
1206 auto rankedFrameRates =
1207 pacesetterSelectorPtrLocked()->getRankedFrameRates(mPolicy.contentRequirements,
1208 globalSignals);
1209
1210 const Fps pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
1211
1212 modeChoices.try_emplace(*mPacesetterDisplayId,
1213 DisplayModeChoice::from(std::move(rankedFrameRates)));
1214 return pacesetterFps;
1215 }();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001216
Dominik Laskowski086507b2024-05-16 15:33:16 -04001217 // Choose a mode for powered-on follower displays.
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001218 for (const auto& [id, display] : mDisplays) {
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001219 if (id == *mPacesetterDisplayId) continue;
Dominik Laskowski086507b2024-05-16 15:33:16 -04001220 if (display.powerMode != hal::PowerMode::ON) continue;
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001221
Ady Abrahamace3d052022-11-17 16:25:05 -08001222 auto rankedFrameRates =
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001223 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals,
1224 pacesetterFps);
1225
1226 modeChoices.try_emplace(id, DisplayModeChoice::from(std::move(rankedFrameRates)));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001227 }
ramindani69b58e82022-09-26 16:48:36 -07001228
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001229 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001230}
1231
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001232GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001233 const bool powerOnImminent = mDisplayPowerTimer &&
1234 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1235 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001236
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001237 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1238 .idle = mPolicy.idleTimer == TimerState::Expired,
1239 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001240}
1241
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001242FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001243 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001244 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001245 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001246 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1247 .ranking.front()
1248 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001249
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001250 // Make sure the stored mode is up to date.
1251 mPolicy.modeOpt = frameRateMode;
1252
1253 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001254}
1255
Peiyong Line9d809e2020-04-14 13:10:48 -07001256void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001257 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1258 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1259
1260 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1261 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1262 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1263 }
1264}
1265
Leon Scroggins III5b581492023-10-31 14:29:41 -04001266bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001267 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1268 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1269 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1270 // We need to composite again as refreshTimeNanos is still in the future.
1271 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001272 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001273
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001274 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001275 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001276 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001277}
1278
Ady Abraham7825c682021-05-17 15:12:14 -07001279void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001280 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001281}
1282
Andy Yu8c2703d2023-11-03 11:22:46 -07001283void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001284 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1285 return;
1286 }
1287
Andy Yu8c2703d2023-11-03 11:22:46 -07001288 if (FlagManager::getInstance().game_default_frame_rate()) {
1289 // update the frame rate override mapping in LayerHistory
1290 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1291 } else {
1292 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1293 }
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001294
1295 onFrameRateOverridesChanged();
Andy Yu8c2703d2023-11-03 11:22:46 -07001296}
1297
1298void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1299 if (!FlagManager::getInstance().game_default_frame_rate() ||
1300 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1301 return;
1302 }
1303
1304 // update the frame rate override mapping in LayerHistory
1305 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001306}
1307
Ady Abraham62a0be22020-12-08 16:54:10 -08001308void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1309 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1310 return;
1311 }
1312
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001313 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001314 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001315}
1316
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001317void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001318 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001319 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1320}
1321
Tony Huangf3621102023-09-04 17:14:22 +08001322void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001323 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001324}
1325
Tony Huangf3621102023-09-04 17:14:22 +08001326bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1327 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1328 if (oThreshold) {
1329 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1330 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001331 return false;
1332}
1333
Dominik Laskowski068173d2021-08-11 17:22:59 -07001334} // namespace android::scheduler