• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 
17 #undef LOG_TAG
18 #define LOG_TAG "Scheduler"
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 
21 #include "Scheduler.h"
22 
23 #include <android-base/properties.h>
24 #include <android-base/stringprintf.h>
25 #include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26 #include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
27 #include <configstore/Utils.h>
28 #include <ftl/concat.h>
29 #include <ftl/enum.h>
30 #include <ftl/fake_guard.h>
31 #include <ftl/small_map.h>
32 #include <gui/TraceUtils.h>
33 #include <gui/WindowInfo.h>
34 #include <system/window.h>
35 #include <ui/DisplayMap.h>
36 #include <utils/Timers.h>
37 
38 #include <FrameTimeline/FrameTimeline.h>
39 #include <scheduler/interface/ICompositor.h>
40 
41 #include <algorithm>
42 #include <cinttypes>
43 #include <cstdint>
44 #include <functional>
45 #include <memory>
46 #include <numeric>
47 
48 #include "../Layer.h"
49 #include "EventThread.h"
50 #include "FrameRateOverrideMappings.h"
51 #include "FrontEnd/LayerHandle.h"
52 #include "OneShotTimer.h"
53 #include "SurfaceFlingerProperties.h"
54 #include "VSyncTracker.h"
55 #include "VsyncController.h"
56 #include "VsyncSchedule.h"
57 
58 #define RETURN_IF_INVALID_HANDLE(handle, ...)                        \
59     do {                                                             \
60         if (mConnections.count(handle) == 0) {                       \
61             ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
62             return __VA_ARGS__;                                      \
63         }                                                            \
64     } while (false)
65 
66 namespace android::scheduler {
67 
Scheduler(ICompositor & compositor,ISchedulerCallback & callback,FeatureFlags features,sp<VsyncModulator> modulatorPtr)68 Scheduler::Scheduler(ICompositor& compositor, ISchedulerCallback& callback, FeatureFlags features,
69                      sp<VsyncModulator> modulatorPtr)
70       : impl::MessageQueue(compositor),
71         mFeatures(features),
72         mVsyncModulator(std::move(modulatorPtr)),
73         mSchedulerCallback(callback) {}
74 
~Scheduler()75 Scheduler::~Scheduler() {
76     // MessageQueue depends on VsyncSchedule, so first destroy it.
77     // Otherwise, MessageQueue will get destroyed after Scheduler's dtor,
78     // which will cause a use-after-free issue.
79     Impl::destroyVsync();
80 
81     // Stop timers and wait for their threads to exit.
82     mDisplayPowerTimer.reset();
83     mTouchTimer.reset();
84 
85     // Stop idle timer and clear callbacks, as the RefreshRateSelector may outlive the Scheduler.
86     demotePacesetterDisplay();
87 }
88 
startTimers()89 void Scheduler::startTimers() {
90     using namespace sysprop;
91     using namespace std::string_literals;
92 
93     if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
94         // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
95         mTouchTimer.emplace(
96                 "TouchTimer", std::chrono::milliseconds(millis),
97                 [this] { touchTimerCallback(TimerState::Reset); },
98                 [this] { touchTimerCallback(TimerState::Expired); });
99         mTouchTimer->start();
100     }
101 
102     if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
103         mDisplayPowerTimer.emplace(
104                 "DisplayPowerTimer", std::chrono::milliseconds(millis),
105                 [this] { displayPowerTimerCallback(TimerState::Reset); },
106                 [this] { displayPowerTimerCallback(TimerState::Expired); });
107         mDisplayPowerTimer->start();
108     }
109 }
110 
setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt)111 void Scheduler::setPacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
112     demotePacesetterDisplay();
113 
114     promotePacesetterDisplay(pacesetterIdOpt);
115 }
116 
registerDisplay(PhysicalDisplayId displayId,RefreshRateSelectorPtr selectorPtr)117 void Scheduler::registerDisplay(PhysicalDisplayId displayId, RefreshRateSelectorPtr selectorPtr) {
118     auto schedulePtr = std::make_shared<VsyncSchedule>(displayId, mFeatures,
119                                                        [this](PhysicalDisplayId id, bool enable) {
120                                                            onHardwareVsyncRequest(id, enable);
121                                                        });
122 
123     registerDisplayInternal(displayId, std::move(selectorPtr), std::move(schedulePtr));
124 }
125 
registerDisplayInternal(PhysicalDisplayId displayId,RefreshRateSelectorPtr selectorPtr,VsyncSchedulePtr schedulePtr)126 void Scheduler::registerDisplayInternal(PhysicalDisplayId displayId,
127                                         RefreshRateSelectorPtr selectorPtr,
128                                         VsyncSchedulePtr schedulePtr) {
129     demotePacesetterDisplay();
130 
131     auto [pacesetterVsyncSchedule, isNew] = [&]() FTL_FAKE_GUARD(kMainThreadContext) {
132         std::scoped_lock lock(mDisplayLock);
133         const bool isNew = mDisplays
134                                    .emplace_or_replace(displayId, displayId, std::move(selectorPtr),
135                                                        std::move(schedulePtr), mFeatures)
136                                    .second;
137 
138         return std::make_pair(promotePacesetterDisplayLocked(), isNew);
139     }();
140 
141     applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
142 
143     // Disable hardware VSYNC if the registration is new, as opposed to a renewal.
144     if (isNew) {
145         onHardwareVsyncRequest(displayId, false);
146     }
147 }
148 
unregisterDisplay(PhysicalDisplayId displayId)149 void Scheduler::unregisterDisplay(PhysicalDisplayId displayId) {
150     demotePacesetterDisplay();
151 
152     std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
153     {
154         std::scoped_lock lock(mDisplayLock);
155         mDisplays.erase(displayId);
156 
157         // Do not allow removing the final display. Code in the scheduler expects
158         // there to be at least one display. (This may be relaxed in the future with
159         // headless virtual display.)
160         LOG_ALWAYS_FATAL_IF(mDisplays.empty(), "Cannot unregister all displays!");
161 
162         pacesetterVsyncSchedule = promotePacesetterDisplayLocked();
163     }
164     applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
165 }
166 
run()167 void Scheduler::run() {
168     while (true) {
169         waitMessage();
170     }
171 }
172 
onFrameSignal(ICompositor & compositor,VsyncId vsyncId,TimePoint expectedVsyncTime)173 void Scheduler::onFrameSignal(ICompositor& compositor, VsyncId vsyncId,
174                               TimePoint expectedVsyncTime) {
175     const FrameTargeter::BeginFrameArgs beginFrameArgs =
176             {.frameBeginTime = SchedulerClock::now(),
177              .vsyncId = vsyncId,
178              // TODO(b/255601557): Calculate per display.
179              .expectedVsyncTime = expectedVsyncTime,
180              .sfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration};
181 
182     LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId);
183     const auto pacesetterId = *mPacesetterDisplayId;
184     const auto pacesetterOpt = mDisplays.get(pacesetterId);
185 
186     FrameTargeter& pacesetterTargeter = *pacesetterOpt->get().targeterPtr;
187     pacesetterTargeter.beginFrame(beginFrameArgs, *pacesetterOpt->get().schedulePtr);
188 
189     FrameTargets targets;
190     targets.try_emplace(pacesetterId, &pacesetterTargeter.target());
191 
192     for (const auto& [id, display] : mDisplays) {
193         if (id == pacesetterId) continue;
194 
195         const FrameTargeter& targeter = *display.targeterPtr;
196         targets.try_emplace(id, &targeter.target());
197     }
198 
199     if (!compositor.commit(pacesetterId, targets)) return;
200 
201     // TODO(b/256196556): Choose the frontrunner display.
202     FrameTargeters targeters;
203     targeters.try_emplace(pacesetterId, &pacesetterTargeter);
204 
205     for (auto& [id, display] : mDisplays) {
206         if (id == pacesetterId) continue;
207 
208         FrameTargeter& targeter = *display.targeterPtr;
209         targeter.beginFrame(beginFrameArgs, *display.schedulePtr);
210 
211         targeters.try_emplace(id, &targeter);
212     }
213 
214     const auto resultsPerDisplay = compositor.composite(pacesetterId, targeters);
215     compositor.sample();
216 
217     for (const auto& [id, targeter] : targeters) {
218         const auto resultOpt = resultsPerDisplay.get(id);
219         LOG_ALWAYS_FATAL_IF(!resultOpt);
220         targeter->endFrame(*resultOpt);
221     }
222 }
223 
getFrameRateOverride(uid_t uid) const224 std::optional<Fps> Scheduler::getFrameRateOverride(uid_t uid) const {
225     const bool supportsFrameRateOverrideByContent =
226             pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
227     return mFrameRateOverrideMappings
228             .getFrameRateOverrideForUid(uid, supportsFrameRateOverrideByContent);
229 }
230 
isVsyncValid(TimePoint expectedVsyncTime,uid_t uid) const231 bool Scheduler::isVsyncValid(TimePoint expectedVsyncTime, uid_t uid) const {
232     const auto frameRate = getFrameRateOverride(uid);
233     if (!frameRate.has_value()) {
234         return true;
235     }
236 
237     ATRACE_FORMAT("%s uid: %d frameRate: %s", __func__, uid, to_string(*frameRate).c_str());
238     return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), *frameRate);
239 }
240 
isVsyncInPhase(TimePoint expectedVsyncTime,Fps frameRate) const241 bool Scheduler::isVsyncInPhase(TimePoint expectedVsyncTime, Fps frameRate) const {
242     return getVsyncSchedule()->getTracker().isVSyncInPhase(expectedVsyncTime.ns(), frameRate);
243 }
244 
makeThrottleVsyncCallback() const245 impl::EventThread::ThrottleVsyncCallback Scheduler::makeThrottleVsyncCallback() const {
246     return [this](nsecs_t expectedVsyncTime, uid_t uid) {
247         return !isVsyncValid(TimePoint::fromNs(expectedVsyncTime), uid);
248     };
249 }
250 
makeGetVsyncPeriodFunction() const251 impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
252     return [this](uid_t uid) {
253         const auto [refreshRate, period] = [this] {
254             std::scoped_lock lock(mDisplayLock);
255             const auto pacesetterOpt = pacesetterDisplayLocked();
256             LOG_ALWAYS_FATAL_IF(!pacesetterOpt);
257             const Display& pacesetter = *pacesetterOpt;
258             return std::make_pair(pacesetter.selectorPtr->getActiveMode().fps,
259                                   pacesetter.schedulePtr->period());
260         }();
261 
262         const Period currentPeriod = period != Period::zero() ? period : refreshRate.getPeriod();
263 
264         const auto frameRate = getFrameRateOverride(uid);
265         if (!frameRate.has_value()) {
266             return currentPeriod.ns();
267         }
268 
269         const auto divisor = RefreshRateSelector::getFrameRateDivisor(refreshRate, *frameRate);
270         if (divisor <= 1) {
271             return currentPeriod.ns();
272         }
273         return currentPeriod.ns() * divisor;
274     };
275 }
276 
createEventThread(Cycle cycle,frametimeline::TokenManager * tokenManager,std::chrono::nanoseconds workDuration,std::chrono::nanoseconds readyDuration)277 ConnectionHandle Scheduler::createEventThread(Cycle cycle,
278                                               frametimeline::TokenManager* tokenManager,
279                                               std::chrono::nanoseconds workDuration,
280                                               std::chrono::nanoseconds readyDuration) {
281     auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
282                                                            getVsyncSchedule(), tokenManager,
283                                                            makeThrottleVsyncCallback(),
284                                                            makeGetVsyncPeriodFunction(),
285                                                            workDuration, readyDuration);
286 
287     auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
288     handle = createConnection(std::move(eventThread));
289     return handle;
290 }
291 
createConnection(std::unique_ptr<EventThread> eventThread)292 ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
293     const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
294     ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
295 
296     auto connection = createConnectionInternal(eventThread.get());
297 
298     std::lock_guard<std::mutex> lock(mConnectionsLock);
299     mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
300     return handle;
301 }
302 
createConnectionInternal(EventThread * eventThread,EventRegistrationFlags eventRegistration,const sp<IBinder> & layerHandle)303 sp<EventThreadConnection> Scheduler::createConnectionInternal(
304         EventThread* eventThread, EventRegistrationFlags eventRegistration,
305         const sp<IBinder>& layerHandle) {
306     int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
307     auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
308     mLayerHistory.attachChoreographer(layerId, connection);
309     return connection;
310 }
311 
createDisplayEventConnection(ConnectionHandle handle,EventRegistrationFlags eventRegistration,const sp<IBinder> & layerHandle)312 sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
313         ConnectionHandle handle, EventRegistrationFlags eventRegistration,
314         const sp<IBinder>& layerHandle) {
315     std::lock_guard<std::mutex> lock(mConnectionsLock);
316     RETURN_IF_INVALID_HANDLE(handle, nullptr);
317     return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration,
318                                     layerHandle);
319 }
320 
getEventConnection(ConnectionHandle handle)321 sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
322     std::lock_guard<std::mutex> lock(mConnectionsLock);
323     RETURN_IF_INVALID_HANDLE(handle, nullptr);
324     return mConnections[handle].connection;
325 }
326 
onHotplugReceived(ConnectionHandle handle,PhysicalDisplayId displayId,bool connected)327 void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
328                                   bool connected) {
329     android::EventThread* thread;
330     {
331         std::lock_guard<std::mutex> lock(mConnectionsLock);
332         RETURN_IF_INVALID_HANDLE(handle);
333         thread = mConnections[handle].thread.get();
334     }
335 
336     thread->onHotplugReceived(displayId, connected);
337 }
338 
enableSyntheticVsync(bool enable)339 void Scheduler::enableSyntheticVsync(bool enable) {
340     // TODO(b/241285945): Remove connection handles.
341     const ConnectionHandle handle = mAppConnectionHandle;
342     android::EventThread* thread;
343     {
344         std::lock_guard<std::mutex> lock(mConnectionsLock);
345         RETURN_IF_INVALID_HANDLE(handle);
346         thread = mConnections[handle].thread.get();
347     }
348     thread->enableSyntheticVsync(enable);
349 }
350 
onFrameRateOverridesChanged(ConnectionHandle handle,PhysicalDisplayId displayId)351 void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId) {
352     const bool supportsFrameRateOverrideByContent =
353             pacesetterSelectorPtr()->supportsAppFrameRateOverrideByContent();
354 
355     std::vector<FrameRateOverride> overrides =
356             mFrameRateOverrideMappings.getAllFrameRateOverrides(supportsFrameRateOverrideByContent);
357 
358     android::EventThread* thread;
359     {
360         std::lock_guard lock(mConnectionsLock);
361         RETURN_IF_INVALID_HANDLE(handle);
362         thread = mConnections[handle].thread.get();
363     }
364     thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
365 }
366 
onPrimaryDisplayModeChanged(ConnectionHandle handle,const FrameRateMode & mode)367 void Scheduler::onPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
368     {
369         std::lock_guard<std::mutex> lock(mPolicyLock);
370         // Cache the last reported modes for primary display.
371         mPolicy.cachedModeChangedParams = {handle, mode};
372 
373         // Invalidate content based refresh rate selection so it could be calculated
374         // again for the new refresh rate.
375         mPolicy.contentRequirements.clear();
376     }
377     onNonPrimaryDisplayModeChanged(handle, mode);
378 }
379 
dispatchCachedReportedMode()380 void Scheduler::dispatchCachedReportedMode() {
381     // Check optional fields first.
382     if (!mPolicy.modeOpt) {
383         ALOGW("No mode ID found, not dispatching cached mode.");
384         return;
385     }
386     if (!mPolicy.cachedModeChangedParams) {
387         ALOGW("No mode changed params found, not dispatching cached mode.");
388         return;
389     }
390 
391     // If the mode is not the current mode, this means that a
392     // mode change is in progress. In that case we shouldn't dispatch an event
393     // as it will be dispatched when the current mode changes.
394     if (pacesetterSelectorPtr()->getActiveMode() != mPolicy.modeOpt) {
395         return;
396     }
397 
398     // If there is no change from cached mode, there is no need to dispatch an event
399     if (*mPolicy.modeOpt == mPolicy.cachedModeChangedParams->mode) {
400         return;
401     }
402 
403     mPolicy.cachedModeChangedParams->mode = *mPolicy.modeOpt;
404     onNonPrimaryDisplayModeChanged(mPolicy.cachedModeChangedParams->handle,
405                                    mPolicy.cachedModeChangedParams->mode);
406 }
407 
onNonPrimaryDisplayModeChanged(ConnectionHandle handle,const FrameRateMode & mode)408 void Scheduler::onNonPrimaryDisplayModeChanged(ConnectionHandle handle, const FrameRateMode& mode) {
409     android::EventThread* thread;
410     {
411         std::lock_guard<std::mutex> lock(mConnectionsLock);
412         RETURN_IF_INVALID_HANDLE(handle);
413         thread = mConnections[handle].thread.get();
414     }
415     thread->onModeChanged(mode);
416 }
417 
getEventThreadConnectionCount(ConnectionHandle handle)418 size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
419     std::lock_guard<std::mutex> lock(mConnectionsLock);
420     RETURN_IF_INVALID_HANDLE(handle, 0);
421     return mConnections[handle].thread->getEventThreadConnectionCount();
422 }
423 
dump(ConnectionHandle handle,std::string & result) const424 void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
425     android::EventThread* thread;
426     {
427         std::lock_guard<std::mutex> lock(mConnectionsLock);
428         RETURN_IF_INVALID_HANDLE(handle);
429         thread = mConnections.at(handle).thread.get();
430     }
431     thread->dump(result);
432 }
433 
setDuration(ConnectionHandle handle,std::chrono::nanoseconds workDuration,std::chrono::nanoseconds readyDuration)434 void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
435                             std::chrono::nanoseconds readyDuration) {
436     android::EventThread* thread;
437     {
438         std::lock_guard<std::mutex> lock(mConnectionsLock);
439         RETURN_IF_INVALID_HANDLE(handle);
440         thread = mConnections[handle].thread.get();
441     }
442     thread->setDuration(workDuration, readyDuration);
443 }
444 
setVsyncConfigSet(const VsyncConfigSet & configs,Period vsyncPeriod)445 void Scheduler::setVsyncConfigSet(const VsyncConfigSet& configs, Period vsyncPeriod) {
446     setVsyncConfig(mVsyncModulator->setVsyncConfigSet(configs), vsyncPeriod);
447 }
448 
setVsyncConfig(const VsyncConfig & config,Period vsyncPeriod)449 void Scheduler::setVsyncConfig(const VsyncConfig& config, Period vsyncPeriod) {
450     setDuration(mAppConnectionHandle,
451                 /* workDuration */ config.appWorkDuration,
452                 /* readyDuration */ config.sfWorkDuration);
453     setDuration(mSfConnectionHandle,
454                 /* workDuration */ vsyncPeriod,
455                 /* readyDuration */ config.sfWorkDuration);
456     setDuration(config.sfWorkDuration);
457 }
458 
enableHardwareVsync(PhysicalDisplayId id)459 void Scheduler::enableHardwareVsync(PhysicalDisplayId id) {
460     auto schedule = getVsyncSchedule(id);
461     LOG_ALWAYS_FATAL_IF(!schedule);
462     schedule->enableHardwareVsync();
463 }
464 
disableHardwareVsync(PhysicalDisplayId id,bool disallow)465 void Scheduler::disableHardwareVsync(PhysicalDisplayId id, bool disallow) {
466     auto schedule = getVsyncSchedule(id);
467     LOG_ALWAYS_FATAL_IF(!schedule);
468     schedule->disableHardwareVsync(disallow);
469 }
470 
resyncAllToHardwareVsync(bool allowToEnable)471 void Scheduler::resyncAllToHardwareVsync(bool allowToEnable) {
472     ATRACE_CALL();
473     std::scoped_lock lock(mDisplayLock);
474     ftl::FakeGuard guard(kMainThreadContext);
475 
476     for (const auto& [id, _] : mDisplays) {
477         resyncToHardwareVsyncLocked(id, allowToEnable);
478     }
479 }
480 
resyncToHardwareVsyncLocked(PhysicalDisplayId id,bool allowToEnable,std::optional<Fps> refreshRate)481 void Scheduler::resyncToHardwareVsyncLocked(PhysicalDisplayId id, bool allowToEnable,
482                                             std::optional<Fps> refreshRate) {
483     const auto displayOpt = mDisplays.get(id);
484     if (!displayOpt) {
485         ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
486         return;
487     }
488     const Display& display = *displayOpt;
489 
490     if (display.schedulePtr->isHardwareVsyncAllowed(allowToEnable)) {
491         if (!refreshRate) {
492             refreshRate = display.selectorPtr->getActiveMode().modePtr->getFps();
493         }
494         if (refreshRate->isValid()) {
495             constexpr bool kForce = false;
496             display.schedulePtr->startPeriodTransition(refreshRate->getPeriod(), kForce);
497         }
498     }
499 }
500 
onHardwareVsyncRequest(PhysicalDisplayId id,bool enabled)501 void Scheduler::onHardwareVsyncRequest(PhysicalDisplayId id, bool enabled) {
502     static const auto& whence = __func__;
503     ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
504 
505     // On main thread to serialize reads/writes of pending hardware VSYNC state.
506     static_cast<void>(
507             schedule([=]() FTL_FAKE_GUARD(mDisplayLock) FTL_FAKE_GUARD(kMainThreadContext) {
508                 ATRACE_NAME(ftl::Concat(whence, ' ', id.value, ' ', enabled).c_str());
509 
510                 if (const auto displayOpt = mDisplays.get(id)) {
511                     auto& display = displayOpt->get();
512                     display.schedulePtr->setPendingHardwareVsyncState(enabled);
513 
514                     if (display.powerMode != hal::PowerMode::OFF) {
515                         mSchedulerCallback.requestHardwareVsync(id, enabled);
516                     }
517                 }
518             }));
519 }
520 
setRenderRate(PhysicalDisplayId id,Fps renderFrameRate)521 void Scheduler::setRenderRate(PhysicalDisplayId id, Fps renderFrameRate) {
522     std::scoped_lock lock(mDisplayLock);
523     ftl::FakeGuard guard(kMainThreadContext);
524 
525     const auto displayOpt = mDisplays.get(id);
526     if (!displayOpt) {
527         ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
528         return;
529     }
530     const Display& display = *displayOpt;
531     const auto mode = display.selectorPtr->getActiveMode();
532 
533     using fps_approx_ops::operator!=;
534     LOG_ALWAYS_FATAL_IF(renderFrameRate != mode.fps,
535                         "Mismatch in render frame rates. Selector: %s, Scheduler: %s, Display: "
536                         "%" PRIu64,
537                         to_string(mode.fps).c_str(), to_string(renderFrameRate).c_str(), id.value);
538 
539     ALOGV("%s %s (%s)", __func__, to_string(mode.fps).c_str(),
540           to_string(mode.modePtr->getFps()).c_str());
541 
542     display.schedulePtr->getTracker().setRenderRate(renderFrameRate);
543 }
544 
resync()545 void Scheduler::resync() {
546     static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
547 
548     const nsecs_t now = systemTime();
549     const nsecs_t last = mLastResyncTime.exchange(now);
550 
551     if (now - last > kIgnoreDelay) {
552         resyncAllToHardwareVsync(false /* allowToEnable */);
553     }
554 }
555 
addResyncSample(PhysicalDisplayId id,nsecs_t timestamp,std::optional<nsecs_t> hwcVsyncPeriodIn)556 bool Scheduler::addResyncSample(PhysicalDisplayId id, nsecs_t timestamp,
557                                 std::optional<nsecs_t> hwcVsyncPeriodIn) {
558     const auto hwcVsyncPeriod = ftl::Optional(hwcVsyncPeriodIn).transform([](nsecs_t nanos) {
559         return Period::fromNs(nanos);
560     });
561     auto schedule = getVsyncSchedule(id);
562     if (!schedule) {
563         ALOGW("%s: Invalid display %s!", __func__, to_string(id).c_str());
564         return false;
565     }
566     return schedule->addResyncSample(TimePoint::fromNs(timestamp), hwcVsyncPeriod);
567 }
568 
addPresentFence(PhysicalDisplayId id,std::shared_ptr<FenceTime> fence)569 void Scheduler::addPresentFence(PhysicalDisplayId id, std::shared_ptr<FenceTime> fence) {
570     const auto scheduleOpt =
571             (ftl::FakeGuard(mDisplayLock), mDisplays.get(id)).and_then([](const Display& display) {
572                 return display.powerMode == hal::PowerMode::OFF
573                         ? std::nullopt
574                         : std::make_optional(display.schedulePtr);
575             });
576 
577     if (!scheduleOpt) return;
578     const auto& schedule = scheduleOpt->get();
579 
580     if (const bool needMoreSignals = schedule->getController().addPresentFence(std::move(fence))) {
581         schedule->enableHardwareVsync();
582     } else {
583         constexpr bool kDisallow = false;
584         schedule->disableHardwareVsync(kDisallow);
585     }
586 }
587 
registerLayer(Layer * layer)588 void Scheduler::registerLayer(Layer* layer) {
589     // If the content detection feature is off, we still keep the layer history,
590     // since we use it for other features (like Frame Rate API), so layers
591     // still need to be registered.
592     mLayerHistory.registerLayer(layer, mFeatures.test(Feature::kContentDetection));
593 }
594 
deregisterLayer(Layer * layer)595 void Scheduler::deregisterLayer(Layer* layer) {
596     mLayerHistory.deregisterLayer(layer);
597 }
598 
recordLayerHistory(int32_t id,const LayerProps & layerProps,nsecs_t presentTime,LayerHistory::LayerUpdateType updateType)599 void Scheduler::recordLayerHistory(int32_t id, const LayerProps& layerProps, nsecs_t presentTime,
600                                    LayerHistory::LayerUpdateType updateType) {
601     if (pacesetterSelectorPtr()->canSwitch()) {
602         mLayerHistory.record(id, layerProps, presentTime, systemTime(), updateType);
603     }
604 }
605 
setModeChangePending(bool pending)606 void Scheduler::setModeChangePending(bool pending) {
607     mLayerHistory.setModeChangePending(pending);
608 }
609 
setDefaultFrameRateCompatibility(Layer * layer)610 void Scheduler::setDefaultFrameRateCompatibility(Layer* layer) {
611     mLayerHistory.setDefaultFrameRateCompatibility(layer,
612                                                    mFeatures.test(Feature::kContentDetection));
613 }
614 
chooseRefreshRateForContent()615 void Scheduler::chooseRefreshRateForContent() {
616     const auto selectorPtr = pacesetterSelectorPtr();
617     if (!selectorPtr->canSwitch()) return;
618 
619     ATRACE_CALL();
620 
621     LayerHistory::Summary summary = mLayerHistory.summarize(*selectorPtr, systemTime());
622     applyPolicy(&Policy::contentRequirements, std::move(summary));
623 }
624 
resetIdleTimer()625 void Scheduler::resetIdleTimer() {
626     pacesetterSelectorPtr()->resetIdleTimer();
627 }
628 
onTouchHint()629 void Scheduler::onTouchHint() {
630     if (mTouchTimer) {
631         mTouchTimer->reset();
632         pacesetterSelectorPtr()->resetKernelIdleTimer();
633     }
634 }
635 
setDisplayPowerMode(PhysicalDisplayId id,hal::PowerMode powerMode)636 void Scheduler::setDisplayPowerMode(PhysicalDisplayId id, hal::PowerMode powerMode) {
637     const bool isPacesetter = [this, id]() REQUIRES(kMainThreadContext) {
638         ftl::FakeGuard guard(mDisplayLock);
639         return id == mPacesetterDisplayId;
640     }();
641     if (isPacesetter) {
642         // TODO (b/255657128): This needs to be handled per display.
643         std::lock_guard<std::mutex> lock(mPolicyLock);
644         mPolicy.displayPowerMode = powerMode;
645     }
646     {
647         std::scoped_lock lock(mDisplayLock);
648 
649         const auto displayOpt = mDisplays.get(id);
650         LOG_ALWAYS_FATAL_IF(!displayOpt);
651         auto& display = displayOpt->get();
652 
653         display.powerMode = powerMode;
654         display.schedulePtr->getController().setDisplayPowerMode(powerMode);
655     }
656     if (!isPacesetter) return;
657 
658     if (mDisplayPowerTimer) {
659         mDisplayPowerTimer->reset();
660     }
661 
662     // Display Power event will boost the refresh rate to performance.
663     // Clear Layer History to get fresh FPS detection
664     mLayerHistory.clear();
665 }
666 
getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const667 auto Scheduler::getVsyncSchedule(std::optional<PhysicalDisplayId> idOpt) const
668         -> ConstVsyncSchedulePtr {
669     std::scoped_lock lock(mDisplayLock);
670     return getVsyncScheduleLocked(idOpt);
671 }
672 
getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const673 auto Scheduler::getVsyncScheduleLocked(std::optional<PhysicalDisplayId> idOpt) const
674         -> ConstVsyncSchedulePtr {
675     ftl::FakeGuard guard(kMainThreadContext);
676 
677     if (!idOpt) {
678         LOG_ALWAYS_FATAL_IF(!mPacesetterDisplayId, "Missing a pacesetter!");
679         idOpt = mPacesetterDisplayId;
680     }
681 
682     const auto displayOpt = mDisplays.get(*idOpt);
683     if (!displayOpt) {
684         return nullptr;
685     }
686     return displayOpt->get().schedulePtr;
687 }
688 
kernelIdleTimerCallback(TimerState state)689 void Scheduler::kernelIdleTimerCallback(TimerState state) {
690     ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
691 
692     // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
693     // magic number
694     const Fps refreshRate = pacesetterSelectorPtr()->getActiveMode().modePtr->getFps();
695 
696     constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
697     using namespace fps_approx_ops;
698 
699     if (state == TimerState::Reset && refreshRate > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
700         // If we're not in performance mode then the kernel timer shouldn't do
701         // anything, as the refresh rate during DPU power collapse will be the
702         // same.
703         resyncAllToHardwareVsync(true /* allowToEnable */);
704     } else if (state == TimerState::Expired && refreshRate <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
705         // Disable HW VSYNC if the timer expired, as we don't need it enabled if
706         // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
707         // need to update the VsyncController model anyway.
708         std::scoped_lock lock(mDisplayLock);
709         ftl::FakeGuard guard(kMainThreadContext);
710         for (const auto& [_, display] : mDisplays) {
711             constexpr bool kDisallow = false;
712             display.schedulePtr->disableHardwareVsync(kDisallow);
713         }
714     }
715 
716     mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
717 }
718 
idleTimerCallback(TimerState state)719 void Scheduler::idleTimerCallback(TimerState state) {
720     applyPolicy(&Policy::idleTimer, state);
721     ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
722 }
723 
touchTimerCallback(TimerState state)724 void Scheduler::touchTimerCallback(TimerState state) {
725     const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
726     // Touch event will boost the refresh rate to performance.
727     // Clear layer history to get fresh FPS detection.
728     // NOTE: Instead of checking all the layers, we should be checking the layer
729     // that is currently on top. b/142507166 will give us this capability.
730     if (applyPolicy(&Policy::touch, touch).touch) {
731         mLayerHistory.clear();
732     }
733     ATRACE_INT("TouchState", static_cast<int>(touch));
734 }
735 
displayPowerTimerCallback(TimerState state)736 void Scheduler::displayPowerTimerCallback(TimerState state) {
737     applyPolicy(&Policy::displayPowerTimer, state);
738     ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
739 }
740 
dump(utils::Dumper & dumper) const741 void Scheduler::dump(utils::Dumper& dumper) const {
742     using namespace std::string_view_literals;
743 
744     {
745         utils::Dumper::Section section(dumper, "Features"sv);
746 
747         for (Feature feature : ftl::enum_range<Feature>()) {
748             if (const auto flagOpt = ftl::flag_name(feature)) {
749                 dumper.dump(flagOpt->substr(1), mFeatures.test(feature));
750             }
751         }
752     }
753     {
754         utils::Dumper::Section section(dumper, "Policy"sv);
755         {
756             std::scoped_lock lock(mDisplayLock);
757             ftl::FakeGuard guard(kMainThreadContext);
758             dumper.dump("pacesetterDisplayId"sv, mPacesetterDisplayId);
759         }
760         dumper.dump("layerHistory"sv, mLayerHistory.dump());
761         dumper.dump("touchTimer"sv, mTouchTimer.transform(&OneShotTimer::interval));
762         dumper.dump("displayPowerTimer"sv, mDisplayPowerTimer.transform(&OneShotTimer::interval));
763     }
764 
765     mFrameRateOverrideMappings.dump(dumper);
766     dumper.eol();
767 
768     {
769         utils::Dumper::Section section(dumper, "Frame Targeting"sv);
770 
771         std::scoped_lock lock(mDisplayLock);
772         ftl::FakeGuard guard(kMainThreadContext);
773 
774         for (const auto& [id, display] : mDisplays) {
775             utils::Dumper::Section
776                     section(dumper,
777                             id == mPacesetterDisplayId
778                                     ? ftl::Concat("Pacesetter Display ", id.value).c_str()
779                                     : ftl::Concat("Follower Display ", id.value).c_str());
780 
781             display.targeterPtr->dump(dumper);
782             dumper.eol();
783         }
784     }
785 }
786 
dumpVsync(std::string & out) const787 void Scheduler::dumpVsync(std::string& out) const {
788     std::scoped_lock lock(mDisplayLock);
789     ftl::FakeGuard guard(kMainThreadContext);
790     if (mPacesetterDisplayId) {
791         base::StringAppendF(&out, "VsyncSchedule for pacesetter %s:\n",
792                             to_string(*mPacesetterDisplayId).c_str());
793         getVsyncScheduleLocked()->dump(out);
794     }
795     for (auto& [id, display] : mDisplays) {
796         if (id == mPacesetterDisplayId) {
797             continue;
798         }
799         base::StringAppendF(&out, "VsyncSchedule for follower %s:\n", to_string(id).c_str());
800         display.schedulePtr->dump(out);
801     }
802 }
803 
updateFrameRateOverrides(GlobalSignals consideredSignals,Fps displayRefreshRate)804 bool Scheduler::updateFrameRateOverrides(GlobalSignals consideredSignals, Fps displayRefreshRate) {
805     if (consideredSignals.idle) return false;
806 
807     const auto frameRateOverrides =
808             pacesetterSelectorPtr()->getFrameRateOverrides(mPolicy.contentRequirements,
809                                                            displayRefreshRate, consideredSignals);
810 
811     // Note that RefreshRateSelector::supportsFrameRateOverrideByContent is checked when querying
812     // the FrameRateOverrideMappings rather than here.
813     return mFrameRateOverrideMappings.updateFrameRateOverridesByContent(frameRateOverrides);
814 }
815 
promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt)816 void Scheduler::promotePacesetterDisplay(std::optional<PhysicalDisplayId> pacesetterIdOpt) {
817     std::shared_ptr<VsyncSchedule> pacesetterVsyncSchedule;
818 
819     {
820         std::scoped_lock lock(mDisplayLock);
821         pacesetterVsyncSchedule = promotePacesetterDisplayLocked(pacesetterIdOpt);
822     }
823 
824     applyNewVsyncSchedule(std::move(pacesetterVsyncSchedule));
825 }
826 
promotePacesetterDisplayLocked(std::optional<PhysicalDisplayId> pacesetterIdOpt)827 std::shared_ptr<VsyncSchedule> Scheduler::promotePacesetterDisplayLocked(
828         std::optional<PhysicalDisplayId> pacesetterIdOpt) {
829     // TODO(b/241286431): Choose the pacesetter display.
830     mPacesetterDisplayId = pacesetterIdOpt.value_or(mDisplays.begin()->first);
831     ALOGI("Display %s is the pacesetter", to_string(*mPacesetterDisplayId).c_str());
832 
833     std::shared_ptr<VsyncSchedule> newVsyncSchedulePtr;
834     if (const auto pacesetterOpt = pacesetterDisplayLocked()) {
835         const Display& pacesetter = *pacesetterOpt;
836 
837         pacesetter.selectorPtr->setIdleTimerCallbacks(
838                 {.platform = {.onReset = [this] { idleTimerCallback(TimerState::Reset); },
839                               .onExpired = [this] { idleTimerCallback(TimerState::Expired); }},
840                  .kernel = {.onReset = [this] { kernelIdleTimerCallback(TimerState::Reset); },
841                             .onExpired =
842                                     [this] { kernelIdleTimerCallback(TimerState::Expired); }}});
843 
844         pacesetter.selectorPtr->startIdleTimer();
845 
846         newVsyncSchedulePtr = pacesetter.schedulePtr;
847 
848         const Fps refreshRate = pacesetter.selectorPtr->getActiveMode().modePtr->getFps();
849         constexpr bool kForce = true;
850         newVsyncSchedulePtr->startPeriodTransition(refreshRate.getPeriod(), kForce);
851     }
852     return newVsyncSchedulePtr;
853 }
854 
applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule)855 void Scheduler::applyNewVsyncSchedule(std::shared_ptr<VsyncSchedule> vsyncSchedule) {
856     onNewVsyncSchedule(vsyncSchedule->getDispatch());
857     std::vector<android::EventThread*> threads;
858     {
859         std::lock_guard<std::mutex> lock(mConnectionsLock);
860         threads.reserve(mConnections.size());
861         for (auto& [_, connection] : mConnections) {
862             threads.push_back(connection.thread.get());
863         }
864     }
865     for (auto* thread : threads) {
866         thread->onNewVsyncSchedule(vsyncSchedule);
867     }
868 }
869 
demotePacesetterDisplay()870 void Scheduler::demotePacesetterDisplay() {
871     // No need to lock for reads on kMainThreadContext.
872     if (const auto pacesetterPtr = FTL_FAKE_GUARD(mDisplayLock, pacesetterSelectorPtrLocked())) {
873         pacesetterPtr->stopIdleTimer();
874         pacesetterPtr->clearIdleTimerCallbacks();
875     }
876 
877     // Clear state that depends on the pacesetter's RefreshRateSelector.
878     std::scoped_lock lock(mPolicyLock);
879     mPolicy = {};
880 }
881 
882 template <typename S, typename T>
applyPolicy(S Policy::* statePtr,T && newState)883 auto Scheduler::applyPolicy(S Policy::*statePtr, T&& newState) -> GlobalSignals {
884     ATRACE_CALL();
885     std::vector<display::DisplayModeRequest> modeRequests;
886     GlobalSignals consideredSignals;
887 
888     bool refreshRateChanged = false;
889     bool frameRateOverridesChanged;
890 
891     {
892         std::scoped_lock lock(mPolicyLock);
893 
894         auto& currentState = mPolicy.*statePtr;
895         if (currentState == newState) return {};
896         currentState = std::forward<T>(newState);
897 
898         DisplayModeChoiceMap modeChoices;
899         ftl::Optional<FrameRateMode> modeOpt;
900         {
901             std::scoped_lock lock(mDisplayLock);
902             ftl::FakeGuard guard(kMainThreadContext);
903 
904             modeChoices = chooseDisplayModes();
905 
906             // TODO(b/240743786): The pacesetter display's mode must change for any
907             // DisplayModeRequest to go through. Fix this by tracking per-display Scheduler::Policy
908             // and timers.
909             std::tie(modeOpt, consideredSignals) =
910                     modeChoices.get(*mPacesetterDisplayId)
911                             .transform([](const DisplayModeChoice& choice) {
912                                 return std::make_pair(choice.mode, choice.consideredSignals);
913                             })
914                             .value();
915         }
916 
917         modeRequests.reserve(modeChoices.size());
918         for (auto& [id, choice] : modeChoices) {
919             modeRequests.emplace_back(
920                     display::DisplayModeRequest{.mode = std::move(choice.mode),
921                                                 .emitEvent = !choice.consideredSignals.idle});
922         }
923 
924         frameRateOverridesChanged = updateFrameRateOverrides(consideredSignals, modeOpt->fps);
925 
926         if (mPolicy.modeOpt != modeOpt) {
927             mPolicy.modeOpt = modeOpt;
928             refreshRateChanged = true;
929         } else {
930             // We don't need to change the display mode, but we might need to send an event
931             // about a mode change, since it was suppressed if previously considered idle.
932             if (!consideredSignals.idle) {
933                 dispatchCachedReportedMode();
934             }
935         }
936     }
937     if (refreshRateChanged) {
938         mSchedulerCallback.requestDisplayModes(std::move(modeRequests));
939     }
940     if (frameRateOverridesChanged) {
941         mSchedulerCallback.triggerOnFrameRateOverridesChanged();
942     }
943     return consideredSignals;
944 }
945 
chooseDisplayModes() const946 auto Scheduler::chooseDisplayModes() const -> DisplayModeChoiceMap {
947     ATRACE_CALL();
948 
949     using RankedRefreshRates = RefreshRateSelector::RankedFrameRates;
950     ui::PhysicalDisplayVector<RankedRefreshRates> perDisplayRanking;
951     const auto globalSignals = makeGlobalSignals();
952     Fps pacesetterFps;
953 
954     for (const auto& [id, display] : mDisplays) {
955         auto rankedFrameRates =
956                 display.selectorPtr->getRankedFrameRates(mPolicy.contentRequirements,
957                                                          globalSignals);
958         if (id == *mPacesetterDisplayId) {
959             pacesetterFps = rankedFrameRates.ranking.front().frameRateMode.fps;
960         }
961         perDisplayRanking.push_back(std::move(rankedFrameRates));
962     }
963 
964     DisplayModeChoiceMap modeChoices;
965     using fps_approx_ops::operator==;
966 
967     for (auto& [rankings, signals] : perDisplayRanking) {
968         const auto chosenFrameRateMode =
969                 ftl::find_if(rankings,
970                              [&](const auto& ranking) {
971                                  return ranking.frameRateMode.fps == pacesetterFps;
972                              })
973                         .transform([](const auto& scoredFrameRate) {
974                             return scoredFrameRate.get().frameRateMode;
975                         })
976                         .value_or(rankings.front().frameRateMode);
977 
978         modeChoices.try_emplace(chosenFrameRateMode.modePtr->getPhysicalDisplayId(),
979                                 DisplayModeChoice{chosenFrameRateMode, signals});
980     }
981     return modeChoices;
982 }
983 
makeGlobalSignals() const984 GlobalSignals Scheduler::makeGlobalSignals() const {
985     const bool powerOnImminent = mDisplayPowerTimer &&
986             (mPolicy.displayPowerMode != hal::PowerMode::ON ||
987              mPolicy.displayPowerTimer == TimerState::Reset);
988 
989     return {.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
990             .idle = mPolicy.idleTimer == TimerState::Expired,
991             .powerOnImminent = powerOnImminent};
992 }
993 
getPreferredDisplayMode()994 FrameRateMode Scheduler::getPreferredDisplayMode() {
995     std::lock_guard<std::mutex> lock(mPolicyLock);
996     const auto frameRateMode =
997             pacesetterSelectorPtr()
998                     ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
999                     .ranking.front()
1000                     .frameRateMode;
1001 
1002     // Make sure the stored mode is up to date.
1003     mPolicy.modeOpt = frameRateMode;
1004 
1005     return frameRateMode;
1006 }
1007 
onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline & timeline)1008 void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
1009     std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1010     mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
1011 
1012     const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
1013     if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
1014         mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
1015     }
1016 }
1017 
onPostComposition(nsecs_t presentTime)1018 bool Scheduler::onPostComposition(nsecs_t presentTime) {
1019     std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
1020     if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
1021         if (presentTime < mLastVsyncPeriodChangeTimeline->refreshTimeNanos) {
1022             // We need to composite again as refreshTimeNanos is still in the future.
1023             return true;
1024         }
1025 
1026         mLastVsyncPeriodChangeTimeline->refreshRequired = false;
1027     }
1028     return false;
1029 }
1030 
onActiveDisplayAreaChanged(uint32_t displayArea)1031 void Scheduler::onActiveDisplayAreaChanged(uint32_t displayArea) {
1032     mLayerHistory.setDisplayArea(displayArea);
1033 }
1034 
setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride)1035 void Scheduler::setGameModeRefreshRateForUid(FrameRateOverride frameRateOverride) {
1036     if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1037         return;
1038     }
1039 
1040     mFrameRateOverrideMappings.setGameModeRefreshRateForUid(frameRateOverride);
1041 }
1042 
setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride)1043 void Scheduler::setPreferredRefreshRateForUid(FrameRateOverride frameRateOverride) {
1044     if (frameRateOverride.frameRateHz > 0.f && frameRateOverride.frameRateHz < 1.f) {
1045         return;
1046     }
1047 
1048     mFrameRateOverrideMappings.setPreferredRefreshRateForUid(frameRateOverride);
1049 }
1050 
updateSmallAreaDetection(std::vector<std::pair<uid_t,float>> & uidThresholdMappings)1051 void Scheduler::updateSmallAreaDetection(
1052         std::vector<std::pair<uid_t, float>>& uidThresholdMappings) {
1053     mSmallAreaDetectionAllowMappings.update(uidThresholdMappings);
1054 }
1055 
setSmallAreaDetectionThreshold(uid_t uid,float threshold)1056 void Scheduler::setSmallAreaDetectionThreshold(uid_t uid, float threshold) {
1057     mSmallAreaDetectionAllowMappings.setThesholdForUid(uid, threshold);
1058 }
1059 
isSmallDirtyArea(uid_t uid,uint32_t dirtyArea)1060 bool Scheduler::isSmallDirtyArea(uid_t uid, uint32_t dirtyArea) {
1061     std::optional<float> oThreshold = mSmallAreaDetectionAllowMappings.getThresholdForUid(uid);
1062     if (oThreshold) return mLayerHistory.isSmallDirtyArea(dirtyArea, oThreshold.value());
1063 
1064     return false;
1065 }
1066 
1067 } // namespace android::scheduler
1068