blob: 0092c7a30924881ee834e2821014624d5813c71d [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
Dominik Laskowski208235c2020-12-03 15:38:51 -0800402 // EventThread does not dispatch VSYNC unless the display is connected and powered on.
403 eventThread->onHotplugReceived(PhysicalDisplayId::fromPort(0), true);
404 eventThread->onScreenAcquired();
405
Dominik Laskowski6505f792019-09-18 11:10:05 -0700406 mInjectorConnectionHandle = createConnection(std::move(eventThread));
407 }
408
409 mInjectVSyncs = enable;
410 return mInjectorConnectionHandle;
411}
412
Ady Abraham9c53ee72020-07-22 21:16:18 -0700413bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime, nsecs_t deadlineTimestamp) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700414 if (!mInjectVSyncs || !mVSyncInjector) {
415 return false;
416 }
417
Ady Abraham9c53ee72020-07-22 21:16:18 -0700418 mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime, deadlineTimestamp);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700419 return true;
420}
421
Ana Krulece588e312018-09-18 12:32:24 -0700422void Scheduler::enableHardwareVsync() {
423 std::lock_guard<std::mutex> lock(mHWVsyncLock);
424 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700425 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700426 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700427 mPrimaryHWVsyncEnabled = true;
428 }
429}
430
431void Scheduler::disableHardwareVsync(bool makeUnavailable) {
432 std::lock_guard<std::mutex> lock(mHWVsyncLock);
433 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700434 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700435 mPrimaryHWVsyncEnabled = false;
436 }
437 if (makeUnavailable) {
438 mHWVsyncAvailable = false;
439 }
440}
441
Ana Krulecc2870422019-01-29 19:00:58 -0800442void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
443 {
444 std::lock_guard<std::mutex> lock(mHWVsyncLock);
445 if (makeAvailable) {
446 mHWVsyncAvailable = makeAvailable;
447 } else if (!mHWVsyncAvailable) {
448 // Hardware vsync is not currently available, so abort the resync
449 // attempt for now
450 return;
451 }
452 }
453
454 if (period <= 0) {
455 return;
456 }
457
458 setVsyncPeriod(period);
459}
460
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700461void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700462 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800463
464 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700465 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800466
467 if (now - last > kIgnoreDelay) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700468 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
Ana Krulecc2870422019-01-29 19:00:58 -0800469 }
470}
471
Dominik Laskowski98041832019-08-01 18:35:59 -0700472void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800473 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ady Abraham8cb21882020-08-26 18:22:05 -0700474 mVsyncSchedule.controller->startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800475
476 if (!mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700477 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700478 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800479 mPrimaryHWVsyncEnabled = true;
480 }
Ana Krulece588e312018-09-18 12:32:24 -0700481}
482
Ady Abraham5dee2f12020-02-05 17:49:47 -0800483void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
484 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700485 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700486 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700487 { // Scope for the lock
488 std::lock_guard<std::mutex> lock(mHWVsyncLock);
489 if (mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700490 needsHwVsync = mVsyncSchedule.controller->addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
491 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700492 }
493 }
494
495 if (needsHwVsync) {
496 enableHardwareVsync();
497 } else {
498 disableHardwareVsync(false);
499 }
500}
501
502void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700503 if (mVsyncSchedule.controller->addPresentFence(fenceTime)) {
Ana Krulece588e312018-09-18 12:32:24 -0700504 enableHardwareVsync();
505 } else {
506 disableHardwareVsync(false);
507 }
508}
509
510void Scheduler::setIgnorePresentFences(bool ignore) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700511 mVsyncSchedule.controller->setIgnorePresentFences(ignore);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800512}
513
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700514void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800515 if (!mLayerHistory) return;
516
Steven Thomasdebafed2020-05-18 17:30:35 -0700517 const auto minFps = mRefreshRateConfigs.getMinRefreshRate().getFps();
518 const auto maxFps = mRefreshRateConfigs.getMaxRefreshRate().getFps();
519
Michael Wright44753b12020-07-08 13:48:11 +0100520 if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700521 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ana Krulec3d367c82020-02-25 15:02:01 -0800522 scheduler::LayerHistory::LayerVoteType::NoVote);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700523 } else if (!mOptions.useContentDetection) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700524 // If the content detection feature is off, all layers are registered at Max. We still keep
525 // the layer history, since we use it for other features (like Frame Rate API), so layers
526 // still need to be registered.
527 mLayerHistory->registerLayer(layer, minFps, maxFps,
528 scheduler::LayerHistory::LayerVoteType::Max);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800529 } else {
Michael Wright44753b12020-07-08 13:48:11 +0100530 if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
Ana Krulec3d367c82020-02-25 15:02:01 -0800531 // Running Wallpaper at Min is considered as part of content detection.
Steven Thomasdebafed2020-05-18 17:30:35 -0700532 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800533 scheduler::LayerHistory::LayerVoteType::Min);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800534 } else {
Steven Thomasdebafed2020-05-18 17:30:35 -0700535 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800536 scheduler::LayerHistory::LayerVoteType::Heuristic);
537 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800538 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700539}
540
Ady Abraham5def7332020-05-29 16:13:47 -0700541void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
542 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800543 if (mLayerHistory) {
Ady Abraham5def7332020-05-29 16:13:47 -0700544 mLayerHistory->record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800545 }
Ana Krulec3084c052018-11-21 20:27:17 +0100546}
547
Ady Abraham32efd542020-05-19 17:49:26 -0700548void Scheduler::setConfigChangePending(bool pending) {
549 if (mLayerHistory) {
550 mLayerHistory->setConfigChangePending(pending);
551 }
552}
553
Dominik Laskowski49cea512019-11-12 14:13:23 -0800554void Scheduler::chooseRefreshRateForContent() {
555 if (!mLayerHistory) return;
556
Ady Abraham8a82ba62020-01-17 12:43:17 -0800557 ATRACE_CALL();
558
559 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800560 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700561 {
562 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800563 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700564 return;
565 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800566 mFeatures.contentRequirements = summary;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800567
Ady Abrahamdfd62162020-06-10 16:11:56 -0700568 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
569 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800570 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700571 // We don't need to change the config, but we might need to send an event
572 // about a config change, since it was suppressed due to a previous idleConsidered
573 if (!consideredSignals.idle) {
574 dispatchCachedReportedConfig();
575 }
Ady Abraham6398a0a2019-04-18 19:30:44 -0700576 return;
577 }
Ady Abraham2139f732019-11-13 18:56:40 -0800578 mFeatures.configId = newConfigId;
Ady Abraham2e1dd892020-03-05 13:48:36 -0800579 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700580 mSchedulerCallback.changeRefreshRate(newRefreshRate,
581 consideredSignals.idle ? ConfigEvent::None
582 : ConfigEvent::Changed);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800583 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800584}
585
Ana Krulecfb772822018-11-30 10:44:07 +0100586void Scheduler::resetIdleTimer() {
587 if (mIdleTimer) {
588 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800589 }
590}
591
Ady Abraham8532d012019-05-08 14:50:56 -0700592void Scheduler::notifyTouchEvent() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700593 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800594 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800595
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700596 if (mOptions.supportKernelTimer && mIdleTimer) {
Steven Thomas540730a2020-01-08 20:12:42 -0800597 mIdleTimer->reset();
598 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800599 }
Ady Abraham8532d012019-05-08 14:50:56 -0700600}
601
Ady Abraham6fe2c172019-07-12 12:37:57 -0700602void Scheduler::setDisplayPowerState(bool normal) {
603 {
604 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700605 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700606 }
607
608 if (mDisplayPowerTimer) {
609 mDisplayPowerTimer->reset();
610 }
611
612 // Display Power event will boost the refresh rate to performance.
613 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800614 if (mLayerHistory) {
615 mLayerHistory->clear();
616 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700617}
618
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700619void Scheduler::kernelIdleTimerCallback(TimerState state) {
620 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100621
Ady Abraham2139f732019-11-13 18:56:40 -0800622 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
623 // magic number
Ady Abraham2e1dd892020-03-05 13:48:36 -0800624 const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800625 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
Ady Abrahamabc27602020-04-08 17:20:29 -0700626 if (state == TimerState::Reset && refreshRate.getFps() > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700627 // If we're not in performance mode then the kernel timer shouldn't do
628 // anything, as the refresh rate during DPU power collapse will be the
629 // same.
Ady Abrahamabc27602020-04-08 17:20:29 -0700630 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
631 } else if (state == TimerState::Expired &&
632 refreshRate.getFps() <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700633 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
634 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700635 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700636 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700637 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800638
639 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700640}
641
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700642void Scheduler::idleTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700643 handleTimerStateChanged(&mFeatures.idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700644 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100645}
646
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700647void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700648 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700649 // Touch event will boost the refresh rate to performance.
650 // Clear layer history to get fresh FPS detection.
651 // NOTE: Instead of checking all the layers, we should be checking the layer
652 // that is currently on top. b/142507166 will give us this capability.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700653 if (handleTimerStateChanged(&mFeatures.touch, touch)) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700654 if (mLayerHistory) {
655 mLayerHistory->clear();
656 }
Ady Abraham1adbb722020-05-15 11:51:48 -0700657 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700658 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700659}
660
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700661void Scheduler::displayPowerTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700662 handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700663 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700664}
665
Dominik Laskowski98041832019-08-01 18:35:59 -0700666void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800667 using base::StringAppendF;
Dominik Laskowski98041832019-08-01 18:35:59 -0700668
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700669 StringAppendF(&result, "+ Idle timer: %s\n", mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Ana Krulec3d367c82020-02-25 15:02:01 -0800670 StringAppendF(&result, "+ Touch timer: %s\n",
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700671 mTouchTimer ? mTouchTimer->dump().c_str() : "off");
672 StringAppendF(&result, "+ Content detection: %s %s\n\n",
Marin Shalamanov27fa3de2020-11-20 16:22:48 +0100673 toContentDetectionString(mOptions.useContentDetection),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700674 mLayerHistory ? mLayerHistory->dump().c_str() : "(no layer history)");
Ana Krulecb43429d2019-01-09 14:28:51 -0800675}
676
Ady Abraham8cb21882020-08-26 18:22:05 -0700677void Scheduler::dumpVsync(std::string& s) const {
Ady Abraham8735eac2020-08-12 16:35:04 -0700678 using base::StringAppendF;
679
680 StringAppendF(&s, "VSyncReactor:\n");
Ady Abraham8cb21882020-08-26 18:22:05 -0700681 mVsyncSchedule.controller->dump(s);
Ady Abraham8735eac2020-08-12 16:35:04 -0700682 StringAppendF(&s, "VSyncDispatch:\n");
683 mVsyncSchedule.dispatch->dump(s);
684}
685
Ady Abraham6fe2c172019-07-12 12:37:57 -0700686template <class T>
Ady Abrahamdfd62162020-06-10 16:11:56 -0700687bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
Ady Abraham2139f732019-11-13 18:56:40 -0800688 HwcConfigIndexType newConfigId;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700689 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700690 {
691 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700692 if (*currentState == newState) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700693 return false;
Ady Abraham8532d012019-05-08 14:50:56 -0700694 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700695 *currentState = newState;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700696 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800697 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700698 // We don't need to change the config, but we might need to send an event
699 // about a config change, since it was suppressed due to a previous idleConsidered
700 if (!consideredSignals.idle) {
701 dispatchCachedReportedConfig();
702 }
703 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700704 }
Ady Abraham2139f732019-11-13 18:56:40 -0800705 mFeatures.configId = newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700706 }
Ady Abraham2139f732019-11-13 18:56:40 -0800707 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700708 mSchedulerCallback.changeRefreshRate(newRefreshRate,
709 consideredSignals.idle ? ConfigEvent::None
710 : ConfigEvent::Changed);
711 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700712}
713
Ady Abrahamdfd62162020-06-10 16:11:56 -0700714HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
715 scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800716 ATRACE_CALL();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700717 if (consideredSignals) *consideredSignals = {};
Ady Abraham09bd3922019-04-08 10:44:56 -0700718
Steven Thomasf734df42020-04-13 21:09:28 -0700719 // If Display Power is not in normal operation we want to be in performance mode. When coming
720 // back to normal mode, a grace period is given with DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800721 if (mDisplayPowerTimer &&
722 (!mFeatures.isDisplayPowerStateNormal ||
723 mFeatures.displayPowerTimer == TimerState::Reset)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700724 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800725 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700726
Steven Thomasbb374322020-04-28 22:47:16 -0700727 const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
728 const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
729
Ady Abraham1adbb722020-05-15 11:51:48 -0700730 return mRefreshRateConfigs
Ady Abrahamdfd62162020-06-10 16:11:56 -0700731 .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
732 consideredSignals)
Ady Abraham1adbb722020-05-15 11:51:48 -0700733 .getConfigId();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800734}
735
Ady Abraham2139f732019-11-13 18:56:40 -0800736std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700737 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800738 // Make sure that the default config ID is first updated, before returned.
739 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800740 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800741 }
Ady Abraham2139f732019-11-13 18:56:40 -0800742 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700743}
744
Peiyong Line9d809e2020-04-14 13:10:48 -0700745void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800746 if (timeline.refreshRequired) {
747 mSchedulerCallback.repaintEverythingForHWC();
748 }
749
750 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
751 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
752
753 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
754 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
755 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
756 }
757}
758
759void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
760 bool callRepaint = false;
761 {
762 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
763 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
764 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
765 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
766 } else {
767 // We need to send another refresh as refreshTimeNanos is still in the future
768 callRepaint = true;
769 }
770 }
771 }
772
773 if (callRepaint) {
774 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800775 }
776}
777
Ady Abraham8a82ba62020-01-17 12:43:17 -0800778void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
779 if (mLayerHistory) {
780 mLayerHistory->setDisplayArea(displayArea);
781 }
782}
783
Ana Krulec98b5b242018-08-10 15:03:23 -0700784} // namespace android