blob: 52bf483fddb6db76b43f3c32c3bccec0950947eb [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>
Ady Abraham8f1ee7f2019-04-05 10:32:50 -070028#include <input/InputWindow.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080029#include <system/window.h>
Ana Krulece588e312018-09-18 12:32:24 -070030#include <ui/DisplayStatInfo.h>
Ana Krulec3084c052018-11-21 20:27:17 +010031#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010032#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070033
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070034#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070035#include <algorithm>
36#include <cinttypes>
37#include <cstdint>
38#include <functional>
39#include <memory>
40#include <numeric>
41
42#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070043#include "DispSyncSource.h"
44#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070045#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070046#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010047#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090048#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080049#include "Timer.h"
50#include "VSyncDispatchTimerQueue.h"
51#include "VSyncPredictor.h"
52#include "VSyncReactor.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070053#include "VsyncController.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070054
Dominik Laskowski98041832019-08-01 18:35:59 -070055#define RETURN_IF_INVALID_HANDLE(handle, ...) \
56 do { \
57 if (mConnections.count(handle) == 0) { \
58 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
59 return __VA_ARGS__; \
60 } \
61 } while (false)
62
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070063using namespace std::string_literals;
64
Ana Krulec98b5b242018-08-10 15:03:23 -070065namespace android {
Ady Abraham5a858552020-03-31 17:54:56 -070066
Dominik Laskowski983f2b52020-06-25 16:54:06 -070067namespace {
Ana Krulec98b5b242018-08-10 15:03:23 -070068
Ady Abraham5a858552020-03-31 17:54:56 -070069std::unique_ptr<scheduler::VSyncTracker> createVSyncTracker() {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070070 // TODO(b/144707443): Tune constants.
71 constexpr int kDefaultRate = 60;
72 constexpr auto initialPeriod = std::chrono::duration<nsecs_t, std::ratio<1, kDefaultRate>>(1);
73 constexpr nsecs_t idealPeriod =
74 std::chrono::duration_cast<std::chrono::nanoseconds>(initialPeriod).count();
75 constexpr size_t vsyncTimestampHistorySize = 20;
76 constexpr size_t minimumSamplesForPrediction = 6;
77 constexpr uint32_t discardOutlierPercent = 20;
78 return std::make_unique<scheduler::VSyncPredictor>(idealPeriod, vsyncTimestampHistorySize,
79 minimumSamplesForPrediction,
80 discardOutlierPercent);
Ady Abraham5a858552020-03-31 17:54:56 -070081}
82
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070083std::unique_ptr<scheduler::VSyncDispatch> createVSyncDispatch(scheduler::VSyncTracker& tracker) {
84 // TODO(b/144707443): Tune constants.
85 constexpr std::chrono::nanoseconds vsyncMoveThreshold = 3ms;
86 constexpr std::chrono::nanoseconds timerSlack = 500us;
Ady Abraham5a858552020-03-31 17:54:56 -070087 return std::make_unique<
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070088 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), tracker,
Ady Abraham5a858552020-03-31 17:54:56 -070089 timerSlack.count(), vsyncMoveThreshold.count());
90}
91
Marin Shalamanov27fa3de2020-11-20 16:22:48 +010092const char* toContentDetectionString(bool useContentDetection) {
93 return useContentDetection ? "on" : "off";
Dominik Laskowski983f2b52020-06-25 16:54:06 -070094}
95
96} // namespace
97
Ady Abraham8735eac2020-08-12 16:35:04 -070098class PredictedVsyncTracer {
99public:
100 PredictedVsyncTracer(scheduler::VSyncDispatch& dispatch)
101 : mRegistration(dispatch, std::bind(&PredictedVsyncTracer::callback, this),
102 "PredictedVsyncTracer") {
103 scheduleRegistration();
104 }
105
106private:
107 TracedOrdinal<bool> mParity = {"VSYNC-predicted", 0};
108 scheduler::VSyncCallbackRegistration mRegistration;
109
110 void scheduleRegistration() { mRegistration.schedule({0, 0, 0}); }
111
112 void callback() {
113 mParity = !mParity;
114 scheduleRegistration();
115 }
116};
117
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700118Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback)
119 : Scheduler(configs, callback,
120 {.supportKernelTimer = sysprop::support_kernel_idle_timer(false),
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100121 .useContentDetection = sysprop::use_content_detection_for_refresh_rate(false)}) {
122}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700123
124Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback,
125 Options options)
Ady Abraham8cb21882020-08-26 18:22:05 -0700126 : Scheduler(createVsyncSchedule(options.supportKernelTimer), configs, callback,
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100127 createLayerHistory(configs), options) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700128 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700129
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700130 const int setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms"s, 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100131
Dominik Laskowski98041832019-08-01 18:35:59 -0700132 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700133 const auto callback = mOptions.supportKernelTimer ? &Scheduler::kernelIdleTimerCallback
134 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700135 mIdleTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800136 "IdleTimer", std::chrono::milliseconds(millis),
Dominik Laskowski98041832019-08-01 18:35:59 -0700137 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
138 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100139 mIdleTimer->start();
140 }
Ady Abraham8532d012019-05-08 14:50:56 -0700141
Dominik Laskowski98041832019-08-01 18:35:59 -0700142 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700143 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700144 mTouchTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800145 "TouchTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700146 [this] { touchTimerCallback(TimerState::Reset); },
147 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700148 mTouchTimer->start();
149 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700150
Dominik Laskowski98041832019-08-01 18:35:59 -0700151 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
152 mDisplayPowerTimer.emplace(
Ady Abrahamdb3dfee2020-11-17 17:07:12 -0800153 "DisplayPowerTimer", std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700154 [this] { displayPowerTimerCallback(TimerState::Reset); },
155 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700156 mDisplayPowerTimer->start();
157 }
Ana Krulece588e312018-09-18 12:32:24 -0700158}
159
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700160Scheduler::Scheduler(VsyncSchedule schedule, const scheduler::RefreshRateConfigs& configs,
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700161 ISchedulerCallback& schedulerCallback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700162 std::unique_ptr<LayerHistory> layerHistory, Options options)
163 : mOptions(options),
164 mVsyncSchedule(std::move(schedule)),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700165 mLayerHistory(std::move(layerHistory)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800166 mSchedulerCallback(schedulerCallback),
Ady Abraham8735eac2020-08-12 16:35:04 -0700167 mRefreshRateConfigs(configs),
168 mPredictedVsyncTracer(
169 base::GetBoolProperty("debug.sf.show_predicted_vsync", false)
170 ? std::make_unique<PredictedVsyncTracer>(*mVsyncSchedule.dispatch)
171 : nullptr) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700172 mSchedulerCallback.setVsyncEnabled(false);
173}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700174
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800175Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700176 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700177 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700178 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800179 mIdleTimer.reset();
180}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700181
Ady Abraham8cb21882020-08-26 18:22:05 -0700182Scheduler::VsyncSchedule Scheduler::createVsyncSchedule(bool supportKernelTimer) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700183 auto clock = std::make_unique<scheduler::SystemClock>();
184 auto tracker = createVSyncTracker();
185 auto dispatch = createVSyncDispatch(*tracker);
186
187 // TODO(b/144707443): Tune constants.
188 constexpr size_t pendingFenceLimit = 20;
Ady Abraham8cb21882020-08-26 18:22:05 -0700189 auto controller =
Ady Abraham8735eac2020-08-12 16:35:04 -0700190 std::make_unique<scheduler::VSyncReactor>(std::move(clock), *tracker, pendingFenceLimit,
Ady Abraham8cb21882020-08-26 18:22:05 -0700191 supportKernelTimer);
192 return {std::move(controller), std::move(tracker), std::move(dispatch)};
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700193}
194
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700195std::unique_ptr<LayerHistory> Scheduler::createLayerHistory(
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100196 const scheduler::RefreshRateConfigs& configs) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700197 if (!configs.canSwitch()) return nullptr;
198
Marin Shalamanov1bc43ee2020-11-20 16:56:52 +0100199 return std::make_unique<scheduler::LayerHistory>(configs);
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700200}
201
Ady Abraham9c53ee72020-07-22 21:16:18 -0700202std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
203 const char* name, std::chrono::nanoseconds workDuration,
204 std::chrono::nanoseconds readyDuration, bool traceVsync) {
205 return std::make_unique<scheduler::DispSyncSource>(*mVsyncSchedule.dispatch, workDuration,
206 readyDuration, traceVsync, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700207}
208
Ady Abraham0bb6a472020-10-12 10:22:13 -0700209bool Scheduler::isVsyncValid(nsecs_t expectedVsyncTimestamp, uid_t uid) const {
210 const auto divider = mRefreshRateConfigs.getRefreshRateDividerForUid(uid);
211 if (divider <= 1) {
212 return true;
213 }
214
215 return mVsyncSchedule.tracker->isVSyncInPhase(expectedVsyncTimestamp, divider);
216}
217
Dominik Laskowski98041832019-08-01 18:35:59 -0700218Scheduler::ConnectionHandle Scheduler::createConnection(
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700219 const char* connectionName, frametimeline::TokenManager* tokenManager,
220 std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
Ana Krulec98b5b242018-08-10 15:03:23 -0700221 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700222 auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700223 auto throttleVsync = [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
224 return !isVsyncValid(expectedVsyncTimestamp, uid);
225 };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700226 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700227 std::move(interceptCallback),
228 std::move(throttleVsync));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700229 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700230}
Ana Krulec98b5b242018-08-10 15:03:23 -0700231
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700232Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700233 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
234 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800235
Ady Abraham62f216c2020-10-13 19:07:23 -0700236 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700237
Ana Krulec6ddd2612020-09-24 13:06:33 -0700238 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700239 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
240 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700241}
242
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700243sp<EventThreadConnection> Scheduler::createConnectionInternal(
Ady Abraham62f216c2020-10-13 19:07:23 -0700244 EventThread* eventThread, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
245 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700246}
247
Ana Krulec98b5b242018-08-10 15:03:23 -0700248sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700249 ConnectionHandle handle, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700250 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700251 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700252 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700253}
254
Dominik Laskowski98041832019-08-01 18:35:59 -0700255sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700256 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700257 RETURN_IF_INVALID_HANDLE(handle, nullptr);
258 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700259}
260
Dominik Laskowski98041832019-08-01 18:35:59 -0700261void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
262 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700263 android::EventThread* thread;
264 {
265 std::lock_guard<std::mutex> lock(mConnectionsLock);
266 RETURN_IF_INVALID_HANDLE(handle);
267 thread = mConnections[handle].thread.get();
268 }
269
270 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700271}
272
Dominik Laskowski98041832019-08-01 18:35:59 -0700273void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700274 android::EventThread* thread;
275 {
276 std::lock_guard<std::mutex> lock(mConnectionsLock);
277 RETURN_IF_INVALID_HANDLE(handle);
278 thread = mConnections[handle].thread.get();
279 }
280 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700281}
282
Dominik Laskowski98041832019-08-01 18:35:59 -0700283void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700284 android::EventThread* thread;
285 {
286 std::lock_guard<std::mutex> lock(mConnectionsLock);
287 RETURN_IF_INVALID_HANDLE(handle);
288 thread = mConnections[handle].thread.get();
289 }
290 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700291}
292
Ady Abraham62f216c2020-10-13 19:07:23 -0700293void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
294 std::vector<FrameRateOverride> overrides) {
295 android::EventThread* thread;
296 {
297 std::lock_guard<std::mutex> lock(mConnectionsLock);
298 RETURN_IF_INVALID_HANDLE(handle);
299 thread = mConnections[handle].thread.get();
300 }
301 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
302}
303
Ady Abrahamdfd62162020-06-10 16:11:56 -0700304void Scheduler::onPrimaryDisplayConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
305 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
306 std::lock_guard<std::mutex> lock(mFeatureStateLock);
307 // Cache the last reported config for primary display.
308 mFeatures.cachedConfigChangedParams = {handle, displayId, configId, vsyncPeriod};
309 onNonPrimaryDisplayConfigChanged(handle, displayId, configId, vsyncPeriod);
310}
311
312void Scheduler::dispatchCachedReportedConfig() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700313 // Check optional fields first.
314 if (!mFeatures.configId.has_value()) {
315 ALOGW("No config ID found, not dispatching cached config.");
316 return;
317 }
318 if (!mFeatures.cachedConfigChangedParams.has_value()) {
319 ALOGW("No config changed params found, not dispatching cached config.");
320 return;
321 }
322
Ady Abrahamdfd62162020-06-10 16:11:56 -0700323 const auto configId = *mFeatures.configId;
324 const auto vsyncPeriod =
325 mRefreshRateConfigs.getRefreshRateFromConfigId(configId).getVsyncPeriod();
326
327 // If there is no change from cached config, there is no need to dispatch an event
328 if (configId == mFeatures.cachedConfigChangedParams->configId &&
329 vsyncPeriod == mFeatures.cachedConfigChangedParams->vsyncPeriod) {
330 return;
331 }
332
333 mFeatures.cachedConfigChangedParams->configId = configId;
334 mFeatures.cachedConfigChangedParams->vsyncPeriod = vsyncPeriod;
335 onNonPrimaryDisplayConfigChanged(mFeatures.cachedConfigChangedParams->handle,
336 mFeatures.cachedConfigChangedParams->displayId,
337 mFeatures.cachedConfigChangedParams->configId,
338 mFeatures.cachedConfigChangedParams->vsyncPeriod);
339}
340
341void Scheduler::onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,
342 PhysicalDisplayId displayId,
343 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700344 android::EventThread* thread;
345 {
346 std::lock_guard<std::mutex> lock(mConnectionsLock);
347 RETURN_IF_INVALID_HANDLE(handle);
348 thread = mConnections[handle].thread.get();
349 }
350 thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800351}
352
Alec Mouri717bcb62020-02-10 17:07:19 -0800353size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700354 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800355 RETURN_IF_INVALID_HANDLE(handle, 0);
356 return mConnections[handle].thread->getEventThreadConnectionCount();
357}
358
Dominik Laskowski98041832019-08-01 18:35:59 -0700359void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700360 android::EventThread* thread;
361 {
362 std::lock_guard<std::mutex> lock(mConnectionsLock);
363 RETURN_IF_INVALID_HANDLE(handle);
364 thread = mConnections.at(handle).thread.get();
365 }
366 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700367}
368
Ady Abraham9c53ee72020-07-22 21:16:18 -0700369void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
370 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700371 android::EventThread* thread;
372 {
373 std::lock_guard<std::mutex> lock(mConnectionsLock);
374 RETURN_IF_INVALID_HANDLE(handle);
375 thread = mConnections[handle].thread.get();
376 }
377 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700378}
Ana Krulece588e312018-09-18 12:32:24 -0700379
Ady Abraham8cb21882020-08-26 18:22:05 -0700380void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats, nsecs_t now) {
381 stats->vsyncTime = mVsyncSchedule.tracker->nextAnticipatedVSyncTimeFrom(now);
382 stats->vsyncPeriod = mVsyncSchedule.tracker->currentPeriod();
Ana Krulece588e312018-09-18 12:32:24 -0700383}
384
Dominik Laskowski6505f792019-09-18 11:10:05 -0700385Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
386 if (mInjectVSyncs == enable) {
387 return {};
388 }
389
390 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
391
392 if (!mInjectorConnectionHandle) {
393 auto vsyncSource = std::make_unique<InjectVSyncSource>();
394 mVSyncInjector = vsyncSource.get();
395
396 auto eventThread =
397 std::make_unique<impl::EventThread>(std::move(vsyncSource),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700398 /*tokenManager=*/nullptr,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700399 impl::EventThread::InterceptVSyncsCallback(),
400 impl::EventThread::ThrottleVsyncCallback());
Dominik Laskowski6505f792019-09-18 11:10:05 -0700401
402 mInjectorConnectionHandle = createConnection(std::move(eventThread));
403 }
404
405 mInjectVSyncs = enable;
406 return mInjectorConnectionHandle;
407}
408
Ady Abraham9c53ee72020-07-22 21:16:18 -0700409bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime, nsecs_t deadlineTimestamp) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700410 if (!mInjectVSyncs || !mVSyncInjector) {
411 return false;
412 }
413
Ady Abraham9c53ee72020-07-22 21:16:18 -0700414 mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime, deadlineTimestamp);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700415 return true;
416}
417
Ana Krulece588e312018-09-18 12:32:24 -0700418void Scheduler::enableHardwareVsync() {
419 std::lock_guard<std::mutex> lock(mHWVsyncLock);
420 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700421 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700422 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700423 mPrimaryHWVsyncEnabled = true;
424 }
425}
426
427void Scheduler::disableHardwareVsync(bool makeUnavailable) {
428 std::lock_guard<std::mutex> lock(mHWVsyncLock);
429 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700430 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700431 mPrimaryHWVsyncEnabled = false;
432 }
433 if (makeUnavailable) {
434 mHWVsyncAvailable = false;
435 }
436}
437
Ana Krulecc2870422019-01-29 19:00:58 -0800438void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
439 {
440 std::lock_guard<std::mutex> lock(mHWVsyncLock);
441 if (makeAvailable) {
442 mHWVsyncAvailable = makeAvailable;
443 } else if (!mHWVsyncAvailable) {
444 // Hardware vsync is not currently available, so abort the resync
445 // attempt for now
446 return;
447 }
448 }
449
450 if (period <= 0) {
451 return;
452 }
453
454 setVsyncPeriod(period);
455}
456
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700457void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700458 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800459
460 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700461 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800462
463 if (now - last > kIgnoreDelay) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700464 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
Ana Krulecc2870422019-01-29 19:00:58 -0800465 }
466}
467
Dominik Laskowski98041832019-08-01 18:35:59 -0700468void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800469 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ady Abraham8cb21882020-08-26 18:22:05 -0700470 mVsyncSchedule.controller->startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800471
472 if (!mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700473 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700474 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800475 mPrimaryHWVsyncEnabled = true;
476 }
Ana Krulece588e312018-09-18 12:32:24 -0700477}
478
Ady Abraham5dee2f12020-02-05 17:49:47 -0800479void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
480 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700481 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700482 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700483 { // Scope for the lock
484 std::lock_guard<std::mutex> lock(mHWVsyncLock);
485 if (mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700486 needsHwVsync = mVsyncSchedule.controller->addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
487 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700488 }
489 }
490
491 if (needsHwVsync) {
492 enableHardwareVsync();
493 } else {
494 disableHardwareVsync(false);
495 }
496}
497
498void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700499 if (mVsyncSchedule.controller->addPresentFence(fenceTime)) {
Ana Krulece588e312018-09-18 12:32:24 -0700500 enableHardwareVsync();
501 } else {
502 disableHardwareVsync(false);
503 }
504}
505
506void Scheduler::setIgnorePresentFences(bool ignore) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700507 mVsyncSchedule.controller->setIgnorePresentFences(ignore);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800508}
509
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700510void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800511 if (!mLayerHistory) return;
512
Steven Thomasdebafed2020-05-18 17:30:35 -0700513 const auto minFps = mRefreshRateConfigs.getMinRefreshRate().getFps();
514 const auto maxFps = mRefreshRateConfigs.getMaxRefreshRate().getFps();
515
Michael Wright44753b12020-07-08 13:48:11 +0100516 if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700517 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ana Krulec3d367c82020-02-25 15:02:01 -0800518 scheduler::LayerHistory::LayerVoteType::NoVote);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700519 } else if (!mOptions.useContentDetection) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700520 // If the content detection feature is off, all layers are registered at Max. We still keep
521 // the layer history, since we use it for other features (like Frame Rate API), so layers
522 // still need to be registered.
523 mLayerHistory->registerLayer(layer, minFps, maxFps,
524 scheduler::LayerHistory::LayerVoteType::Max);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800525 } else {
Michael Wright44753b12020-07-08 13:48:11 +0100526 if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
Ana Krulec3d367c82020-02-25 15:02:01 -0800527 // Running Wallpaper at Min is considered as part of content detection.
Steven Thomasdebafed2020-05-18 17:30:35 -0700528 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800529 scheduler::LayerHistory::LayerVoteType::Min);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800530 } else {
Steven Thomasdebafed2020-05-18 17:30:35 -0700531 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800532 scheduler::LayerHistory::LayerVoteType::Heuristic);
533 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800534 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700535}
536
Ady Abraham5def7332020-05-29 16:13:47 -0700537void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
538 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800539 if (mLayerHistory) {
Ady Abraham5def7332020-05-29 16:13:47 -0700540 mLayerHistory->record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800541 }
Ana Krulec3084c052018-11-21 20:27:17 +0100542}
543
Ady Abraham32efd542020-05-19 17:49:26 -0700544void Scheduler::setConfigChangePending(bool pending) {
545 if (mLayerHistory) {
546 mLayerHistory->setConfigChangePending(pending);
547 }
548}
549
Dominik Laskowski49cea512019-11-12 14:13:23 -0800550void Scheduler::chooseRefreshRateForContent() {
551 if (!mLayerHistory) return;
552
Ady Abraham8a82ba62020-01-17 12:43:17 -0800553 ATRACE_CALL();
554
555 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800556 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700557 {
558 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800559 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700560 return;
561 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800562 mFeatures.contentRequirements = summary;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800563
Ady Abrahamdfd62162020-06-10 16:11:56 -0700564 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
565 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800566 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700567 // We don't need to change the config, but we might need to send an event
568 // about a config change, since it was suppressed due to a previous idleConsidered
569 if (!consideredSignals.idle) {
570 dispatchCachedReportedConfig();
571 }
Ady Abraham6398a0a2019-04-18 19:30:44 -0700572 return;
573 }
Ady Abraham2139f732019-11-13 18:56:40 -0800574 mFeatures.configId = newConfigId;
Ady Abraham2e1dd892020-03-05 13:48:36 -0800575 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700576 mSchedulerCallback.changeRefreshRate(newRefreshRate,
577 consideredSignals.idle ? ConfigEvent::None
578 : ConfigEvent::Changed);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800579 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800580}
581
Ana Krulecfb772822018-11-30 10:44:07 +0100582void Scheduler::resetIdleTimer() {
583 if (mIdleTimer) {
584 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800585 }
586}
587
Ady Abraham8532d012019-05-08 14:50:56 -0700588void Scheduler::notifyTouchEvent() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700589 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800590 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800591
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700592 if (mOptions.supportKernelTimer && mIdleTimer) {
Steven Thomas540730a2020-01-08 20:12:42 -0800593 mIdleTimer->reset();
594 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800595 }
Ady Abraham8532d012019-05-08 14:50:56 -0700596}
597
Ady Abraham6fe2c172019-07-12 12:37:57 -0700598void Scheduler::setDisplayPowerState(bool normal) {
599 {
600 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700601 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700602 }
603
604 if (mDisplayPowerTimer) {
605 mDisplayPowerTimer->reset();
606 }
607
608 // Display Power event will boost the refresh rate to performance.
609 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800610 if (mLayerHistory) {
611 mLayerHistory->clear();
612 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700613}
614
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700615void Scheduler::kernelIdleTimerCallback(TimerState state) {
616 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100617
Ady Abraham2139f732019-11-13 18:56:40 -0800618 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
619 // magic number
Ady Abraham2e1dd892020-03-05 13:48:36 -0800620 const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800621 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
Ady Abrahamabc27602020-04-08 17:20:29 -0700622 if (state == TimerState::Reset && refreshRate.getFps() > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700623 // If we're not in performance mode then the kernel timer shouldn't do
624 // anything, as the refresh rate during DPU power collapse will be the
625 // same.
Ady Abrahamabc27602020-04-08 17:20:29 -0700626 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
627 } else if (state == TimerState::Expired &&
628 refreshRate.getFps() <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700629 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
630 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700631 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700632 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700633 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800634
635 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700636}
637
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700638void Scheduler::idleTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700639 handleTimerStateChanged(&mFeatures.idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700640 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100641}
642
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700643void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700644 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700645 // Touch event will boost the refresh rate to performance.
646 // Clear layer history to get fresh FPS detection.
647 // NOTE: Instead of checking all the layers, we should be checking the layer
648 // that is currently on top. b/142507166 will give us this capability.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700649 if (handleTimerStateChanged(&mFeatures.touch, touch)) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700650 if (mLayerHistory) {
651 mLayerHistory->clear();
652 }
Ady Abraham1adbb722020-05-15 11:51:48 -0700653 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700654 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700655}
656
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700657void Scheduler::displayPowerTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700658 handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700659 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700660}
661
Dominik Laskowski98041832019-08-01 18:35:59 -0700662void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800663 using base::StringAppendF;
Dominik Laskowski98041832019-08-01 18:35:59 -0700664
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700665 StringAppendF(&result, "+ Idle timer: %s\n", mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Ana Krulec3d367c82020-02-25 15:02:01 -0800666 StringAppendF(&result, "+ Touch timer: %s\n",
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700667 mTouchTimer ? mTouchTimer->dump().c_str() : "off");
668 StringAppendF(&result, "+ Content detection: %s %s\n\n",
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100669 toContentDetectionString(mOptions.useContentDetection),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700670 mLayerHistory ? mLayerHistory->dump().c_str() : "(no layer history)");
Ana Krulecb43429d2019-01-09 14:28:51 -0800671}
672
Ady Abraham8cb21882020-08-26 18:22:05 -0700673void Scheduler::dumpVsync(std::string& s) const {
Ady Abraham8735eac2020-08-12 16:35:04 -0700674 using base::StringAppendF;
675
676 StringAppendF(&s, "VSyncReactor:\n");
Ady Abraham8cb21882020-08-26 18:22:05 -0700677 mVsyncSchedule.controller->dump(s);
Ady Abraham8735eac2020-08-12 16:35:04 -0700678 StringAppendF(&s, "VSyncDispatch:\n");
679 mVsyncSchedule.dispatch->dump(s);
680}
681
Ady Abraham6fe2c172019-07-12 12:37:57 -0700682template <class T>
Ady Abrahamdfd62162020-06-10 16:11:56 -0700683bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
Ady Abraham2139f732019-11-13 18:56:40 -0800684 HwcConfigIndexType newConfigId;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700685 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700686 {
687 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700688 if (*currentState == newState) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700689 return false;
Ady Abraham8532d012019-05-08 14:50:56 -0700690 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700691 *currentState = newState;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700692 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800693 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700694 // We don't need to change the config, but we might need to send an event
695 // about a config change, since it was suppressed due to a previous idleConsidered
696 if (!consideredSignals.idle) {
697 dispatchCachedReportedConfig();
698 }
699 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700700 }
Ady Abraham2139f732019-11-13 18:56:40 -0800701 mFeatures.configId = newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700702 }
Ady Abraham2139f732019-11-13 18:56:40 -0800703 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700704 mSchedulerCallback.changeRefreshRate(newRefreshRate,
705 consideredSignals.idle ? ConfigEvent::None
706 : ConfigEvent::Changed);
707 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700708}
709
Ady Abrahamdfd62162020-06-10 16:11:56 -0700710HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
711 scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800712 ATRACE_CALL();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700713 if (consideredSignals) *consideredSignals = {};
Ady Abraham09bd3922019-04-08 10:44:56 -0700714
Steven Thomasf734df42020-04-13 21:09:28 -0700715 // If Display Power is not in normal operation we want to be in performance mode. When coming
716 // back to normal mode, a grace period is given with DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800717 if (mDisplayPowerTimer &&
718 (!mFeatures.isDisplayPowerStateNormal ||
719 mFeatures.displayPowerTimer == TimerState::Reset)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700720 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800721 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700722
Steven Thomasbb374322020-04-28 22:47:16 -0700723 const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
724 const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
725
Ady Abraham1adbb722020-05-15 11:51:48 -0700726 return mRefreshRateConfigs
Ady Abrahamdfd62162020-06-10 16:11:56 -0700727 .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
728 consideredSignals)
Ady Abraham1adbb722020-05-15 11:51:48 -0700729 .getConfigId();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800730}
731
Ady Abraham2139f732019-11-13 18:56:40 -0800732std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700733 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800734 // Make sure that the default config ID is first updated, before returned.
735 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800736 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800737 }
Ady Abraham2139f732019-11-13 18:56:40 -0800738 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700739}
740
Peiyong Line9d809e2020-04-14 13:10:48 -0700741void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800742 if (timeline.refreshRequired) {
743 mSchedulerCallback.repaintEverythingForHWC();
744 }
745
746 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
747 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
748
749 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
750 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
751 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
752 }
753}
754
755void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
756 bool callRepaint = false;
757 {
758 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
759 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
760 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
761 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
762 } else {
763 // We need to send another refresh as refreshTimeNanos is still in the future
764 callRepaint = true;
765 }
766 }
767 }
768
769 if (callRepaint) {
770 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800771 }
772}
773
Ady Abraham8a82ba62020-01-17 12:43:17 -0800774void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
775 if (mLayerHistory) {
776 mLayerHistory->setDisplayArea(displayArea);
777 }
778}
779
Ana Krulec98b5b242018-08-10 15:03:23 -0700780} // namespace android