blob: 6eea7f1aa166ab8aa12f0b29916025f7b4d5cdec [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"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090054#include "SurfaceFlingerProperties.h"
Dominik Laskowskic404cb42023-03-03 19:57:53 -050055#include "VSyncTracker.h"
56#include "VsyncController.h"
57#include "VsyncSchedule.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070058
Dominik Laskowski98041832019-08-01 18:35:59 -070059#define RETURN_IF_INVALID_HANDLE(handle, ...) \
60 do { \
61 if (mConnections.count(handle) == 0) { \
62 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
63 return __VA_ARGS__; \
64 } \
65 } while (false)
66
Dominik Laskowski068173d2021-08-11 17:22:59 -070067namespace android::scheduler {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070068
Dominik Laskowski1c99a002023-01-20 17:10:36 -050069Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
ramindanid4354a92023-10-02 15:11:09 -070070 sp<VsyncModulator> modulatorPtr, IVsyncTrackerCallback& vsyncTrackerCallback)
Dominik Laskowski1c99a002023-01-20 17:10:36 -050071 : impl::MessageQueue(compositor),
72 mFeatures(features),
73 mVsyncModulator(std::move(modulatorPtr)),
ramindanid4354a92023-10-02 15:11:09 -070074 mSchedulerCallback(callback),
75 mVsyncTrackerCallback(vsyncTrackerCallback) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070076
Dominik Laskowski83bd7712022-01-07 14:30:53 -080077Scheduler::~Scheduler() {
Ady Abraham011f8ba2022-11-22 15:09:07 -080078 // MessageQueue depends on VsyncSchedule, so first destroy it.
79 // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
80 // which will cause a use-after-free issue.
81 Impl::destroyVsync();
82
Dominik Laskowski83bd7712022-01-07 14:30:53 -080083 // Stop timers and wait for their threads to exit.
84 mDisplayPowerTimer.reset();
85 mTouchTimer.reset();
86
Dominik Laskowskid82e0f02022-10-26 15:23:04 -040087 // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -050088 demotePacesetterDisplay();
Dominik Laskowski83bd7712022-01-07 14:30:53 -080089}
90
Dominik Laskowski9c93d602021-10-07 19:38:26 -070091void Scheduler::startTimers() {
Dominik Laskowski98041832019-08-01 18:35:59 -070092 using namespace sysprop;
Dominik Laskowski068173d2021-08-11 17:22:59 -070093 using namespace std::string_literals;
Ady Abraham8532d012019-05-08 14:50:56 -070094
Dominik Laskowski98041832019-08-01 18:35:59 -070095 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070096 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070097 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -080098 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070099 [this] { touchTimerCallback(TimerState::Reset); },
100 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700101 mTouchTimer->start();
102 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700103
Dominik Laskowski98041832019-08-01 18:35:59 -0700104 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
105 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800106 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700107 [this] { displayPowerTimerCallback(TimerState::Reset); },
108 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700109 mDisplayPowerTimer->start();
110 }
Ana Krulece588e312018-09-18 12:32:24 -0700111}
112
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500113void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
114 demotePacesetterDisplay();
Dominik Laskowski59db9562022-10-27 16:18:53 -0400115
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500116 promotePacesetterDisplay(pacesetterIdOpt);
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800117}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700118
Dominik Laskowskib5a094b2022-10-27 12:00:12 -0400119void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
ramindanid4354a92023-10-02 15:11:09 -0700120 auto schedulePtr = std::make_shared<VsyncSchedule>(
Ady Abrahamc585dba2023-11-15 18:41:35 -0800121 selectorPtr->getActiveMode().modePtr, mFeatures,
ramindanid4354a92023-10-02 15:11:09 -0700122 [this](PhysicalDisplayId id, bool enable) { onHardwareVsyncRequest(id, enable); },
123 mVsyncTrackerCallback);
Dominik Laskowski66295432023-03-14 12:25:36 -0400124
125 registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr));
Leon Scroggins III67388622023-02-06 20:36:20 -0500126}
127
128void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
129 RefreshRateSelectorPtr selectorPtr,
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500130 VsyncSchedulePtr schedulePtr) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500131 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400132
Dominik Laskowski008bec02023-03-14 12:04:58 -0400133 auto [pacesetterVsyncSchedule, isNew] = [&]() FTL_FAKE_GUARD(kMainThreadContext) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400134 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400135 const bool isNew = mDisplays
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500136 .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
137 std::move(schedulePtr), mFeatures)
Dominik Laskowski008bec02023-03-14 12:04:58 -0400138 .second;
Dominik Laskowski596a2562022-10-28 11:26:12 -0400139
Dominik Laskowski008bec02023-03-14 12:04:58 -0400140 return std::make_pair(promotePacesetterDisplayLocked(), isNew);
141 }();
142
Leon Scroggins39d25342023-04-19 17:11:01 +0000143 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski008bec02023-03-14 12:04:58 -0400144
145 // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
146 if (isNew) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400147 onHardwareVsyncRequest(displayId, false);
Dominik Laskowski008bec02023-03-14 12:04:58 -0400148 }
Dominik Laskowski01602522022-10-07 19:02:28 -0400149}
150
151void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500152 demotePacesetterDisplay();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -0400153
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400154 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
155 {
156 std::scoped_lock lock(mDisplayLock);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500157 mDisplays.erase(displayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400158
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400159 // Do not allow removing the final display. Code in the scheduler expects
160 // there to be at least one display. (This may be relaxed in the future with
161 // headless virtual display.)
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500162 LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
Leon Scroggins IIIda21f422023-01-30 20:17:56 -0500163
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400164 pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
165 }
Leon Scroggins39d25342023-04-19 17:11:01 +0000166 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Dominik Laskowski01602522022-10-07 19:02:28 -0400167}
168
Dominik Laskowski756b7892021-08-04 12:53:59 -0700169void Scheduler::run() {
170 while (true) {
171 waitMessage();
172 }
173}
174
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700175void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
176 TimePoint expectedVsyncTime) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500177 const FrameTargeter::BeginFrameArgs beginFrameArgs =
178 {.frameBeginTime = SchedulerClock::now(),
179 .vsyncId = vsyncId,
180 // TODO(b/255601557): Calculate per display.
181 .expectedVsyncTime = expectedVsyncTime,
182 .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration};
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700183
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500184 ftl::NonNull<const Display*> pacesetterPtr = pacesetterPtrLocked();
185 pacesetterPtr->targeterPtr->beginFrame(beginFrameArgs, *pacesetterPtr->schedulePtr);
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500186
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500187 {
188 FrameTargets targets;
189 targets.try_emplace(pacesetterPtr->displayId, &pacesetterPtr->targeterPtr->target());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500190
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500191 for (const auto& [id, display] : mDisplays) {
192 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400193
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500194 FrameTargeter& targeter = *display.targeterPtr;
195 targeter.beginFrame(beginFrameArgs, *display.schedulePtr);
196 targets.try_emplace(id, &targeter.target());
197 }
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400198
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500199 if (!compositor.commit(pacesetterPtr->displayId, targets)) return;
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400200 }
201
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500202 // The pacesetter may have changed or been registered anew during commit.
203 pacesetterPtr = pacesetterPtrLocked();
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500204
205 // TODO(b/256196556): Choose the frontrunner display.
206 FrameTargeters targeters;
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500207 targeters.try_emplace(pacesetterPtr->displayId, pacesetterPtr->targeterPtr.get());
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500208
209 for (auto& [id, display] : mDisplays) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500210 if (id == pacesetterPtr->displayId) continue;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500211
212 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500213 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700214 }
215
Ady Abrahamd6d80162023-10-23 12:57:41 -0700216 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000217 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500218 const auto period = pacesetterPtr->targeterPtr->target().expectedFrameDuration();
Alec Mouri1c7938e2023-09-22 04:17:23 +0000219 const auto skipDuration = Duration::fromNs(
220 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
221 ATRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
222 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
223 std::this_thread::sleep_for(skipDuration);
224 mPacesetterFrameDurationFractionToSkip = 0.f;
225 }
226
Ady Abrahame9883032023-11-20 17:54:54 -0800227 if (FlagManager::getInstance().vrr_config()) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500228 const auto minFramePeriod = pacesetterPtr->schedulePtr->minFramePeriod();
Ady Abrahame9883032023-11-20 17:54:54 -0800229 const auto presentFenceForPastVsync =
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500230 pacesetterPtr->targeterPtr->target().presentFenceForPastVsync(minFramePeriod);
Ady Abrahame9883032023-11-20 17:54:54 -0800231 const auto lastConfirmedPresentTime = presentFenceForPastVsync->getSignalTime();
232 if (lastConfirmedPresentTime != Fence::SIGNAL_TIME_PENDING &&
233 lastConfirmedPresentTime != Fence::SIGNAL_TIME_INVALID) {
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500234 pacesetterPtr->schedulePtr->getTracker()
Ady Abrahame9883032023-11-20 17:54:54 -0800235 .onFrameBegin(expectedVsyncTime, TimePoint::fromNs(lastConfirmedPresentTime));
236 }
237 }
238
Dominik Laskowskifb4b7372023-11-22 09:56:54 -0500239 const auto resultsPerDisplay = compositor.composite(pacesetterPtr->displayId, targeters);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700240 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400241
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500242 for (const auto& [id, targeter] : targeters) {
243 const auto resultOpt = resultsPerDisplay.get(id);
244 LOG_ALWAYS_FATAL_IF(!resultOpt);
245 targeter->endFrame(*resultOpt);
246 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700247}
248
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500249std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800250 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500251 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800252 return mFrameRateOverrideMappings
253 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800254}
255
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400256bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800257 const auto frameRate = getFrameRateOverride(uid);
258 if (!frameRate.has_value()) {
259 return true;
260 }
261
Ady Abraham9243bba2023-02-10 15:31:14 -0800262 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400263 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700264}
265
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400266bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
267 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700268}
269
Ady Abrahamf2851612023-09-25 17:19:00 -0700270bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
271 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500272}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800273
Ady Abrahamf2851612023-09-25 17:19:00 -0700274Period Scheduler::getVsyncPeriod(uid_t uid) {
275 const auto [refreshRate, period] = [this] {
276 std::scoped_lock lock(mDisplayLock);
277 const auto pacesetterOpt = pacesetterDisplayLocked();
278 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
279 const Display& pacesetter = *pacesetterOpt;
280 return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
281 pacesetter.schedulePtr->period());
282 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500283
Ady Abrahamf2851612023-09-25 17:19:00 -0700284 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800285
Ady Abrahamf2851612023-09-25 17:19:00 -0700286 const auto frameRate = getFrameRateOverride(uid);
287 if (!frameRate.has_value()) {
288 return currentPeriod;
289 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100290
Ady Abrahamf2851612023-09-25 17:19:00 -0700291 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
292 if (divisor <= 1) {
293 return currentPeriod;
294 }
295
296 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
297 // behaviour.
298 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100299}
300
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500301ConnectionHandle Scheduler::createEventThread(Cycle cycle,
302 frametimeline::TokenManager* tokenManager,
303 std::chrono::nanoseconds workDuration,
304 std::chrono::nanoseconds readyDuration) {
305 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Ady Abrahamf2851612023-09-25 17:19:00 -0700306 getVsyncSchedule(), tokenManager, *this,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500307 workDuration, readyDuration);
308
309 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
310 handle = createConnection(std::move(eventThread));
311 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700312}
Ana Krulec98b5b242018-08-10 15:03:23 -0700313
Dominik Laskowski068173d2021-08-11 17:22:59 -0700314ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700315 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
316 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800317
Ady Abrahamf2851612023-09-25 17:19:00 -0700318 auto connection = eventThread->createEventConnection();
Dominik Laskowski98041832019-08-01 18:35:59 -0700319
Ana Krulec6ddd2612020-09-24 13:06:33 -0700320 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700321 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
322 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700323}
324
325sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800326 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
327 const sp<IBinder>& layerHandle) {
Ady Abraham822ecbd2023-07-07 16:16:09 -0700328 const auto connection = [&]() -> sp<EventThreadConnection> {
329 std::scoped_lock lock(mConnectionsLock);
330 RETURN_IF_INVALID_HANDLE(handle, nullptr);
331
Ady Abrahamf2851612023-09-25 17:19:00 -0700332 return mConnections[handle].thread->createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700333 }();
334 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
335
336 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
337 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
338 // processed on the main thread.
339 mSchedulerCallback.onChoreographerAttached();
340
341 std::scoped_lock lock(mChoreographerLock);
342 const auto [iter, emplaced] =
343 mAttachedChoreographers.emplace(layerId,
344 AttachedChoreographers{Fps(), {connection}});
345 if (!emplaced) {
346 iter->second.connections.emplace(connection);
347 connection->frameRate = iter->second.frameRate;
348 }
349 }
350 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700351}
352
Dominik Laskowski98041832019-08-01 18:35:59 -0700353sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700354 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700355 RETURN_IF_INVALID_HANDLE(handle, nullptr);
356 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700357}
358
Dominik Laskowski98041832019-08-01 18:35:59 -0700359void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
360 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700361 android::EventThread* thread;
362 {
363 std::lock_guard<std::mutex> lock(mConnectionsLock);
364 RETURN_IF_INVALID_HANDLE(handle);
365 thread = mConnections[handle].thread.get();
366 }
367
368 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700369}
370
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700371void Scheduler::onHotplugConnectionError(ConnectionHandle handle, int32_t errorCode) {
372 android::EventThread* thread;
373 {
374 std::lock_guard<std::mutex> lock(mConnectionsLock);
375 RETURN_IF_INVALID_HANDLE(handle);
376 thread = mConnections[handle].thread.get();
377 }
378
379 thread->onHotplugConnectionError(errorCode);
380}
381
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500382void Scheduler::enableSyntheticVsync(bool enable) {
383 // TODO(b/241285945): Remove connection handles.
384 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700385 android::EventThread* thread;
386 {
387 std::lock_guard<std::mutex> lock(mConnectionsLock);
388 RETURN_IF_INVALID_HANDLE(handle);
389 thread = mConnections[handle].thread.get();
390 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500391 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700392}
393
Ady Abraham62a0be22020-12-08 16:54:10 -0800394void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800395 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500396 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800397
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800398 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800399 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800400
Ady Abraham62f216c2020-10-13 19:07:23 -0700401 android::EventThread* thread;
402 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800403 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700404 RETURN_IF_INVALID_HANDLE(handle);
405 thread = mConnections[handle].thread.get();
406 }
407 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
408}
409
Ady Abrahamace3d052022-11-17 16:25:05 -0800410void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800411 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700412 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100413 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700414 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700415
416 // Invalidate content based refresh rate selection so it could be calculated
417 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700418 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800419 }
Ady Abraham690f4612021-07-01 23:24:03 -0700420 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700421}
422
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100423void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700424 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800425 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100426 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700427 return;
428 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700429 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100430 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700431 return;
432 }
433
Ady Abrahamd1591702021-07-27 16:27:56 -0700434 // If the mode is not the current mode, this means that a
435 // mode change is in progress. In that case we shouldn't dispatch an event
436 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500437 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700438 return;
439 }
440
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100441 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800442 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700443 return;
444 }
445
Ady Abrahamace3d052022-11-17 16:25:05 -0800446 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700447 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
448 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700449}
450
Ady Abrahamace3d052022-11-17 16:25:05 -0800451void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700452 android::EventThread* thread;
453 {
454 std::lock_guard<std::mutex> lock(mConnectionsLock);
455 RETURN_IF_INVALID_HANDLE(handle);
456 thread = mConnections[handle].thread.get();
457 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800458 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800459}
460
Dominik Laskowski98041832019-08-01 18:35:59 -0700461void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700462 android::EventThread* thread;
463 {
464 std::lock_guard<std::mutex> lock(mConnectionsLock);
465 RETURN_IF_INVALID_HANDLE(handle);
466 thread = mConnections.at(handle).thread.get();
467 }
468 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700469}
470
Ady Abraham9c53ee72020-07-22 21:16:18 -0700471void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
472 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700473 android::EventThread* thread;
474 {
475 std::lock_guard<std::mutex> lock(mConnectionsLock);
476 RETURN_IF_INVALID_HANDLE(handle);
477 thread = mConnections[handle].thread.get();
478 }
479 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700480}
Ana Krulece588e312018-09-18 12:32:24 -0700481
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500482void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
483 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
484}
485
486void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
487 setDuration(mAppConnectionHandle,
488 /* workDuration */ config.appWorkDuration,
489 /* readyDuration */ config.sfWorkDuration);
490 setDuration(mSfConnectionHandle,
491 /* workDuration */ vsyncPeriod,
492 /* readyDuration */ config.sfWorkDuration);
493 setDuration(config.sfWorkDuration);
494}
495
Leon Scroggins III67388622023-02-06 20:36:20 -0500496void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
497 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400498 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400499 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700500}
501
Leon Scroggins III67388622023-02-06 20:36:20 -0500502void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
503 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400504 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400505 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700506}
507
Leon Scroggins III67388622023-02-06 20:36:20 -0500508void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800509 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500510 std::scoped_lock lock(mDisplayLock);
511 ftl::FakeGuard guard(kMainThreadContext);
512
Leon Scroggins III792ea802023-11-27 17:32:51 -0500513 for (const auto& [id, display] : mDisplays) {
514 if (display.powerMode != hal::PowerMode::OFF ||
515 !FlagManager::getInstance().multithreaded_present()) {
516 resyncToHardwareVsyncLocked(id, allowToEnable);
517 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500518 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500519}
520
Leon Scroggins III67388622023-02-06 20:36:20 -0500521void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
Ady Abrahamc585dba2023-11-15 18:41:35 -0800522 DisplayModePtr modePtr) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500523 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400524 if (!displayOpt) {
525 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
526 return;
527 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500528 const Display& display = *displayOpt;
529
530 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Ady Abrahamc585dba2023-11-15 18:41:35 -0800531 if (!modePtr) {
532 modePtr = display.selectorPtr->getActiveMode().modePtr.get();
Leon Scroggins III67388622023-02-06 20:36:20 -0500533 }
Ady Abrahamc585dba2023-11-15 18:41:35 -0800534 if (modePtr->getVsyncRate().isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400535 constexpr bool kForce = false;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800536 display.schedulePtr->onDisplayModeChanged(ftl::as_non_null(modePtr), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500537 }
538 }
539}
540
Dominik Laskowski66295432023-03-14 12:25:36 -0400541void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
542 static const auto& whence = __func__;
543 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
544
545 // On main thread to serialize reads/writes of pending hardware VSYNC state.
546 static_cast<void>(
547 schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
548 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
549
550 if (const auto displayOpt = mDisplays.get(id)) {
551 auto& display = displayOpt->get();
552 display.schedulePtr->setPendingHardwareVsyncState(enabled);
553
554 if (display.powerMode != hal::PowerMode::OFF) {
555 mSchedulerCallback.requestHardwareVsync(id, enabled);
556 }
557 }
558 }));
559}
560
Leon Scroggins III67388622023-02-06 20:36:20 -0500561void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
562 std::scoped_lock lock(mDisplayLock);
563 ftl::FakeGuard guard(kMainThreadContext);
564
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500565 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400566 if (!displayOpt) {
567 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
568 return;
569 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500570 const Display& display = *displayOpt;
571 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800572
573 using fps_approx_ops::operator!=;
574 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500575 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
576 "%" PRIu64,
577 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800578
579 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700580 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800581
Ady Abrahamc585dba2023-11-15 18:41:35 -0800582 display.schedulePtr->getTracker().setRenderRate(renderFrameRate);
Ady Abrahamace3d052022-11-17 16:25:05 -0800583}
584
ramindani0491e642023-11-16 17:42:14 -0800585Fps Scheduler::getNextFrameInterval(PhysicalDisplayId id,
586 TimePoint currentExpectedPresentTime) const {
587 std::scoped_lock lock(mDisplayLock);
588 ftl::FakeGuard guard(kMainThreadContext);
589
590 const auto displayOpt = mDisplays.get(id);
591 if (!displayOpt) {
592 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
593 return Fps{};
594 }
595 const Display& display = *displayOpt;
596 const nsecs_t threshold =
597 display.selectorPtr->getActiveMode().modePtr->getVsyncRate().getPeriodNsecs() / 2;
598 const nsecs_t nextVsyncTime = display.schedulePtr->getTracker().nextAnticipatedVSyncTimeFrom(
599 currentExpectedPresentTime.ns() + threshold);
600 return Fps::fromPeriodNsecs(nextVsyncTime - currentExpectedPresentTime.ns());
601}
602
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700603void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700604 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800605
606 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700607 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800608
609 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500610 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800611 }
612}
613
Leon Scroggins III67388622023-02-06 20:36:20 -0500614bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
615 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500616 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
617 return Period::fromNs(nanos);
618 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400619 auto schedule = getVsyncSchedule(id);
620 if (!schedule) {
621 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
622 return false;
623 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400624 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700625}
626
Leon Scroggins III67388622023-02-06 20:36:20 -0500627void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500628 const auto scheduleOpt =
629 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
630 return display.powerMode == hal::PowerMode::OFF
631 ? std::nullopt
632 : std::make_optional(display.schedulePtr);
633 });
634
635 if (!scheduleOpt) return;
636 const auto& schedule = scheduleOpt->get();
637
Dominik Laskowski66295432023-03-14 12:25:36 -0400638 if (const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence))) {
639 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700640 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400641 constexpr bool kDisallow = false;
642 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700643 }
644}
645
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700646void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200647 // If the content detection feature is off, we still keep the layer history,
648 // since we use it for other features (like Frame Rate API), so layers
649 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000650 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700651}
652
Ady Abrahambdda8f02021-04-01 16:06:11 -0700653void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700654 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700655}
656
Ady Abraham822ecbd2023-07-07 16:16:09 -0700657void Scheduler::onLayerDestroyed(Layer* layer) {
658 std::scoped_lock lock(mChoreographerLock);
659 mAttachedChoreographers.erase(layer->getSequence());
660}
661
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000662void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700663 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500664 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700665 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800666 }
Ana Krulec3084c052018-11-21 20:27:17 +0100667}
668
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100669void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700670 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700671}
672
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700673void Scheduler::setDefaultFrameRateCompatibility(
674 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
675 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000676 mFeatures.test(Feature::kContentDetection));
677}
678
Vishnu Nair41376b62023-11-08 05:08:58 -0800679void Scheduler::setLayerProperties(int32_t id, const android::scheduler::LayerProps& properties) {
680 mLayerHistory.setLayerProperties(id, properties);
681}
682
Ady Abraham822ecbd2023-07-07 16:16:09 -0700683void Scheduler::chooseRefreshRateForContent(
684 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
685 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500686 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400687 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800688
Ady Abraham8a82ba62020-01-17 12:43:17 -0800689 ATRACE_CALL();
690
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400691 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800692 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700693
694 if (updateAttachedChoreographer) {
695 LOG_ALWAYS_FATAL_IF(!hierarchy);
696
697 // update the attached choreographers after we selected the render rate.
698 const ftl::Optional<FrameRateMode> modeOpt = [&] {
699 std::scoped_lock lock(mPolicyLock);
700 return mPolicy.modeOpt;
701 }();
702
703 if (modeOpt) {
704 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
705 }
706 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800707}
708
Ana Krulecfb772822018-11-30 10:44:07 +0100709void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500710 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800711}
712
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700713void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700714 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800715 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500716 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800717 }
Ady Abraham8532d012019-05-08 14:50:56 -0700718}
719
Leon Scroggins III67388622023-02-06 20:36:20 -0500720void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500721 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500722 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500723 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500724 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500725 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500726 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700727 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700728 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700729 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500730 {
731 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400732
733 const auto displayOpt = mDisplays.get(id);
734 LOG_ALWAYS_FATAL_IF(!displayOpt);
735 auto& display = displayOpt->get();
736
737 display.powerMode = powerMode;
738 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500739 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500740 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700741
742 if (mDisplayPowerTimer) {
743 mDisplayPowerTimer->reset();
744 }
745
746 // Display Power event will boost the refresh rate to performance.
747 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700748 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700749}
750
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500751auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
752 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500753 std::scoped_lock lock(mDisplayLock);
754 return getVsyncScheduleLocked(idOpt);
755}
756
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500757auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
758 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500759 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500760
Leon Scroggins III67388622023-02-06 20:36:20 -0500761 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500762 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
763 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500764 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500765
766 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400767 if (!displayOpt) {
768 return nullptr;
769 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500770 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500771}
772
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700773void Scheduler::kernelIdleTimerCallback(TimerState state) {
774 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100775
Ady Abraham2139f732019-11-13 18:56:40 -0800776 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
777 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700778 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700779
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700780 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
781 using namespace fps_approx_ops;
782
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800783 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700784 // If we're not in performance mode then the kernel timer shouldn't do
785 // anything, as the refresh rate during DPU power collapse will be the
786 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500787 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800788 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700789 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
790 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700791 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500792 std::scoped_lock lock(mDisplayLock);
793 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500794 for (const auto& [_, display] : mDisplays) {
795 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400796 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500797 }
Alec Mouridc28b372019-04-18 21:17:13 -0700798 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800799
800 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700801}
802
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700803void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800804 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700805 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100806}
807
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700808void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700809 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700810 // Touch event will boost the refresh rate to performance.
811 // Clear layer history to get fresh FPS detection.
812 // NOTE: Instead of checking all the layers, we should be checking the layer
813 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800814 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700815 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700816 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700817 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700818}
819
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700820void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800821 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700822 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700823}
824
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400825void Scheduler::dump(utils::Dumper& dumper) const {
826 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700827
828 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400829 utils::Dumper::Section section(dumper, "Features"sv);
830
831 for (Feature feature : ftl::enum_range<Feature>()) {
832 if (const auto flagOpt = ftl::flag_name(feature)) {
833 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
834 }
835 }
836 }
837 {
838 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400839 {
840 std::scoped_lock lock(mDisplayLock);
841 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500842 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400843 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400844 dumper.dump("layerHistory"sv, mLayerHistory.dump());
845 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
846 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
847 }
848
849 mFrameRateOverrideMappings.dump(dumper);
850 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400851
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500852 {
853 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
854
855 std::scoped_lock lock(mDisplayLock);
856 ftl::FakeGuard guard(kMainThreadContext);
857
858 for (const auto& [id, display] : mDisplays) {
859 utils::Dumper::Section
860 section(dumper,
861 id == mPacesetterDisplayId
862 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
863 : ftl::Concat("Follower Display ", id.value).c_str());
864
865 display.targeterPtr->dump(dumper);
866 dumper.eol();
867 }
868 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800869}
870
Dominik Laskowski068173d2021-08-11 17:22:59 -0700871void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500872 std::scoped_lock lock(mDisplayLock);
873 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500874 if (mPacesetterDisplayId) {
875 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
876 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500877 getVsyncScheduleLocked()->dump(out);
878 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500879 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500880 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500881 continue;
882 }
883 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500884 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500885 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700886}
887
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800888bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700889 std::scoped_lock lock(mPolicyLock);
890 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
891}
892
893bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
894 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400895 if (consideredSignals.idle) return false;
896
897 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500898 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
899 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400900
901 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
902 // the FrameRateOverrideMappings rather than here.
903 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
904}
905
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500906void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400907 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
908
909 {
910 std::scoped_lock lock(mDisplayLock);
911 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
912 }
913
Leon Scroggins39d25342023-04-19 17:11:01 +0000914 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400915}
916
917std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
918 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500919 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500920 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500921 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400922
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500923 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
924 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
925 const Display& pacesetter = *pacesetterOpt;
926
927 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400928 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
929 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
930 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
931 .onExpired =
932 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
933
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500934 pacesetter.selectorPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500935
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500936 newVsyncSchedulePtr = pacesetter.schedulePtr;
937
Dominik Laskowski66295432023-03-14 12:25:36 -0400938 constexpr bool kForce = true;
Ady Abrahamc585dba2023-11-15 18:41:35 -0800939 newVsyncSchedulePtr->onDisplayModeChanged(pacesetter.selectorPtr->getActiveMode().modePtr,
940 kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500941 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500942 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400943}
Leon Scroggins III67388622023-02-06 20:36:20 -0500944
Leon Scroggins39d25342023-04-19 17:11:01 +0000945void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
946 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400947 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500948 {
949 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400950 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -0500951 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400952 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -0500953 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800954 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400955 for (auto* thread : threads) {
Leon Scroggins39d25342023-04-19 17:11:01 +0000956 thread->onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400957 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400958}
959
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500960void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400961 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500962 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
963 pacesetterPtr->stopIdleTimer();
964 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400965 }
966
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500967 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400968 std::scoped_lock lock(mPolicyLock);
969 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800970}
971
Ady Abraham822ecbd2023-07-07 16:16:09 -0700972void Scheduler::updateAttachedChoreographersFrameRate(
973 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
974 std::scoped_lock lock(mChoreographerLock);
975
976 const auto layerId = static_cast<int32_t>(layer.id);
977 const auto choreographers = mAttachedChoreographers.find(layerId);
978 if (choreographers == mAttachedChoreographers.end()) {
979 return;
980 }
981
982 auto& layerChoreographers = choreographers->second;
983
984 layerChoreographers.frameRate = fps;
985 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
986 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
987
988 auto it = layerChoreographers.connections.begin();
989 while (it != layerChoreographers.connections.end()) {
990 sp<EventThreadConnection> choreographerConnection = it->promote();
991 if (choreographerConnection) {
992 choreographerConnection->frameRate = fps;
993 it++;
994 } else {
995 it = choreographers->second.connections.erase(it);
996 }
997 }
998
999 if (layerChoreographers.connections.empty()) {
1000 mAttachedChoreographers.erase(choreographers);
1001 }
1002}
1003
1004int Scheduler::updateAttachedChoreographersInternal(
1005 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
1006 int parentDivisor) {
1007 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
1008
1009 int divisor = 0;
1010 if (layerHierarchy.getLayer()) {
1011 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
1012 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
1013 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
1014 parentDivisor);
1015
1016 if (frameRate.isValid()) {
1017 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
1018 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
1019 // Since this layer wants an exact match, we would only set a frame rate if the
1020 // desired rate is a divisor of the display refresh rate.
1021 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
1022 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
1023 // find the closest frame rate divisor for the desired frame rate.
1024 divisor = static_cast<int>(
1025 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1026 }
1027 }
1028 }
1029
1030 // We start by traversing the children, updating their choreographers, and getting back the
1031 // aggregated frame rate.
1032 int childrenDivisor = 0;
1033 for (const auto& [child, _] : layerHierarchy.mChildren) {
1034 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1035
1036 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1037
1038 const int childDivisor =
1039 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1040 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1041 if (childDivisor > 0) {
1042 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1043 }
1044 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1045 }
1046
1047 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1048
1049 // If there is no explicit vote for this layer. Use the children's vote if exists
1050 divisor = (divisor == 0) ? childrenDivisor : divisor;
1051 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1052
1053 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1054 divisor = (divisor == 0) ? parentDivisor : divisor;
1055 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1056
1057 if (layerHierarchy.getLayer()) {
1058 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1059 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1060 }
1061
1062 return divisor;
1063}
1064
1065void Scheduler::updateAttachedChoreographers(
1066 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1067 ATRACE_CALL();
1068 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1069}
1070
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001071template <typename S, typename T>
1072auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001073 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001074 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001075 GlobalSignals consideredSignals;
1076
Ady Abraham62a0be22020-12-08 16:54:10 -08001077 bool refreshRateChanged = false;
1078 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001079
Ady Abraham8532d012019-05-08 14:50:56 -07001080 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001081 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001082
1083 auto& currentState = mPolicy.*statePtr;
1084 if (currentState == newState) return {};
1085 currentState = std::forward<T>(newState);
1086
Dominik Laskowski596a2562022-10-28 11:26:12 -04001087 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001088 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001089 {
1090 std::scoped_lock lock(mDisplayLock);
1091 ftl::FakeGuard guard(kMainThreadContext);
1092
1093 modeChoices = chooseDisplayModes();
1094
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001095 // TODO(b/240743786): The pacesetter display's mode must change for any
1096 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1097 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001098 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001099 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001100 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001101 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001102 })
1103 .value();
1104 }
ramindani69b58e82022-09-26 16:48:36 -07001105
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001106 modeRequests.reserve(modeChoices.size());
1107 for (auto& [id, choice] : modeChoices) {
1108 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001109 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001110 .emitEvent = !choice.consideredSignals.idle});
1111 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001112
Ady Abraham33a386b2023-07-18 15:37:11 -07001113 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001114
Ady Abrahamace3d052022-11-17 16:25:05 -08001115 if (mPolicy.modeOpt != modeOpt) {
1116 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001117 refreshRateChanged = true;
1118 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001119 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001120 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001121 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001122 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001123 }
Ady Abraham8532d012019-05-08 14:50:56 -07001124 }
Ady Abraham8532d012019-05-08 14:50:56 -07001125 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001126 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001127 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001128 }
1129 if (frameRateOverridesChanged) {
1130 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1131 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001132 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001133}
1134
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001135auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001136 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001137
Ady Abraham68636062022-11-16 17:07:25 -08001138 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski6b049ff2023-01-29 15:46:45 -05001139 ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -04001140 const auto globalSignals = makeGlobalSignals();
ramindani22f2ead2023-04-21 10:27:11 -07001141 Fps pacesetterFps;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001142
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001143 for (const auto& [id, display] : mDisplays) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001144 auto rankedFrameRates =
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001145 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
1146 globalSignals);
ramindani22f2ead2023-04-21 10:27:11 -07001147 if (id == *mPacesetterDisplayId) {
1148 pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
Dominik Laskowski01602522022-10-07 19:02:28 -04001149 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001150 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001151 }
ramindani69b58e82022-09-26 16:48:36 -07001152
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001153 DisplayModeChoiceMap modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001154 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -04001155
ramindani22f2ead2023-04-21 10:27:11 -07001156 for (auto& [rankings, signals] : perDisplayRanking) {
1157 const auto chosenFrameRateMode =
1158 ftl::find_if(rankings,
1159 [&](const auto& ranking) {
1160 return ranking.frameRateMode.fps == pacesetterFps;
1161 })
1162 .transform([](const auto& scoredFrameRate) {
1163 return scoredFrameRate.get().frameRateMode;
1164 })
1165 .value_or(rankings.front().frameRateMode);
Dominik Laskowski01602522022-10-07 19:02:28 -04001166
ramindani22f2ead2023-04-21 10:27:11 -07001167 modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
1168 DisplayModeChoice{chosenFrameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -04001169 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001170 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001171}
1172
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001173GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001174 const bool powerOnImminent = mDisplayPowerTimer &&
1175 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1176 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001177
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001178 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1179 .idle = mPolicy.idleTimer == TimerState::Expired,
1180 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001181}
1182
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001183FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001184 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001185 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001186 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001187 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1188 .ranking.front()
1189 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001190
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001191 // Make sure the stored mode is up to date.
1192 mPolicy.modeOpt = frameRateMode;
1193
1194 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001195}
1196
Peiyong Line9d809e2020-04-14 13:10:48 -07001197void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001198 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1199 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1200
1201 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1202 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1203 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1204 }
1205}
1206
Leon Scroggins III5b581492023-10-31 14:29:41 -04001207bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001208 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1209 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1210 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1211 // We need to composite again as refreshTimeNanos is still in the future.
1212 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001213 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001214
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001215 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001216 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001217 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001218}
1219
Ady Abraham7825c682021-05-17 15:12:14 -07001220void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001221 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001222}
1223
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001224void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
1225 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1226 return;
1227 }
1228
1229 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1230}
1231
Ady Abraham62a0be22020-12-08 16:54:10 -08001232void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1233 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1234 return;
1235 }
1236
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001237 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001238}
1239
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001240void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001241 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001242 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1243}
1244
Tony Huangf3621102023-09-04 17:14:22 +08001245void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
1246 mSmallAreaDetectionAllowMappings.setThesholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001247}
1248
Tony Huangf3621102023-09-04 17:14:22 +08001249bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1250 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1251 if (oThreshold) {
1252 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1253 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001254 return false;
1255}
1256
Dominik Laskowski068173d2021-08-11 17:22:59 -07001257} // namespace android::scheduler