blob: 566bb8ede832dc7756a1754373da2b5ef1a8154b [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);
Dominik Laskowskie0bc94b2024-08-04 15:39:25 -0400125
126 // Cancel the pending refresh rate change, if any, before updating the phase configuration.
127 mVsyncModulator->cancelRefreshRateChange();
128
129 mVsyncConfiguration->reset();
130 updatePhaseConfiguration(pacesetterSelectorPtr()->getActiveMode().fps);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800131}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700132
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400133void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr,
134 PhysicalDisplayId activeDisplayId) {
ramindaniae645822024-01-11 10:57:29 -0800135 auto schedulePtr =
136 std::make_shared<VsyncSchedule>(selectorPtr->getActiveMode().modePtr, mFeatures,
137 [this](PhysicalDisplayId id, bool enable) {
138 onHardwareVsyncRequest(id, enable);
139 });
Dominik Laskowski66295432023-03-14 12:25:36 -0400140
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400141 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr),
142 activeDisplayId);
Leon Scroggins III67388622023-02-06 20:36:20 -0500143}
144
145void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
146 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400147 VsyncSchedulePtr schedulePtr,
148 PhysicalDisplayId activeDisplayId) {
Dominik Laskowskib9724192024-07-12 15:55:28 -0400149 const bool isPrimary = (ftl::FakeGuard(mDisplayLock), !mPacesetterDisplayId);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400150
Dominik Laskowskib9724192024-07-12 15:55:28 -0400151 // Start the idle timer for the first registered (i.e. primary) display.
152 const PromotionParams promotionParams = {.toggleIdleTimer = isPrimary};
153
154 demotePacesetterDisplay(promotionParams);
155
156 auto [pacesetterVsyncSchedule, isNew] = [&]() REQUIRES(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400157 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400158 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500159 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
160 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400161 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400162
Dominik Laskowskib9724192024-07-12 15:55:28 -0400163 return std::make_pair(promotePacesetterDisplayLocked(activeDisplayId, promotionParams),
164 isNew);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400165 }();
166
Leon Scroggins39d25342023-04-19 17:11:01 +0000167 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400168
169 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
170 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400171 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400172 }
Dominik Laskowski091129a2024-02-21 14:26:03 -0500173
174 dispatchHotplug(displayId, Hotplug::Connected);
Dominik Laskowski01602522022-10-07 19:02:28 -0400175}
176
Dominik Laskowski3ff44c72024-06-17 11:03:30 -0400177void Scheduler::unregisterDisplay(PhysicalDisplayId displayId, PhysicalDisplayId activeDisplayId) {
178 LOG_ALWAYS_FATAL_IF(displayId == activeDisplayId, "Cannot unregister the active display!");
179
Dominik Laskowski091129a2024-02-21 14:26:03 -0500180 dispatchHotplug(displayId, Hotplug::Disconnected);
181
Dominik Laskowskib9724192024-07-12 15:55:28 -0400182 constexpr PromotionParams kPromotionParams = {.toggleIdleTimer = false};
183 demotePacesetterDisplay(kPromotionParams);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400184
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400185 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
186 {
187 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500188 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400189
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400190 // Do not allow removing the final display. Code in the scheduler expects
191 // there to be at least one display. (This may be relaxed in the future with
192 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500193 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500194
Dominik Laskowskib9724192024-07-12 15:55:28 -0400195 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(activeDisplayId, kPromotionParams);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400196 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000197 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400198}
199
Dominik Laskowski756b7892021-08-04 12:53:59 -0700200void Scheduler::run() {
201 while (true) {
202 waitMessage();
203 }
204}
205
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700206void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
207 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500208 const FrameTargeter::BeginFrameArgs beginFrameArgs =
209 {.frameBeginTime = SchedulerClock::now(),
210 .vsyncId = vsyncId,
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500211 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500212 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
213 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700214
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500215 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
216 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500217
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500218 {
219 FrameTargets targets;
220 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500221
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500222 // TODO (b/256196556): Followers should use the next VSYNC after the frontrunner, not the
223 // pacesetter.
224 // Update expectedVsyncTime, which may have been adjusted by beginFrame.
225 expectedVsyncTime = pacesetterPtr->targeterPtr->target().expectedPresentTime();
226
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500227 for (const auto& [id, display] : mDisplays) {
228 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400229
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500230 auto followerBeginFrameArgs = beginFrameArgs;
231 followerBeginFrameArgs.expectedVsyncTime =
232 display.schedulePtr->vsyncDeadlineAfter(expectedVsyncTime);
233
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500234 FrameTargeter& targeter = *display.targeterPtr;
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500235 targeter.beginFrame(followerBeginFrameArgs, *display.schedulePtr);
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500236 targets.try_emplace(id, &targeter.target());
237 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400238
ramindaniae645822024-01-11 10:57:29 -0800239 if (!compositor.commit(pacesetterPtr->displayId, targets)) {
240 if (FlagManager::getInstance().vrr_config()) {
241 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
242 }
Ady Abraham14beed72024-05-15 17:16:45 -0700243 mSchedulerCallback.onCommitNotComposited(pacesetterPtr->displayId);
ramindaniae645822024-01-11 10:57:29 -0800244 return;
245 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400246 }
247
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500248 // The pacesetter may have changed or been registered anew during commit.
249 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500250
251 // TODO(b/256196556): Choose the frontrunner display.
252 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500253 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500254
255 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500256 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500257
258 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500259 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700260 }
261
Ady Abrahamd6d80162023-10-23 12:57:41 -0700262 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000263 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500264 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000265 const auto skipDuration = Duration::fromNs(
266 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000267 SFTRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
268 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
Alec Mouri1c7938e2023-09-22 04:17:23 +0000269 std::this_thread::sleep_for(skipDuration);
270 mPacesetterFrameDurationFractionToSkip = 0.f;
271 }
272
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500273 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
ramindaniae645822024-01-11 10:57:29 -0800274 if (FlagManager::getInstance().vrr_config()) {
275 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
276 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700277 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400278
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500279 for (const auto& [id, targeter] : targeters) {
280 const auto resultOpt = resultsPerDisplay.get(id);
281 LOG_ALWAYS_FATAL_IF(!resultOpt);
282 targeter->endFrame(*resultOpt);
283 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700284}
285
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500286std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800287 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500288 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800289 return mFrameRateOverrideMappings
290 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800291}
292
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400293bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800294 const auto frameRate = getFrameRateOverride(uid);
295 if (!frameRate.has_value()) {
296 return true;
297 }
298
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000299 SFTRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400300 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700301}
302
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400303bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
304 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700305}
306
Ady Abrahamf2851612023-09-25 17:19:00 -0700307bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
308 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500309}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800310
Ady Abrahamf2851612023-09-25 17:19:00 -0700311Period Scheduler::getVsyncPeriod(uid_t uid) {
312 const auto [refreshRate, period] = [this] {
313 std::scoped_lock lock(mDisplayLock);
314 const auto pacesetterOpt = pacesetterDisplayLocked();
315 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
316 const Display& pacesetter = *pacesetterOpt;
Ying Weiaf854ad2024-03-16 05:24:39 +0000317 const FrameRateMode& frameRateMode = pacesetter.selectorPtr->getActiveMode();
318 const auto refreshRate = frameRateMode.fps;
319 const auto displayVsync = frameRateMode.modePtr->getVsyncRate();
320 const auto numPeriod = RefreshRateSelector::getFrameRateDivisor(displayVsync, refreshRate);
321 return std::make_pair(refreshRate, numPeriod * pacesetter.schedulePtr->period());
Ady Abrahamf2851612023-09-25 17:19:00 -0700322 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500323
Ady Abrahamf2851612023-09-25 17:19:00 -0700324 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800325
Ady Abrahamf2851612023-09-25 17:19:00 -0700326 const auto frameRate = getFrameRateOverride(uid);
327 if (!frameRate.has_value()) {
328 return currentPeriod;
329 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100330
Ady Abrahamf2851612023-09-25 17:19:00 -0700331 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
332 if (divisor <= 1) {
333 return currentPeriod;
334 }
335
336 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
337 // behaviour.
338 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100339}
ramindaniae645822024-01-11 10:57:29 -0800340void Scheduler::onExpectedPresentTimePosted(TimePoint expectedPresentTime) {
341 const auto frameRateMode = [this] {
342 std::scoped_lock lock(mDisplayLock);
343 const auto pacesetterOpt = pacesetterDisplayLocked();
344 const Display& pacesetter = *pacesetterOpt;
345 return pacesetter.selectorPtr->getActiveMode();
346 }();
347
348 if (frameRateMode.modePtr->getVrrConfig()) {
349 mSchedulerCallback.onExpectedPresentTimePosted(expectedPresentTime, frameRateMode.modePtr,
350 frameRateMode.fps);
351 }
352}
Jorim Jaggic0086af2021-02-12 18:18:11 +0100353
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500354void Scheduler::createEventThread(Cycle cycle, frametimeline::TokenManager* tokenManager,
355 std::chrono::nanoseconds workDuration,
356 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500357 auto eventThread =
358 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
359 getVsyncSchedule(), tokenManager, *this,
360 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500361
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500362 if (cycle == Cycle::Render) {
363 mRenderEventThread = std::move(eventThread);
364 mRenderEventConnection = mRenderEventThread->createEventConnection();
365 } else {
366 mLastCompositeEventThread = std::move(eventThread);
367 mLastCompositeEventConnection = mLastCompositeEventThread->createEventConnection();
368 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700369}
370
371sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500372 Cycle cycle, EventRegistrationFlags eventRegistration, const sp<IBinder>& layerHandle) {
373 const auto connection = eventThreadFor(cycle).createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700374 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
375
376 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
377 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
378 // processed on the main thread.
379 mSchedulerCallback.onChoreographerAttached();
380
381 std::scoped_lock lock(mChoreographerLock);
382 const auto [iter, emplaced] =
383 mAttachedChoreographers.emplace(layerId,
384 AttachedChoreographers{Fps(), {connection}});
385 if (!emplaced) {
386 iter->second.connections.emplace(connection);
387 connection->frameRate = iter->second.frameRate;
388 }
389 }
390 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700391}
392
Dominik Laskowski091129a2024-02-21 14:26:03 -0500393void Scheduler::dispatchHotplug(PhysicalDisplayId displayId, Hotplug hotplug) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500394 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500395 const bool connected = hotplug == Hotplug::Connected;
396 eventThreadFor(Cycle::Render).onHotplugReceived(displayId, connected);
397 eventThreadFor(Cycle::LastComposite).onHotplugReceived(displayId, connected);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500398 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700399}
400
Dominik Laskowski091129a2024-02-21 14:26:03 -0500401void Scheduler::dispatchHotplugError(int32_t errorCode) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500402 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500403 eventThreadFor(Cycle::Render).onHotplugConnectionError(errorCode);
404 eventThreadFor(Cycle::LastComposite).onHotplugConnectionError(errorCode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700405 }
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700406}
407
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500408void Scheduler::enableSyntheticVsync(bool enable) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500409 eventThreadFor(Cycle::Render).enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700410}
411
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400412void Scheduler::onFrameRateOverridesChanged() {
413 const auto [pacesetterId, supportsFrameRateOverrideByContent] = [this] {
414 std::scoped_lock lock(mDisplayLock);
415 const auto pacesetterOpt = pacesetterDisplayLocked();
416 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
417 const Display& pacesetter = *pacesetterOpt;
418 return std::make_pair(FTL_FAKE_GUARD(kMainThreadContext, *mPacesetterDisplayId),
419 pacesetter.selectorPtr->supportsAppFrameRateOverrideByContent());
420 }();
Andy Yud6a36202022-01-26 04:08:22 -0800421
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800422 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800423 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800424
Dominik Laskowski1d7be062024-07-24 13:59:07 -0400425 eventThreadFor(Cycle::Render).onFrameRateOverridesChanged(pacesetterId, std::move(overrides));
Ady Abraham62f216c2020-10-13 19:07:23 -0700426}
427
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500428void Scheduler::onHdcpLevelsChanged(Cycle cycle, PhysicalDisplayId displayId,
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700429 int32_t connectedLevel, int32_t maxLevel) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500430 eventThreadFor(cycle).onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700431}
432
Dominik Laskowskibda52362024-08-04 00:41:46 -0400433bool Scheduler::onDisplayModeChanged(PhysicalDisplayId displayId, const FrameRateMode& mode) {
434 const bool isPacesetter =
435 FTL_FAKE_GUARD(kMainThreadContext,
436 (std::scoped_lock(mDisplayLock), displayId == mPacesetterDisplayId));
437
438 if (isPacesetter) {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700439 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400440 mPolicy.emittedModeOpt = mode;
Ady Abraham5cc2e262021-03-25 13:09:17 -0700441
442 // Invalidate content based refresh rate selection so it could be calculated
443 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700444 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800445 }
Dominik Laskowskibda52362024-08-04 00:41:46 -0400446
447 if (hasEventThreads()) {
448 eventThreadFor(Cycle::Render).onModeChanged(mode);
449 }
450
451 return isPacesetter;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700452}
453
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400454void Scheduler::emitModeChangeIfNeeded() {
455 if (!mPolicy.modeOpt || !mPolicy.emittedModeOpt) {
456 ALOGW("No mode change to emit");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700457 return;
458 }
459
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400460 const auto& mode = *mPolicy.modeOpt;
461
462 if (mode != pacesetterSelectorPtr()->getActiveMode()) {
463 // A mode change is pending. The event will be emitted when the mode becomes active.
Ady Abrahamd1591702021-07-27 16:27:56 -0700464 return;
465 }
466
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400467 if (mode == *mPolicy.emittedModeOpt) {
468 // The event was already emitted.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700469 return;
470 }
471
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400472 mPolicy.emittedModeOpt = mode;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700473
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500474 if (hasEventThreads()) {
Dominik Laskowskifc94b412024-08-03 15:02:23 -0400475 eventThreadFor(Cycle::Render).onModeChanged(mode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700476 }
Ady Abraham447052e2019-02-13 16:07:27 -0800477}
478
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500479void Scheduler::dump(Cycle cycle, std::string& result) const {
480 eventThreadFor(cycle).dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700481}
482
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500483void Scheduler::setDuration(Cycle cycle, std::chrono::nanoseconds workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700484 std::chrono::nanoseconds readyDuration) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500485 if (hasEventThreads()) {
486 eventThreadFor(cycle).setDuration(workDuration, readyDuration);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700487 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700488}
Ana Krulece588e312018-09-18 12:32:24 -0700489
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500490void Scheduler::updatePhaseConfiguration(Fps refreshRate) {
491 mRefreshRateStats->setRefreshRate(refreshRate);
492 mVsyncConfiguration->setRefreshRateFps(refreshRate);
493 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
494 refreshRate.getPeriod());
495}
496
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500497void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
498 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500499}
500
501void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500502 setDuration(Cycle::Render,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500503 /* workDuration */ config.appWorkDuration,
504 /* readyDuration */ config.sfWorkDuration);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500505 setDuration(Cycle::LastComposite,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500506 /* workDuration */ vsyncPeriod,
507 /* readyDuration */ config.sfWorkDuration);
508 setDuration(config.sfWorkDuration);
509}
510
Leon Scroggins III67388622023-02-06 20:36:20 -0500511void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
512 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400513 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400514 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700515}
516
Leon Scroggins III67388622023-02-06 20:36:20 -0500517void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
518 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400519 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400520 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700521}
522
Leon Scroggins III67388622023-02-06 20:36:20 -0500523void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000524 SFTRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500525 std::scoped_lock lock(mDisplayLock);
526 ftl::FakeGuard guard(kMainThreadContext);
527
Leon Scroggins III792ea802023-11-27 17:32:51 -0500528 for (const auto& [id, display] : mDisplays) {
529 if (display.powerMode != hal::PowerMode::OFF ||
530 !FlagManager::getInstance().multithreaded_present()) {
531 resyncToHardwareVsyncLocked(id, allowToEnable);
532 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500533 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500534}
535
Leon Scroggins III67388622023-02-06 20:36:20 -0500536void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800537 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500538 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400539 if (!displayOpt) {
540 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
541 return;
542 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500543 const Display& display = *displayOpt;
544
545 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800546 if (!modePtr) {
547 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500548 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800549 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400550 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800551 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500552 }
553 }
554}
555
Dominik Laskowski66295432023-03-14 12:25:36 -0400556void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
557 static const auto& whence = __func__;
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000558 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400559
560 // On main thread to serialize reads/writes of pending hardware VSYNC state.
561 static_cast<void>(
Leon Scroggins III53ca9562023-12-27 16:32:12 -0500562 schedule([=, this]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000563 SFTRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
Dominik Laskowski66295432023-03-14 12:25:36 -0400564
565 if (const auto displayOpt = mDisplays.get(id)) {
566 auto& display = displayOpt->get();
567 display.schedulePtr->setPendingHardwareVsyncState(enabled);
568
569 if (display.powerMode != hal::PowerMode::OFF) {
570 mSchedulerCallback.requestHardwareVsync(id, enabled);
571 }
572 }
573 }));
574}
575
Ady Abrahamee6365b2024-03-06 14:31:45 -0800576void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate, bool applyImmediately) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500577 std::scoped_lock lock(mDisplayLock);
578 ftl::FakeGuard guard(kMainThreadContext);
579
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500580 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400581 if (!displayOpt) {
582 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
583 return;
584 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500585 const Display& display = *displayOpt;
586 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800587
588 using fps_approx_ops::operator!=;
589 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500590 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
591 "%" PRIu64,
592 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800593
594 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700595 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800596
Ady Abrahamee6365b2024-03-06 14:31:45 -0800597 display.schedulePtr->getTracker().setRenderRate(renderFrameRate, applyImmediately);
Ady Abrahamace3d052022-11-17 16:25:05 -0800598}
599
ramindani0491e642023-11-16 17:42:14 -0800600Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
601 TimePoint currentExpectedPresentTime) const {
602 std::scoped_lock lock(mDisplayLock);
603 ftl::FakeGuard guard(kMainThreadContext);
604
605 const auto displayOpt = mDisplays.get(id);
606 if (!displayOpt) {
607 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
608 return Fps{};
609 }
610 const Display& display = *displayOpt;
Leon Scroggins IIIa0785012024-01-23 16:05:59 -0500611 const Duration threshold =
612 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriod() / 2;
613 const TimePoint nextVsyncTime =
614 display.schedulePtr->vsyncDeadlineAfter(currentExpectedPresentTime + threshold,
615 currentExpectedPresentTime);
616 const Duration frameInterval = nextVsyncTime - currentExpectedPresentTime;
617 return Fps::fromPeriodNsecs(frameInterval.ns());
ramindani0491e642023-11-16 17:42:14 -0800618}
619
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700620void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700621 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800622
623 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700624 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800625
626 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500627 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800628 }
629}
630
Leon Scroggins III67388622023-02-06 20:36:20 -0500631bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
632 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500633 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
634 return Period::fromNs(nanos);
635 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400636 auto schedule = getVsyncSchedule(id);
637 if (!schedule) {
638 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
639 return false;
640 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400641 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700642}
643
Leon Scroggins III67388622023-02-06 20:36:20 -0500644void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000645 SFTRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500646 const auto scheduleOpt =
647 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
648 return display.powerMode == hal::PowerMode::OFF
649 ? std::nullopt
650 : std::make_optional(display.schedulePtr);
651 });
652
653 if (!scheduleOpt) return;
654 const auto& schedule = scheduleOpt->get();
655
Yi Kong08d7c812023-12-12 16:40:22 +0900656 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
657 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400658 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700659 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400660 constexpr bool kDisallow = false;
661 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700662 }
663}
664
Vishnu Nair5c61a012024-08-05 21:14:39 -0700665void Scheduler::registerLayer(Layer* layer, FrameRateCompatibility frameRateCompatibility) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200666 // If the content detection feature is off, we still keep the layer history,
667 // since we use it for other features (like Frame Rate API), so layers
668 // still need to be registered.
Vishnu Nair5c61a012024-08-05 21:14:39 -0700669 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection),
670 frameRateCompatibility);
Ady Abraham09bd3922019-04-08 10:44:56 -0700671}
672
Ady Abrahambdda8f02021-04-01 16:06:11 -0700673void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700674 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700675}
676
Ady Abraham822ecbd2023-07-07 16:16:09 -0700677void Scheduler::onLayerDestroyed(Layer* layer) {
678 std::scoped_lock lock(mChoreographerLock);
679 mAttachedChoreographers.erase(layer->getSequence());
680}
681
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000682void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700683 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Ady Abrahamf8fdc452024-04-05 16:22:55 +0000684 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700685 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800686 }
Ana Krulec3084c052018-11-21 20:27:17 +0100687}
688
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100689void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700690 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700691}
692
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700693void Scheduler::setDefaultFrameRateCompatibility(
694 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
695 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000696 mFeatures.test(Feature::kContentDetection));
697}
698
Vishnu Nair41376b62023-11-08 05:08:58 -0800699void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
700 mLayerHistory.setLayerProperties(id, properties);
701}
702
Ady Abraham822ecbd2023-07-07 16:16:09 -0700703void Scheduler::chooseRefreshRateForContent(
704 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
705 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500706 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400707 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800708
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000709 SFTRACE_CALL();
Ady Abraham8a82ba62020-01-17 12:43:17 -0800710
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400711 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800712 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700713
714 if (updateAttachedChoreographer) {
715 LOG_ALWAYS_FATAL_IF(!hierarchy);
716
717 // update the attached choreographers after we selected the render rate.
718 const ftl::Optional<FrameRateMode> modeOpt = [&] {
719 std::scoped_lock lock(mPolicyLock);
720 return mPolicy.modeOpt;
721 }();
722
723 if (modeOpt) {
724 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
725 }
726 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800727}
728
Ana Krulecfb772822018-11-30 10:44:07 +0100729void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500730 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800731}
732
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700733void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700734 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800735 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500736 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800737 }
Ady Abraham8532d012019-05-08 14:50:56 -0700738}
739
Leon Scroggins III67388622023-02-06 20:36:20 -0500740void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500741 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500742 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500743 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500744 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500745 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500746 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700747 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700748 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700749 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500750 {
751 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400752
753 const auto displayOpt = mDisplays.get(id);
754 LOG_ALWAYS_FATAL_IF(!displayOpt);
755 auto& display = displayOpt->get();
756
757 display.powerMode = powerMode;
758 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500759 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500760 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700761
762 if (mDisplayPowerTimer) {
763 mDisplayPowerTimer->reset();
764 }
765
766 // Display Power event will boost the refresh rate to performance.
767 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700768 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700769}
770
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500771auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
772 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500773 std::scoped_lock lock(mDisplayLock);
774 return getVsyncScheduleLocked(idOpt);
775}
776
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500777auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
778 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500779 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500780
Leon Scroggins III67388622023-02-06 20:36:20 -0500781 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500782 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
783 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500784 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500785
786 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400787 if (!displayOpt) {
788 return nullptr;
789 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500790 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500791}
792
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700793void Scheduler::kernelIdleTimerCallback(TimerState state) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000794 SFTRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100795
Ady Abraham2139f732019-11-13 18:56:40 -0800796 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
797 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700798 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700799
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700800 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
801 using namespace fps_approx_ops;
802
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800803 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700804 // If we're not in performance mode then the kernel timer shouldn't do
805 // anything, as the refresh rate during DPU power collapse will be the
806 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500807 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800808 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700809 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
810 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700811 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500812 std::scoped_lock lock(mDisplayLock);
813 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500814 for (const auto& [_, display] : mDisplays) {
815 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400816 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500817 }
Alec Mouridc28b372019-04-18 21:17:13 -0700818 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800819
820 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700821}
822
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700823void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800824 applyPolicy(&Policy::idleTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000825 SFTRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100826}
827
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700828void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700829 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700830 // Touch event will boost the refresh rate to performance.
831 // Clear layer history to get fresh FPS detection.
832 // NOTE: Instead of checking all the layers, we should be checking the layer
833 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800834 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700835 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700836 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000837 SFTRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700838}
839
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700840void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800841 applyPolicy(&Policy::displayPowerTimer, state);
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000842 SFTRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700843}
844
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400845void Scheduler::dump(utils::Dumper& dumper) const {
846 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700847
848 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400849 utils::Dumper::Section section(dumper, "Features"sv);
850
851 for (Feature feature : ftl::enum_range<Feature>()) {
852 if (const auto flagOpt = ftl::flag_name(feature)) {
853 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
854 }
855 }
856 }
857 {
858 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400859 {
860 std::scoped_lock lock(mDisplayLock);
861 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500862 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400863 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400864 dumper.dump("layerHistory"sv, mLayerHistory.dump());
865 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
866 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
867 }
868
869 mFrameRateOverrideMappings.dump(dumper);
870 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400871
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500872 mVsyncConfiguration->dump(dumper.out());
873 dumper.eol();
874
875 mRefreshRateStats->dump(dumper.out());
876 dumper.eol();
877
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400878 std::scoped_lock lock(mDisplayLock);
879 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500880
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400881 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());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500887
Dominik Laskowskife749dc2024-07-26 10:09:31 -0400888 display.selectorPtr->dump(dumper);
889 display.targeterPtr->dump(dumper);
890 dumper.eol();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500891 }
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 Laskowski1d7be062024-07-24 13:59:07 -0400911void Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
912 const bool changed = (std::scoped_lock(mPolicyLock),
913 updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate));
914
915 if (changed) {
916 onFrameRateOverridesChanged();
917 }
Ady Abraham33a386b2023-07-18 15:37:11 -0700918}
919
920bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
921 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400922 if (consideredSignals.idle) return false;
923
924 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500925 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
926 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400927
928 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
929 // the FrameRateOverrideMappings rather than here.
930 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
931}
932
Dominik Laskowskib9724192024-07-12 15:55:28 -0400933void Scheduler::promotePacesetterDisplay(PhysicalDisplayId pacesetterId, PromotionParams params) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400934 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400935 {
936 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskib9724192024-07-12 15:55:28 -0400937 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterId, params);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400938 }
939
Leon Scroggins39d25342023-04-19 17:11:01 +0000940 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400941}
942
943std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
Dominik Laskowskib9724192024-07-12 15:55:28 -0400944 PhysicalDisplayId pacesetterId, PromotionParams params) {
Dominik Laskowski16d1b3c2024-07-12 14:35:00 -0400945 // TODO: b/241286431 - Choose the pacesetter among mDisplays.
946 mPacesetterDisplayId = pacesetterId;
947 ALOGI("Display %s is the pacesetter", to_string(pacesetterId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400948
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500949 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
950 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
951 const Display& pacesetter = *pacesetterOpt;
952
Dominik Laskowskib9724192024-07-12 15:55:28 -0400953 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
954 pacesetter.selectorPtr->setIdleTimerCallbacks(
955 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
956 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
957 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
958 .onExpired =
959 [this] { kernelIdleTimerCallback(TimerState::Expired); }},
960 .vrr = {.onReset = [this] { mSchedulerCallback.vrrDisplayIdle(false); },
961 .onExpired = [this] { mSchedulerCallback.vrrDisplayIdle(true); }}});
Dominik Laskowski596a2562022-10-28 11:26:12 -0400962
Dominik Laskowskib9724192024-07-12 15:55:28 -0400963 pacesetter.selectorPtr->startIdleTimer();
964 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500965
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500966 newVsyncSchedulePtr = pacesetter.schedulePtr;
967
Dominik Laskowski66295432023-03-14 12:25:36 -0400968 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800969 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
970 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500971 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500972 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400973}
Leon Scroggins III67388622023-02-06 20:36:20 -0500974
Leon Scroggins39d25342023-04-19 17:11:01 +0000975void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
976 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500977
978 if (hasEventThreads()) {
979 eventThreadFor(Cycle::Render).onNewVsyncSchedule(vsyncSchedule);
980 eventThreadFor(Cycle::LastComposite).onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400981 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400982}
983
Dominik Laskowskib9724192024-07-12 15:55:28 -0400984void Scheduler::demotePacesetterDisplay(PromotionParams params) {
985 if (!FlagManager::getInstance().connected_display() || params.toggleIdleTimer) {
986 // No need to lock for reads on kMainThreadContext.
987 if (const auto pacesetterPtr =
988 FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
989 pacesetterPtr->stopIdleTimer();
990 pacesetterPtr->clearIdleTimerCallbacks();
991 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400992 }
993
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500994 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400995 std::scoped_lock lock(mPolicyLock);
996 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800997}
998
Ady Abraham822ecbd2023-07-07 16:16:09 -0700999void Scheduler::updateAttachedChoreographersFrameRate(
1000 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
1001 std::scoped_lock lock(mChoreographerLock);
1002
1003 const auto layerId = static_cast<int32_t>(layer.id);
1004 const auto choreographers = mAttachedChoreographers.find(layerId);
1005 if (choreographers == mAttachedChoreographers.end()) {
1006 return;
1007 }
1008
1009 auto& layerChoreographers = choreographers->second;
1010
1011 layerChoreographers.frameRate = fps;
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001012 SFTRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
Ady Abraham822ecbd2023-07-07 16:16:09 -07001013 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1014
1015 auto it = layerChoreographers.connections.begin();
1016 while (it != layerChoreographers.connections.end()) {
1017 sp<EventThreadConnection> choreographerConnection = it->promote();
1018 if (choreographerConnection) {
1019 choreographerConnection->frameRate = fps;
1020 it++;
1021 } else {
1022 it = choreographers->second.connections.erase(it);
1023 }
1024 }
1025
1026 if (layerChoreographers.connections.empty()) {
1027 mAttachedChoreographers.erase(choreographers);
1028 }
1029}
1030
1031int Scheduler::updateAttachedChoreographersInternal(
1032 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1033 int parentDivisor) {
1034 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1035
1036 int divisor = 0;
1037 if (layerHierarchy.getLayer()) {
1038 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1039 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1040 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1041 parentDivisor);
1042
1043 if (frameRate.isValid()) {
1044 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1045 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1046 // Since this layer wants an exact match, we would only set a frame rate if the
1047 // desired rate is a divisor of the display refresh rate.
1048 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1049 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1050 // find the closest frame rate divisor for the desired frame rate.
1051 divisor = static_cast<int>(
1052 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1053 }
1054 }
1055 }
1056
1057 // We start by traversing the children, updating their choreographers, and getting back the
1058 // aggregated frame rate.
1059 int childrenDivisor = 0;
1060 for (const auto& [child, _] : layerHierarchy.mChildren) {
1061 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1062
1063 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1064
1065 const int childDivisor =
1066 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1067 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1068 if (childDivisor > 0) {
1069 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1070 }
1071 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1072 }
1073
1074 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1075
1076 // If there is no explicit vote for this layer. Use the children's vote if exists
1077 divisor = (divisor == 0) ? childrenDivisor : divisor;
1078 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1079
1080 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1081 divisor = (divisor == 0) ? parentDivisor : divisor;
1082 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1083
1084 if (layerHierarchy.getLayer()) {
1085 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1086 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1087 }
1088
1089 return divisor;
1090}
1091
1092void Scheduler::updateAttachedChoreographers(
1093 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001094 SFTRACE_CALL();
Ady Abraham822ecbd2023-07-07 16:16:09 -07001095 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1096}
1097
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001098template <typename S, typename T>
1099auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001100 SFTRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001101 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001102 GlobalSignals consideredSignals;
1103
Ady Abraham62a0be22020-12-08 16:54:10 -08001104 bool refreshRateChanged = false;
1105 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001106
Ady Abraham8532d012019-05-08 14:50:56 -07001107 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001108 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001109
1110 auto& currentState = mPolicy.*statePtr;
1111 if (currentState == newState) return {};
1112 currentState = std::forward<T>(newState);
1113
Dominik Laskowski596a2562022-10-28 11:26:12 -04001114 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001115 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001116 {
1117 std::scoped_lock lock(mDisplayLock);
1118 ftl::FakeGuard guard(kMainThreadContext);
1119
1120 modeChoices = chooseDisplayModes();
1121
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001122 // TODO(b/240743786): The pacesetter display's mode must change for any
1123 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1124 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001125 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001126 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001127 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001128 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001129 })
1130 .value();
1131 }
ramindani69b58e82022-09-26 16:48:36 -07001132
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001133 modeRequests.reserve(modeChoices.size());
1134 for (auto& [id, choice] : modeChoices) {
1135 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001136 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001137 .emitEvent = choice.consideredSignals
1138 .shouldEmitEvent()});
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001139 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001140
ramindanif2f40f42024-06-18 16:48:28 -07001141 if (!FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1142 frameRateOverridesChanged =
1143 updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
1144 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001145 if (mPolicy.modeOpt != modeOpt) {
1146 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001147 refreshRateChanged = true;
Dominik Laskowskifc94b412024-08-03 15:02:23 -04001148 } else if (consideredSignals.shouldEmitEvent()) {
1149 // The mode did not change, but we may need to emit if DisplayModeRequest::emitEvent was
1150 // previously false.
1151 emitModeChangeIfNeeded();
Ady Abraham8532d012019-05-08 14:50:56 -07001152 }
Ady Abraham8532d012019-05-08 14:50:56 -07001153 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001154 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001155 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001156 }
ramindanif2f40f42024-06-18 16:48:28 -07001157
1158 if (FlagManager::getInstance().vrr_bugfix_dropped_frame()) {
1159 std::scoped_lock lock(mPolicyLock);
1160 frameRateOverridesChanged =
1161 updateFrameRateOverridesLocked(consideredSignals, mPolicy.modeOpt->fps);
1162 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001163 if (frameRateOverridesChanged) {
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001164 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001165 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001166 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001167}
1168
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001169auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001170 SFTRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001171
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001172 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -04001173 const auto globalSignals = makeGlobalSignals();
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001174
1175 const Fps pacesetterFps = [&]() REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext) {
1176 auto rankedFrameRates =
1177 pacesetterSelectorPtrLocked()->getRankedFrameRates(mPolicy.contentRequirements,
1178 globalSignals);
1179
1180 const Fps pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
1181
1182 modeChoices.try_emplace(*mPacesetterDisplayId,
1183 DisplayModeChoice::from(std::move(rankedFrameRates)));
1184 return pacesetterFps;
1185 }();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001186
Dominik Laskowski086507b2024-05-16 15:33:16 -04001187 // Choose a mode for powered-on follower displays.
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001188 for (const auto& [id, display] : mDisplays) {
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001189 if (id == *mPacesetterDisplayId) continue;
Dominik Laskowski086507b2024-05-16 15:33:16 -04001190 if (display.powerMode != hal::PowerMode::ON) continue;
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001191
Ady Abrahamace3d052022-11-17 16:25:05 -08001192 auto rankedFrameRates =
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001193 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals,
1194 pacesetterFps);
1195
1196 modeChoices.try_emplace(id, DisplayModeChoice::from(std::move(rankedFrameRates)));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001197 }
ramindani69b58e82022-09-26 16:48:36 -07001198
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001199 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001200}
1201
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001202GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001203 const bool powerOnImminent = mDisplayPowerTimer &&
1204 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1205 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001206
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001207 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1208 .idle = mPolicy.idleTimer == TimerState::Expired,
1209 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001210}
1211
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001212FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001213 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001214 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001215 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001216 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1217 .ranking.front()
1218 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001219
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001220 // Make sure the stored mode is up to date.
1221 mPolicy.modeOpt = frameRateMode;
1222
1223 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001224}
1225
Peiyong Line9d809e2020-04-14 13:10:48 -07001226void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001227 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1228 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1229
1230 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1231 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1232 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1233 }
1234}
1235
Leon Scroggins III5b581492023-10-31 14:29:41 -04001236bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001237 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1238 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1239 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1240 // We need to composite again as refreshTimeNanos is still in the future.
1241 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001242 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001243
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001244 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001245 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001246 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001247}
1248
Ady Abraham7825c682021-05-17 15:12:14 -07001249void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001250 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001251}
1252
Andy Yu8c2703d2023-11-03 11:22:46 -07001253void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001254 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1255 return;
1256 }
1257
Andy Yu8c2703d2023-11-03 11:22:46 -07001258 if (FlagManager::getInstance().game_default_frame_rate()) {
1259 // update the frame rate override mapping in LayerHistory
1260 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1261 } else {
1262 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1263 }
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001264
1265 onFrameRateOverridesChanged();
Andy Yu8c2703d2023-11-03 11:22:46 -07001266}
1267
1268void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1269 if (!FlagManager::getInstance().game_default_frame_rate() ||
1270 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1271 return;
1272 }
1273
1274 // update the frame rate override mapping in LayerHistory
1275 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001276}
1277
Ady Abraham62a0be22020-12-08 16:54:10 -08001278void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1279 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1280 return;
1281 }
1282
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001283 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Dominik Laskowski1d7be062024-07-24 13:59:07 -04001284 onFrameRateOverridesChanged();
Ady Abraham62a0be22020-12-08 16:54:10 -08001285}
1286
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001287void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001288 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001289 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1290}
1291
Tony Huangf3621102023-09-04 17:14:22 +08001292void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001293 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001294}
1295
Tony Huangf3621102023-09-04 17:14:22 +08001296bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1297 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1298 if (oThreshold) {
1299 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1300 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001301 return false;
1302}
1303
Dominik Laskowski068173d2021-08-11 17:22:59 -07001304} // namespace android::scheduler