blob: 5e131548aa939c1c6721cd3d553b0dc15e10c5f6 [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) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500206 const FrameTargeter::BeginFrameArgs beginFrameArgs =
207 {.frameBeginTime = SchedulerClock::now(),
208 .vsyncId = vsyncId,
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500209 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500210 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
211 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700212
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500213 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
214 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500215
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500216 {
217 FrameTargets targets;
218 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500219
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500220 // TODO (b/256196556): Followers should use the next VSYNC after the frontrunner, not the
221 // pacesetter.
222 // Update expectedVsyncTime, which may have been adjusted by beginFrame.
223 expectedVsyncTime = pacesetterPtr->targeterPtr->target().expectedPresentTime();
224
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500225 for (const auto& [id, display] : mDisplays) {
226 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400227
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500228 auto followerBeginFrameArgs = beginFrameArgs;
229 followerBeginFrameArgs.expectedVsyncTime =
230 display.schedulePtr->vsyncDeadlineAfter(expectedVsyncTime);
231
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500232 FrameTargeter& targeter = *display.targeterPtr;
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500233 targeter.beginFrame(followerBeginFrameArgs, *display.schedulePtr);
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500234 targets.try_emplace(id, &targeter.target());
235 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400236
ramindaniae645822024-01-11 10:57:29 -0800237 if (!compositor.commit(pacesetterPtr->displayId, targets)) {
238 if (FlagManager::getInstance().vrr_config()) {
239 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
240 }
Ady Abraham14beed72024-05-15 17:16:45 -0700241 mSchedulerCallback.onCommitNotComposited(pacesetterPtr->displayId);
ramindaniae645822024-01-11 10:57:29 -0800242 return;
243 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400244 }
245
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500246 // The pacesetter may have changed or been registered anew during commit.
247 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500248
249 // TODO(b/256196556): Choose the frontrunner display.
250 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500251 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500252
253 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500254 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500255
256 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500257 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700258 }
259
Ady Abrahamd6d80162023-10-23 12:57:41 -0700260 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000261 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500262 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000263 const auto skipDuration = Duration::fromNs(
264 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000265 SFTRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
266 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
Alec Mouri1c7938e2023-09-22 04:17:23 +0000267 std::this_thread::sleep_for(skipDuration);
268 mPacesetterFrameDurationFractionToSkip = 0.f;
269 }
270
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500271 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
ramindaniae645822024-01-11 10:57:29 -0800272 if (FlagManager::getInstance().vrr_config()) {
273 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
274 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700275 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400276
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500277 for (const auto& [id, targeter] : targeters) {
278 const auto resultOpt = resultsPerDisplay.get(id);
279 LOG_ALWAYS_FATAL_IF(!resultOpt);
280 targeter->endFrame(*resultOpt);
281 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700282}
283
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500284std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800285 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500286 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800287 return mFrameRateOverrideMappings
288 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800289}
290
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400291bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800292 const auto frameRate = getFrameRateOverride(uid);
293 if (!frameRate.has_value()) {
294 return true;
295 }
296
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000297 SFTRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400298 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700299}
300
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400301bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
302 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700303}
304
Ady Abrahamf2851612023-09-25 17:19:00 -0700305bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
306 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500307}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800308
Ady Abrahamf2851612023-09-25 17:19:00 -0700309Period Scheduler::getVsyncPeriod(uid_t uid) {
310 const auto [refreshRate, period] = [this] {
311 std::scoped_lock lock(mDisplayLock);
312 const auto pacesetterOpt = pacesetterDisplayLocked();
313 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
314 const Display& pacesetter = *pacesetterOpt;
Ying Weiaf854ad2024-03-16 05:24:39 +0000315 const FrameRateMode& frameRateMode = pacesetter.selectorPtr->getActiveMode();
316 const auto refreshRate = frameRateMode.fps;
317 const auto displayVsync = frameRateMode.modePtr->getVsyncRate();
318 const auto numPeriod = RefreshRateSelector::getFrameRateDivisor(displayVsync, refreshRate);
319 return std::make_pair(refreshRate, numPeriod * pacesetter.schedulePtr->period());
Ady Abrahamf2851612023-09-25 17:19:00 -0700320 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500321
Ady Abrahamf2851612023-09-25 17:19:00 -0700322 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800323
Ady Abrahamf2851612023-09-25 17:19:00 -0700324 const auto frameRate = getFrameRateOverride(uid);
325 if (!frameRate.has_value()) {
326 return currentPeriod;
327 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100328
Ady Abrahamf2851612023-09-25 17:19:00 -0700329 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
330 if (divisor <= 1) {
331 return currentPeriod;
332 }
333
334 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
335 // behaviour.
336 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100337}
ramindaniae645822024-01-11 10:57:29 -0800338void Scheduler::onExpectedPresentTimePosted(TimePoint expectedPresentTime) {
339 const auto frameRateMode = [this] {
340 std::scoped_lock lock(mDisplayLock);
341 const auto pacesetterOpt = pacesetterDisplayLocked();
342 const Display& pacesetter = *pacesetterOpt;
343 return pacesetter.selectorPtr->getActiveMode();
344 }();
345
346 if (frameRateMode.modePtr->getVrrConfig()) {
347 mSchedulerCallback.onExpectedPresentTimePosted(expectedPresentTime, frameRateMode.modePtr,
348 frameRateMode.fps);
349 }
350}
Jorim Jaggic0086af2021-02-12 18:18:11 +0100351
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500352void Scheduler::createEventThread(Cycle cycle, frametimeline::TokenManager* tokenManager,
353 std::chrono::nanoseconds workDuration,
354 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500355 auto eventThread =
356 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
357 getVsyncSchedule(), tokenManager, *this,
358 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500359
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500360 if (cycle == Cycle::Render) {
361 mRenderEventThread = std::move(eventThread);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500362 } else {
363 mLastCompositeEventThread = std::move(eventThread);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500364 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700365}
366
367sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500368 Cycle cycle, EventRegistrationFlags eventRegistration, const sp<IBinder>& layerHandle) {
369 const auto connection = eventThreadFor(cycle).createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700370 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
371
372 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
373 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
374 // processed on the main thread.
375 mSchedulerCallback.onChoreographerAttached();
376
377 std::scoped_lock lock(mChoreographerLock);
378 const auto [iter, emplaced] =
379 mAttachedChoreographers.emplace(layerId,
380 AttachedChoreographers{Fps(), {connection}});
381 if (!emplaced) {
382 iter->second.connections.emplace(connection);
383 connection->frameRate = iter->second.frameRate;
384 }
385 }
386 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700387}
388
Dominik Laskowski091129a2024-02-21 14:26:03 -0500389void Scheduler::dispatchHotplug(PhysicalDisplayId displayId, Hotplug hotplug) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500390 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500391 const bool connected = hotplug == Hotplug::Connected;
392 eventThreadFor(Cycle::Render).onHotplugReceived(displayId, connected);
393 eventThreadFor(Cycle::LastComposite).onHotplugReceived(displayId, connected);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500394 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700395}
396
Dominik Laskowski091129a2024-02-21 14:26:03 -0500397void Scheduler::dispatchHotplugError(int32_t errorCode) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500398 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500399 eventThreadFor(Cycle::Render).onHotplugConnectionError(errorCode);
400 eventThreadFor(Cycle::LastComposite).onHotplugConnectionError(errorCode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700401 }
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700402}
403
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500404void Scheduler::enableSyntheticVsync(bool enable) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500405 eventThreadFor(Cycle::Render).enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700406}
407
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400408void Scheduler::onFrameRateOverridesChanged() {
409 const auto [pacesetterId, supportsFrameRateOverrideByContent] = [this] {
410 std::scoped_lock lock(mDisplayLock);
411 const auto pacesetterOpt = pacesetterDisplayLocked();
412 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
413 const Display& pacesetter = *pacesetterOpt;
414 return std::make_pair(FTL_FAKE_GUARD(kMainThreadContext, *mPacesetterDisplayId),
415 pacesetter.selectorPtr->supportsAppFrameRateOverrideByContent());
416 }();
Andy Yud6a36202022-01-26 04:08:22 -0800417
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800418 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800419 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800420
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400421 eventThreadFor(Cycle::Render).onFrameRateOverridesChanged(pacesetterId, std::move(overrides));
Ady Abraham62f216c2020-10-13 19:07:23 -0700422}
423
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500424void Scheduler::onHdcpLevelsChanged(Cycle cycle, PhysicalDisplayId displayId,
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700425 int32_t connectedLevel, int32_t maxLevel) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500426 eventThreadFor(cycle).onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700427}
428
Dominik Laskowskibda52362024-08-04 00:41:46 -0400429bool Scheduler::onDisplayModeChanged(PhysicalDisplayId displayId, const FrameRateMode& mode) {
430 const bool isPacesetter =
431 FTL_FAKE_GUARD(kMainThreadContext,
432 (std::scoped_lock(mDisplayLock), displayId == mPacesetterDisplayId));
433
434 if (isPacesetter) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700435 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400436 mPolicy.emittedModeOpt = mode;
Ady Abraham5cc2e262021-03-25 13:09:17 -0700437
438 // Invalidate content based refresh rate selection so it could be calculated
439 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700440 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800441 }
Dominik Laskowskibda52362024-08-04 00:41:46 -0400442
443 if (hasEventThreads()) {
444 eventThreadFor(Cycle::Render).onModeChanged(mode);
445 }
446
447 return isPacesetter;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700448}
449
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400450void Scheduler::emitModeChangeIfNeeded() {
451 if (!mPolicy.modeOpt || !mPolicy.emittedModeOpt) {
452 ALOGW("No mode change to emit");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700453 return;
454 }
455
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400456 const auto& mode = *mPolicy.modeOpt;
457
458 if (mode != pacesetterSelectorPtr()->getActiveMode()) {
459 // A mode change is pending. The event will be emitted when the mode becomes active.
Ady Abrahamd1591702021-07-27 16:27:56 -0700460 return;
461 }
462
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400463 if (mode == *mPolicy.emittedModeOpt) {
464 // The event was already emitted.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700465 return;
466 }
467
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400468 mPolicy.emittedModeOpt = mode;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700469
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500470 if (hasEventThreads()) {
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400471 eventThreadFor(Cycle::Render).onModeChanged(mode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700472 }
Ady Abraham447052e2019-02-13 16:07:27 -0800473}
474
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500475void Scheduler::dump(Cycle cycle, std::string& result) const {
476 eventThreadFor(cycle).dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700477}
478
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500479void Scheduler::setDuration(Cycle cycle, std::chrono::nanoseconds workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700480 std::chrono::nanoseconds readyDuration) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500481 if (hasEventThreads()) {
482 eventThreadFor(cycle).setDuration(workDuration, readyDuration);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700483 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700484}
Ana Krulece588e312018-09-18 12:32:24 -0700485
Dominik Laskowskie37c04e2024-08-04 15:48:00 -0400486void Scheduler::updatePhaseConfiguration(PhysicalDisplayId displayId, Fps refreshRate) {
487 const bool isPacesetter =
488 FTL_FAKE_GUARD(kMainThreadContext,
489 (std::scoped_lock(mDisplayLock), displayId == mPacesetterDisplayId));
490 if (!isPacesetter) return;
491
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500492 mRefreshRateStats->setRefreshRate(refreshRate);
493 mVsyncConfiguration->setRefreshRateFps(refreshRate);
494 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
495 refreshRate.getPeriod());
496}
497
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500498void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
499 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500500}
501
502void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500503 setDuration(Cycle::Render,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500504 /* workDuration */ config.appWorkDuration,
505 /* readyDuration */ config.sfWorkDuration);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500506 setDuration(Cycle::LastComposite,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500507 /* workDuration */ vsyncPeriod,
508 /* readyDuration */ config.sfWorkDuration);
509 setDuration(config.sfWorkDuration);
510}
511
Leon Scroggins III67388622023-02-06 20:36:20 -0500512void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
513 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400514 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400515 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700516}
517
Leon Scroggins III67388622023-02-06 20:36:20 -0500518void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
519 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400520 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400521 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700522}
523
Leon Scroggins III67388622023-02-06 20:36:20 -0500524void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000525 SFTRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500526 std::scoped_lock lock(mDisplayLock);
527 ftl::FakeGuard guard(kMainThreadContext);
528
Leon Scroggins III792ea802023-11-27 17:32:51 -0500529 for (const auto& [id, display] : mDisplays) {
530 if (display.powerMode != hal::PowerMode::OFF ||
531 !FlagManager::getInstance().multithreaded_present()) {
532 resyncToHardwareVsyncLocked(id, allowToEnable);
533 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500534 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500535}
536
Leon Scroggins III67388622023-02-06 20:36:20 -0500537void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800538 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500539 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400540 if (!displayOpt) {
541 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
542 return;
543 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500544 const Display& display = *displayOpt;
545
546 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800547 if (!modePtr) {
548 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500549 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800550 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400551 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800552 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500553 }
554 }
555}
556
Dominik Laskowski66295432023-03-14 12:25:36 -0400557void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
558 static const auto& whence = __func__;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000559 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400560
561 // On main thread to serialize reads/writes of pending hardware VSYNC state.
562 static_cast<void>(
Leon Scroggins III53ca9562023-12-27 16:32:12 -0500563 schedule([=, this]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000564 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400565
566 if (const auto displayOpt = mDisplays.get(id)) {
567 auto& display = displayOpt->get();
568 display.schedulePtr->setPendingHardwareVsyncState(enabled);
569
570 if (display.powerMode != hal::PowerMode::OFF) {
571 mSchedulerCallback.requestHardwareVsync(id, enabled);
572 }
573 }
574 }));
575}
576
Ady Abrahamee6365b2024-03-06 14:31:45 -0800577void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate, bool applyImmediately) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500578 std::scoped_lock lock(mDisplayLock);
579 ftl::FakeGuard guard(kMainThreadContext);
580
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500581 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400582 if (!displayOpt) {
583 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
584 return;
585 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500586 const Display& display = *displayOpt;
587 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800588
589 using fps_approx_ops::operator!=;
590 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500591 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
592 "%" PRIu64,
593 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800594
595 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700596 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800597
Ady Abrahamee6365b2024-03-06 14:31:45 -0800598 display.schedulePtr->getTracker().setRenderRate(renderFrameRate, applyImmediately);
Ady Abrahamace3d052022-11-17 16:25:05 -0800599}
600
ramindani0491e642023-11-16 17:42:14 -0800601Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
602 TimePoint currentExpectedPresentTime) const {
603 std::scoped_lock lock(mDisplayLock);
604 ftl::FakeGuard guard(kMainThreadContext);
605
606 const auto displayOpt = mDisplays.get(id);
607 if (!displayOpt) {
608 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
609 return Fps{};
610 }
611 const Display& display = *displayOpt;
Leon Scroggins IIIa0785012024-01-23 16:05:59 -0500612 const Duration threshold =
613 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriod() / 2;
614 const TimePoint nextVsyncTime =
615 display.schedulePtr->vsyncDeadlineAfter(currentExpectedPresentTime + threshold,
616 currentExpectedPresentTime);
617 const Duration frameInterval = nextVsyncTime - currentExpectedPresentTime;
618 return Fps::fromPeriodNsecs(frameInterval.ns());
ramindani0491e642023-11-16 17:42:14 -0800619}
620
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700621void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700622 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800623
624 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700625 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800626
627 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500628 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800629 }
630}
631
Leon Scroggins III67388622023-02-06 20:36:20 -0500632bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
633 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500634 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
635 return Period::fromNs(nanos);
636 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400637 auto schedule = getVsyncSchedule(id);
638 if (!schedule) {
639 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
640 return false;
641 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400642 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700643}
644
Leon Scroggins III67388622023-02-06 20:36:20 -0500645void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000646 SFTRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500647 const auto scheduleOpt =
648 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
649 return display.powerMode == hal::PowerMode::OFF
650 ? std::nullopt
651 : std::make_optional(display.schedulePtr);
652 });
653
654 if (!scheduleOpt) return;
655 const auto& schedule = scheduleOpt->get();
656
Yi Kong08d7c812023-12-12 16:40:22 +0900657 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
658 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400659 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700660 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400661 constexpr bool kDisallow = false;
662 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700663 }
664}
665
Vishnu Nair5c61a012024-08-05 21:14:39 -0700666void Scheduler::registerLayer(Layer* layer, FrameRateCompatibility frameRateCompatibility) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200667 // If the content detection feature is off, we still keep the layer history,
668 // since we use it for other features (like Frame Rate API), so layers
669 // still need to be registered.
Vishnu Nair5c61a012024-08-05 21:14:39 -0700670 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection),
671 frameRateCompatibility);
Ady Abraham09bd3922019-04-08 10:44:56 -0700672}
673
Ady Abrahambdda8f02021-04-01 16:06:11 -0700674void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700675 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700676}
677
Ady Abraham822ecbd2023-07-07 16:16:09 -0700678void Scheduler::onLayerDestroyed(Layer* layer) {
679 std::scoped_lock lock(mChoreographerLock);
680 mAttachedChoreographers.erase(layer->getSequence());
681}
682
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000683void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700684 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Ady Abrahamf8fdc452024-04-05 16:22:55 +0000685 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700686 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800687 }
Ana Krulec3084c052018-11-21 20:27:17 +0100688}
689
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100690void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700691 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700692}
693
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700694void Scheduler::setDefaultFrameRateCompatibility(
695 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
696 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000697 mFeatures.test(Feature::kContentDetection));
698}
699
Vishnu Nair41376b62023-11-08 05:08:58 -0800700void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
701 mLayerHistory.setLayerProperties(id, properties);
702}
703
Ady Abraham822ecbd2023-07-07 16:16:09 -0700704void Scheduler::chooseRefreshRateForContent(
705 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
706 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500707 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400708 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800709
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000710 SFTRACE_CALL();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800711
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400712 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800713 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700714
715 if (updateAttachedChoreographer) {
716 LOG_ALWAYS_FATAL_IF(!hierarchy);
717
718 // update the attached choreographers after we selected the render rate.
719 const ftl::Optional<FrameRateMode> modeOpt = [&] {
720 std::scoped_lock lock(mPolicyLock);
721 return mPolicy.modeOpt;
722 }();
723
724 if (modeOpt) {
725 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
726 }
727 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800728}
729
Ana Krulecfb772822018-11-30 10:44:07 +0100730void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500731 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800732}
733
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700734void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700735 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800736 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500737 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800738 }
Ady Abraham8532d012019-05-08 14:50:56 -0700739}
740
Leon Scroggins III67388622023-02-06 20:36:20 -0500741void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500742 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500743 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500744 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500745 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500746 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500747 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700748 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700749 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700750 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500751 {
752 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400753
754 const auto displayOpt = mDisplays.get(id);
755 LOG_ALWAYS_FATAL_IF(!displayOpt);
756 auto& display = displayOpt->get();
757
758 display.powerMode = powerMode;
759 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500760 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500761 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700762
763 if (mDisplayPowerTimer) {
764 mDisplayPowerTimer->reset();
765 }
766
767 // Display Power event will boost the refresh rate to performance.
768 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700769 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700770}
771
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500772auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
773 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500774 std::scoped_lock lock(mDisplayLock);
775 return getVsyncScheduleLocked(idOpt);
776}
777
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500778auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
779 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500780 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500781
Leon Scroggins III67388622023-02-06 20:36:20 -0500782 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500783 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
784 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500785 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500786
787 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400788 if (!displayOpt) {
789 return nullptr;
790 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500791 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500792}
793
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700794void Scheduler::kernelIdleTimerCallback(TimerState state) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000795 SFTRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100796
Ady Abraham2139f732019-11-13 18:56:40 -0800797 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
798 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700799 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700800
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700801 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
802 using namespace fps_approx_ops;
803
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800804 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700805 // If we're not in performance mode then the kernel timer shouldn't do
806 // anything, as the refresh rate during DPU power collapse will be the
807 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500808 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800809 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700810 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
811 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700812 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500813 std::scoped_lock lock(mDisplayLock);
814 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500815 for (const auto& [_, display] : mDisplays) {
816 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400817 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500818 }
Alec Mouridc28b372019-04-18 21:17:13 -0700819 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800820
821 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700822}
823
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700824void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800825 applyPolicy(&Policy::idleTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000826 SFTRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100827}
828
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700829void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700830 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700831 // Touch event will boost the refresh rate to performance.
832 // Clear layer history to get fresh FPS detection.
833 // NOTE: Instead of checking all the layers, we should be checking the layer
834 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800835 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700836 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700837 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000838 SFTRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700839}
840
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700841void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800842 applyPolicy(&Policy::displayPowerTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000843 SFTRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700844}
845
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400846void Scheduler::dump(utils::Dumper& dumper) const {
847 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700848
849 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400850 utils::Dumper::Section section(dumper, "Features"sv);
851
852 for (Feature feature : ftl::enum_range<Feature>()) {
853 if (const auto flagOpt = ftl::flag_name(feature)) {
854 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
855 }
856 }
857 }
858 {
859 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400860 {
861 std::scoped_lock lock(mDisplayLock);
862 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500863 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400864 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400865 dumper.dump("layerHistory"sv, mLayerHistory.dump());
866 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
867 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
868 }
869
870 mFrameRateOverrideMappings.dump(dumper);
871 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400872
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500873 mVsyncConfiguration->dump(dumper.out());
874 dumper.eol();
875
876 mRefreshRateStats->dump(dumper.out());
877 dumper.eol();
878
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400879 std::scoped_lock lock(mDisplayLock);
880 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500881
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400882 for (const auto& [id, display] : mDisplays) {
883 utils::Dumper::Section
884 section(dumper,
885 id == mPacesetterDisplayId
886 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
887 : ftl::Concat("Follower Display ", id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500888
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400889 display.selectorPtr->dump(dumper);
890 display.targeterPtr->dump(dumper);
891 dumper.eol();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500892 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800893}
894
Dominik Laskowski068173d2021-08-11 17:22:59 -0700895void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500896 std::scoped_lock lock(mDisplayLock);
897 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500898 if (mPacesetterDisplayId) {
899 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
900 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500901 getVsyncScheduleLocked()->dump(out);
902 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500903 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500904 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500905 continue;
906 }
907 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500908 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500909 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700910}
911
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400912void Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
913 const bool changed = (std::scoped_lock(mPolicyLock),
914 updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate));
915
916 if (changed) {
917 onFrameRateOverridesChanged();
918 }
Ady Abraham33a386b2023-07-18 15:37:11 -0700919}
920
921bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
922 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400923 if (consideredSignals.idle) return false;
924
925 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500926 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
927 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400928
929 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
930 // the FrameRateOverrideMappings rather than here.
931 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
932}
933
Dominik Laskowskib9724192024-07-12 15:55:28 -0400934void Scheduler::promotePacesetterDisplay(PhysicalDisplayId pacesetterId, PromotionParams params) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400935 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400936 {
937 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib9724192024-07-12 15:55:28 -0400938 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterId, params);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400939 }
940
Leon Scroggins39d25342023-04-19 17:11:01 +0000941 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400942}
943
944std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
Dominik Laskowskib9724192024-07-12 15:55:28 -0400945 PhysicalDisplayId pacesetterId, PromotionParams params) {
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400946 // TODO: b/241286431 - Choose the pacesetter among mDisplays.
947 mPacesetterDisplayId = pacesetterId;
948 ALOGI("Display %s is the pacesetter", to_string(pacesetterId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400949
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500950 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
951 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
952 const Display& pacesetter = *pacesetterOpt;
953
Dominik Laskowskib9724192024-07-12 15:55:28 -0400954 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
955 pacesetter.selectorPtr->setIdleTimerCallbacks(
956 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
957 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
958 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
959 .onExpired =
960 [this] { kernelIdleTimerCallback(TimerState::Expired); }},
961 .vrr = {.onReset = [this] { mSchedulerCallback.vrrDisplayIdle(false); },
962 .onExpired = [this] { mSchedulerCallback.vrrDisplayIdle(true); }}});
Dominik Laskowski596a2562022-10-28 11:26:12 -0400963
Dominik Laskowskib9724192024-07-12 15:55:28 -0400964 pacesetter.selectorPtr->startIdleTimer();
965 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500966
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500967 newVsyncSchedulePtr = pacesetter.schedulePtr;
968
Dominik Laskowski66295432023-03-14 12:25:36 -0400969 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800970 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
971 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500972 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500973 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400974}
Leon Scroggins III67388622023-02-06 20:36:20 -0500975
Leon Scroggins39d25342023-04-19 17:11:01 +0000976void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
977 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500978
979 if (hasEventThreads()) {
980 eventThreadFor(Cycle::Render).onNewVsyncSchedule(vsyncSchedule);
981 eventThreadFor(Cycle::LastComposite).onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400982 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400983}
984
Dominik Laskowskib9724192024-07-12 15:55:28 -0400985void Scheduler::demotePacesetterDisplay(PromotionParams params) {
986 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
987 // No need to lock for reads on kMainThreadContext.
988 if (const auto pacesetterPtr =
989 FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
990 pacesetterPtr->stopIdleTimer();
991 pacesetterPtr->clearIdleTimerCallbacks();
992 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400993 }
994
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500995 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400996 std::scoped_lock lock(mPolicyLock);
997 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800998}
999
Ady Abraham822ecbd2023-07-07 16:16:09 -07001000void Scheduler::updateAttachedChoreographersFrameRate(
1001 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
1002 std::scoped_lock lock(mChoreographerLock);
1003
1004 const auto layerId = static_cast<int32_t>(layer.id);
1005 const auto choreographers = mAttachedChoreographers.find(layerId);
1006 if (choreographers == mAttachedChoreographers.end()) {
1007 return;
1008 }
1009
1010 auto& layerChoreographers = choreographers->second;
1011
1012 layerChoreographers.frameRate = fps;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001013 SFTRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
Ady Abraham822ecbd2023-07-07 16:16:09 -07001014 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1015
1016 auto it = layerChoreographers.connections.begin();
1017 while (it != layerChoreographers.connections.end()) {
1018 sp<EventThreadConnection> choreographerConnection = it->promote();
1019 if (choreographerConnection) {
1020 choreographerConnection->frameRate = fps;
1021 it++;
1022 } else {
1023 it = choreographers->second.connections.erase(it);
1024 }
1025 }
1026
1027 if (layerChoreographers.connections.empty()) {
1028 mAttachedChoreographers.erase(choreographers);
1029 }
1030}
1031
1032int Scheduler::updateAttachedChoreographersInternal(
1033 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1034 int parentDivisor) {
1035 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1036
1037 int divisor = 0;
1038 if (layerHierarchy.getLayer()) {
1039 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1040 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1041 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1042 parentDivisor);
1043
1044 if (frameRate.isValid()) {
1045 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1046 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1047 // Since this layer wants an exact match, we would only set a frame rate if the
1048 // desired rate is a divisor of the display refresh rate.
1049 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1050 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1051 // find the closest frame rate divisor for the desired frame rate.
1052 divisor = static_cast<int>(
1053 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1054 }
1055 }
1056 }
1057
1058 // We start by traversing the children, updating their choreographers, and getting back the
1059 // aggregated frame rate.
1060 int childrenDivisor = 0;
1061 for (const auto& [child, _] : layerHierarchy.mChildren) {
1062 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1063
1064 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1065
1066 const int childDivisor =
1067 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1068 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1069 if (childDivisor > 0) {
1070 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1071 }
1072 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1073 }
1074
1075 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1076
1077 // If there is no explicit vote for this layer. Use the children's vote if exists
1078 divisor = (divisor == 0) ? childrenDivisor : divisor;
1079 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1080
1081 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1082 divisor = (divisor == 0) ? parentDivisor : divisor;
1083 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1084
1085 if (layerHierarchy.getLayer()) {
1086 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1087 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1088 }
1089
1090 return divisor;
1091}
1092
1093void Scheduler::updateAttachedChoreographers(
1094 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001095 SFTRACE_CALL();
Ady Abraham822ecbd2023-07-07 16:16:09 -07001096 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1097}
1098
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001099template <typename S, typename T>
1100auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001101 SFTRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001102 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001103 GlobalSignals consideredSignals;
1104
Ady Abraham62a0be22020-12-08 16:54:10 -08001105 bool refreshRateChanged = false;
1106 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001107
Ady Abraham8532d012019-05-08 14:50:56 -07001108 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001109 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001110
1111 auto& currentState = mPolicy.*statePtr;
1112 if (currentState == newState) return {};
1113 currentState = std::forward<T>(newState);
1114
Dominik Laskowski596a2562022-10-28 11:26:12 -04001115 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001116 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001117 {
1118 std::scoped_lock lock(mDisplayLock);
1119 ftl::FakeGuard guard(kMainThreadContext);
1120
1121 modeChoices = chooseDisplayModes();
1122
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001123 // TODO(b/240743786): The pacesetter display's mode must change for any
1124 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1125 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001126 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001127 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001128 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001129 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001130 })
1131 .value();
1132 }
ramindani69b58e82022-09-26 16:48:36 -07001133
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001134 modeRequests.reserve(modeChoices.size());
1135 for (auto& [id, choice] : modeChoices) {
1136 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001137 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001138 .emitEvent = choice.consideredSignals
1139 .shouldEmitEvent()});
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001140 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001141
ramindanif2f40f42024-06-18 16:48:28 -07001142 if (!FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1143 frameRateOverridesChanged =
1144 updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
1145 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001146 if (mPolicy.modeOpt != modeOpt) {
1147 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001148 refreshRateChanged = true;
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001149 } else if (consideredSignals.shouldEmitEvent()) {
1150 // The mode did not change, but we may need to emit if DisplayModeRequest::emitEvent was
1151 // previously false.
1152 emitModeChangeIfNeeded();
Ady Abraham8532d012019-05-08 14:50:56 -07001153 }
Ady Abraham8532d012019-05-08 14:50:56 -07001154 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001155 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001156 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001157 }
ramindanif2f40f42024-06-18 16:48:28 -07001158
1159 if (FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1160 std::scoped_lock lock(mPolicyLock);
1161 frameRateOverridesChanged =
1162 updateFrameRateOverridesLocked(consideredSignals, mPolicy.modeOpt->fps);
1163 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001164 if (frameRateOverridesChanged) {
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001165 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001166 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001167 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001168}
1169
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001170auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001171 SFTRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001172
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001173 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -04001174 const auto globalSignals = makeGlobalSignals();
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001175
1176 const Fps pacesetterFps = [&]() REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext) {
1177 auto rankedFrameRates =
1178 pacesetterSelectorPtrLocked()->getRankedFrameRates(mPolicy.contentRequirements,
1179 globalSignals);
1180
1181 const Fps pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
1182
1183 modeChoices.try_emplace(*mPacesetterDisplayId,
1184 DisplayModeChoice::from(std::move(rankedFrameRates)));
1185 return pacesetterFps;
1186 }();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001187
Dominik Laskowski086507b2024-05-16 15:33:16 -04001188 // Choose a mode for powered-on follower displays.
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001189 for (const auto& [id, display] : mDisplays) {
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001190 if (id == *mPacesetterDisplayId) continue;
Dominik Laskowski086507b2024-05-16 15:33:16 -04001191 if (display.powerMode != hal::PowerMode::ON) continue;
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001192
Ady Abrahamace3d052022-11-17 16:25:05 -08001193 auto rankedFrameRates =
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001194 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals,
1195 pacesetterFps);
1196
1197 modeChoices.try_emplace(id, DisplayModeChoice::from(std::move(rankedFrameRates)));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001198 }
ramindani69b58e82022-09-26 16:48:36 -07001199
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001200 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001201}
1202
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001203GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001204 const bool powerOnImminent = mDisplayPowerTimer &&
1205 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1206 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001207
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001208 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1209 .idle = mPolicy.idleTimer == TimerState::Expired,
1210 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001211}
1212
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001213FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001214 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001215 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001216 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001217 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1218 .ranking.front()
1219 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001220
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001221 // Make sure the stored mode is up to date.
1222 mPolicy.modeOpt = frameRateMode;
1223
1224 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001225}
1226
Peiyong Line9d809e2020-04-14 13:10:48 -07001227void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001228 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1229 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1230
1231 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1232 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1233 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1234 }
1235}
1236
Leon Scroggins III5b581492023-10-31 14:29:41 -04001237bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001238 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1239 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1240 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1241 // We need to composite again as refreshTimeNanos is still in the future.
1242 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001243 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001244
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001245 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001246 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001247 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001248}
1249
Ady Abraham7825c682021-05-17 15:12:14 -07001250void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001251 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001252}
1253
Andy Yu8c2703d2023-11-03 11:22:46 -07001254void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001255 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1256 return;
1257 }
1258
Andy Yu8c2703d2023-11-03 11:22:46 -07001259 if (FlagManager::getInstance().game_default_frame_rate()) {
1260 // update the frame rate override mapping in LayerHistory
1261 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1262 } else {
1263 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1264 }
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001265
1266 onFrameRateOverridesChanged();
Andy Yu8c2703d2023-11-03 11:22:46 -07001267}
1268
1269void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1270 if (!FlagManager::getInstance().game_default_frame_rate() ||
1271 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1272 return;
1273 }
1274
1275 // update the frame rate override mapping in LayerHistory
1276 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001277}
1278
Ady Abraham62a0be22020-12-08 16:54:10 -08001279void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1280 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1281 return;
1282 }
1283
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001284 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001285 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001286}
1287
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001288void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001289 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001290 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1291}
1292
Tony Huangf3621102023-09-04 17:14:22 +08001293void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001294 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001295}
1296
Tony Huangf3621102023-09-04 17:14:22 +08001297bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1298 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1299 if (oThreshold) {
1300 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1301 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001302 return false;
1303}
1304
Dominik Laskowski068173d2021-08-11 17:22:59 -07001305} // namespace android::scheduler