blob: 799bc6d1c0a259499faaacc2bf34b0c9337821ef [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 <algorithm>
42#include <cinttypes>
43#include <cstdint>
44#include <functional>
45#include <memory>
46#include <numeric>
47
Alec Mouri9b133ca2023-11-14 19:00:01 +000048#include <common/FlagManager.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070049#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070050#include "EventThread.h"
Andy Yu2ae6b6b2021-11-18 14:51:06 -080051#include "FrameRateOverrideMappings.h"
Rachel Lee2248f522023-01-27 16:45:23 -080052#include "FrontEnd/LayerHandle.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070053#include "OneShotTimer.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050054#include "RefreshRateStats.h"
55#include "SurfaceFlingerFactory.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090056#include "SurfaceFlingerProperties.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050057#include "TimeStats/TimeStats.h"
Dominik Laskowskic404cb42023-03-03 19:57:53 -050058#include "VSyncTracker.h"
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050059#include "VsyncConfiguration.h"
Dominik Laskowskic404cb42023-03-03 19:57:53 -050060#include "VsyncController.h"
61#include "VsyncSchedule.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070062
Dominik Laskowski068173d2021-08-11 17:22:59 -070063namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070064
Dominik Laskowski1c99a002023-01-20 17:10:36 -050065Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
ramindaniae645822024-01-11 10:57:29 -080066 surfaceflinger::Factory& factory, Fps activeRefreshRate, TimeStats& timeStats)
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050067 : android::impl::MessageQueue(compositor),
Dominik Laskowski1c99a002023-01-20 17:10:36 -050068 mFeatures(features),
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050069 mVsyncConfiguration(factory.createVsyncConfiguration(activeRefreshRate)),
70 mVsyncModulator(sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs())),
Leon Scroggins IIIde8d9a12024-01-23 12:05:49 -050071 mRefreshRateStats(std::make_unique<RefreshRateStats>(timeStats, activeRefreshRate)),
ramindaniae645822024-01-11 10:57:29 -080072 mSchedulerCallback(callback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070073
Dominik Laskowski83bd7712022-01-07 14:30:53 -080074Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080075 // MessageQueue depends on VsyncSchedule, so first destroy it.
76 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
77 // which will cause a use-after-free issue.
78 Impl::destroyVsync();
79
Dominik Laskowski83bd7712022-01-07 14:30:53 -080080 // Stop timers and wait for their threads to exit.
81 mDisplayPowerTimer.reset();
82 mTouchTimer.reset();
83
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040084 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Dominik Laskowskib9724192024-07-12 15:55:28 -040085 demotePacesetterDisplay({.toggleIdleTimer = true});
Dominik Laskowski83bd7712022-01-07 14:30:53 -080086}
87
Leon Scroggins IIIa7be94e2024-01-23 12:24:30 -050088void Scheduler::initVsync(frametimeline::TokenManager& tokenManager,
89 std::chrono::nanoseconds workDuration) {
90 Impl::initVsyncInternal(getVsyncSchedule()->getDispatch(), tokenManager, workDuration);
91}
92
Dominik Laskowski9c93d602021-10-07 19:38:26 -070093void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070094 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070095 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070096
Ady Abrahamc496b432023-12-01 21:35:05 +000097 const int32_t defaultTouchTimerValue =
Ady Abraham3f84c502023-11-30 18:18:06 -080098 FlagManager::getInstance().enable_fro_dependent_features() &&
99 sysprop::enable_frame_rate_override(true)
100 ? 200
101 : 0;
Ady Abrahamc496b432023-12-01 21:35:05 +0000102 if (const int32_t millis = set_touch_timer_ms(defaultTouchTimerValue); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700103 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700104 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800105 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700106 [this] { touchTimerCallback(TimerState::Reset); },
107 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700108 mTouchTimer->start();
109 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700110
Dominik Laskowski98041832019-08-01 18:35:59 -0700111 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
112 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800113 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700114 [this] { displayPowerTimerCallback(TimerState::Reset); },
115 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700116 mDisplayPowerTimer->start();
117 }
Ana Krulece588e312018-09-18 12:32:24 -0700118}
119
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400120void Scheduler::setPacesetterDisplay(PhysicalDisplayId pacesetterId) {
Dominik Laskowskib9724192024-07-12 15:55:28 -0400121 constexpr PromotionParams kPromotionParams = {.toggleIdleTimer = true};
Dominik Laskowski59db9562022-10-27 16:18:53 -0400122
Dominik Laskowskib9724192024-07-12 15:55:28 -0400123 demotePacesetterDisplay(kPromotionParams);
124 promotePacesetterDisplay(pacesetterId, kPromotionParams);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800125}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700126
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400127void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr,
128 PhysicalDisplayId activeDisplayId) {
ramindaniae645822024-01-11 10:57:29 -0800129 auto schedulePtr =
130 std::make_shared<VsyncSchedule>(selectorPtr->getActiveMode().modePtr, mFeatures,
131 [this](PhysicalDisplayId id, bool enable) {
132 onHardwareVsyncRequest(id, enable);
133 });
Dominik Laskowski66295432023-03-14 12:25:36 -0400134
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400135 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr),
136 activeDisplayId);
Leon Scroggins III67388622023-02-06 20:36:20 -0500137}
138
139void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
140 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400141 VsyncSchedulePtr schedulePtr,
142 PhysicalDisplayId activeDisplayId) {
Dominik Laskowskib9724192024-07-12 15:55:28 -0400143 const bool isPrimary = (ftl::FakeGuard(mDisplayLock), !mPacesetterDisplayId);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400144
Dominik Laskowskib9724192024-07-12 15:55:28 -0400145 // Start the idle timer for the first registered (i.e. primary) display.
146 const PromotionParams promotionParams = {.toggleIdleTimer = isPrimary};
147
148 demotePacesetterDisplay(promotionParams);
149
150 auto [pacesetterVsyncSchedule, isNew] = [&]() REQUIRES(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400151 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400152 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500153 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
154 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400155 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400156
Dominik Laskowskib9724192024-07-12 15:55:28 -0400157 return std::make_pair(promotePacesetterDisplayLocked(activeDisplayId, promotionParams),
158 isNew);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400159 }();
160
Leon Scroggins39d25342023-04-19 17:11:01 +0000161 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400162
163 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
164 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400165 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400166 }
Dominik Laskowski091129a2024-02-21 14:26:03 -0500167
168 dispatchHotplug(displayId, Hotplug::Connected);
Dominik Laskowski01602522022-10-07 19:02:28 -0400169}
170
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400171void Scheduler::unregisterDisplay(PhysicalDisplayId displayId, PhysicalDisplayId activeDisplayId) {
172 LOG_ALWAYS_FATAL_IF(displayId == activeDisplayId, "Cannot unregister the active display!");
173
Dominik Laskowski091129a2024-02-21 14:26:03 -0500174 dispatchHotplug(displayId, Hotplug::Disconnected);
175
Dominik Laskowskib9724192024-07-12 15:55:28 -0400176 constexpr PromotionParams kPromotionParams = {.toggleIdleTimer = false};
177 demotePacesetterDisplay(kPromotionParams);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400178
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400179 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
180 {
181 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500182 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400183
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400184 // Do not allow removing the final display. Code in the scheduler expects
185 // there to be at least one display. (This may be relaxed in the future with
186 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500187 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500188
Dominik Laskowskib9724192024-07-12 15:55:28 -0400189 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(activeDisplayId, kPromotionParams);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400190 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000191 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400192}
193
Dominik Laskowski756b7892021-08-04 12:53:59 -0700194void Scheduler::run() {
195 while (true) {
196 waitMessage();
197 }
198}
199
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700200void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
201 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500202 const FrameTargeter::BeginFrameArgs beginFrameArgs =
203 {.frameBeginTime = SchedulerClock::now(),
204 .vsyncId = vsyncId,
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500205 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500206 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
207 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700208
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500209 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
210 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500211
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500212 {
213 FrameTargets targets;
214 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500215
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500216 // TODO (b/256196556): Followers should use the next VSYNC after the frontrunner, not the
217 // pacesetter.
218 // Update expectedVsyncTime, which may have been adjusted by beginFrame.
219 expectedVsyncTime = pacesetterPtr->targeterPtr->target().expectedPresentTime();
220
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500221 for (const auto& [id, display] : mDisplays) {
222 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400223
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500224 auto followerBeginFrameArgs = beginFrameArgs;
225 followerBeginFrameArgs.expectedVsyncTime =
226 display.schedulePtr->vsyncDeadlineAfter(expectedVsyncTime);
227
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500228 FrameTargeter& targeter = *display.targeterPtr;
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500229 targeter.beginFrame(followerBeginFrameArgs, *display.schedulePtr);
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500230 targets.try_emplace(id, &targeter.target());
231 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400232
ramindaniae645822024-01-11 10:57:29 -0800233 if (!compositor.commit(pacesetterPtr->displayId, targets)) {
234 if (FlagManager::getInstance().vrr_config()) {
235 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
236 }
Ady Abraham14beed72024-05-15 17:16:45 -0700237 mSchedulerCallback.onCommitNotComposited(pacesetterPtr->displayId);
ramindaniae645822024-01-11 10:57:29 -0800238 return;
239 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400240 }
241
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500242 // The pacesetter may have changed or been registered anew during commit.
243 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500244
245 // TODO(b/256196556): Choose the frontrunner display.
246 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500247 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500248
249 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500250 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500251
252 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500253 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700254 }
255
Ady Abrahamd6d80162023-10-23 12:57:41 -0700256 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000257 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500258 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000259 const auto skipDuration = Duration::fromNs(
260 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000261 SFTRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
262 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
Alec Mouri1c7938e2023-09-22 04:17:23 +0000263 std::this_thread::sleep_for(skipDuration);
264 mPacesetterFrameDurationFractionToSkip = 0.f;
265 }
266
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500267 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
ramindaniae645822024-01-11 10:57:29 -0800268 if (FlagManager::getInstance().vrr_config()) {
269 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
270 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700271 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400272
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500273 for (const auto& [id, targeter] : targeters) {
274 const auto resultOpt = resultsPerDisplay.get(id);
275 LOG_ALWAYS_FATAL_IF(!resultOpt);
276 targeter->endFrame(*resultOpt);
277 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700278}
279
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500280std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800281 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500282 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800283 return mFrameRateOverrideMappings
284 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800285}
286
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400287bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800288 const auto frameRate = getFrameRateOverride(uid);
289 if (!frameRate.has_value()) {
290 return true;
291 }
292
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000293 SFTRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400294 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700295}
296
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400297bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
298 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700299}
300
Ady Abrahamf2851612023-09-25 17:19:00 -0700301bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
302 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500303}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800304
Ady Abrahamf2851612023-09-25 17:19:00 -0700305Period Scheduler::getVsyncPeriod(uid_t uid) {
306 const auto [refreshRate, period] = [this] {
307 std::scoped_lock lock(mDisplayLock);
308 const auto pacesetterOpt = pacesetterDisplayLocked();
309 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
310 const Display& pacesetter = *pacesetterOpt;
Ying Weiaf854ad2024-03-16 05:24:39 +0000311 const FrameRateMode& frameRateMode = pacesetter.selectorPtr->getActiveMode();
312 const auto refreshRate = frameRateMode.fps;
313 const auto displayVsync = frameRateMode.modePtr->getVsyncRate();
314 const auto numPeriod = RefreshRateSelector::getFrameRateDivisor(displayVsync, refreshRate);
315 return std::make_pair(refreshRate, numPeriod * pacesetter.schedulePtr->period());
Ady Abrahamf2851612023-09-25 17:19:00 -0700316 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500317
Ady Abrahamf2851612023-09-25 17:19:00 -0700318 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800319
Ady Abrahamf2851612023-09-25 17:19:00 -0700320 const auto frameRate = getFrameRateOverride(uid);
321 if (!frameRate.has_value()) {
322 return currentPeriod;
323 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100324
Ady Abrahamf2851612023-09-25 17:19:00 -0700325 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
326 if (divisor <= 1) {
327 return currentPeriod;
328 }
329
330 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
331 // behaviour.
332 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100333}
ramindaniae645822024-01-11 10:57:29 -0800334void Scheduler::onExpectedPresentTimePosted(TimePoint expectedPresentTime) {
335 const auto frameRateMode = [this] {
336 std::scoped_lock lock(mDisplayLock);
337 const auto pacesetterOpt = pacesetterDisplayLocked();
338 const Display& pacesetter = *pacesetterOpt;
339 return pacesetter.selectorPtr->getActiveMode();
340 }();
341
342 if (frameRateMode.modePtr->getVrrConfig()) {
343 mSchedulerCallback.onExpectedPresentTimePosted(expectedPresentTime, frameRateMode.modePtr,
344 frameRateMode.fps);
345 }
346}
Jorim Jaggic0086af2021-02-12 18:18:11 +0100347
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500348void Scheduler::createEventThread(Cycle cycle, frametimeline::TokenManager* tokenManager,
349 std::chrono::nanoseconds workDuration,
350 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500351 auto eventThread =
352 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
353 getVsyncSchedule(), tokenManager, *this,
354 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500355
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500356 if (cycle == Cycle::Render) {
357 mRenderEventThread = std::move(eventThread);
358 mRenderEventConnection = mRenderEventThread->createEventConnection();
359 } else {
360 mLastCompositeEventThread = std::move(eventThread);
361 mLastCompositeEventConnection = mLastCompositeEventThread->createEventConnection();
362 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700363}
364
365sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500366 Cycle cycle, EventRegistrationFlags eventRegistration, const sp<IBinder>& layerHandle) {
367 const auto connection = eventThreadFor(cycle).createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700368 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
369
370 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
371 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
372 // processed on the main thread.
373 mSchedulerCallback.onChoreographerAttached();
374
375 std::scoped_lock lock(mChoreographerLock);
376 const auto [iter, emplaced] =
377 mAttachedChoreographers.emplace(layerId,
378 AttachedChoreographers{Fps(), {connection}});
379 if (!emplaced) {
380 iter->second.connections.emplace(connection);
381 connection->frameRate = iter->second.frameRate;
382 }
383 }
384 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700385}
386
Dominik Laskowski091129a2024-02-21 14:26:03 -0500387void Scheduler::dispatchHotplug(PhysicalDisplayId displayId, Hotplug hotplug) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500388 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500389 const bool connected = hotplug == Hotplug::Connected;
390 eventThreadFor(Cycle::Render).onHotplugReceived(displayId, connected);
391 eventThreadFor(Cycle::LastComposite).onHotplugReceived(displayId, connected);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500392 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700393}
394
Dominik Laskowski091129a2024-02-21 14:26:03 -0500395void Scheduler::dispatchHotplugError(int32_t errorCode) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500396 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500397 eventThreadFor(Cycle::Render).onHotplugConnectionError(errorCode);
398 eventThreadFor(Cycle::LastComposite).onHotplugConnectionError(errorCode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700399 }
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700400}
401
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500402void Scheduler::enableSyntheticVsync(bool enable) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500403 eventThreadFor(Cycle::Render).enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700404}
405
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500406void Scheduler::onFrameRateOverridesChanged(Cycle cycle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800407 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500408 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800409
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800410 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800411 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800412
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500413 eventThreadFor(cycle).onFrameRateOverridesChanged(displayId, std::move(overrides));
Ady Abraham62f216c2020-10-13 19:07:23 -0700414}
415
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500416void Scheduler::onHdcpLevelsChanged(Cycle cycle, PhysicalDisplayId displayId,
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700417 int32_t connectedLevel, int32_t maxLevel) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500418 eventThreadFor(cycle).onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700419}
420
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500421void Scheduler::onPrimaryDisplayModeChanged(Cycle cycle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800422 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700423 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100424 // Cache the last reported modes for primary display.
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500425 mPolicy.cachedModeChangedParams = {cycle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700426
427 // Invalidate content based refresh rate selection so it could be calculated
428 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700429 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800430 }
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500431 onNonPrimaryDisplayModeChanged(cycle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700432}
433
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100434void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700435 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800436 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100437 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700438 return;
439 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700440 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100441 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700442 return;
443 }
444
Ady Abrahamd1591702021-07-27 16:27:56 -0700445 // If the mode is not the current mode, this means that a
446 // mode change is in progress. In that case we shouldn't dispatch an event
447 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500448 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700449 return;
450 }
451
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100452 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800453 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700454 return;
455 }
456
Ady Abrahamace3d052022-11-17 16:25:05 -0800457 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500458 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->cycle,
Dominik Laskowski068173d2021-08-11 17:22:59 -0700459 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700460}
461
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500462void Scheduler::onNonPrimaryDisplayModeChanged(Cycle cycle, const FrameRateMode& mode) {
463 if (hasEventThreads()) {
464 eventThreadFor(cycle).onModeChanged(mode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700465 }
Ady Abraham447052e2019-02-13 16:07:27 -0800466}
467
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500468void Scheduler::dump(Cycle cycle, std::string& result) const {
469 eventThreadFor(cycle).dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700470}
471
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500472void Scheduler::setDuration(Cycle cycle, std::chrono::nanoseconds workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700473 std::chrono::nanoseconds readyDuration) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500474 if (hasEventThreads()) {
475 eventThreadFor(cycle).setDuration(workDuration, readyDuration);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700476 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700477}
Ana Krulece588e312018-09-18 12:32:24 -0700478
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500479void Scheduler::updatePhaseConfiguration(Fps refreshRate) {
480 mRefreshRateStats->setRefreshRate(refreshRate);
481 mVsyncConfiguration->setRefreshRateFps(refreshRate);
482 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
483 refreshRate.getPeriod());
484}
485
486void Scheduler::resetPhaseConfiguration(Fps refreshRate) {
487 // Cancel the pending refresh rate change, if any, before updating the phase configuration.
488 mVsyncModulator->cancelRefreshRateChange();
489
490 mVsyncConfiguration->reset();
491 updatePhaseConfiguration(refreshRate);
492}
493
494void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
495 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500496}
497
498void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500499 setDuration(Cycle::Render,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500500 /* workDuration */ config.appWorkDuration,
501 /* readyDuration */ config.sfWorkDuration);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500502 setDuration(Cycle::LastComposite,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500503 /* workDuration */ vsyncPeriod,
504 /* readyDuration */ config.sfWorkDuration);
505 setDuration(config.sfWorkDuration);
506}
507
Leon Scroggins III67388622023-02-06 20:36:20 -0500508void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
509 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400510 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400511 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700512}
513
Leon Scroggins III67388622023-02-06 20:36:20 -0500514void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
515 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400516 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400517 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700518}
519
Leon Scroggins III67388622023-02-06 20:36:20 -0500520void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000521 SFTRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500522 std::scoped_lock lock(mDisplayLock);
523 ftl::FakeGuard guard(kMainThreadContext);
524
Leon Scroggins III792ea802023-11-27 17:32:51 -0500525 for (const auto& [id, display] : mDisplays) {
526 if (display.powerMode != hal::PowerMode::OFF ||
527 !FlagManager::getInstance().multithreaded_present()) {
528 resyncToHardwareVsyncLocked(id, allowToEnable);
529 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500530 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500531}
532
Leon Scroggins III67388622023-02-06 20:36:20 -0500533void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800534 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500535 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400536 if (!displayOpt) {
537 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
538 return;
539 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500540 const Display& display = *displayOpt;
541
542 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800543 if (!modePtr) {
544 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500545 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800546 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400547 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800548 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500549 }
550 }
551}
552
Dominik Laskowski66295432023-03-14 12:25:36 -0400553void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
554 static const auto& whence = __func__;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000555 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400556
557 // On main thread to serialize reads/writes of pending hardware VSYNC state.
558 static_cast<void>(
Leon Scroggins III53ca9562023-12-27 16:32:12 -0500559 schedule([=, this]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000560 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400561
562 if (const auto displayOpt = mDisplays.get(id)) {
563 auto& display = displayOpt->get();
564 display.schedulePtr->setPendingHardwareVsyncState(enabled);
565
566 if (display.powerMode != hal::PowerMode::OFF) {
567 mSchedulerCallback.requestHardwareVsync(id, enabled);
568 }
569 }
570 }));
571}
572
Ady Abrahamee6365b2024-03-06 14:31:45 -0800573void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate, bool applyImmediately) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500574 std::scoped_lock lock(mDisplayLock);
575 ftl::FakeGuard guard(kMainThreadContext);
576
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500577 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400578 if (!displayOpt) {
579 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
580 return;
581 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500582 const Display& display = *displayOpt;
583 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800584
585 using fps_approx_ops::operator!=;
586 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500587 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
588 "%" PRIu64,
589 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800590
591 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700592 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800593
Ady Abrahamee6365b2024-03-06 14:31:45 -0800594 display.schedulePtr->getTracker().setRenderRate(renderFrameRate, applyImmediately);
Ady Abrahamace3d052022-11-17 16:25:05 -0800595}
596
ramindani0491e642023-11-16 17:42:14 -0800597Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
598 TimePoint currentExpectedPresentTime) const {
599 std::scoped_lock lock(mDisplayLock);
600 ftl::FakeGuard guard(kMainThreadContext);
601
602 const auto displayOpt = mDisplays.get(id);
603 if (!displayOpt) {
604 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
605 return Fps{};
606 }
607 const Display& display = *displayOpt;
Leon Scroggins IIIa0785012024-01-23 16:05:59 -0500608 const Duration threshold =
609 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriod() / 2;
610 const TimePoint nextVsyncTime =
611 display.schedulePtr->vsyncDeadlineAfter(currentExpectedPresentTime + threshold,
612 currentExpectedPresentTime);
613 const Duration frameInterval = nextVsyncTime - currentExpectedPresentTime;
614 return Fps::fromPeriodNsecs(frameInterval.ns());
ramindani0491e642023-11-16 17:42:14 -0800615}
616
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700617void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700618 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800619
620 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700621 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800622
623 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500624 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800625 }
626}
627
Leon Scroggins III67388622023-02-06 20:36:20 -0500628bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
629 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500630 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
631 return Period::fromNs(nanos);
632 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400633 auto schedule = getVsyncSchedule(id);
634 if (!schedule) {
635 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
636 return false;
637 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400638 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700639}
640
Leon Scroggins III67388622023-02-06 20:36:20 -0500641void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000642 SFTRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500643 const auto scheduleOpt =
644 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
645 return display.powerMode == hal::PowerMode::OFF
646 ? std::nullopt
647 : std::make_optional(display.schedulePtr);
648 });
649
650 if (!scheduleOpt) return;
651 const auto& schedule = scheduleOpt->get();
652
Yi Kong08d7c812023-12-12 16:40:22 +0900653 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
654 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400655 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700656 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400657 constexpr bool kDisallow = false;
658 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700659 }
660}
661
Vishnu Nair5c61a012024-08-05 21:14:39 -0700662void Scheduler::registerLayer(Layer* layer, FrameRateCompatibility frameRateCompatibility) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200663 // If the content detection feature is off, we still keep the layer history,
664 // since we use it for other features (like Frame Rate API), so layers
665 // still need to be registered.
Vishnu Nair5c61a012024-08-05 21:14:39 -0700666 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection),
667 frameRateCompatibility);
Ady Abraham09bd3922019-04-08 10:44:56 -0700668}
669
Ady Abrahambdda8f02021-04-01 16:06:11 -0700670void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700671 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700672}
673
Ady Abraham822ecbd2023-07-07 16:16:09 -0700674void Scheduler::onLayerDestroyed(Layer* layer) {
675 std::scoped_lock lock(mChoreographerLock);
676 mAttachedChoreographers.erase(layer->getSequence());
677}
678
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000679void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700680 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Ady Abrahamf8fdc452024-04-05 16:22:55 +0000681 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700682 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800683 }
Ana Krulec3084c052018-11-21 20:27:17 +0100684}
685
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100686void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700687 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700688}
689
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700690void Scheduler::setDefaultFrameRateCompatibility(
691 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
692 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000693 mFeatures.test(Feature::kContentDetection));
694}
695
Vishnu Nair41376b62023-11-08 05:08:58 -0800696void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
697 mLayerHistory.setLayerProperties(id, properties);
698}
699
Ady Abraham822ecbd2023-07-07 16:16:09 -0700700void Scheduler::chooseRefreshRateForContent(
701 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
702 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500703 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400704 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800705
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000706 SFTRACE_CALL();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800707
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400708 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800709 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700710
711 if (updateAttachedChoreographer) {
712 LOG_ALWAYS_FATAL_IF(!hierarchy);
713
714 // update the attached choreographers after we selected the render rate.
715 const ftl::Optional<FrameRateMode> modeOpt = [&] {
716 std::scoped_lock lock(mPolicyLock);
717 return mPolicy.modeOpt;
718 }();
719
720 if (modeOpt) {
721 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
722 }
723 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800724}
725
Ana Krulecfb772822018-11-30 10:44:07 +0100726void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500727 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800728}
729
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700730void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700731 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800732 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500733 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800734 }
Ady Abraham8532d012019-05-08 14:50:56 -0700735}
736
Leon Scroggins III67388622023-02-06 20:36:20 -0500737void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500738 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500739 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500740 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500741 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500742 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500743 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700744 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700745 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700746 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500747 {
748 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400749
750 const auto displayOpt = mDisplays.get(id);
751 LOG_ALWAYS_FATAL_IF(!displayOpt);
752 auto& display = displayOpt->get();
753
754 display.powerMode = powerMode;
755 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500756 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500757 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700758
759 if (mDisplayPowerTimer) {
760 mDisplayPowerTimer->reset();
761 }
762
763 // Display Power event will boost the refresh rate to performance.
764 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700765 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700766}
767
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500768auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
769 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500770 std::scoped_lock lock(mDisplayLock);
771 return getVsyncScheduleLocked(idOpt);
772}
773
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500774auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
775 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500776 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500777
Leon Scroggins III67388622023-02-06 20:36:20 -0500778 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500779 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
780 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500781 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500782
783 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400784 if (!displayOpt) {
785 return nullptr;
786 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500787 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500788}
789
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700790void Scheduler::kernelIdleTimerCallback(TimerState state) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000791 SFTRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100792
Ady Abraham2139f732019-11-13 18:56:40 -0800793 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
794 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700795 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700796
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700797 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
798 using namespace fps_approx_ops;
799
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800800 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700801 // If we're not in performance mode then the kernel timer shouldn't do
802 // anything, as the refresh rate during DPU power collapse will be the
803 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500804 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800805 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700806 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
807 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700808 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500809 std::scoped_lock lock(mDisplayLock);
810 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500811 for (const auto& [_, display] : mDisplays) {
812 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400813 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500814 }
Alec Mouridc28b372019-04-18 21:17:13 -0700815 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800816
817 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700818}
819
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700820void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800821 applyPolicy(&Policy::idleTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000822 SFTRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100823}
824
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700825void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700826 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700827 // Touch event will boost the refresh rate to performance.
828 // Clear layer history to get fresh FPS detection.
829 // NOTE: Instead of checking all the layers, we should be checking the layer
830 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800831 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700832 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700833 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000834 SFTRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700835}
836
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700837void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800838 applyPolicy(&Policy::displayPowerTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000839 SFTRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700840}
841
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400842void Scheduler::dump(utils::Dumper& dumper) const {
843 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700844
845 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400846 utils::Dumper::Section section(dumper, "Features"sv);
847
848 for (Feature feature : ftl::enum_range<Feature>()) {
849 if (const auto flagOpt = ftl::flag_name(feature)) {
850 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
851 }
852 }
853 }
854 {
855 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400856 {
857 std::scoped_lock lock(mDisplayLock);
858 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500859 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400860 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400861 dumper.dump("layerHistory"sv, mLayerHistory.dump());
862 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
863 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
864 }
865
866 mFrameRateOverrideMappings.dump(dumper);
867 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400868
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500869 mVsyncConfiguration->dump(dumper.out());
870 dumper.eol();
871
872 mRefreshRateStats->dump(dumper.out());
873 dumper.eol();
874
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500875 {
876 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
877
878 std::scoped_lock lock(mDisplayLock);
879 ftl::FakeGuard guard(kMainThreadContext);
880
881 for (const auto& [id, display] : mDisplays) {
882 utils::Dumper::Section
883 section(dumper,
884 id == mPacesetterDisplayId
885 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
886 : ftl::Concat("Follower Display ", id.value).c_str());
887
888 display.targeterPtr->dump(dumper);
889 dumper.eol();
890 }
891 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800892}
893
Dominik Laskowski068173d2021-08-11 17:22:59 -0700894void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500895 std::scoped_lock lock(mDisplayLock);
896 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500897 if (mPacesetterDisplayId) {
898 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
899 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500900 getVsyncScheduleLocked()->dump(out);
901 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500902 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500903 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500904 continue;
905 }
906 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500907 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500908 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700909}
910
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800911bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700912 std::scoped_lock lock(mPolicyLock);
913 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
914}
915
916bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
917 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400918 if (consideredSignals.idle) return false;
919
920 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500921 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
922 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400923
924 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
925 // the FrameRateOverrideMappings rather than here.
926 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
927}
928
Dominik Laskowskib9724192024-07-12 15:55:28 -0400929void Scheduler::promotePacesetterDisplay(PhysicalDisplayId pacesetterId, PromotionParams params) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400930 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400931 {
932 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib9724192024-07-12 15:55:28 -0400933 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterId, params);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400934 }
935
Leon Scroggins39d25342023-04-19 17:11:01 +0000936 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400937}
938
939std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
Dominik Laskowskib9724192024-07-12 15:55:28 -0400940 PhysicalDisplayId pacesetterId, PromotionParams params) {
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400941 // TODO: b/241286431 - Choose the pacesetter among mDisplays.
942 mPacesetterDisplayId = pacesetterId;
943 ALOGI("Display %s is the pacesetter", to_string(pacesetterId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400944
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500945 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
946 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
947 const Display& pacesetter = *pacesetterOpt;
948
Dominik Laskowskib9724192024-07-12 15:55:28 -0400949 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
950 pacesetter.selectorPtr->setIdleTimerCallbacks(
951 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
952 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
953 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
954 .onExpired =
955 [this] { kernelIdleTimerCallback(TimerState::Expired); }},
956 .vrr = {.onReset = [this] { mSchedulerCallback.vrrDisplayIdle(false); },
957 .onExpired = [this] { mSchedulerCallback.vrrDisplayIdle(true); }}});
Dominik Laskowski596a2562022-10-28 11:26:12 -0400958
Dominik Laskowskib9724192024-07-12 15:55:28 -0400959 pacesetter.selectorPtr->startIdleTimer();
960 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500961
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500962 newVsyncSchedulePtr = pacesetter.schedulePtr;
963
Dominik Laskowski66295432023-03-14 12:25:36 -0400964 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800965 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
966 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500967 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500968 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400969}
Leon Scroggins III67388622023-02-06 20:36:20 -0500970
Leon Scroggins39d25342023-04-19 17:11:01 +0000971void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
972 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500973
974 if (hasEventThreads()) {
975 eventThreadFor(Cycle::Render).onNewVsyncSchedule(vsyncSchedule);
976 eventThreadFor(Cycle::LastComposite).onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400977 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400978}
979
Dominik Laskowskib9724192024-07-12 15:55:28 -0400980void Scheduler::demotePacesetterDisplay(PromotionParams params) {
981 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
982 // No need to lock for reads on kMainThreadContext.
983 if (const auto pacesetterPtr =
984 FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
985 pacesetterPtr->stopIdleTimer();
986 pacesetterPtr->clearIdleTimerCallbacks();
987 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400988 }
989
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500990 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400991 std::scoped_lock lock(mPolicyLock);
992 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800993}
994
Ady Abraham822ecbd2023-07-07 16:16:09 -0700995void Scheduler::updateAttachedChoreographersFrameRate(
996 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
997 std::scoped_lock lock(mChoreographerLock);
998
999 const auto layerId = static_cast<int32_t>(layer.id);
1000 const auto choreographers = mAttachedChoreographers.find(layerId);
1001 if (choreographers == mAttachedChoreographers.end()) {
1002 return;
1003 }
1004
1005 auto& layerChoreographers = choreographers->second;
1006
1007 layerChoreographers.frameRate = fps;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001008 SFTRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
Ady Abraham822ecbd2023-07-07 16:16:09 -07001009 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1010
1011 auto it = layerChoreographers.connections.begin();
1012 while (it != layerChoreographers.connections.end()) {
1013 sp<EventThreadConnection> choreographerConnection = it->promote();
1014 if (choreographerConnection) {
1015 choreographerConnection->frameRate = fps;
1016 it++;
1017 } else {
1018 it = choreographers->second.connections.erase(it);
1019 }
1020 }
1021
1022 if (layerChoreographers.connections.empty()) {
1023 mAttachedChoreographers.erase(choreographers);
1024 }
1025}
1026
1027int Scheduler::updateAttachedChoreographersInternal(
1028 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1029 int parentDivisor) {
1030 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1031
1032 int divisor = 0;
1033 if (layerHierarchy.getLayer()) {
1034 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1035 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1036 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1037 parentDivisor);
1038
1039 if (frameRate.isValid()) {
1040 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1041 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1042 // Since this layer wants an exact match, we would only set a frame rate if the
1043 // desired rate is a divisor of the display refresh rate.
1044 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1045 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1046 // find the closest frame rate divisor for the desired frame rate.
1047 divisor = static_cast<int>(
1048 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1049 }
1050 }
1051 }
1052
1053 // We start by traversing the children, updating their choreographers, and getting back the
1054 // aggregated frame rate.
1055 int childrenDivisor = 0;
1056 for (const auto& [child, _] : layerHierarchy.mChildren) {
1057 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1058
1059 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1060
1061 const int childDivisor =
1062 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1063 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1064 if (childDivisor > 0) {
1065 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1066 }
1067 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1068 }
1069
1070 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1071
1072 // If there is no explicit vote for this layer. Use the children's vote if exists
1073 divisor = (divisor == 0) ? childrenDivisor : divisor;
1074 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1075
1076 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1077 divisor = (divisor == 0) ? parentDivisor : divisor;
1078 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1079
1080 if (layerHierarchy.getLayer()) {
1081 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1082 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1083 }
1084
1085 return divisor;
1086}
1087
1088void Scheduler::updateAttachedChoreographers(
1089 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001090 SFTRACE_CALL();
Ady Abraham822ecbd2023-07-07 16:16:09 -07001091 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1092}
1093
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001094template <typename S, typename T>
1095auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001096 SFTRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001097 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001098 GlobalSignals consideredSignals;
1099
Ady Abraham62a0be22020-12-08 16:54:10 -08001100 bool refreshRateChanged = false;
1101 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001102
Ady Abraham8532d012019-05-08 14:50:56 -07001103 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001104 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001105
1106 auto& currentState = mPolicy.*statePtr;
1107 if (currentState == newState) return {};
1108 currentState = std::forward<T>(newState);
1109
Dominik Laskowski596a2562022-10-28 11:26:12 -04001110 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001111 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001112 {
1113 std::scoped_lock lock(mDisplayLock);
1114 ftl::FakeGuard guard(kMainThreadContext);
1115
1116 modeChoices = chooseDisplayModes();
1117
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001118 // TODO(b/240743786): The pacesetter display's mode must change for any
1119 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1120 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001121 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001122 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001123 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001124 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001125 })
1126 .value();
1127 }
ramindani69b58e82022-09-26 16:48:36 -07001128
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001129 modeRequests.reserve(modeChoices.size());
1130 for (auto& [id, choice] : modeChoices) {
1131 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001132 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001133 .emitEvent = !choice.consideredSignals.idle});
1134 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001135
ramindanif2f40f42024-06-18 16:48:28 -07001136 if (!FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1137 frameRateOverridesChanged =
1138 updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
1139 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001140 if (mPolicy.modeOpt != modeOpt) {
1141 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001142 refreshRateChanged = true;
1143 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001144 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001145 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001146 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001147 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001148 }
Ady Abraham8532d012019-05-08 14:50:56 -07001149 }
Ady Abraham8532d012019-05-08 14:50:56 -07001150 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001151 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001152 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001153 }
ramindanif2f40f42024-06-18 16:48:28 -07001154
1155 if (FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1156 std::scoped_lock lock(mPolicyLock);
1157 frameRateOverridesChanged =
1158 updateFrameRateOverridesLocked(consideredSignals, mPolicy.modeOpt->fps);
1159 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001160 if (frameRateOverridesChanged) {
1161 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1162 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001163 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001164}
1165
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001166auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001167 SFTRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001168
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001169 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -04001170 const auto globalSignals = makeGlobalSignals();
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001171
1172 const Fps pacesetterFps = [&]() REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext) {
1173 auto rankedFrameRates =
1174 pacesetterSelectorPtrLocked()->getRankedFrameRates(mPolicy.contentRequirements,
1175 globalSignals);
1176
1177 const Fps pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
1178
1179 modeChoices.try_emplace(*mPacesetterDisplayId,
1180 DisplayModeChoice::from(std::move(rankedFrameRates)));
1181 return pacesetterFps;
1182 }();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001183
Dominik Laskowski086507b2024-05-16 15:33:16 -04001184 // Choose a mode for powered-on follower displays.
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001185 for (const auto& [id, display] : mDisplays) {
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001186 if (id == *mPacesetterDisplayId) continue;
Dominik Laskowski086507b2024-05-16 15:33:16 -04001187 if (display.powerMode != hal::PowerMode::ON) continue;
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001188
Ady Abrahamace3d052022-11-17 16:25:05 -08001189 auto rankedFrameRates =
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001190 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals,
1191 pacesetterFps);
1192
1193 modeChoices.try_emplace(id, DisplayModeChoice::from(std::move(rankedFrameRates)));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001194 }
ramindani69b58e82022-09-26 16:48:36 -07001195
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001196 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001197}
1198
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001199GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001200 const bool powerOnImminent = mDisplayPowerTimer &&
1201 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1202 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001203
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001204 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1205 .idle = mPolicy.idleTimer == TimerState::Expired,
1206 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001207}
1208
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001209FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001210 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001211 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001212 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001213 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1214 .ranking.front()
1215 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001216
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001217 // Make sure the stored mode is up to date.
1218 mPolicy.modeOpt = frameRateMode;
1219
1220 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001221}
1222
Peiyong Line9d809e2020-04-14 13:10:48 -07001223void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001224 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1225 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1226
1227 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1228 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1229 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1230 }
1231}
1232
Leon Scroggins III5b581492023-10-31 14:29:41 -04001233bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001234 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1235 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1236 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1237 // We need to composite again as refreshTimeNanos is still in the future.
1238 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001239 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001240
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001241 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001242 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001243 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001244}
1245
Ady Abraham7825c682021-05-17 15:12:14 -07001246void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001247 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001248}
1249
Andy Yu8c2703d2023-11-03 11:22:46 -07001250void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001251 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1252 return;
1253 }
1254
Andy Yu8c2703d2023-11-03 11:22:46 -07001255 if (FlagManager::getInstance().game_default_frame_rate()) {
1256 // update the frame rate override mapping in LayerHistory
1257 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1258 } else {
1259 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1260 }
1261}
1262
1263void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1264 if (!FlagManager::getInstance().game_default_frame_rate() ||
1265 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1266 return;
1267 }
1268
1269 // update the frame rate override mapping in LayerHistory
1270 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001271}
1272
Ady Abraham62a0be22020-12-08 16:54:10 -08001273void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1274 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1275 return;
1276 }
1277
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001278 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001279}
1280
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001281void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001282 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001283 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1284}
1285
Tony Huangf3621102023-09-04 17:14:22 +08001286void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001287 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001288}
1289
Tony Huangf3621102023-09-04 17:14:22 +08001290bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1291 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1292 if (oThreshold) {
1293 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1294 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001295 return false;
1296}
1297
Dominik Laskowski068173d2021-08-11 17:22:59 -07001298} // namespace android::scheduler