blob: 5f10e79ebc9a435a064eb86f2f0a7b05983f0c65 [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 Laskowski98041832019-08-01 18:35:59 -070063#define RETURN_IF_INVALID_HANDLE(handle, ...) \
64 do { \
65 if (mConnections.count(handle) == 0) { \
66 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
67 return __VA_ARGS__; \
68 } \
69 } while (false)
70
Dominik Laskowski068173d2021-08-11 17:22:59 -070071namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070072
Dominik Laskowski1c99a002023-01-20 17:10:36 -050073Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050074 surfaceflinger::Factory& factory, Fps activeRefreshRate, TimeStats& timeStats,
75 IVsyncTrackerCallback& vsyncTrackerCallback)
76 : android::impl::MessageQueue(compositor),
Dominik Laskowski1c99a002023-01-20 17:10:36 -050077 mFeatures(features),
Leon Scroggins III823d4ca2023-12-12 16:57:34 -050078 mVsyncConfiguration(factory.createVsyncConfiguration(activeRefreshRate)),
79 mVsyncModulator(sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs())),
80 mRefreshRateStats(std::make_unique<RefreshRateStats>(timeStats, activeRefreshRate,
81 hal::PowerMode::OFF)),
ramindanid4354a92023-10-02 15:11:09 -070082 mSchedulerCallback(callback),
83 mVsyncTrackerCallback(vsyncTrackerCallback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070084
Dominik Laskowski83bd7712022-01-07 14:30:53 -080085Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080086 // MessageQueue depends on VsyncSchedule, so first destroy it.
87 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
88 // which will cause a use-after-free issue.
89 Impl::destroyVsync();
90
Dominik Laskowski83bd7712022-01-07 14:30:53 -080091 // Stop timers and wait for their threads to exit.
92 mDisplayPowerTimer.reset();
93 mTouchTimer.reset();
94
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040095 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -050096 demotePacesetterDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080097}
98
Dominik Laskowski9c93d602021-10-07 19:38:26 -070099void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -0700100 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700101 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -0700102
Ady Abrahamc496b432023-12-01 21:35:05 +0000103 const int32_t defaultTouchTimerValue =
Ady Abraham3f84c502023-11-30 18:18:06 -0800104 FlagManager::getInstance().enable_fro_dependent_features() &&
105 sysprop::enable_frame_rate_override(true)
106 ? 200
107 : 0;
Ady Abrahamc496b432023-12-01 21:35:05 +0000108 if (const int32_t millis = set_touch_timer_ms(defaultTouchTimerValue); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700109 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700110 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800111 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700112 [this] { touchTimerCallback(TimerState::Reset); },
113 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700114 mTouchTimer->start();
115 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700116
Dominik Laskowski98041832019-08-01 18:35:59 -0700117 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
118 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800119 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700120 [this] { displayPowerTimerCallback(TimerState::Reset); },
121 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700122 mDisplayPowerTimer->start();
123 }
Ana Krulece588e312018-09-18 12:32:24 -0700124}
125
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500126void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
127 demotePacesetterDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400128
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500129 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800130}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700131
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400132void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
ramindanid4354a92023-10-02 15:11:09 -0700133 auto schedulePtr = std::make_shared<VsyncSchedule>(
Ady Abrahamc585dba2023-11-15 18:41:35 -0800134 selectorPtr->getActiveMode().modePtr, mFeatures,
ramindanid4354a92023-10-02 15:11:09 -0700135 [this](PhysicalDisplayId id, bool enable) { onHardwareVsyncRequest(id, enable); },
136 mVsyncTrackerCallback);
Dominik Laskowski66295432023-03-14 12:25:36 -0400137
138 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr));
Leon Scroggins III67388622023-02-06 20:36:20 -0500139}
140
141void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
142 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500143 VsyncSchedulePtr schedulePtr) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500144 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400145
Dominik Laskowski008bec02023-03-14 12:04:58 -0400146 auto [pacesetterVsyncSchedule, isNew] = [&]() FTL_FAKE_GUARD(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400147 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400148 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500149 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
150 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400151 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400152
Dominik Laskowski008bec02023-03-14 12:04:58 -0400153 return std::make_pair(promotePacesetterDisplayLocked(), isNew);
154 }();
155
Leon Scroggins39d25342023-04-19 17:11:01 +0000156 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400157
158 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
159 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400160 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400161 }
Dominik Laskowski01602522022-10-07 19:02:28 -0400162}
163
164void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500165 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400166
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400167 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
168 {
169 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500170 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400171
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400172 // Do not allow removing the final display. Code in the scheduler expects
173 // there to be at least one display. (This may be relaxed in the future with
174 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500175 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500176
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400177 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
178 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000179 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400180}
181
Dominik Laskowski756b7892021-08-04 12:53:59 -0700182void Scheduler::run() {
183 while (true) {
184 waitMessage();
185 }
186}
187
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700188void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
189 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500190 const FrameTargeter::BeginFrameArgs beginFrameArgs =
191 {.frameBeginTime = SchedulerClock::now(),
192 .vsyncId = vsyncId,
193 // TODO(b/255601557): Calculate per display.
194 .expectedVsyncTime = expectedVsyncTime,
Leon Scroggins III0bd0d4c2022-12-08 13:20:45 -0500195 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration,
196 .hwcMinWorkDuration = mVsyncConfiguration->getCurrentConfigs().hwcMinWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700197
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500198 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
199 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500200
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500201 {
202 FrameTargets targets;
203 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500204
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500205 for (const auto& [id, display] : mDisplays) {
206 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400207
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500208 FrameTargeter& targeter = *display.targeterPtr;
209 targeter.beginFrame(beginFrameArgs, *display.schedulePtr);
210 targets.try_emplace(id, &targeter.target());
211 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400212
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500213 if (!compositor.commit(pacesetterPtr->displayId, targets)) return;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400214 }
215
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500216 // The pacesetter may have changed or been registered anew during commit.
217 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500218
219 // TODO(b/256196556): Choose the frontrunner display.
220 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500221 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500222
223 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500224 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500225
226 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500227 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700228 }
229
Ady Abrahamd6d80162023-10-23 12:57:41 -0700230 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000231 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500232 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000233 const auto skipDuration = Duration::fromNs(
234 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
235 ATRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
236 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
237 std::this_thread::sleep_for(skipDuration);
238 mPacesetterFrameDurationFractionToSkip = 0.f;
239 }
240
Ady Abrahame9883032023-11-20 17:54:54 -0800241 if (FlagManager::getInstance().vrr_config()) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500242 const auto minFramePeriod = pacesetterPtr->schedulePtr->minFramePeriod();
Ady Abrahame9883032023-11-20 17:54:54 -0800243 const auto presentFenceForPastVsync =
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500244 pacesetterPtr->targeterPtr->target().presentFenceForPastVsync(minFramePeriod);
Ady Abrahame9883032023-11-20 17:54:54 -0800245 const auto lastConfirmedPresentTime = presentFenceForPastVsync->getSignalTime();
246 if (lastConfirmedPresentTime != Fence::SIGNAL_TIME_PENDING &&
247 lastConfirmedPresentTime != Fence::SIGNAL_TIME_INVALID) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500248 pacesetterPtr->schedulePtr->getTracker()
Ady Abrahame9883032023-11-20 17:54:54 -0800249 .onFrameBegin(expectedVsyncTime, TimePoint::fromNs(lastConfirmedPresentTime));
250 }
251 }
252
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500253 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700254 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400255
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500256 for (const auto& [id, targeter] : targeters) {
257 const auto resultOpt = resultsPerDisplay.get(id);
258 LOG_ALWAYS_FATAL_IF(!resultOpt);
259 targeter->endFrame(*resultOpt);
260 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700261}
262
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500263std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800264 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500265 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800266 return mFrameRateOverrideMappings
267 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800268}
269
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400270bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800271 const auto frameRate = getFrameRateOverride(uid);
272 if (!frameRate.has_value()) {
273 return true;
274 }
275
Ady Abraham9243bba2023-02-10 15:31:14 -0800276 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400277 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700278}
279
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400280bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
281 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700282}
283
Ady Abrahamf2851612023-09-25 17:19:00 -0700284bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
285 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500286}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800287
Ady Abrahamf2851612023-09-25 17:19:00 -0700288Period Scheduler::getVsyncPeriod(uid_t uid) {
289 const auto [refreshRate, period] = [this] {
290 std::scoped_lock lock(mDisplayLock);
291 const auto pacesetterOpt = pacesetterDisplayLocked();
292 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
293 const Display& pacesetter = *pacesetterOpt;
294 return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
295 pacesetter.schedulePtr->period());
296 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500297
Ady Abrahamf2851612023-09-25 17:19:00 -0700298 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800299
Ady Abrahamf2851612023-09-25 17:19:00 -0700300 const auto frameRate = getFrameRateOverride(uid);
301 if (!frameRate.has_value()) {
302 return currentPeriod;
303 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100304
Ady Abrahamf2851612023-09-25 17:19:00 -0700305 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
306 if (divisor <= 1) {
307 return currentPeriod;
308 }
309
310 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
311 // behaviour.
312 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100313}
314
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500315ConnectionHandle Scheduler::createEventThread(Cycle cycle,
316 frametimeline::TokenManager* tokenManager,
317 std::chrono::nanoseconds workDuration,
318 std::chrono::nanoseconds readyDuration) {
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500319 auto eventThread =
320 std::make_unique<android::impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
321 getVsyncSchedule(), tokenManager, *this,
322 workDuration, readyDuration);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500323
324 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
325 handle = createConnection(std::move(eventThread));
326 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700327}
Ana Krulec98b5b242018-08-10 15:03:23 -0700328
Dominik Laskowski068173d2021-08-11 17:22:59 -0700329ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700330 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
331 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800332
Ady Abrahamf2851612023-09-25 17:19:00 -0700333 auto connection = eventThread->createEventConnection();
Dominik Laskowski98041832019-08-01 18:35:59 -0700334
Ana Krulec6ddd2612020-09-24 13:06:33 -0700335 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700336 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
337 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700338}
339
340sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800341 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
342 const sp<IBinder>& layerHandle) {
Ady Abraham822ecbd2023-07-07 16:16:09 -0700343 const auto connection = [&]() -> sp<EventThreadConnection> {
344 std::scoped_lock lock(mConnectionsLock);
345 RETURN_IF_INVALID_HANDLE(handle, nullptr);
346
Ady Abrahamf2851612023-09-25 17:19:00 -0700347 return mConnections[handle].thread->createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700348 }();
349 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
350
351 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
352 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
353 // processed on the main thread.
354 mSchedulerCallback.onChoreographerAttached();
355
356 std::scoped_lock lock(mChoreographerLock);
357 const auto [iter, emplaced] =
358 mAttachedChoreographers.emplace(layerId,
359 AttachedChoreographers{Fps(), {connection}});
360 if (!emplaced) {
361 iter->second.connections.emplace(connection);
362 connection->frameRate = iter->second.frameRate;
363 }
364 }
365 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700366}
367
Dominik Laskowski98041832019-08-01 18:35:59 -0700368sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700369 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700370 RETURN_IF_INVALID_HANDLE(handle, nullptr);
371 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700372}
373
Dominik Laskowski98041832019-08-01 18:35:59 -0700374void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
375 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700376 android::EventThread* thread;
377 {
378 std::lock_guard<std::mutex> lock(mConnectionsLock);
379 RETURN_IF_INVALID_HANDLE(handle);
380 thread = mConnections[handle].thread.get();
381 }
382
383 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700384}
385
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700386void Scheduler::onHotplugConnectionError(ConnectionHandle handle, int32_t errorCode) {
387 android::EventThread* thread;
388 {
389 std::lock_guard<std::mutex> lock(mConnectionsLock);
390 RETURN_IF_INVALID_HANDLE(handle);
391 thread = mConnections[handle].thread.get();
392 }
393
394 thread->onHotplugConnectionError(errorCode);
395}
396
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500397void Scheduler::enableSyntheticVsync(bool enable) {
398 // TODO(b/241285945): Remove connection handles.
399 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700400 android::EventThread* thread;
401 {
402 std::lock_guard<std::mutex> lock(mConnectionsLock);
403 RETURN_IF_INVALID_HANDLE(handle);
404 thread = mConnections[handle].thread.get();
405 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500406 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700407}
408
Ady Abraham62a0be22020-12-08 16:54:10 -0800409void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800410 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500411 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800412
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800413 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800414 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800415
Ady Abraham62f216c2020-10-13 19:07:23 -0700416 android::EventThread* thread;
417 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800418 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700419 RETURN_IF_INVALID_HANDLE(handle);
420 thread = mConnections[handle].thread.get();
421 }
422 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
423}
424
Huihong Luo9ebb7a72023-06-27 17:01:50 -0700425void Scheduler::onHdcpLevelsChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
426 int32_t connectedLevel, int32_t maxLevel) {
427 android::EventThread* thread;
428 {
429 std::lock_guard<std::mutex> lock(mConnectionsLock);
430 RETURN_IF_INVALID_HANDLE(handle);
431 thread = mConnections[handle].thread.get();
432 }
433 thread->onHdcpLevelsChanged(displayId, connectedLevel, maxLevel);
434}
435
Ady Abrahamace3d052022-11-17 16:25:05 -0800436void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800437 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700438 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100439 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700440 mPolicy.cachedModeChangedParams = {handle, 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 }
Ady Abraham690f4612021-07-01 23:24:03 -0700446 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700447}
448
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100449void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700450 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800451 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100452 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700453 return;
454 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700455 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100456 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700457 return;
458 }
459
Ady Abrahamd1591702021-07-27 16:27:56 -0700460 // If the mode is not the current mode, this means that a
461 // mode change is in progress. In that case we shouldn't dispatch an event
462 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500463 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700464 return;
465 }
466
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100467 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800468 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700469 return;
470 }
471
Ady Abrahamace3d052022-11-17 16:25:05 -0800472 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700473 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
474 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700475}
476
Ady Abrahamace3d052022-11-17 16:25:05 -0800477void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700478 android::EventThread* thread;
479 {
480 std::lock_guard<std::mutex> lock(mConnectionsLock);
481 RETURN_IF_INVALID_HANDLE(handle);
482 thread = mConnections[handle].thread.get();
483 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800484 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800485}
486
Dominik Laskowski98041832019-08-01 18:35:59 -0700487void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700488 android::EventThread* thread;
489 {
490 std::lock_guard<std::mutex> lock(mConnectionsLock);
491 RETURN_IF_INVALID_HANDLE(handle);
492 thread = mConnections.at(handle).thread.get();
493 }
494 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700495}
496
Ady Abraham9c53ee72020-07-22 21:16:18 -0700497void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
498 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700499 android::EventThread* thread;
500 {
501 std::lock_guard<std::mutex> lock(mConnectionsLock);
502 RETURN_IF_INVALID_HANDLE(handle);
503 thread = mConnections[handle].thread.get();
504 }
505 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700506}
Ana Krulece588e312018-09-18 12:32:24 -0700507
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500508void Scheduler::updatePhaseConfiguration(Fps refreshRate) {
509 mRefreshRateStats->setRefreshRate(refreshRate);
510 mVsyncConfiguration->setRefreshRateFps(refreshRate);
511 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(mVsyncConfiguration->getCurrentConfigs()),
512 refreshRate.getPeriod());
513}
514
515void Scheduler::resetPhaseConfiguration(Fps refreshRate) {
516 // Cancel the pending refresh rate change, if any, before updating the phase configuration.
517 mVsyncModulator->cancelRefreshRateChange();
518
519 mVsyncConfiguration->reset();
520 updatePhaseConfiguration(refreshRate);
521}
522
523void Scheduler::setActiveDisplayPowerModeForRefreshRateStats(hal::PowerMode powerMode) {
524 mRefreshRateStats->setPowerMode(powerMode);
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500525}
526
527void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
528 setDuration(mAppConnectionHandle,
529 /* workDuration */ config.appWorkDuration,
530 /* readyDuration */ config.sfWorkDuration);
531 setDuration(mSfConnectionHandle,
532 /* workDuration */ vsyncPeriod,
533 /* readyDuration */ config.sfWorkDuration);
534 setDuration(config.sfWorkDuration);
535}
536
Leon Scroggins III67388622023-02-06 20:36:20 -0500537void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
538 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400539 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400540 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700541}
542
Leon Scroggins III67388622023-02-06 20:36:20 -0500543void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
544 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400545 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400546 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700547}
548
Leon Scroggins III67388622023-02-06 20:36:20 -0500549void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800550 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500551 std::scoped_lock lock(mDisplayLock);
552 ftl::FakeGuard guard(kMainThreadContext);
553
Leon Scroggins III792ea802023-11-27 17:32:51 -0500554 for (const auto& [id, display] : mDisplays) {
555 if (display.powerMode != hal::PowerMode::OFF ||
556 !FlagManager::getInstance().multithreaded_present()) {
557 resyncToHardwareVsyncLocked(id, allowToEnable);
558 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500559 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500560}
561
Leon Scroggins III67388622023-02-06 20:36:20 -0500562void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800563 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500564 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400565 if (!displayOpt) {
566 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
567 return;
568 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500569 const Display& display = *displayOpt;
570
571 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800572 if (!modePtr) {
573 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500574 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800575 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400576 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800577 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500578 }
579 }
580}
581
Dominik Laskowski66295432023-03-14 12:25:36 -0400582void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
583 static const auto& whence = __func__;
584 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
585
586 // On main thread to serialize reads/writes of pending hardware VSYNC state.
587 static_cast<void>(
588 schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
589 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
590
591 if (const auto displayOpt = mDisplays.get(id)) {
592 auto& display = displayOpt->get();
593 display.schedulePtr->setPendingHardwareVsyncState(enabled);
594
595 if (display.powerMode != hal::PowerMode::OFF) {
596 mSchedulerCallback.requestHardwareVsync(id, enabled);
597 }
598 }
599 }));
600}
601
Leon Scroggins III67388622023-02-06 20:36:20 -0500602void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
603 std::scoped_lock lock(mDisplayLock);
604 ftl::FakeGuard guard(kMainThreadContext);
605
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500606 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400607 if (!displayOpt) {
608 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
609 return;
610 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500611 const Display& display = *displayOpt;
612 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800613
614 using fps_approx_ops::operator!=;
615 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500616 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
617 "%" PRIu64,
618 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800619
620 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700621 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800622
Ady Abrahamc585dba2023-11-15 18:41:35 -0800623 display.schedulePtr->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800624}
625
ramindani0491e642023-11-16 17:42:14 -0800626Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
627 TimePoint currentExpectedPresentTime) const {
628 std::scoped_lock lock(mDisplayLock);
629 ftl::FakeGuard guard(kMainThreadContext);
630
631 const auto displayOpt = mDisplays.get(id);
632 if (!displayOpt) {
633 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
634 return Fps{};
635 }
636 const Display& display = *displayOpt;
637 const nsecs_t threshold =
638 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriodNsecs() / 2;
Ady Abraham4335afd2023-12-18 19:10:47 -0800639 const nsecs_t nextVsyncTime =
640 display.schedulePtr->getTracker()
641 .nextAnticipatedVSyncTimeFrom(currentExpectedPresentTime.ns() + threshold,
642 currentExpectedPresentTime.ns());
ramindani0491e642023-11-16 17:42:14 -0800643 return Fps::fromPeriodNsecs(nextVsyncTime - currentExpectedPresentTime.ns());
644}
645
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700646void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700647 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800648
649 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700650 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800651
652 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500653 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800654 }
655}
656
Leon Scroggins III67388622023-02-06 20:36:20 -0500657bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
658 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500659 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
660 return Period::fromNs(nanos);
661 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400662 auto schedule = getVsyncSchedule(id);
663 if (!schedule) {
664 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
665 return false;
666 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400667 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700668}
669
Leon Scroggins III67388622023-02-06 20:36:20 -0500670void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Ady Abrahamf0b2bf92023-12-13 23:36:35 +0000671 ATRACE_NAME(ftl::Concat(__func__, ' ', id.value).c_str());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500672 const auto scheduleOpt =
673 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
674 return display.powerMode == hal::PowerMode::OFF
675 ? std::nullopt
676 : std::make_optional(display.schedulePtr);
677 });
678
679 if (!scheduleOpt) return;
680 const auto& schedule = scheduleOpt->get();
681
Yi Kong08d7c812023-12-12 16:40:22 +0900682 const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence));
683 if (needMoreSignals) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400684 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700685 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400686 constexpr bool kDisallow = false;
687 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700688 }
689}
690
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700691void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200692 // If the content detection feature is off, we still keep the layer history,
693 // since we use it for other features (like Frame Rate API), so layers
694 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000695 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700696}
697
Ady Abrahambdda8f02021-04-01 16:06:11 -0700698void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700699 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700700}
701
Ady Abraham822ecbd2023-07-07 16:16:09 -0700702void Scheduler::onLayerDestroyed(Layer* layer) {
703 std::scoped_lock lock(mChoreographerLock);
704 mAttachedChoreographers.erase(layer->getSequence());
705}
706
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000707void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700708 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500709 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700710 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800711 }
Ana Krulec3084c052018-11-21 20:27:17 +0100712}
713
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100714void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700715 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700716}
717
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700718void Scheduler::setDefaultFrameRateCompatibility(
719 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
720 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000721 mFeatures.test(Feature::kContentDetection));
722}
723
Vishnu Nair41376b62023-11-08 05:08:58 -0800724void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
725 mLayerHistory.setLayerProperties(id, properties);
726}
727
Ady Abraham822ecbd2023-07-07 16:16:09 -0700728void Scheduler::chooseRefreshRateForContent(
729 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
730 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500731 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400732 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800733
Ady Abraham8a82ba62020-01-17 12:43:17 -0800734 ATRACE_CALL();
735
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400736 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800737 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700738
739 if (updateAttachedChoreographer) {
740 LOG_ALWAYS_FATAL_IF(!hierarchy);
741
742 // update the attached choreographers after we selected the render rate.
743 const ftl::Optional<FrameRateMode> modeOpt = [&] {
744 std::scoped_lock lock(mPolicyLock);
745 return mPolicy.modeOpt;
746 }();
747
748 if (modeOpt) {
749 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
750 }
751 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800752}
753
Ana Krulecfb772822018-11-30 10:44:07 +0100754void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500755 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800756}
757
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700758void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700759 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800760 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500761 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800762 }
Ady Abraham8532d012019-05-08 14:50:56 -0700763}
764
Leon Scroggins III67388622023-02-06 20:36:20 -0500765void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500766 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500767 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500768 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500769 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500770 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500771 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700772 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700773 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700774 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500775 {
776 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400777
778 const auto displayOpt = mDisplays.get(id);
779 LOG_ALWAYS_FATAL_IF(!displayOpt);
780 auto& display = displayOpt->get();
781
782 display.powerMode = powerMode;
783 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500784 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500785 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700786
787 if (mDisplayPowerTimer) {
788 mDisplayPowerTimer->reset();
789 }
790
791 // Display Power event will boost the refresh rate to performance.
792 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700793 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700794}
795
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500796auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
797 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500798 std::scoped_lock lock(mDisplayLock);
799 return getVsyncScheduleLocked(idOpt);
800}
801
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500802auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
803 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500804 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500805
Leon Scroggins III67388622023-02-06 20:36:20 -0500806 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500807 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
808 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500809 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500810
811 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400812 if (!displayOpt) {
813 return nullptr;
814 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500815 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500816}
817
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700818void Scheduler::kernelIdleTimerCallback(TimerState state) {
819 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100820
Ady Abraham2139f732019-11-13 18:56:40 -0800821 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
822 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700823 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700824
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700825 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
826 using namespace fps_approx_ops;
827
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800828 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700829 // If we're not in performance mode then the kernel timer shouldn't do
830 // anything, as the refresh rate during DPU power collapse will be the
831 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500832 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800833 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700834 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
835 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700836 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500837 std::scoped_lock lock(mDisplayLock);
838 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500839 for (const auto& [_, display] : mDisplays) {
840 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400841 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500842 }
Alec Mouridc28b372019-04-18 21:17:13 -0700843 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800844
845 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700846}
847
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700848void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800849 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700850 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100851}
852
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700853void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700854 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700855 // Touch event will boost the refresh rate to performance.
856 // Clear layer history to get fresh FPS detection.
857 // NOTE: Instead of checking all the layers, we should be checking the layer
858 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800859 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700860 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700861 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700862 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700863}
864
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700865void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800866 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700867 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700868}
869
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400870void Scheduler::dump(utils::Dumper& dumper) const {
871 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700872
873 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400874 utils::Dumper::Section section(dumper, "Features"sv);
875
876 for (Feature feature : ftl::enum_range<Feature>()) {
877 if (const auto flagOpt = ftl::flag_name(feature)) {
878 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
879 }
880 }
881 }
882 {
883 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400884 {
885 std::scoped_lock lock(mDisplayLock);
886 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500887 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400888 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400889 dumper.dump("layerHistory"sv, mLayerHistory.dump());
890 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
891 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
892 }
893
894 mFrameRateOverrideMappings.dump(dumper);
895 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400896
Leon Scroggins III823d4ca2023-12-12 16:57:34 -0500897 mVsyncConfiguration->dump(dumper.out());
898 dumper.eol();
899
900 mRefreshRateStats->dump(dumper.out());
901 dumper.eol();
902
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500903 {
904 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
905
906 std::scoped_lock lock(mDisplayLock);
907 ftl::FakeGuard guard(kMainThreadContext);
908
909 for (const auto& [id, display] : mDisplays) {
910 utils::Dumper::Section
911 section(dumper,
912 id == mPacesetterDisplayId
913 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
914 : ftl::Concat("Follower Display ", id.value).c_str());
915
916 display.targeterPtr->dump(dumper);
917 dumper.eol();
918 }
919 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800920}
921
Dominik Laskowski068173d2021-08-11 17:22:59 -0700922void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500923 std::scoped_lock lock(mDisplayLock);
924 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500925 if (mPacesetterDisplayId) {
926 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
927 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500928 getVsyncScheduleLocked()->dump(out);
929 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500930 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500931 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500932 continue;
933 }
934 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500935 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500936 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700937}
938
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800939bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700940 std::scoped_lock lock(mPolicyLock);
941 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
942}
943
944bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
945 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400946 if (consideredSignals.idle) return false;
947
948 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500949 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
950 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400951
952 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
953 // the FrameRateOverrideMappings rather than here.
954 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
955}
956
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500957void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400958 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
959
960 {
961 std::scoped_lock lock(mDisplayLock);
962 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
963 }
964
Leon Scroggins39d25342023-04-19 17:11:01 +0000965 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400966}
967
968std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
969 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500970 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500971 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500972 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400973
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500974 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
975 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
976 const Display& pacesetter = *pacesetterOpt;
977
978 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400979 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
980 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
981 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
982 .onExpired =
983 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
984
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500985 pacesetter.selectorPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500986
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500987 newVsyncSchedulePtr = pacesetter.schedulePtr;
988
Dominik Laskowski66295432023-03-14 12:25:36 -0400989 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800990 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
991 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500992 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500993 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400994}
Leon Scroggins III67388622023-02-06 20:36:20 -0500995
Leon Scroggins39d25342023-04-19 17:11:01 +0000996void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
997 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400998 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500999 {
1000 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001001 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -05001002 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001003 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -05001004 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001005 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001006 for (auto* thread : threads) {
Leon Scroggins39d25342023-04-19 17:11:01 +00001007 thread->onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -04001008 }
Dominik Laskowski596a2562022-10-28 11:26:12 -04001009}
1010
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001011void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001012 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001013 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
1014 pacesetterPtr->stopIdleTimer();
1015 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -04001016 }
1017
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001018 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -04001019 std::scoped_lock lock(mPolicyLock);
1020 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -08001021}
1022
Ady Abraham822ecbd2023-07-07 16:16:09 -07001023void Scheduler::updateAttachedChoreographersFrameRate(
1024 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
1025 std::scoped_lock lock(mChoreographerLock);
1026
1027 const auto layerId = static_cast<int32_t>(layer.id);
1028 const auto choreographers = mAttachedChoreographers.find(layerId);
1029 if (choreographers == mAttachedChoreographers.end()) {
1030 return;
1031 }
1032
1033 auto& layerChoreographers = choreographers->second;
1034
1035 layerChoreographers.frameRate = fps;
1036 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1037 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
1038
1039 auto it = layerChoreographers.connections.begin();
1040 while (it != layerChoreographers.connections.end()) {
1041 sp<EventThreadConnection> choreographerConnection = it->promote();
1042 if (choreographerConnection) {
1043 choreographerConnection->frameRate = fps;
1044 it++;
1045 } else {
1046 it = choreographers->second.connections.erase(it);
1047 }
1048 }
1049
1050 if (layerChoreographers.connections.empty()) {
1051 mAttachedChoreographers.erase(choreographers);
1052 }
1053}
1054
1055int Scheduler::updateAttachedChoreographersInternal(
1056 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1057 int parentDivisor) {
1058 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1059
1060 int divisor = 0;
1061 if (layerHierarchy.getLayer()) {
1062 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1063 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1064 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1065 parentDivisor);
1066
1067 if (frameRate.isValid()) {
1068 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1069 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1070 // Since this layer wants an exact match, we would only set a frame rate if the
1071 // desired rate is a divisor of the display refresh rate.
1072 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1073 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1074 // find the closest frame rate divisor for the desired frame rate.
1075 divisor = static_cast<int>(
1076 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1077 }
1078 }
1079 }
1080
1081 // We start by traversing the children, updating their choreographers, and getting back the
1082 // aggregated frame rate.
1083 int childrenDivisor = 0;
1084 for (const auto& [child, _] : layerHierarchy.mChildren) {
1085 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1086
1087 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1088
1089 const int childDivisor =
1090 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1091 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1092 if (childDivisor > 0) {
1093 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1094 }
1095 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1096 }
1097
1098 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1099
1100 // If there is no explicit vote for this layer. Use the children's vote if exists
1101 divisor = (divisor == 0) ? childrenDivisor : divisor;
1102 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1103
1104 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1105 divisor = (divisor == 0) ? parentDivisor : divisor;
1106 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1107
1108 if (layerHierarchy.getLayer()) {
1109 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1110 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1111 }
1112
1113 return divisor;
1114}
1115
1116void Scheduler::updateAttachedChoreographers(
1117 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1118 ATRACE_CALL();
1119 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1120}
1121
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001122template <typename S, typename T>
1123auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001124 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001125 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001126 GlobalSignals consideredSignals;
1127
Ady Abraham62a0be22020-12-08 16:54:10 -08001128 bool refreshRateChanged = false;
1129 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001130
Ady Abraham8532d012019-05-08 14:50:56 -07001131 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001132 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001133
1134 auto& currentState = mPolicy.*statePtr;
1135 if (currentState == newState) return {};
1136 currentState = std::forward<T>(newState);
1137
Dominik Laskowski596a2562022-10-28 11:26:12 -04001138 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001139 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001140 {
1141 std::scoped_lock lock(mDisplayLock);
1142 ftl::FakeGuard guard(kMainThreadContext);
1143
1144 modeChoices = chooseDisplayModes();
1145
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001146 // TODO(b/240743786): The pacesetter display's mode must change for any
1147 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1148 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001149 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001150 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001151 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001152 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001153 })
1154 .value();
1155 }
ramindani69b58e82022-09-26 16:48:36 -07001156
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001157 modeRequests.reserve(modeChoices.size());
1158 for (auto& [id, choice] : modeChoices) {
1159 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001160 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001161 .emitEvent = !choice.consideredSignals.idle});
1162 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001163
Ady Abraham33a386b2023-07-18 15:37:11 -07001164 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001165
Ady Abrahamace3d052022-11-17 16:25:05 -08001166 if (mPolicy.modeOpt != modeOpt) {
1167 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001168 refreshRateChanged = true;
1169 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001170 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001171 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001172 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001173 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001174 }
Ady Abraham8532d012019-05-08 14:50:56 -07001175 }
Ady Abraham8532d012019-05-08 14:50:56 -07001176 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001177 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001178 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001179 }
1180 if (frameRateOverridesChanged) {
1181 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1182 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001183 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001184}
1185
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001186auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001187 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001188
Ady Abraham68636062022-11-16 17:07:25 -08001189 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski6b049ff2023-01-29 15:46:45 -05001190 ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -04001191 const auto globalSignals = makeGlobalSignals();
ramindani22f2ead2023-04-21 10:27:11 -07001192 Fps pacesetterFps;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001193
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001194 for (const auto& [id, display] : mDisplays) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001195 auto rankedFrameRates =
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001196 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
1197 globalSignals);
ramindani22f2ead2023-04-21 10:27:11 -07001198 if (id == *mPacesetterDisplayId) {
1199 pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
Dominik Laskowski01602522022-10-07 19:02:28 -04001200 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001201 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001202 }
ramindani69b58e82022-09-26 16:48:36 -07001203
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001204 DisplayModeChoiceMap modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001205 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -04001206
ramindani22f2ead2023-04-21 10:27:11 -07001207 for (auto& [rankings, signals] : perDisplayRanking) {
1208 const auto chosenFrameRateMode =
1209 ftl::find_if(rankings,
1210 [&](const auto& ranking) {
1211 return ranking.frameRateMode.fps == pacesetterFps;
1212 })
1213 .transform([](const auto& scoredFrameRate) {
1214 return scoredFrameRate.get().frameRateMode;
1215 })
1216 .value_or(rankings.front().frameRateMode);
Dominik Laskowski01602522022-10-07 19:02:28 -04001217
ramindani22f2ead2023-04-21 10:27:11 -07001218 modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
1219 DisplayModeChoice{chosenFrameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -04001220 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001221 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001222}
1223
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001224GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001225 const bool powerOnImminent = mDisplayPowerTimer &&
1226 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1227 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001228
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001229 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1230 .idle = mPolicy.idleTimer == TimerState::Expired,
1231 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001232}
1233
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001234FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001235 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001236 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001237 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001238 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1239 .ranking.front()
1240 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001241
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001242 // Make sure the stored mode is up to date.
1243 mPolicy.modeOpt = frameRateMode;
1244
1245 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001246}
1247
Peiyong Line9d809e2020-04-14 13:10:48 -07001248void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001249 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1250 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1251
1252 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1253 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1254 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1255 }
1256}
1257
Leon Scroggins III5b581492023-10-31 14:29:41 -04001258bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001259 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1260 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1261 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1262 // We need to composite again as refreshTimeNanos is still in the future.
1263 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001264 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001265
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001266 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001267 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001268 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001269}
1270
Ady Abraham7825c682021-05-17 15:12:14 -07001271void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001272 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001273}
1274
Andy Yu8c2703d2023-11-03 11:22:46 -07001275void Scheduler::setGameModeFrameRateForUid(FrameRateOverride frameRateOverride) {
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001276 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1277 return;
1278 }
1279
Andy Yu8c2703d2023-11-03 11:22:46 -07001280 if (FlagManager::getInstance().game_default_frame_rate()) {
1281 // update the frame rate override mapping in LayerHistory
1282 mLayerHistory.updateGameModeFrameRateOverride(frameRateOverride);
1283 } else {
1284 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1285 }
1286}
1287
1288void Scheduler::setGameDefaultFrameRateForUid(FrameRateOverride frameRateOverride) {
1289 if (!FlagManager::getInstance().game_default_frame_rate() ||
1290 (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f)) {
1291 return;
1292 }
1293
1294 // update the frame rate override mapping in LayerHistory
1295 mLayerHistory.updateGameDefaultFrameRateOverride(frameRateOverride);
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001296}
1297
Ady Abraham62a0be22020-12-08 16:54:10 -08001298void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1299 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1300 return;
1301 }
1302
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001303 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001304}
1305
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001306void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001307 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001308 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1309}
1310
Tony Huangf3621102023-09-04 17:14:22 +08001311void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
Jerry Chang36678002023-11-29 16:56:17 +00001312 mSmallAreaDetectionAllowMappings.setThresholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001313}
1314
Tony Huangf3621102023-09-04 17:14:22 +08001315bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1316 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1317 if (oThreshold) {
1318 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1319 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001320 return false;
1321}
1322
Dominik Laskowski068173d2021-08-11 17:22:59 -07001323} // namespace android::scheduler