blob: 56a4ae25695c3f3e7ae94a765be00171195213d3 [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
48#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070049#include "EventThread.h"
Ady Abrahamd6d80162023-10-23 12:57:41 -070050#include "FlagManager.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>(
121 displayId, mFeatures,
122 [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 Laskowskiec0eac22023-01-28 16:16:19 -0500184 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId);
185 const auto pacesetterId = *mPacesetterDisplayId;
186 const auto pacesetterOpt = mDisplays.get(pacesetterId);
187
188 FrameTargeter& pacesetterTargeter = *pacesetterOpt->get().targeterPtr;
189 pacesetterTargeter.beginFrame(beginFrameArgs, *pacesetterOpt->get().schedulePtr);
190
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400191 FrameTargets targets;
192 targets.try_emplace(pacesetterId, &pacesetterTargeter.target());
193
194 for (const auto& [id, display] : mDisplays) {
195 if (id == pacesetterId) continue;
196
Dominik Laskowski50e2e4d2023-10-04 10:58:28 -0400197 FrameTargeter& targeter = *display.targeterPtr;
198 targeter.beginFrame(beginFrameArgs, *display.schedulePtr);
Dominik Laskowskifdac5652023-06-29 12:01:13 -0400199 targets.try_emplace(id, &targeter.target());
200 }
201
202 if (!compositor.commit(pacesetterId, targets)) return;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500203
204 // TODO(b/256196556): Choose the frontrunner display.
205 FrameTargeters targeters;
206 targeters.try_emplace(pacesetterId, &pacesetterTargeter);
207
208 for (auto& [id, display] : mDisplays) {
209 if (id == pacesetterId) continue;
210
211 FrameTargeter& targeter = *display.targeterPtr;
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500212 targeters.try_emplace(id, &targeter);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700213 }
214
Ady Abrahamd6d80162023-10-23 12:57:41 -0700215 if (FlagManager::getInstance().vrr_config() &&
Alec Mouri1c7938e2023-09-22 04:17:23 +0000216 CC_UNLIKELY(mPacesetterFrameDurationFractionToSkip > 0.f)) {
217 const auto period = pacesetterTargeter.target().expectedFrameDuration();
218 const auto skipDuration = Duration::fromNs(
219 static_cast<nsecs_t>(period.ns() * mPacesetterFrameDurationFractionToSkip));
220 ATRACE_FORMAT("Injecting jank for %f%% of the frame (%" PRId64 " ns)",
221 mPacesetterFrameDurationFractionToSkip * 100, skipDuration.ns());
222 std::this_thread::sleep_for(skipDuration);
223 mPacesetterFrameDurationFractionToSkip = 0.f;
224 }
225
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500226 const auto resultsPerDisplay = compositor.composite(pacesetterId, targeters);
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700227 compositor.sample();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400228
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500229 for (const auto& [id, targeter] : targeters) {
230 const auto resultOpt = resultsPerDisplay.get(id);
231 LOG_ALWAYS_FATAL_IF(!resultOpt);
232 targeter->endFrame(*resultOpt);
233 }
Dominik Laskowski08fbd852022-07-14 08:53:42 -0700234}
235
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500236std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800237 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500238 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800239 return mFrameRateOverrideMappings
240 .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
Ady Abraham62a0be22020-12-08 16:54:10 -0800241}
242
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400243bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
Ady Abraham62a0be22020-12-08 16:54:10 -0800244 const auto frameRate = getFrameRateOverride(uid);
245 if (!frameRate.has_value()) {
246 return true;
247 }
248
Ady Abraham9243bba2023-02-10 15:31:14 -0800249 ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400250 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700251}
252
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400253bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
254 return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
Huihong Luo1768cb02022-10-11 11:10:34 -0700255}
256
Ady Abrahamf2851612023-09-25 17:19:00 -0700257bool Scheduler::throttleVsync(android::TimePoint expectedPresentTime, uid_t uid) {
258 return !isVsyncValid(expectedPresentTime, uid);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500259}
Ady Abraham64c2fc02020-12-29 12:07:50 -0800260
Ady Abrahamf2851612023-09-25 17:19:00 -0700261Period Scheduler::getVsyncPeriod(uid_t uid) {
262 const auto [refreshRate, period] = [this] {
263 std::scoped_lock lock(mDisplayLock);
264 const auto pacesetterOpt = pacesetterDisplayLocked();
265 LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
266 const Display& pacesetter = *pacesetterOpt;
267 return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
268 pacesetter.schedulePtr->period());
269 }();
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500270
Ady Abrahamf2851612023-09-25 17:19:00 -0700271 const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800272
Ady Abrahamf2851612023-09-25 17:19:00 -0700273 const auto frameRate = getFrameRateOverride(uid);
274 if (!frameRate.has_value()) {
275 return currentPeriod;
276 }
Jorim Jaggic0086af2021-02-12 18:18:11 +0100277
Ady Abrahamf2851612023-09-25 17:19:00 -0700278 const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
279 if (divisor <= 1) {
280 return currentPeriod;
281 }
282
283 // TODO(b/299378819): the casting is not needed, but we need a flag as it might change
284 // behaviour.
285 return Period::fromNs(currentPeriod.ns() * divisor);
Jorim Jaggic0086af2021-02-12 18:18:11 +0100286}
287
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500288ConnectionHandle Scheduler::createEventThread(Cycle cycle,
289 frametimeline::TokenManager* tokenManager,
290 std::chrono::nanoseconds workDuration,
291 std::chrono::nanoseconds readyDuration) {
292 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
Ady Abrahamf2851612023-09-25 17:19:00 -0700293 getVsyncSchedule(), tokenManager, *this,
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500294 workDuration, readyDuration);
295
296 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
297 handle = createConnection(std::move(eventThread));
298 return handle;
Dominik Laskowski98041832019-08-01 18:35:59 -0700299}
Ana Krulec98b5b242018-08-10 15:03:23 -0700300
Dominik Laskowski068173d2021-08-11 17:22:59 -0700301ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700302 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
303 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800304
Ady Abrahamf2851612023-09-25 17:19:00 -0700305 auto connection = eventThread->createEventConnection();
Dominik Laskowski98041832019-08-01 18:35:59 -0700306
Ana Krulec6ddd2612020-09-24 13:06:33 -0700307 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700308 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
309 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700310}
311
312sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Rachel Lee2248f522023-01-27 16:45:23 -0800313 ConnectionHandle handle, EventRegistrationFlags eventRegistration,
314 const sp<IBinder>& layerHandle) {
Ady Abraham822ecbd2023-07-07 16:16:09 -0700315 const auto connection = [&]() -> sp<EventThreadConnection> {
316 std::scoped_lock lock(mConnectionsLock);
317 RETURN_IF_INVALID_HANDLE(handle, nullptr);
318
Ady Abrahamf2851612023-09-25 17:19:00 -0700319 return mConnections[handle].thread->createEventConnection(eventRegistration);
Ady Abraham822ecbd2023-07-07 16:16:09 -0700320 }();
321 const auto layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
322
323 if (layerId != static_cast<int32_t>(UNASSIGNED_LAYER_ID)) {
324 // TODO(b/290409668): Moving the choreographer attachment to be a transaction that will be
325 // processed on the main thread.
326 mSchedulerCallback.onChoreographerAttached();
327
328 std::scoped_lock lock(mChoreographerLock);
329 const auto [iter, emplaced] =
330 mAttachedChoreographers.emplace(layerId,
331 AttachedChoreographers{Fps(), {connection}});
332 if (!emplaced) {
333 iter->second.connections.emplace(connection);
334 connection->frameRate = iter->second.frameRate;
335 }
336 }
337 return connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700338}
339
Dominik Laskowski98041832019-08-01 18:35:59 -0700340sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700341 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700342 RETURN_IF_INVALID_HANDLE(handle, nullptr);
343 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700344}
345
Dominik Laskowski98041832019-08-01 18:35:59 -0700346void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
347 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700348 android::EventThread* thread;
349 {
350 std::lock_guard<std::mutex> lock(mConnectionsLock);
351 RETURN_IF_INVALID_HANDLE(handle);
352 thread = mConnections[handle].thread.get();
353 }
354
355 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700356}
357
Brian Johnson5dcd75d2023-08-15 09:36:37 -0700358void Scheduler::onHotplugConnectionError(ConnectionHandle handle, int32_t errorCode) {
359 android::EventThread* thread;
360 {
361 std::lock_guard<std::mutex> lock(mConnectionsLock);
362 RETURN_IF_INVALID_HANDLE(handle);
363 thread = mConnections[handle].thread.get();
364 }
365
366 thread->onHotplugConnectionError(errorCode);
367}
368
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500369void Scheduler::enableSyntheticVsync(bool enable) {
370 // TODO(b/241285945): Remove connection handles.
371 const ConnectionHandle handle = mAppConnectionHandle;
Ana Krulec6ddd2612020-09-24 13:06:33 -0700372 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 }
Dominik Laskowskie99b98c2023-02-02 12:37:23 -0500378 thread->enableSyntheticVsync(enable);
Ana Krulec98b5b242018-08-10 15:03:23 -0700379}
380
Ady Abraham62a0be22020-12-08 16:54:10 -0800381void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
Andy Yud6a36202022-01-26 04:08:22 -0800382 const bool supportsFrameRateOverrideByContent =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500383 pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
Andy Yud6a36202022-01-26 04:08:22 -0800384
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800385 std::vector<FrameRateOverride> overrides =
Andy Yud6a36202022-01-26 04:08:22 -0800386 mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
Andy Yu2ae6b6b2021-11-18 14:51:06 -0800387
Ady Abraham62f216c2020-10-13 19:07:23 -0700388 android::EventThread* thread;
389 {
Ady Abraham62a0be22020-12-08 16:54:10 -0800390 std::lock_guard lock(mConnectionsLock);
Ady Abraham62f216c2020-10-13 19:07:23 -0700391 RETURN_IF_INVALID_HANDLE(handle);
392 thread = mConnections[handle].thread.get();
393 }
394 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
395}
396
Ady Abrahamace3d052022-11-17 16:25:05 -0800397void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ady Abraham62a0be22020-12-08 16:54:10 -0800398 {
Dominik Laskowski068173d2021-08-11 17:22:59 -0700399 std::lock_guard<std::mutex> lock(mPolicyLock);
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100400 // Cache the last reported modes for primary display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700401 mPolicy.cachedModeChangedParams = {handle, mode};
Ady Abraham5cc2e262021-03-25 13:09:17 -0700402
403 // Invalidate content based refresh rate selection so it could be calculated
404 // again for the new refresh rate.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700405 mPolicy.contentRequirements.clear();
Ady Abraham62a0be22020-12-08 16:54:10 -0800406 }
Ady Abraham690f4612021-07-01 23:24:03 -0700407 onNonPrimaryDisplayModeChanged(handle, mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700408}
409
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100410void Scheduler::dispatchCachedReportedMode() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700411 // Check optional fields first.
Ady Abrahamace3d052022-11-17 16:25:05 -0800412 if (!mPolicy.modeOpt) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100413 ALOGW("No mode ID found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700414 return;
415 }
Dominik Laskowski068173d2021-08-11 17:22:59 -0700416 if (!mPolicy.cachedModeChangedParams) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100417 ALOGW("No mode changed params found, not dispatching cached mode.");
Ana Krulec6ddd2612020-09-24 13:06:33 -0700418 return;
419 }
420
Ady Abrahamd1591702021-07-27 16:27:56 -0700421 // If the mode is not the current mode, this means that a
422 // mode change is in progress. In that case we shouldn't dispatch an event
423 // as it will be dispatched when the current mode changes.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500424 if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
Ady Abrahamd1591702021-07-27 16:27:56 -0700425 return;
426 }
427
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100428 // If there is no change from cached mode, there is no need to dispatch an event
Ady Abrahamace3d052022-11-17 16:25:05 -0800429 if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700430 return;
431 }
432
Ady Abrahamace3d052022-11-17 16:25:05 -0800433 mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
Dominik Laskowski068173d2021-08-11 17:22:59 -0700434 onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
435 mPolicy.cachedModeChangedParams->mode);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700436}
437
Ady Abrahamace3d052022-11-17 16:25:05 -0800438void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700439 android::EventThread* thread;
440 {
441 std::lock_guard<std::mutex> lock(mConnectionsLock);
442 RETURN_IF_INVALID_HANDLE(handle);
443 thread = mConnections[handle].thread.get();
444 }
Ady Abraham67434eb2022-12-01 17:48:12 -0800445 thread->onModeChanged(mode);
Ady Abraham447052e2019-02-13 16:07:27 -0800446}
447
Dominik Laskowski98041832019-08-01 18:35:59 -0700448void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700449 android::EventThread* thread;
450 {
451 std::lock_guard<std::mutex> lock(mConnectionsLock);
452 RETURN_IF_INVALID_HANDLE(handle);
453 thread = mConnections.at(handle).thread.get();
454 }
455 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700456}
457
Ady Abraham9c53ee72020-07-22 21:16:18 -0700458void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
459 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700460 android::EventThread* thread;
461 {
462 std::lock_guard<std::mutex> lock(mConnectionsLock);
463 RETURN_IF_INVALID_HANDLE(handle);
464 thread = mConnections[handle].thread.get();
465 }
466 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700467}
Ana Krulece588e312018-09-18 12:32:24 -0700468
Dominik Laskowski1c99a002023-01-20 17:10:36 -0500469void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
470 setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
471}
472
473void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
474 setDuration(mAppConnectionHandle,
475 /* workDuration */ config.appWorkDuration,
476 /* readyDuration */ config.sfWorkDuration);
477 setDuration(mSfConnectionHandle,
478 /* workDuration */ vsyncPeriod,
479 /* readyDuration */ config.sfWorkDuration);
480 setDuration(config.sfWorkDuration);
481}
482
Leon Scroggins III67388622023-02-06 20:36:20 -0500483void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
484 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400485 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400486 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700487}
488
Leon Scroggins III67388622023-02-06 20:36:20 -0500489void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
490 auto schedule = getVsyncSchedule(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400491 LOG_ALWAYS_FATAL_IF(!schedule);
Dominik Laskowski66295432023-03-14 12:25:36 -0400492 schedule->disableHardwareVsync(disallow);
Ana Krulece588e312018-09-18 12:32:24 -0700493}
494
Leon Scroggins III67388622023-02-06 20:36:20 -0500495void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
Rachel Leea5be3282023-03-08 20:15:54 -0800496 ATRACE_CALL();
Leon Scroggins III67388622023-02-06 20:36:20 -0500497 std::scoped_lock lock(mDisplayLock);
498 ftl::FakeGuard guard(kMainThreadContext);
499
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500500 for (const auto& [id, _] : mDisplays) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500501 resyncToHardwareVsyncLocked(id, allowToEnable);
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500502 }
Leon Scroggins IIIdb16a2b2023-02-06 17:50:05 -0500503}
504
Leon Scroggins III67388622023-02-06 20:36:20 -0500505void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
506 std::optional<Fps> refreshRate) {
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500507 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400508 if (!displayOpt) {
509 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
510 return;
511 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500512 const Display& display = *displayOpt;
513
514 if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500515 if (!refreshRate) {
ramindania04b8a52023-08-07 18:49:47 -0700516 refreshRate = display.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Leon Scroggins III67388622023-02-06 20:36:20 -0500517 }
518 if (refreshRate->isValid()) {
Dominik Laskowski66295432023-03-14 12:25:36 -0400519 constexpr bool kForce = false;
520 display.schedulePtr->startPeriodTransition(refreshRate->getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500521 }
522 }
523}
524
Dominik Laskowski66295432023-03-14 12:25:36 -0400525void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
526 static const auto& whence = __func__;
527 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
528
529 // On main thread to serialize reads/writes of pending hardware VSYNC state.
530 static_cast<void>(
531 schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
532 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
533
534 if (const auto displayOpt = mDisplays.get(id)) {
535 auto& display = displayOpt->get();
536 display.schedulePtr->setPendingHardwareVsyncState(enabled);
537
538 if (display.powerMode != hal::PowerMode::OFF) {
539 mSchedulerCallback.requestHardwareVsync(id, enabled);
540 }
541 }
542 }));
543}
544
Leon Scroggins III67388622023-02-06 20:36:20 -0500545void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
546 std::scoped_lock lock(mDisplayLock);
547 ftl::FakeGuard guard(kMainThreadContext);
548
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500549 const auto displayOpt = mDisplays.get(id);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400550 if (!displayOpt) {
551 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
552 return;
553 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500554 const Display& display = *displayOpt;
555 const auto mode = display.selectorPtr->getActiveMode();
Ady Abrahamace3d052022-11-17 16:25:05 -0800556
557 using fps_approx_ops::operator!=;
558 LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
Leon Scroggins III67388622023-02-06 20:36:20 -0500559 "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
560 "%" PRIu64,
561 to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
Ady Abrahamace3d052022-11-17 16:25:05 -0800562
563 ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
ramindania04b8a52023-08-07 18:49:47 -0700564 to_string(mode.modePtr->getVsyncRate()).c_str());
Ady Abrahamace3d052022-11-17 16:25:05 -0800565
ramindanid4354a92023-10-02 15:11:09 -0700566 display.schedulePtr->getTracker().setDisplayModeData(
567 {.renderRate = renderFrameRate,
568 .notifyExpectedPresentTimeoutOpt = getNotifyExpectedPresentTimeout(mode)});
569}
570
571std::optional<Period> Scheduler::getNotifyExpectedPresentTimeout(const FrameRateMode& mode) {
572 if (mode.modePtr->getVrrConfig() && mode.modePtr->getVrrConfig()->notifyExpectedPresentConfig) {
573 return Period::fromNs(
574 mode.modePtr->getVrrConfig()
575 ->notifyExpectedPresentConfig->notifyExpectedPresentTimeoutNs);
576 } else {
577 return std::nullopt;
578 }
Ady Abrahamace3d052022-11-17 16:25:05 -0800579}
580
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700581void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700582 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800583
584 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700585 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800586
587 if (now - last > kIgnoreDelay) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500588 resyncAllToHardwareVsync(false /* allowToEnable */);
Ana Krulecc2870422019-01-29 19:00:58 -0800589 }
590}
591
Leon Scroggins III67388622023-02-06 20:36:20 -0500592bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
593 std::optional<nsecs_t> hwcVsyncPeriodIn) {
Leon Scroggins IIIc275df42023-02-07 16:40:21 -0500594 const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
595 return Period::fromNs(nanos);
596 });
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400597 auto schedule = getVsyncSchedule(id);
598 if (!schedule) {
599 ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
600 return false;
601 }
Dominik Laskowski66295432023-03-14 12:25:36 -0400602 return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
Ana Krulece588e312018-09-18 12:32:24 -0700603}
604
Leon Scroggins III67388622023-02-06 20:36:20 -0500605void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500606 const auto scheduleOpt =
607 (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
608 return display.powerMode == hal::PowerMode::OFF
609 ? std::nullopt
610 : std::make_optional(display.schedulePtr);
611 });
612
613 if (!scheduleOpt) return;
614 const auto& schedule = scheduleOpt->get();
615
Dominik Laskowski66295432023-03-14 12:25:36 -0400616 if (const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence))) {
617 schedule->enableHardwareVsync();
Ana Krulece588e312018-09-18 12:32:24 -0700618 } else {
Dominik Laskowski66295432023-03-14 12:25:36 -0400619 constexpr bool kDisallow = false;
620 schedule->disableHardwareVsync(kDisallow);
Ana Krulece588e312018-09-18 12:32:24 -0700621 }
622}
623
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700624void Scheduler::registerLayer(Layer* layer) {
Marin Shalamanov4be385e2021-04-23 13:25:30 +0200625 // If the content detection feature is off, we still keep the layer history,
626 // since we use it for other features (like Frame Rate API), so layers
627 // still need to be registered.
Andy Labrada096227e2022-06-15 16:58:11 +0000628 mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
Ady Abraham09bd3922019-04-08 10:44:56 -0700629}
630
Ady Abrahambdda8f02021-04-01 16:06:11 -0700631void Scheduler::deregisterLayer(Layer* layer) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700632 mLayerHistory.deregisterLayer(layer);
Ady Abrahambdda8f02021-04-01 16:06:11 -0700633}
634
Ady Abraham822ecbd2023-07-07 16:16:09 -0700635void Scheduler::onLayerDestroyed(Layer* layer) {
636 std::scoped_lock lock(mChoreographerLock);
637 mAttachedChoreographers.erase(layer->getSequence());
638}
639
Vishnu Nairef68d6d2023-02-28 06:18:27 +0000640void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700641 nsecs_t now, LayerHistory::LayerUpdateType updateType) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500642 if (pacesetterSelectorPtr()->canSwitch()) {
Vishnu Nair47b7bb42023-09-29 16:27:33 -0700643 mLayerHistory.record(id, layerProps, presentTime, now, updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800644 }
Ana Krulec3084c052018-11-21 20:27:17 +0100645}
646
Marin Shalamanova7fe3042021-01-29 21:02:08 +0100647void Scheduler::setModeChangePending(bool pending) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700648 mLayerHistory.setModeChangePending(pending);
Ady Abraham32efd542020-05-19 17:49:26 -0700649}
650
Vishnu Nair80e8cfe2023-09-29 17:03:45 -0700651void Scheduler::setDefaultFrameRateCompatibility(
652 int32_t id, scheduler::FrameRateCompatibility frameRateCompatibility) {
653 mLayerHistory.setDefaultFrameRateCompatibility(id, frameRateCompatibility,
Andy Labrada096227e2022-06-15 16:58:11 +0000654 mFeatures.test(Feature::kContentDetection));
655}
656
Ady Abraham822ecbd2023-07-07 16:16:09 -0700657void Scheduler::chooseRefreshRateForContent(
658 const surfaceflinger::frontend::LayerHierarchy* hierarchy,
659 bool updateAttachedChoreographer) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500660 const auto selectorPtr = pacesetterSelectorPtr();
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400661 if (!selectorPtr->canSwitch()) return;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800662
Ady Abraham8a82ba62020-01-17 12:43:17 -0800663 ATRACE_CALL();
664
Dominik Laskowskid82e0f02022-10-26 15:23:04 -0400665 LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800666 applyPolicy(&Policy::contentRequirements, std::move(summary));
Ady Abraham822ecbd2023-07-07 16:16:09 -0700667
668 if (updateAttachedChoreographer) {
669 LOG_ALWAYS_FATAL_IF(!hierarchy);
670
671 // update the attached choreographers after we selected the render rate.
672 const ftl::Optional<FrameRateMode> modeOpt = [&] {
673 std::scoped_lock lock(mPolicyLock);
674 return mPolicy.modeOpt;
675 }();
676
677 if (modeOpt) {
678 updateAttachedChoreographers(*hierarchy, modeOpt->fps);
679 }
680 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800681}
682
Ana Krulecfb772822018-11-30 10:44:07 +0100683void Scheduler::resetIdleTimer() {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500684 pacesetterSelectorPtr()->resetIdleTimer();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800685}
686
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700687void Scheduler::onTouchHint() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700688 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800689 mTouchTimer->reset();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500690 pacesetterSelectorPtr()->resetKernelIdleTimer();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800691 }
Ady Abraham8532d012019-05-08 14:50:56 -0700692}
693
Leon Scroggins III67388622023-02-06 20:36:20 -0500694void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500695 const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500696 ftl::FakeGuard guard(mDisplayLock);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500697 return id == mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500698 }();
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500699 if (isPacesetter) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500700 // TODO (b/255657128): This needs to be handled per display.
Dominik Laskowski068173d2021-08-11 17:22:59 -0700701 std::lock_guard<std::mutex> lock(mPolicyLock);
Rachel Lee6a9731d2022-06-06 17:08:14 -0700702 mPolicy.displayPowerMode = powerMode;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700703 }
Leon Scroggins III67388622023-02-06 20:36:20 -0500704 {
705 std::scoped_lock lock(mDisplayLock);
Dominik Laskowski66295432023-03-14 12:25:36 -0400706
707 const auto displayOpt = mDisplays.get(id);
708 LOG_ALWAYS_FATAL_IF(!displayOpt);
709 auto& display = displayOpt->get();
710
711 display.powerMode = powerMode;
712 display.schedulePtr->getController().setDisplayPowerMode(powerMode);
Leon Scroggins III67388622023-02-06 20:36:20 -0500713 }
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500714 if (!isPacesetter) return;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700715
716 if (mDisplayPowerTimer) {
717 mDisplayPowerTimer->reset();
718 }
719
720 // Display Power event will boost the refresh rate to performance.
721 // Clear Layer History to get fresh FPS detection
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700722 mLayerHistory.clear();
Ady Abraham6fe2c172019-07-12 12:37:57 -0700723}
724
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500725auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
726 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500727 std::scoped_lock lock(mDisplayLock);
728 return getVsyncScheduleLocked(idOpt);
729}
730
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500731auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
732 -> ConstVsyncSchedulePtr {
Leon Scroggins III67388622023-02-06 20:36:20 -0500733 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500734
Leon Scroggins III67388622023-02-06 20:36:20 -0500735 if (!idOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500736 LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
737 idOpt = mPacesetterDisplayId;
Leon Scroggins III67388622023-02-06 20:36:20 -0500738 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500739
740 const auto displayOpt = mDisplays.get(*idOpt);
Leon Scroggins III4235ea02023-04-17 15:14:20 -0400741 if (!displayOpt) {
742 return nullptr;
743 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500744 return displayOpt->get().schedulePtr;
Leon Scroggins III67388622023-02-06 20:36:20 -0500745}
746
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700747void Scheduler::kernelIdleTimerCallback(TimerState state) {
748 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100749
Ady Abraham2139f732019-11-13 18:56:40 -0800750 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
751 // magic number
ramindania04b8a52023-08-07 18:49:47 -0700752 const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getPeakFps();
Ady Abraham3efa3942021-06-24 19:01:25 -0700753
Dominik Laskowski6eab42d2021-09-13 14:34:13 -0700754 constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
755 using namespace fps_approx_ops;
756
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800757 if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700758 // If we're not in performance mode then the kernel timer shouldn't do
759 // anything, as the refresh rate during DPU power collapse will be the
760 // same.
Leon Scroggins III67388622023-02-06 20:36:20 -0500761 resyncAllToHardwareVsync(true /* allowToEnable */);
Dominik Laskowskib0054a22022-03-03 09:03:06 -0800762 } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700763 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
764 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700765 // need to update the VsyncController model anyway.
Leon Scroggins III67388622023-02-06 20:36:20 -0500766 std::scoped_lock lock(mDisplayLock);
767 ftl::FakeGuard guard(kMainThreadContext);
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500768 for (const auto& [_, display] : mDisplays) {
769 constexpr bool kDisallow = false;
Dominik Laskowski66295432023-03-14 12:25:36 -0400770 display.schedulePtr->disableHardwareVsync(kDisallow);
Leon Scroggins III67388622023-02-06 20:36:20 -0500771 }
Alec Mouridc28b372019-04-18 21:17:13 -0700772 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800773
774 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700775}
776
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700777void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800778 applyPolicy(&Policy::idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700779 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100780}
781
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700782void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700783 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700784 // Touch event will boost the refresh rate to performance.
785 // Clear layer history to get fresh FPS detection.
786 // NOTE: Instead of checking all the layers, we should be checking the layer
787 // that is currently on top. b/142507166 will give us this capability.
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800788 if (applyPolicy(&Policy::touch, touch).touch) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -0700789 mLayerHistory.clear();
Ady Abraham1adbb722020-05-15 11:51:48 -0700790 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700791 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700792}
793
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700794void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -0800795 applyPolicy(&Policy::displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700796 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700797}
798
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400799void Scheduler::dump(utils::Dumper& dumper) const {
800 using namespace std::string_view_literals;
Ady Abraham4f960d12021-10-13 16:59:49 -0700801
802 {
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400803 utils::Dumper::Section section(dumper, "Features"sv);
804
805 for (Feature feature : ftl::enum_range<Feature>()) {
806 if (const auto flagOpt = ftl::flag_name(feature)) {
807 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
808 }
809 }
810 }
811 {
812 utils::Dumper::Section section(dumper, "Policy"sv);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400813 {
814 std::scoped_lock lock(mDisplayLock);
815 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500816 dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400817 }
Dominik Laskowski03cfce82022-11-02 12:13:29 -0400818 dumper.dump("layerHistory"sv, mLayerHistory.dump());
819 dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
820 dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
821 }
822
823 mFrameRateOverrideMappings.dump(dumper);
824 dumper.eol();
Dominik Laskowskib418dd72023-06-13 17:31:04 -0400825
Dominik Laskowskiec0eac22023-01-28 16:16:19 -0500826 {
827 utils::Dumper::Section section(dumper, "Frame Targeting"sv);
828
829 std::scoped_lock lock(mDisplayLock);
830 ftl::FakeGuard guard(kMainThreadContext);
831
832 for (const auto& [id, display] : mDisplays) {
833 utils::Dumper::Section
834 section(dumper,
835 id == mPacesetterDisplayId
836 ? ftl::Concat("Pacesetter Display ", id.value).c_str()
837 : ftl::Concat("Follower Display ", id.value).c_str());
838
839 display.targeterPtr->dump(dumper);
840 dumper.eol();
841 }
842 }
Ana Krulecb43429d2019-01-09 14:28:51 -0800843}
844
Dominik Laskowski068173d2021-08-11 17:22:59 -0700845void Scheduler::dumpVsync(std::string& out) const {
Leon Scroggins III67388622023-02-06 20:36:20 -0500846 std::scoped_lock lock(mDisplayLock);
847 ftl::FakeGuard guard(kMainThreadContext);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500848 if (mPacesetterDisplayId) {
849 base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
850 to_string(*mPacesetterDisplayId).c_str());
Leon Scroggins III67388622023-02-06 20:36:20 -0500851 getVsyncScheduleLocked()->dump(out);
852 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500853 for (auto& [id, display] : mDisplays) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500854 if (id == mPacesetterDisplayId) {
Leon Scroggins III67388622023-02-06 20:36:20 -0500855 continue;
856 }
857 base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500858 display.schedulePtr->dump(out);
Leon Scroggins III67388622023-02-06 20:36:20 -0500859 }
Ady Abraham8735eac2020-08-12 16:35:04 -0700860}
861
Dominik Laskowskia8626ec2021-12-15 18:13:30 -0800862bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
Ady Abraham33a386b2023-07-18 15:37:11 -0700863 std::scoped_lock lock(mPolicyLock);
864 return updateFrameRateOverridesLocked(consideredSignals, displayRefreshRate);
865}
866
867bool Scheduler::updateFrameRateOverridesLocked(GlobalSignals consideredSignals,
868 Fps displayRefreshRate) {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400869 if (consideredSignals.idle) return false;
870
871 const auto frameRateOverrides =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500872 pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
873 displayRefreshRate, consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -0400874
875 // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
876 // the FrameRateOverrideMappings rather than here.
877 return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
878}
879
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500880void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400881 std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
882
883 {
884 std::scoped_lock lock(mDisplayLock);
885 pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
886 }
887
Leon Scroggins39d25342023-04-19 17:11:01 +0000888 applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400889}
890
891std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
892 std::optional<PhysicalDisplayId> pacesetterIdOpt) {
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500893 // TODO(b/241286431): Choose the pacesetter display.
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500894 mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500895 ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
Dominik Laskowski596a2562022-10-28 11:26:12 -0400896
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500897 std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
898 if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
899 const Display& pacesetter = *pacesetterOpt;
900
901 pacesetter.selectorPtr->setIdleTimerCallbacks(
Dominik Laskowski596a2562022-10-28 11:26:12 -0400902 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
903 .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
904 .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
905 .onExpired =
906 [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
907
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500908 pacesetter.selectorPtr->startIdleTimer();
Leon Scroggins III67388622023-02-06 20:36:20 -0500909
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500910 newVsyncSchedulePtr = pacesetter.schedulePtr;
911
ramindania04b8a52023-08-07 18:49:47 -0700912 const Fps refreshRate = pacesetter.selectorPtr->getActiveMode().modePtr->getVsyncRate();
Dominik Laskowski66295432023-03-14 12:25:36 -0400913 constexpr bool kForce = true;
914 newVsyncSchedulePtr->startPeriodTransition(refreshRate.getPeriod(), kForce);
Leon Scroggins III67388622023-02-06 20:36:20 -0500915 }
Dominik Laskowskic404cb42023-03-03 19:57:53 -0500916 return newVsyncSchedulePtr;
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400917}
Leon Scroggins III67388622023-02-06 20:36:20 -0500918
Leon Scroggins39d25342023-04-19 17:11:01 +0000919void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
920 onNewVsyncSchedule(vsyncSchedule->getDispatch());
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400921 std::vector<android::EventThread*> threads;
Leon Scroggins III67388622023-02-06 20:36:20 -0500922 {
923 std::lock_guard<std::mutex> lock(mConnectionsLock);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400924 threads.reserve(mConnections.size());
Leon Scroggins III67388622023-02-06 20:36:20 -0500925 for (auto& [_, connection] : mConnections) {
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400926 threads.push_back(connection.thread.get());
Leon Scroggins III67388622023-02-06 20:36:20 -0500927 }
Ady Abraham62a0be22020-12-08 16:54:10 -0800928 }
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400929 for (auto* thread : threads) {
Leon Scroggins39d25342023-04-19 17:11:01 +0000930 thread->onNewVsyncSchedule(vsyncSchedule);
Leon Scroggins III6fc45192023-03-16 12:13:28 -0400931 }
Dominik Laskowski596a2562022-10-28 11:26:12 -0400932}
933
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500934void Scheduler::demotePacesetterDisplay() {
Dominik Laskowski596a2562022-10-28 11:26:12 -0400935 // No need to lock for reads on kMainThreadContext.
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500936 if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
937 pacesetterPtr->stopIdleTimer();
938 pacesetterPtr->clearIdleTimerCallbacks();
Dominik Laskowski596a2562022-10-28 11:26:12 -0400939 }
940
Leon Scroggins III1af0fb62023-03-02 14:21:44 -0500941 // Clear state that depends on the pacesetter's RefreshRateSelector.
Dominik Laskowski596a2562022-10-28 11:26:12 -0400942 std::scoped_lock lock(mPolicyLock);
943 mPolicy = {};
Ady Abraham62a0be22020-12-08 16:54:10 -0800944}
945
Ady Abraham822ecbd2023-07-07 16:16:09 -0700946void Scheduler::updateAttachedChoreographersFrameRate(
947 const surfaceflinger::frontend::RequestedLayerState& layer, Fps fps) {
948 std::scoped_lock lock(mChoreographerLock);
949
950 const auto layerId = static_cast<int32_t>(layer.id);
951 const auto choreographers = mAttachedChoreographers.find(layerId);
952 if (choreographers == mAttachedChoreographers.end()) {
953 return;
954 }
955
956 auto& layerChoreographers = choreographers->second;
957
958 layerChoreographers.frameRate = fps;
959 ATRACE_FORMAT_INSTANT("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
960 ALOGV("%s: %s for %s", __func__, to_string(fps).c_str(), layer.name.c_str());
961
962 auto it = layerChoreographers.connections.begin();
963 while (it != layerChoreographers.connections.end()) {
964 sp<EventThreadConnection> choreographerConnection = it->promote();
965 if (choreographerConnection) {
966 choreographerConnection->frameRate = fps;
967 it++;
968 } else {
969 it = choreographers->second.connections.erase(it);
970 }
971 }
972
973 if (layerChoreographers.connections.empty()) {
974 mAttachedChoreographers.erase(choreographers);
975 }
976}
977
978int Scheduler::updateAttachedChoreographersInternal(
979 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate,
980 int parentDivisor) {
981 const char* name = layerHierarchy.getLayer() ? layerHierarchy.getLayer()->name.c_str() : "Root";
982
983 int divisor = 0;
984 if (layerHierarchy.getLayer()) {
985 const auto frameRateCompatibility = layerHierarchy.getLayer()->frameRateCompatibility;
986 const auto frameRate = Fps::fromValue(layerHierarchy.getLayer()->frameRate);
987 ALOGV("%s: %s frameRate %s parentDivisor=%d", __func__, name, to_string(frameRate).c_str(),
988 parentDivisor);
989
990 if (frameRate.isValid()) {
991 if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_FIXED_SOURCE ||
992 frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_EXACT) {
993 // Since this layer wants an exact match, we would only set a frame rate if the
994 // desired rate is a divisor of the display refresh rate.
995 divisor = RefreshRateSelector::getFrameRateDivisor(displayRefreshRate, frameRate);
996 } else if (frameRateCompatibility == ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT) {
997 // find the closest frame rate divisor for the desired frame rate.
998 divisor = static_cast<int>(
999 std::round(displayRefreshRate.getValue() / frameRate.getValue()));
1000 }
1001 }
1002 }
1003
1004 // We start by traversing the children, updating their choreographers, and getting back the
1005 // aggregated frame rate.
1006 int childrenDivisor = 0;
1007 for (const auto& [child, _] : layerHierarchy.mChildren) {
1008 LOG_ALWAYS_FATAL_IF(child == nullptr || child->getLayer() == nullptr);
1009
1010 ALOGV("%s: %s traversing child %s", __func__, name, child->getLayer()->name.c_str());
1011
1012 const int childDivisor =
1013 updateAttachedChoreographersInternal(*child, displayRefreshRate, divisor);
1014 childrenDivisor = childrenDivisor > 0 ? childrenDivisor : childDivisor;
1015 if (childDivisor > 0) {
1016 childrenDivisor = std::gcd(childrenDivisor, childDivisor);
1017 }
1018 ALOGV("%s: %s childrenDivisor=%d", __func__, name, childrenDivisor);
1019 }
1020
1021 ALOGV("%s: %s divisor=%d", __func__, name, divisor);
1022
1023 // If there is no explicit vote for this layer. Use the children's vote if exists
1024 divisor = (divisor == 0) ? childrenDivisor : divisor;
1025 ALOGV("%s: %s divisor=%d with children", __func__, name, divisor);
1026
1027 // If there is no explicit vote for this layer or its children, Use the parent vote if exists
1028 divisor = (divisor == 0) ? parentDivisor : divisor;
1029 ALOGV("%s: %s divisor=%d with parent", __func__, name, divisor);
1030
1031 if (layerHierarchy.getLayer()) {
1032 Fps fps = divisor > 1 ? displayRefreshRate / (unsigned int)divisor : Fps();
1033 updateAttachedChoreographersFrameRate(*layerHierarchy.getLayer(), fps);
1034 }
1035
1036 return divisor;
1037}
1038
1039void Scheduler::updateAttachedChoreographers(
1040 const surfaceflinger::frontend::LayerHierarchy& layerHierarchy, Fps displayRefreshRate) {
1041 ATRACE_CALL();
1042 updateAttachedChoreographersInternal(layerHierarchy, displayRefreshRate, 0);
1043}
1044
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001045template <typename S, typename T>
1046auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
Ady Abraham73c3df52023-01-12 18:09:31 -08001047 ATRACE_CALL();
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001048 std::vector<display::DisplayModeRequest> modeRequests;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001049 GlobalSignals consideredSignals;
1050
Ady Abraham62a0be22020-12-08 16:54:10 -08001051 bool refreshRateChanged = false;
1052 bool frameRateOverridesChanged;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001053
Ady Abraham8532d012019-05-08 14:50:56 -07001054 {
Dominik Laskowski596a2562022-10-28 11:26:12 -04001055 std::scoped_lock lock(mPolicyLock);
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001056
1057 auto& currentState = mPolicy.*statePtr;
1058 if (currentState == newState) return {};
1059 currentState = std::forward<T>(newState);
1060
Dominik Laskowski596a2562022-10-28 11:26:12 -04001061 DisplayModeChoiceMap modeChoices;
Ady Abrahamace3d052022-11-17 16:25:05 -08001062 ftl::Optional<FrameRateMode> modeOpt;
Dominik Laskowski596a2562022-10-28 11:26:12 -04001063 {
1064 std::scoped_lock lock(mDisplayLock);
1065 ftl::FakeGuard guard(kMainThreadContext);
1066
1067 modeChoices = chooseDisplayModes();
1068
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001069 // TODO(b/240743786): The pacesetter display's mode must change for any
1070 // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
1071 // and timers.
Ady Abrahamace3d052022-11-17 16:25:05 -08001072 std::tie(modeOpt, consideredSignals) =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001073 modeChoices.get(*mPacesetterDisplayId)
Dominik Laskowski596a2562022-10-28 11:26:12 -04001074 .transform([](const DisplayModeChoice& choice) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001075 return std::make_pair(choice.mode, choice.consideredSignals);
Dominik Laskowski596a2562022-10-28 11:26:12 -04001076 })
1077 .value();
1078 }
ramindani69b58e82022-09-26 16:48:36 -07001079
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001080 modeRequests.reserve(modeChoices.size());
1081 for (auto& [id, choice] : modeChoices) {
1082 modeRequests.emplace_back(
Ady Abrahamace3d052022-11-17 16:25:05 -08001083 display::DisplayModeRequest{.mode = std::move(choice.mode),
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001084 .emitEvent = !choice.consideredSignals.idle});
1085 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001086
Ady Abraham33a386b2023-07-18 15:37:11 -07001087 frameRateOverridesChanged = updateFrameRateOverridesLocked(consideredSignals, modeOpt->fps);
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001088
Ady Abrahamace3d052022-11-17 16:25:05 -08001089 if (mPolicy.modeOpt != modeOpt) {
1090 mPolicy.modeOpt = modeOpt;
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001091 refreshRateChanged = true;
1092 } else {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001093 // We don't need to change the display mode, but we might need to send an event
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001094 // about a mode change, since it was suppressed if previously considered idle.
Ady Abrahamdfd62162020-06-10 16:11:56 -07001095 if (!consideredSignals.idle) {
Marin Shalamanova7fe3042021-01-29 21:02:08 +01001096 dispatchCachedReportedMode();
Ady Abrahamdfd62162020-06-10 16:11:56 -07001097 }
Ady Abraham8532d012019-05-08 14:50:56 -07001098 }
Ady Abraham8532d012019-05-08 14:50:56 -07001099 }
Ady Abraham62a0be22020-12-08 16:54:10 -08001100 if (refreshRateChanged) {
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001101 mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
Ady Abraham62a0be22020-12-08 16:54:10 -08001102 }
1103 if (frameRateOverridesChanged) {
1104 mSchedulerCallback.triggerOnFrameRateOverridesChanged();
1105 }
Dominik Laskowski0c41ffa2021-12-24 16:45:12 -08001106 return consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -07001107}
1108
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001109auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
Ady Abraham4ccdcb42020-02-11 17:34:34 -08001110 ATRACE_CALL();
Ady Abraham09bd3922019-04-08 10:44:56 -07001111
Ady Abraham68636062022-11-16 17:07:25 -08001112 using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
Dominik Laskowski6b049ff2023-01-29 15:46:45 -05001113 ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
Dominik Laskowski01602522022-10-07 19:02:28 -04001114 const auto globalSignals = makeGlobalSignals();
ramindani22f2ead2023-04-21 10:27:11 -07001115 Fps pacesetterFps;
Dominik Laskowskia8626ec2021-12-15 18:13:30 -08001116
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001117 for (const auto& [id, display] : mDisplays) {
Ady Abrahamace3d052022-11-17 16:25:05 -08001118 auto rankedFrameRates =
Dominik Laskowskic404cb42023-03-03 19:57:53 -05001119 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
1120 globalSignals);
ramindani22f2ead2023-04-21 10:27:11 -07001121 if (id == *mPacesetterDisplayId) {
1122 pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
Dominik Laskowski01602522022-10-07 19:02:28 -04001123 }
Ady Abrahamace3d052022-11-17 16:25:05 -08001124 perDisplayRanking.push_back(std::move(rankedFrameRates));
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001125 }
ramindani69b58e82022-09-26 16:48:36 -07001126
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001127 DisplayModeChoiceMap modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001128 using fps_approx_ops::operator==;
Dominik Laskowski01602522022-10-07 19:02:28 -04001129
ramindani22f2ead2023-04-21 10:27:11 -07001130 for (auto& [rankings, signals] : perDisplayRanking) {
1131 const auto chosenFrameRateMode =
1132 ftl::find_if(rankings,
1133 [&](const auto& ranking) {
1134 return ranking.frameRateMode.fps == pacesetterFps;
1135 })
1136 .transform([](const auto& scoredFrameRate) {
1137 return scoredFrameRate.get().frameRateMode;
1138 })
1139 .value_or(rankings.front().frameRateMode);
Dominik Laskowski01602522022-10-07 19:02:28 -04001140
ramindani22f2ead2023-04-21 10:27:11 -07001141 modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
1142 DisplayModeChoice{chosenFrameRateMode, signals});
Dominik Laskowski01602522022-10-07 19:02:28 -04001143 }
Dominik Laskowski530d6bd2022-10-10 16:55:54 -04001144 return modeChoices;
ramindani69b58e82022-09-26 16:48:36 -07001145}
1146
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001147GlobalSignals Scheduler::makeGlobalSignals() const {
ramindani38c84982022-08-29 18:02:57 +00001148 const bool powerOnImminent = mDisplayPowerTimer &&
1149 (mPolicy.displayPowerMode != hal::PowerMode::ON ||
1150 mPolicy.displayPowerTimer == TimerState::Reset);
Ady Abraham6fe2c172019-07-12 12:37:57 -07001151
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001152 return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
1153 .idle = mPolicy.idleTimer == TimerState::Expired,
1154 .powerOnImminent = powerOnImminent};
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001155}
1156
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001157FrameRateMode Scheduler::getPreferredDisplayMode() {
Dominik Laskowski068173d2021-08-11 17:22:59 -07001158 std::lock_guard<std::mutex> lock(mPolicyLock);
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001159 const auto frameRateMode =
Leon Scroggins III1af0fb62023-03-02 14:21:44 -05001160 pacesetterSelectorPtr()
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001161 ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
1162 .ranking.front()
1163 .frameRateMode;
Dominik Laskowski95df6a12022-10-07 18:11:07 -04001164
Dominik Laskowskifc378b02022-12-02 14:56:05 -05001165 // Make sure the stored mode is up to date.
1166 mPolicy.modeOpt = frameRateMode;
1167
1168 return frameRateMode;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -07001169}
1170
Peiyong Line9d809e2020-04-14 13:10:48 -07001171void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001172 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1173 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1174
1175 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1176 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1177 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1178 }
1179}
1180
Leon Scroggins III5b581492023-10-31 14:29:41 -04001181bool Scheduler::onCompositionPresented(nsecs_t presentTime) {
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001182 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1183 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1184 if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1185 // We need to composite again as refreshTimeNanos is still in the future.
1186 return true;
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001187 }
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001188
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001189 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001190 }
Dominik Laskowskidd5827a2022-03-17 12:44:23 -07001191 return false;
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001192}
1193
Ady Abraham7825c682021-05-17 15:12:14 -07001194void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
Dominik Laskowski9c93d602021-10-07 19:38:26 -07001195 mLayerHistory.setDisplayArea(displayArea);
Ady Abraham8a82ba62020-01-17 12:43:17 -08001196}
1197
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001198void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
1199 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1200 return;
1201 }
1202
1203 mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1204}
1205
Ady Abraham62a0be22020-12-08 16:54:10 -08001206void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1207 if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1208 return;
1209 }
1210
Andy Yu2ae6b6b2021-11-18 14:51:06 -08001211 mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
Ady Abraham62a0be22020-12-08 16:54:10 -08001212}
1213
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001214void Scheduler::updateSmallAreaDetection(
Tony Huangf3621102023-09-04 17:14:22 +08001215 std::vector<std::pair<int32_t, float>>& uidThresholdMappings) {
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001216 mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1217}
1218
Tony Huangf3621102023-09-04 17:14:22 +08001219void Scheduler::setSmallAreaDetectionThreshold(int32_t appId, float threshold) {
1220 mSmallAreaDetectionAllowMappings.setThesholdForAppId(appId, threshold);
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001221}
1222
Tony Huangf3621102023-09-04 17:14:22 +08001223bool Scheduler::isSmallDirtyArea(int32_t appId, uint32_t dirtyArea) {
1224 std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForAppId(appId);
1225 if (oThreshold) {
1226 return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1227 }
Tony Huang9ac5e6e2023-08-24 09:01:44 +00001228 return false;
1229}
1230
Dominik Laskowski068173d2021-08-11 17:22:59 -07001231} // namespace android::scheduler