blob: 32279aeda2b21429354a11495132755114daa563 [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Dominik Laskowski98041832019-08-01 18:35:59 -070017#undef LOG_TAG
18#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010019#define ATRACE_TAG ATRACE_TAG_GRAPHICS
20
Ana Krulec98b5b242018-08-10 15:03:23 -070021#include "Scheduler.h"
22
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070023#include <android-base/properties.h>
Dominik Laskowski49cea512019-11-12 14:13:23 -080024#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070025#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070027#include <configstore/Utils.h>
Dominik Laskowskiec0eac22023-01-28 16:16:19 -050028#include <ftl/concat.h>
Dominik Laskowski03cfce82022-11-02 12:13:29 -040029#include <ftl/enum.h>
ramindania556d072022-06-14 23:25:11 +000030#include <ftl/fake_guard.h>
Dominik Laskowski01602522022-10-07 19:02:28 -040031#include <ftl/small_map.h>
Ady Abraham9243bba2023-02-10 15:31:14 -080032#include <gui/TraceUtils.h>
chaviw3277faf2021-05-19 16:45:23 -050033#include <gui/WindowInfo.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080034#include <system/window.h>
Dominik Laskowski6b049ff2023-01-29 15:46:45 -050035#include <ui/DisplayMap.h>
Ana Krulec3084c052018-11-21 20:27:17 +010036#include <utils/Timers.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070037
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070038#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowski63f12792023-01-21 16:58:22 -050039#include <scheduler/interface/ICompositor.h>
40
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070041#include <algorithm>
42#include <cinttypes>
43#include <cstdint>
44#include <functional>
45#include <memory>
46#include <numeric>
47
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.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -050085 demotePacesetterDisplay();
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
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500120void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
121 demotePacesetterDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400122
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500123 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800124}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700125
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400126void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
ramindaniae645822024-01-11 10:57:29 -0800127 auto schedulePtr =
128 std::make_shared<VsyncSchedule>(selectorPtr->getActiveMode().modePtr, mFeatures,
129 [this](PhysicalDisplayId id, bool enable) {
130 onHardwareVsyncRequest(id, enable);
131 });
Dominik Laskowski66295432023-03-14 12:25:36 -0400132
133 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr));
Leon Scroggins III67388622023-02-06 20:36:20 -0500134}
135
136void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
137 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500138 VsyncSchedulePtr schedulePtr) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500139 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400140
Dominik Laskowski008bec02023-03-14 12:04:58 -0400141 auto [pacesetterVsyncSchedule, isNew] = [&]() FTL_FAKE_GUARD(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400142 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400143 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500144 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
145 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400146 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400147
Dominik Laskowski008bec02023-03-14 12:04:58 -0400148 return std::make_pair(promotePacesetterDisplayLocked(), isNew);
149 }();
150
Leon Scroggins39d25342023-04-19 17:11:01 +0000151 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400152
153 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
154 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400155 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400156 }
Dominik Laskowski091129a2024-02-21 14:26:03 -0500157
158 dispatchHotplug(displayId, Hotplug::Connected);
Dominik Laskowski01602522022-10-07 19:02:28 -0400159}
160
161void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500162 dispatchHotplug(displayId, Hotplug::Disconnected);
163
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500164 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400165
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400166 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
167 {
168 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500169 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400170
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400171 // Do not allow removing the final display. Code in the scheduler expects
172 // there to be at least one display. (This may be relaxed in the future with
173 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500174 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500175
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400176 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
177 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000178 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400179}
180
Dominik Laskowski756b7892021-08-04 12:53:59 -0700181void Scheduler::run() {
182 while (true) {
183 waitMessage();
184 }
185}
186
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700187void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
188 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500189 const FrameTargeter::BeginFrameArgs beginFrameArgs =
190 {.frameBeginTime = SchedulerClock::now(),
191 .vsyncId = vsyncId,
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500192 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500193 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
194 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700195
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500196 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
197 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500198
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500199 {
200 FrameTargets targets;
201 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500202
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500203 // TODO (b/256196556): Followers should use the next VSYNC after the frontrunner, not the
204 // pacesetter.
205 // Update expectedVsyncTime, which may have been adjusted by beginFrame.
206 expectedVsyncTime = pacesetterPtr->targeterPtr->target().expectedPresentTime();
207
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500208 for (const auto& [id, display] : mDisplays) {
209 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400210
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500211 auto followerBeginFrameArgs = beginFrameArgs;
212 followerBeginFrameArgs.expectedVsyncTime =
213 display.schedulePtr->vsyncDeadlineAfter(expectedVsyncTime);
214
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500215 FrameTargeter& targeter = *display.targeterPtr;
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500216 targeter.beginFrame(followerBeginFrameArgs, *display.schedulePtr);
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500217 targets.try_emplace(id, &targeter.target());
218 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400219
ramindaniae645822024-01-11 10:57:29 -0800220 if (!compositor.commit(pacesetterPtr->displayId, targets)) {
221 if (FlagManager::getInstance().vrr_config()) {
222 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
223 }
224 return;
225 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400226 }
227
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500228 // The pacesetter may have changed or been registered anew during commit.
229 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500230
231 // TODO(b/256196556): Choose the frontrunner display.
232 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500233 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500234
235 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500236 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500237
238 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500239 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700240 }
241
Ady Abrahamd6d80162023-10-23 12:57:41 -0700242 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000243 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500244 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000245 const auto skipDuration = Duration::fromNs(
246 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
247 ATRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
248 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
249 std::this_thread::sleep_for(skipDuration);
250 mPacesetterFrameDurationFractionToSkip = 0.f;
251 }
252
Ady Abrahame9883032023-11-20 17:54:54 -0800253 if (FlagManager::getInstance().vrr_config()) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500254 const auto minFramePeriod = pacesetterPtr->schedulePtr->minFramePeriod();
Ady Abrahame9883032023-11-20 17:54:54 -0800255 const auto presentFenceForPastVsync =
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500256 pacesetterPtr->targeterPtr->target().presentFenceForPastVsync(minFramePeriod);
Ady Abrahame9883032023-11-20 17:54:54 -0800257 const auto lastConfirmedPresentTime = presentFenceForPastVsync->getSignalTime();
258 if (lastConfirmedPresentTime != Fence::SIGNAL_TIME_PENDING &&
259 lastConfirmedPresentTime != Fence::SIGNAL_TIME_INVALID) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500260 pacesetterPtr->schedulePtr->getTracker()
Ady Abrahame9883032023-11-20 17:54:54 -0800261 .onFrameBegin(expectedVsyncTime, TimePoint::fromNs(lastConfirmedPresentTime));
262 }
263 }
264
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500265 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
ramindaniae645822024-01-11 10:57:29 -0800266 if (FlagManager::getInstance().vrr_config()) {
267 compositor.sendNotifyExpectedPresentHint(pacesetterPtr->displayId);
268 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700269 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400270
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500271 for (const auto& [id, targeter] : targeters) {
272 const auto resultOpt = resultsPerDisplay.get(id);
273 LOG_ALWAYS_FATAL_IF(!resultOpt);
274 targeter->endFrame(*resultOpt);
275 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700276}
277
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500278std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800279 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500280 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800281 return mFrameRateOverrideMappings
282 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800283}
284
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400285bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800286 const auto frameRate = getFrameRateOverride(uid);
287 if (!frameRate.has_value()) {
288 return true;
289 }
290
Ady Abraham9243bba2023-02-10 15:31:14 -0800291 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400292 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700293}
294
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400295bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
296 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700297}
298
Ady Abrahamf2851612023-09-25 17:19:00 -0700299bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
300 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500301}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800302
Ady Abrahamf2851612023-09-25 17:19:00 -0700303Period Scheduler::getVsyncPeriod(uid_t uid) {
304 const auto [refreshRate, period] = [this] {
305 std::scoped_lock lock(mDisplayLock);
306 const auto pacesetterOpt = pacesetterDisplayLocked();
307 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
308 const Display& pacesetter = *pacesetterOpt;
Ying Weiaf854ad2024-03-16 05:24:39 +0000309 const FrameRateMode& frameRateMode = pacesetter.selectorPtr->getActiveMode();
310 const auto refreshRate = frameRateMode.fps;
311 const auto displayVsync = frameRateMode.modePtr->getVsyncRate();
312 const auto numPeriod = RefreshRateSelector::getFrameRateDivisor(displayVsync, refreshRate);
313 return std::make_pair(refreshRate, numPeriod * pacesetter.schedulePtr->period());
Ady Abrahamf2851612023-09-25 17:19:00 -0700314 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500315
Ady Abrahamf2851612023-09-25 17:19:00 -0700316 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800317
Ady Abrahamf2851612023-09-25 17:19:00 -0700318 const auto frameRate = getFrameRateOverride(uid);
319 if (!frameRate.has_value()) {
320 return currentPeriod;
321 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100322
Ady Abrahamf2851612023-09-25 17:19:00 -0700323 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
324 if (divisor <= 1) {
325 return currentPeriod;
326 }
327
328 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
329 // behaviour.
330 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100331}
ramindaniae645822024-01-11 10:57:29 -0800332void Scheduler::onExpectedPresentTimePosted(TimePoint expectedPresentTime) {
333 const auto frameRateMode = [this] {
334 std::scoped_lock lock(mDisplayLock);
335 const auto pacesetterOpt = pacesetterDisplayLocked();
336 const Display& pacesetter = *pacesetterOpt;
337 return pacesetter.selectorPtr->getActiveMode();
338 }();
339
340 if (frameRateMode.modePtr->getVrrConfig()) {
341 mSchedulerCallback.onExpectedPresentTimePosted(expectedPresentTime, frameRateMode.modePtr,
342 frameRateMode.fps);
343 }
344}
Jorim Jaggic0086af2021-02-12 18:18:11 +0100345
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500346void Scheduler::createEventThread(Cycle cycle, frametimeline::TokenManager* tokenManager,
347 std::chrono::nanoseconds workDuration,
348 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500349 auto eventThread =
350 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
351 getVsyncSchedule(), tokenManager, *this,
352 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500353
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500354 if (cycle == Cycle::Render) {
355 mRenderEventThread = std::move(eventThread);
356 mRenderEventConnection = mRenderEventThread->createEventConnection();
357 } else {
358 mLastCompositeEventThread = std::move(eventThread);
359 mLastCompositeEventConnection = mLastCompositeEventThread->createEventConnection();
360 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700361}
362
363sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500364 Cycle cycle, EventRegistrationFlags eventRegistration, const sp<IBinder>& layerHandle) {
365 const auto connection = eventThreadFor(cycle).createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700366 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
367
368 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
369 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
370 // processed on the main thread.
371 mSchedulerCallback.onChoreographerAttached();
372
373 std::scoped_lock lock(mChoreographerLock);
374 const auto [iter, emplaced] =
375 mAttachedChoreographers.emplace(layerId,
376 AttachedChoreographers{Fps(), {connection}});
377 if (!emplaced) {
378 iter->second.connections.emplace(connection);
379 connection->frameRate = iter->second.frameRate;
380 }
381 }
382 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700383}
384
Dominik Laskowski091129a2024-02-21 14:26:03 -0500385void Scheduler::dispatchHotplug(PhysicalDisplayId displayId, Hotplug hotplug) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500386 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500387 const bool connected = hotplug == Hotplug::Connected;
388 eventThreadFor(Cycle::Render).onHotplugReceived(displayId, connected);
389 eventThreadFor(Cycle::LastComposite).onHotplugReceived(displayId, connected);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500390 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700391}
392
Dominik Laskowski091129a2024-02-21 14:26:03 -0500393void Scheduler::dispatchHotplugError(int32_t errorCode) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500394 if (hasEventThreads()) {
Dominik Laskowski091129a2024-02-21 14:26:03 -0500395 eventThreadFor(Cycle::Render).onHotplugConnectionError(errorCode);
396 eventThreadFor(Cycle::LastComposite).onHotplugConnectionError(errorCode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700397 }
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700398}
399
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500400void Scheduler::enableSyntheticVsync(bool enable) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500401 eventThreadFor(Cycle::Render).enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700402}
403
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500404void Scheduler::onFrameRateOverridesChanged(Cycle cycle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800405 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500406 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800407
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800408 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800409 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800410
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500411 eventThreadFor(cycle).onFrameRateOverridesChanged(displayId, std::move(overrides));
Ady Abraham62f216c2020-10-13 19:07:23 -0700412}
413
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500414void Scheduler::onHdcpLevelsChanged(Cycle cycle, PhysicalDisplayId displayId,
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700415 int32_t connectedLevel, int32_t maxLevel) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500416 eventThreadFor(cycle).onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700417}
418
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500419void Scheduler::onPrimaryDisplayModeChanged(Cycle cycle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800420 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700421 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100422 // Cache the last reported modes for primary display.
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500423 mPolicy.cachedModeChangedParams = {cycle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700424
425 // Invalidate content based refresh rate selection so it could be calculated
426 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700427 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800428 }
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500429 onNonPrimaryDisplayModeChanged(cycle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700430}
431
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100432void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700433 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800434 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100435 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700436 return;
437 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700438 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100439 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700440 return;
441 }
442
Ady Abrahamd1591702021-07-27 16:27:56 -0700443 // If the mode is not the current mode, this means that a
444 // mode change is in progress. In that case we shouldn't dispatch an event
445 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500446 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700447 return;
448 }
449
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100450 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800451 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700452 return;
453 }
454
Ady Abrahamace3d052022-11-17 16:25:05 -0800455 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500456 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->cycle,
Dominik Laskowski068173d2021-08-11 17:22:59 -0700457 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700458}
459
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500460void Scheduler::onNonPrimaryDisplayModeChanged(Cycle cycle, const FrameRateMode& mode) {
461 if (hasEventThreads()) {
462 eventThreadFor(cycle).onModeChanged(mode);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700463 }
Ady Abraham447052e2019-02-13 16:07:27 -0800464}
465
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500466void Scheduler::dump(Cycle cycle, std::string& result) const {
467 eventThreadFor(cycle).dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700468}
469
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500470void Scheduler::setDuration(Cycle cycle, std::chrono::nanoseconds workDuration,
Ady Abraham9c53ee72020-07-22 21:16:18 -0700471 std::chrono::nanoseconds readyDuration) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500472 if (hasEventThreads()) {
473 eventThreadFor(cycle).setDuration(workDuration, readyDuration);
Ana Krulec6ddd2612020-09-24 13:06:33 -0700474 }
Ana Krulec98b5b242018-08-10 15:03:23 -0700475}
Ana Krulece588e312018-09-18 12:32:24 -0700476
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500477void Scheduler::updatePhaseConfiguration(Fps refreshRate) {
478 mRefreshRateStats->setRefreshRate(refreshRate);
479 mVsyncConfiguration->setRefreshRateFps(refreshRate);
480 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
481 refreshRate.getPeriod());
482}
483
484void Scheduler::resetPhaseConfiguration(Fps refreshRate) {
485 // Cancel the pending refresh rate change, if any, before updating the phase configuration.
486 mVsyncModulator->cancelRefreshRateChange();
487
488 mVsyncConfiguration->reset();
489 updatePhaseConfiguration(refreshRate);
490}
491
492void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
493 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500494}
495
496void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500497 setDuration(Cycle::Render,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500498 /* workDuration */ config.appWorkDuration,
499 /* readyDuration */ config.sfWorkDuration);
Dominik Laskowski4babfc42024-02-16 12:28:40 -0500500 setDuration(Cycle::LastComposite,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500501 /* workDuration */ vsyncPeriod,
502 /* readyDuration */ config.sfWorkDuration);
503 setDuration(config.sfWorkDuration);
504}
505
Leon Scroggins III67388622023-02-06 20:36:20 -0500506void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
507 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400508 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400509 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700510}
511
Leon Scroggins III67388622023-02-06 20:36:20 -0500512void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
513 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400514 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400515 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700516}
517
Leon Scroggins III67388622023-02-06 20:36:20 -0500518void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800519 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500520 std::scoped_lock lock(mDisplayLock);
521 ftl::FakeGuard guard(kMainThreadContext);
522
Leon Scroggins III792ea802023-11-27 17:32:51 -0500523 for (const auto& [id, display] : mDisplays) {
524 if (display.powerMode != hal::PowerMode::OFF ||
525 !FlagManager::getInstance().multithreaded_present()) {
526 resyncToHardwareVsyncLocked(id, allowToEnable);
527 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500528 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500529}
530
Leon Scroggins III67388622023-02-06 20:36:20 -0500531void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800532 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500533 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400534 if (!displayOpt) {
535 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
536 return;
537 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500538 const Display& display = *displayOpt;
539
540 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800541 if (!modePtr) {
542 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500543 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800544 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400545 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800546 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500547 }
548 }
549}
550
Dominik Laskowski66295432023-03-14 12:25:36 -0400551void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
552 static const auto& whence = __func__;
553 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
554
555 // On main thread to serialize reads/writes of pending hardware VSYNC state.
556 static_cast<void>(
Leon Scroggins III53ca9562023-12-27 16:32:12 -0500557 schedule([=, this]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400558 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
559
560 if (const auto displayOpt = mDisplays.get(id)) {
561 auto& display = displayOpt->get();
562 display.schedulePtr->setPendingHardwareVsyncState(enabled);
563
564 if (display.powerMode != hal::PowerMode::OFF) {
565 mSchedulerCallback.requestHardwareVsync(id, enabled);
566 }
567 }
568 }));
569}
570
Ady Abrahamee6365b2024-03-06 14:31:45 -0800571void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate, bool applyImmediately) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500572 std::scoped_lock lock(mDisplayLock);
573 ftl::FakeGuard guard(kMainThreadContext);
574
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500575 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400576 if (!displayOpt) {
577 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
578 return;
579 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500580 const Display& display = *displayOpt;
581 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800582
583 using fps_approx_ops::operator!=;
584 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500585 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
586 "%" PRIu64,
587 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800588
589 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700590 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800591
Ady Abrahamee6365b2024-03-06 14:31:45 -0800592 display.schedulePtr->getTracker().setRenderRate(renderFrameRate, applyImmediately);
Ady Abrahamace3d052022-11-17 16:25:05 -0800593}
594
ramindani0491e642023-11-16 17:42:14 -0800595Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
596 TimePoint currentExpectedPresentTime) const {
597 std::scoped_lock lock(mDisplayLock);
598 ftl::FakeGuard guard(kMainThreadContext);
599
600 const auto displayOpt = mDisplays.get(id);
601 if (!displayOpt) {
602 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
603 return Fps{};
604 }
605 const Display& display = *displayOpt;
Leon Scroggins IIIa0785012024-01-23 16:05:59 -0500606 const Duration threshold =
607 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriod() / 2;
608 const TimePoint nextVsyncTime =
609 display.schedulePtr->vsyncDeadlineAfter(currentExpectedPresentTime + threshold,
610 currentExpectedPresentTime);
611 const Duration frameInterval = nextVsyncTime - currentExpectedPresentTime;
612 return Fps::fromPeriodNsecs(frameInterval.ns());
ramindani0491e642023-11-16 17:42:14 -0800613}
614
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700615void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700616 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800617
618 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700619 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800620
621 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500622 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800623 }
624}
625
Leon Scroggins III67388622023-02-06 20:36:20 -0500626bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
627 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500628 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
629 return Period::fromNs(nanos);
630 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400631 auto schedule = getVsyncSchedule(id);
632 if (!schedule) {
633 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
634 return false;
635 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400636 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700637}
638
Leon Scroggins III67388622023-02-06 20:36:20 -0500639void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000640 ATRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500641 const auto scheduleOpt =
642 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
643 return display.powerMode == hal::PowerMode::OFF
644 ? std::nullopt
645 : std::make_optional(display.schedulePtr);
646 });
647
648 if (!scheduleOpt) return;
649 const auto& schedule = scheduleOpt->get();
650
Yi Kong08d7c812023-12-12 16:40:22 +0900651 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
652 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400653 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700654 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400655 constexpr bool kDisallow = false;
656 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700657 }
658}
659
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700660void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200661 // If the content detection feature is off, we still keep the layer history,
662 // since we use it for other features (like Frame Rate API), so layers
663 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000664 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700665}
666
Ady Abrahambdda8f02021-04-01 16:06:11 -0700667void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700668 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700669}
670
Ady Abraham822ecbd2023-07-07 16:16:09 -0700671void Scheduler::onLayerDestroyed(Layer* layer) {
672 std::scoped_lock lock(mChoreographerLock);
673 mAttachedChoreographers.erase(layer->getSequence());
674}
675
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000676void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700677 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Rachel Leec790ab72024-03-25 10:47:51 -0700678 const auto& selectorPtr = pacesetterSelectorPtr();
679 // Skip recording layer history on LayerUpdateType::SetFrameRate for MRR devices when the
680 // dVRR vote types are guarded (disabled) for MRR. This is to avoid activity when setting dVRR
681 // vote types.
682 if (selectorPtr->canSwitch() &&
683 (updateType != LayerHistory::LayerUpdateType::SetFrameRate ||
684 layerProps.setFrameRateVote.isVoteValidForMrr(selectorPtr->isVrrDevice()))) {
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
Ady Abraham8a82ba62020-01-17 12:43:17 -0800709 ATRACE_CALL();
710
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) {
794 ATRACE_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);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700825 ATRACE_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 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700837 ATRACE_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);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700842 ATRACE_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 Laskowskiec0eac22023-01-28 16:16:19 -0500878 {
879 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
880
881 std::scoped_lock lock(mDisplayLock);
882 ftl::FakeGuard guard(kMainThreadContext);
883
884 for (const auto& [id, display] : mDisplays) {
885 utils::Dumper::Section
886 section(dumper,
887 id == mPacesetterDisplayId
888 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
889 : ftl::Concat("Follower Display ", id.value).c_str());
890
891 display.targeterPtr->dump(dumper);
892 dumper.eol();
893 }
894 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800895}
896
Dominik Laskowski068173d2021-08-11 17:22:59 -0700897void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500898 std::scoped_lock lock(mDisplayLock);
899 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500900 if (mPacesetterDisplayId) {
901 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
902 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500903 getVsyncScheduleLocked()->dump(out);
904 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500905 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500906 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500907 continue;
908 }
909 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500910 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500911 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700912}
913
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800914bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700915 std::scoped_lock lock(mPolicyLock);
916 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
917}
918
919bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
920 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400921 if (consideredSignals.idle) return false;
922
923 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500924 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
925 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400926
927 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
928 // the FrameRateOverrideMappings rather than here.
929 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
930}
931
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500932void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400933 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
934
935 {
936 std::scoped_lock lock(mDisplayLock);
937 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
938 }
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(
944 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500945 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500946 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500947 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).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
953 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400954 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
955 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
956 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
957 .onExpired =
958 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
959
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500960 pacesetter.selectorPtr->startIdleTimer();
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
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500980void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400981 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500982 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
983 pacesetterPtr->stopIdleTimer();
984 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400985 }
986
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500987 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400988 std::scoped_lock lock(mPolicyLock);
989 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800990}
991
Ady Abraham822ecbd2023-07-07 16:16:09 -0700992void Scheduler::updateAttachedChoreographersFrameRate(
993 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
994 std::scoped_lock lock(mChoreographerLock);
995
996 const auto layerId = static_cast<int32_t>(layer.id);
997 const auto choreographers = mAttachedChoreographers.find(layerId);
998 if (choreographers == mAttachedChoreographers.end()) {
999 return;
1000 }
1001
1002 auto& layerChoreographers = choreographers->second;
1003
1004 layerChoreographers.frameRate = fps;
1005 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1006 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1007
1008 auto it = layerChoreographers.connections.begin();
1009 while (it != layerChoreographers.connections.end()) {
1010 sp<EventThreadConnection> choreographerConnection = it->promote();
1011 if (choreographerConnection) {
1012 choreographerConnection->frameRate = fps;
1013 it++;
1014 } else {
1015 it = choreographers->second.connections.erase(it);
1016 }
1017 }
1018
1019 if (layerChoreographers.connections.empty()) {
1020 mAttachedChoreographers.erase(choreographers);
1021 }
1022}
1023
1024int Scheduler::updateAttachedChoreographersInternal(
1025 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1026 int parentDivisor) {
1027 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1028
1029 int divisor = 0;
1030 if (layerHierarchy.getLayer()) {
1031 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1032 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1033 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1034 parentDivisor);
1035
1036 if (frameRate.isValid()) {
1037 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1038 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1039 // Since this layer wants an exact match, we would only set a frame rate if the
1040 // desired rate is a divisor of the display refresh rate.
1041 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1042 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1043 // find the closest frame rate divisor for the desired frame rate.
1044 divisor = static_cast<int>(
1045 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1046 }
1047 }
1048 }
1049
1050 // We start by traversing the children, updating their choreographers, and getting back the
1051 // aggregated frame rate.
1052 int childrenDivisor = 0;
1053 for (const auto& [child, _] : layerHierarchy.mChildren) {
1054 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1055
1056 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1057
1058 const int childDivisor =
1059 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1060 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1061 if (childDivisor > 0) {
1062 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1063 }
1064 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1065 }
1066
1067 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1068
1069 // If there is no explicit vote for this layer. Use the children's vote if exists
1070 divisor = (divisor == 0) ? childrenDivisor : divisor;
1071 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1072
1073 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1074 divisor = (divisor == 0) ? parentDivisor : divisor;
1075 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1076
1077 if (layerHierarchy.getLayer()) {
1078 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1079 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1080 }
1081
1082 return divisor;
1083}
1084
1085void Scheduler::updateAttachedChoreographers(
1086 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1087 ATRACE_CALL();
1088 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1089}
1090
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001091template <typename S, typename T>
1092auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001093 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001094 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001095 GlobalSignals consideredSignals;
1096
Ady Abraham62a0be22020-12-08 16:54:10 -08001097 bool refreshRateChanged = false;
1098 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001099
Ady Abraham8532d012019-05-08 14:50:56 -07001100 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001101 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001102
1103 auto& currentState = mPolicy.*statePtr;
1104 if (currentState == newState) return {};
1105 currentState = std::forward<T>(newState);
1106
Dominik Laskowski596a2562022-10-28 11:26:12 -04001107 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001108 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001109 {
1110 std::scoped_lock lock(mDisplayLock);
1111 ftl::FakeGuard guard(kMainThreadContext);
1112
1113 modeChoices = chooseDisplayModes();
1114
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001115 // TODO(b/240743786): The pacesetter display's mode must change for any
1116 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1117 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001118 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001119 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001120 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001121 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001122 })
1123 .value();
1124 }
ramindani69b58e82022-09-26 16:48:36 -07001125
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001126 modeRequests.reserve(modeChoices.size());
1127 for (auto& [id, choice] : modeChoices) {
1128 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001129 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001130 .emitEvent = !choice.consideredSignals.idle});
1131 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001132
Ady Abraham33a386b2023-07-18 15:37:11 -07001133 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001134
Ady Abrahamace3d052022-11-17 16:25:05 -08001135 if (mPolicy.modeOpt != modeOpt) {
1136 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001137 refreshRateChanged = true;
1138 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001139 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001140 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001141 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001142 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001143 }
Ady Abraham8532d012019-05-08 14:50:56 -07001144 }
Ady Abraham8532d012019-05-08 14:50:56 -07001145 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001146 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001147 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001148 }
1149 if (frameRateOverridesChanged) {
1150 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1151 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001152 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001153}
1154
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001155auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001156 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001157
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001158 DisplayModeChoiceMap modeChoices;
Dominik Laskowski01602522022-10-07 19:02:28 -04001159 const auto globalSignals = makeGlobalSignals();
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001160
1161 const Fps pacesetterFps = [&]() REQUIRES(mPolicyLock, mDisplayLock, kMainThreadContext) {
1162 auto rankedFrameRates =
1163 pacesetterSelectorPtrLocked()->getRankedFrameRates(mPolicy.contentRequirements,
1164 globalSignals);
1165
1166 const Fps pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
1167
1168 modeChoices.try_emplace(*mPacesetterDisplayId,
1169 DisplayModeChoice::from(std::move(rankedFrameRates)));
1170 return pacesetterFps;
1171 }();
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001172
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001173 for (const auto& [id, display] : mDisplays) {
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001174 if (id == *mPacesetterDisplayId) continue;
1175
Ady Abrahamace3d052022-11-17 16:25:05 -08001176 auto rankedFrameRates =
Dominik Laskowski9e88d622024-03-06 17:42:39 -05001177 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements, globalSignals,
1178 pacesetterFps);
1179
1180 modeChoices.try_emplace(id, DisplayModeChoice::from(std::move(rankedFrameRates)));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001181 }
ramindani69b58e82022-09-26 16:48:36 -07001182
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001183 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001184}
1185
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001186GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001187 const bool powerOnImminent = mDisplayPowerTimer &&
1188 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1189 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001190
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001191 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1192 .idle = mPolicy.idleTimer == TimerState::Expired,
1193 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001194}
1195
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001196FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001197 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001198 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001199 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001200 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1201 .ranking.front()
1202 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001203
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001204 // Make sure the stored mode is up to date.
1205 mPolicy.modeOpt = frameRateMode;
1206
1207 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001208}
1209
Peiyong Line9d809e2020-04-14 13:10:48 -07001210void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001211 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1212 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1213
1214 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1215 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1216 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1217 }
1218}
1219
Leon Scroggins III5b581492023-10-31 14:29:41 -04001220bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001221 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1222 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1223 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1224 // We need to composite again as refreshTimeNanos is still in the future.
1225 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001226 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001227
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001228 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001229 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001230 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001231}
1232
Ady Abraham7825c682021-05-17 15:12:14 -07001233void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001234 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001235}
1236
Andy Yu8c2703d2023-11-03 11:22:46 -07001237void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001238 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1239 return;
1240 }
1241
Andy Yu8c2703d2023-11-03 11:22:46 -07001242 if (FlagManager::getInstance().game_default_frame_rate()) {
1243 // update the frame rate override mapping in LayerHistory
1244 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1245 } else {
1246 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1247 }
1248}
1249
1250void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1251 if (!FlagManager::getInstance().game_default_frame_rate() ||
1252 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1253 return;
1254 }
1255
1256 // update the frame rate override mapping in LayerHistory
1257 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001258}
1259
Ady Abraham62a0be22020-12-08 16:54:10 -08001260void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1261 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1262 return;
1263 }
1264
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001265 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001266}
1267
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001268void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001269 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001270 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1271}
1272
Tony Huangf3621102023-09-04 17:14:22 +08001273void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001274 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001275}
1276
Tony Huangf3621102023-09-04 17:14:22 +08001277bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1278 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1279 if (oThreshold) {
1280 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1281 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001282 return false;
1283}
1284
Dominik Laskowski068173d2021-08-11 17:22:59 -07001285} // namespace android::scheduler