blob: a14019eeb5280e4242061943a753aed5c3d83b1f [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
Dominik Laskowski983f2b52020-06-25 16:54:06 -070092const char* toContentDetectionString(bool useContentDetection, bool useContentDetectionV2) {
93 if (!useContentDetection) return "off";
94 return useContentDetectionV2 ? "V2" : "V1";
95}
96
97} // namespace
98
Ady Abraham8735eac2020-08-12 16:35:04 -070099class PredictedVsyncTracer {
100public:
101 PredictedVsyncTracer(scheduler::VSyncDispatch& dispatch)
102 : mRegistration(dispatch, std::bind(&PredictedVsyncTracer::callback, this),
103 "PredictedVsyncTracer") {
104 scheduleRegistration();
105 }
106
107private:
108 TracedOrdinal<bool> mParity = {"VSYNC-predicted", 0};
109 scheduler::VSyncCallbackRegistration mRegistration;
110
111 void scheduleRegistration() { mRegistration.schedule({0, 0, 0}); }
112
113 void callback() {
114 mParity = !mParity;
115 scheduleRegistration();
116 }
117};
118
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700119Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback)
120 : Scheduler(configs, callback,
121 {.supportKernelTimer = sysprop::support_kernel_idle_timer(false),
122 .useContentDetection = sysprop::use_content_detection_for_refresh_rate(false),
123 .useContentDetectionV2 =
Ady Abraham49cb7d52020-07-22 18:37:07 -0700124 base::GetBoolProperty("debug.sf.use_content_detection_v2"s, true)}) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700125
126Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback,
127 Options options)
Ady Abraham8cb21882020-08-26 18:22:05 -0700128 : Scheduler(createVsyncSchedule(options.supportKernelTimer), configs, callback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700129 createLayerHistory(configs, options.useContentDetectionV2), options) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700130 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700131
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700132 const int setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms"s, 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100133
Dominik Laskowski98041832019-08-01 18:35:59 -0700134 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700135 const auto callback = mOptions.supportKernelTimer ? &Scheduler::kernelIdleTimerCallback
136 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700137 mIdleTimer.emplace(
138 std::chrono::milliseconds(millis),
139 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
140 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100141 mIdleTimer->start();
142 }
Ady Abraham8532d012019-05-08 14:50:56 -0700143
Dominik Laskowski98041832019-08-01 18:35:59 -0700144 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700145 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700146 mTouchTimer.emplace(
147 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700148 [this] { touchTimerCallback(TimerState::Reset); },
149 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700150 mTouchTimer->start();
151 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700152
Dominik Laskowski98041832019-08-01 18:35:59 -0700153 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
154 mDisplayPowerTimer.emplace(
155 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700156 [this] { displayPowerTimerCallback(TimerState::Reset); },
157 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700158 mDisplayPowerTimer->start();
159 }
Ana Krulece588e312018-09-18 12:32:24 -0700160}
161
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700162Scheduler::Scheduler(VsyncSchedule schedule, const scheduler::RefreshRateConfigs& configs,
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700163 ISchedulerCallback& schedulerCallback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700164 std::unique_ptr<LayerHistory> layerHistory, Options options)
165 : mOptions(options),
166 mVsyncSchedule(std::move(schedule)),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700167 mLayerHistory(std::move(layerHistory)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800168 mSchedulerCallback(schedulerCallback),
Ady Abraham8735eac2020-08-12 16:35:04 -0700169 mRefreshRateConfigs(configs),
170 mPredictedVsyncTracer(
171 base::GetBoolProperty("debug.sf.show_predicted_vsync", false)
172 ? std::make_unique<PredictedVsyncTracer>(*mVsyncSchedule.dispatch)
173 : nullptr) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700174 mSchedulerCallback.setVsyncEnabled(false);
175}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700176
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800177Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700178 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700179 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700180 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800181 mIdleTimer.reset();
182}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700183
Ady Abraham8cb21882020-08-26 18:22:05 -0700184Scheduler::VsyncSchedule Scheduler::createVsyncSchedule(bool supportKernelTimer) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700185 auto clock = std::make_unique<scheduler::SystemClock>();
186 auto tracker = createVSyncTracker();
187 auto dispatch = createVSyncDispatch(*tracker);
188
189 // TODO(b/144707443): Tune constants.
190 constexpr size_t pendingFenceLimit = 20;
Ady Abraham8cb21882020-08-26 18:22:05 -0700191 auto controller =
Ady Abraham8735eac2020-08-12 16:35:04 -0700192 std::make_unique<scheduler::VSyncReactor>(std::move(clock), *tracker, pendingFenceLimit,
Ady Abraham8cb21882020-08-26 18:22:05 -0700193 supportKernelTimer);
194 return {std::move(controller), std::move(tracker), std::move(dispatch)};
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700195}
196
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700197std::unique_ptr<LayerHistory> Scheduler::createLayerHistory(
198 const scheduler::RefreshRateConfigs& configs, bool useContentDetectionV2) {
199 if (!configs.canSwitch()) return nullptr;
200
201 if (useContentDetectionV2) {
202 return std::make_unique<scheduler::impl::LayerHistoryV2>(configs);
203 }
204
205 return std::make_unique<scheduler::impl::LayerHistory>();
206}
207
Ady Abraham9c53ee72020-07-22 21:16:18 -0700208std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
209 const char* name, std::chrono::nanoseconds workDuration,
210 std::chrono::nanoseconds readyDuration, bool traceVsync) {
211 return std::make_unique<scheduler::DispSyncSource>(*mVsyncSchedule.dispatch, workDuration,
212 readyDuration, traceVsync, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700213}
214
Ady Abraham0bb6a472020-10-12 10:22:13 -0700215bool Scheduler::isVsyncValid(nsecs_t expectedVsyncTimestamp, uid_t uid) const {
216 const auto divider = mRefreshRateConfigs.getRefreshRateDividerForUid(uid);
217 if (divider <= 1) {
218 return true;
219 }
220
221 return mVsyncSchedule.tracker->isVSyncInPhase(expectedVsyncTimestamp, divider);
222}
223
Dominik Laskowski98041832019-08-01 18:35:59 -0700224Scheduler::ConnectionHandle Scheduler::createConnection(
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700225 const char* connectionName, frametimeline::TokenManager* tokenManager,
226 std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
Ana Krulec98b5b242018-08-10 15:03:23 -0700227 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700228 auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700229 auto throttleVsync = [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
230 return !isVsyncValid(expectedVsyncTimestamp, uid);
231 };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700232 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700233 std::move(interceptCallback),
234 std::move(throttleVsync));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700235 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700236}
Ana Krulec98b5b242018-08-10 15:03:23 -0700237
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700238Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700239 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
240 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800241
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700242 auto connection =
243 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700244
Ana Krulec6ddd2612020-09-24 13:06:33 -0700245 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700246 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
247 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700248}
249
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700250sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700251 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
252 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700253}
254
Ana Krulec98b5b242018-08-10 15:03:23 -0700255sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700256 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700257 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700258 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700259 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700260}
261
Dominik Laskowski98041832019-08-01 18:35:59 -0700262sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700263 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700264 RETURN_IF_INVALID_HANDLE(handle, nullptr);
265 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700266}
267
Dominik Laskowski98041832019-08-01 18:35:59 -0700268void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
269 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700270 android::EventThread* thread;
271 {
272 std::lock_guard<std::mutex> lock(mConnectionsLock);
273 RETURN_IF_INVALID_HANDLE(handle);
274 thread = mConnections[handle].thread.get();
275 }
276
277 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700278}
279
Dominik Laskowski98041832019-08-01 18:35:59 -0700280void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700281 android::EventThread* thread;
282 {
283 std::lock_guard<std::mutex> lock(mConnectionsLock);
284 RETURN_IF_INVALID_HANDLE(handle);
285 thread = mConnections[handle].thread.get();
286 }
287 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700288}
289
Dominik Laskowski98041832019-08-01 18:35:59 -0700290void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700291 android::EventThread* thread;
292 {
293 std::lock_guard<std::mutex> lock(mConnectionsLock);
294 RETURN_IF_INVALID_HANDLE(handle);
295 thread = mConnections[handle].thread.get();
296 }
297 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700298}
299
Ady Abrahamdfd62162020-06-10 16:11:56 -0700300void Scheduler::onPrimaryDisplayConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
301 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
302 std::lock_guard<std::mutex> lock(mFeatureStateLock);
303 // Cache the last reported config for primary display.
304 mFeatures.cachedConfigChangedParams = {handle, displayId, configId, vsyncPeriod};
305 onNonPrimaryDisplayConfigChanged(handle, displayId, configId, vsyncPeriod);
306}
307
308void Scheduler::dispatchCachedReportedConfig() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700309 // Check optional fields first.
310 if (!mFeatures.configId.has_value()) {
311 ALOGW("No config ID found, not dispatching cached config.");
312 return;
313 }
314 if (!mFeatures.cachedConfigChangedParams.has_value()) {
315 ALOGW("No config changed params found, not dispatching cached config.");
316 return;
317 }
318
Ady Abrahamdfd62162020-06-10 16:11:56 -0700319 const auto configId = *mFeatures.configId;
320 const auto vsyncPeriod =
321 mRefreshRateConfigs.getRefreshRateFromConfigId(configId).getVsyncPeriod();
322
323 // If there is no change from cached config, there is no need to dispatch an event
324 if (configId == mFeatures.cachedConfigChangedParams->configId &&
325 vsyncPeriod == mFeatures.cachedConfigChangedParams->vsyncPeriod) {
326 return;
327 }
328
329 mFeatures.cachedConfigChangedParams->configId = configId;
330 mFeatures.cachedConfigChangedParams->vsyncPeriod = vsyncPeriod;
331 onNonPrimaryDisplayConfigChanged(mFeatures.cachedConfigChangedParams->handle,
332 mFeatures.cachedConfigChangedParams->displayId,
333 mFeatures.cachedConfigChangedParams->configId,
334 mFeatures.cachedConfigChangedParams->vsyncPeriod);
335}
336
337void Scheduler::onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,
338 PhysicalDisplayId displayId,
339 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700340 android::EventThread* thread;
341 {
342 std::lock_guard<std::mutex> lock(mConnectionsLock);
343 RETURN_IF_INVALID_HANDLE(handle);
344 thread = mConnections[handle].thread.get();
345 }
346 thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800347}
348
Alec Mouri717bcb62020-02-10 17:07:19 -0800349size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700350 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800351 RETURN_IF_INVALID_HANDLE(handle, 0);
352 return mConnections[handle].thread->getEventThreadConnectionCount();
353}
354
Dominik Laskowski98041832019-08-01 18:35:59 -0700355void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700356 android::EventThread* thread;
357 {
358 std::lock_guard<std::mutex> lock(mConnectionsLock);
359 RETURN_IF_INVALID_HANDLE(handle);
360 thread = mConnections.at(handle).thread.get();
361 }
362 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700363}
364
Ady Abraham9c53ee72020-07-22 21:16:18 -0700365void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
366 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700367 android::EventThread* thread;
368 {
369 std::lock_guard<std::mutex> lock(mConnectionsLock);
370 RETURN_IF_INVALID_HANDLE(handle);
371 thread = mConnections[handle].thread.get();
372 }
373 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700374}
Ana Krulece588e312018-09-18 12:32:24 -0700375
Ady Abraham8cb21882020-08-26 18:22:05 -0700376void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats, nsecs_t now) {
377 stats->vsyncTime = mVsyncSchedule.tracker->nextAnticipatedVSyncTimeFrom(now);
378 stats->vsyncPeriod = mVsyncSchedule.tracker->currentPeriod();
Ana Krulece588e312018-09-18 12:32:24 -0700379}
380
Dominik Laskowski6505f792019-09-18 11:10:05 -0700381Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
382 if (mInjectVSyncs == enable) {
383 return {};
384 }
385
386 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
387
388 if (!mInjectorConnectionHandle) {
389 auto vsyncSource = std::make_unique<InjectVSyncSource>();
390 mVSyncInjector = vsyncSource.get();
391
392 auto eventThread =
393 std::make_unique<impl::EventThread>(std::move(vsyncSource),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700394 /*tokenManager=*/nullptr,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700395 impl::EventThread::InterceptVSyncsCallback(),
396 impl::EventThread::ThrottleVsyncCallback());
Dominik Laskowski6505f792019-09-18 11:10:05 -0700397
398 mInjectorConnectionHandle = createConnection(std::move(eventThread));
399 }
400
401 mInjectVSyncs = enable;
402 return mInjectorConnectionHandle;
403}
404
Ady Abraham9c53ee72020-07-22 21:16:18 -0700405bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime, nsecs_t deadlineTimestamp) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700406 if (!mInjectVSyncs || !mVSyncInjector) {
407 return false;
408 }
409
Ady Abraham9c53ee72020-07-22 21:16:18 -0700410 mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime, deadlineTimestamp);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700411 return true;
412}
413
Ana Krulece588e312018-09-18 12:32:24 -0700414void Scheduler::enableHardwareVsync() {
415 std::lock_guard<std::mutex> lock(mHWVsyncLock);
416 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700417 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700418 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700419 mPrimaryHWVsyncEnabled = true;
420 }
421}
422
423void Scheduler::disableHardwareVsync(bool makeUnavailable) {
424 std::lock_guard<std::mutex> lock(mHWVsyncLock);
425 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700426 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700427 mPrimaryHWVsyncEnabled = false;
428 }
429 if (makeUnavailable) {
430 mHWVsyncAvailable = false;
431 }
432}
433
Ana Krulecc2870422019-01-29 19:00:58 -0800434void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
435 {
436 std::lock_guard<std::mutex> lock(mHWVsyncLock);
437 if (makeAvailable) {
438 mHWVsyncAvailable = makeAvailable;
439 } else if (!mHWVsyncAvailable) {
440 // Hardware vsync is not currently available, so abort the resync
441 // attempt for now
442 return;
443 }
444 }
445
446 if (period <= 0) {
447 return;
448 }
449
450 setVsyncPeriod(period);
451}
452
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700453void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700454 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800455
456 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700457 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800458
459 if (now - last > kIgnoreDelay) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700460 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
Ana Krulecc2870422019-01-29 19:00:58 -0800461 }
462}
463
Dominik Laskowski98041832019-08-01 18:35:59 -0700464void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800465 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ady Abraham8cb21882020-08-26 18:22:05 -0700466 mVsyncSchedule.controller->startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800467
468 if (!mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700469 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700470 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800471 mPrimaryHWVsyncEnabled = true;
472 }
Ana Krulece588e312018-09-18 12:32:24 -0700473}
474
Ady Abraham5dee2f12020-02-05 17:49:47 -0800475void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
476 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700477 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700478 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700479 { // Scope for the lock
480 std::lock_guard<std::mutex> lock(mHWVsyncLock);
481 if (mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700482 needsHwVsync = mVsyncSchedule.controller->addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
483 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700484 }
485 }
486
487 if (needsHwVsync) {
488 enableHardwareVsync();
489 } else {
490 disableHardwareVsync(false);
491 }
492}
493
494void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700495 if (mVsyncSchedule.controller->addPresentFence(fenceTime)) {
Ana Krulece588e312018-09-18 12:32:24 -0700496 enableHardwareVsync();
497 } else {
498 disableHardwareVsync(false);
499 }
500}
501
502void Scheduler::setIgnorePresentFences(bool ignore) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700503 mVsyncSchedule.controller->setIgnorePresentFences(ignore);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800504}
505
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700506void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800507 if (!mLayerHistory) return;
508
Steven Thomasdebafed2020-05-18 17:30:35 -0700509 const auto minFps = mRefreshRateConfigs.getMinRefreshRate().getFps();
510 const auto maxFps = mRefreshRateConfigs.getMaxRefreshRate().getFps();
511
Michael Wright44753b12020-07-08 13:48:11 +0100512 if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700513 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ana Krulec3d367c82020-02-25 15:02:01 -0800514 scheduler::LayerHistory::LayerVoteType::NoVote);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700515 } else if (!mOptions.useContentDetection) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700516 // If the content detection feature is off, all layers are registered at Max. We still keep
517 // the layer history, since we use it for other features (like Frame Rate API), so layers
518 // still need to be registered.
519 mLayerHistory->registerLayer(layer, minFps, maxFps,
520 scheduler::LayerHistory::LayerVoteType::Max);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700521 } else if (!mOptions.useContentDetectionV2) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700522 // In V1 of content detection, all layers are registered as Heuristic (unless it's
523 // wallpaper).
524 const auto highFps =
Michael Wright44753b12020-07-08 13:48:11 +0100525 layer->getWindowType() == InputWindowInfo::Type::WALLPAPER ? minFps : maxFps;
Ana Krulec3d367c82020-02-25 15:02:01 -0800526
Steven Thomasdebafed2020-05-18 17:30:35 -0700527 mLayerHistory->registerLayer(layer, minFps, highFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800528 scheduler::LayerHistory::LayerVoteType::Heuristic);
529 } 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 Abraham4ccdcb42020-02-11 17:34:34 -0800567 mFeatures.contentDetectionV1 =
Ady Abraham8a82ba62020-01-17 12:43:17 -0800568 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
569
Ady Abrahamdfd62162020-06-10 16:11:56 -0700570 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
571 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800572 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700573 // We don't need to change the config, but we might need to send an event
574 // about a config change, since it was suppressed due to a previous idleConsidered
575 if (!consideredSignals.idle) {
576 dispatchCachedReportedConfig();
577 }
Ady Abraham6398a0a2019-04-18 19:30:44 -0700578 return;
579 }
Ady Abraham2139f732019-11-13 18:56:40 -0800580 mFeatures.configId = newConfigId;
Ady Abraham2e1dd892020-03-05 13:48:36 -0800581 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700582 mSchedulerCallback.changeRefreshRate(newRefreshRate,
583 consideredSignals.idle ? ConfigEvent::None
584 : ConfigEvent::Changed);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800585 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800586}
587
Ana Krulecfb772822018-11-30 10:44:07 +0100588void Scheduler::resetIdleTimer() {
589 if (mIdleTimer) {
590 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800591 }
592}
593
Ady Abraham8532d012019-05-08 14:50:56 -0700594void Scheduler::notifyTouchEvent() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700595 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800596 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800597
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700598 if (mOptions.supportKernelTimer && mIdleTimer) {
Steven Thomas540730a2020-01-08 20:12:42 -0800599 mIdleTimer->reset();
600 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800601 }
Ady Abraham8532d012019-05-08 14:50:56 -0700602}
603
Ady Abraham6fe2c172019-07-12 12:37:57 -0700604void Scheduler::setDisplayPowerState(bool normal) {
605 {
606 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700607 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700608 }
609
610 if (mDisplayPowerTimer) {
611 mDisplayPowerTimer->reset();
612 }
613
614 // Display Power event will boost the refresh rate to performance.
615 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800616 if (mLayerHistory) {
617 mLayerHistory->clear();
618 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700619}
620
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700621void Scheduler::kernelIdleTimerCallback(TimerState state) {
622 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100623
Ady Abraham2139f732019-11-13 18:56:40 -0800624 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
625 // magic number
Ady Abraham2e1dd892020-03-05 13:48:36 -0800626 const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800627 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
Ady Abrahamabc27602020-04-08 17:20:29 -0700628 if (state == TimerState::Reset && refreshRate.getFps() > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700629 // If we're not in performance mode then the kernel timer shouldn't do
630 // anything, as the refresh rate during DPU power collapse will be the
631 // same.
Ady Abrahamabc27602020-04-08 17:20:29 -0700632 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
633 } else if (state == TimerState::Expired &&
634 refreshRate.getFps() <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700635 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
636 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700637 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700638 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700639 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800640
641 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700642}
643
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700644void Scheduler::idleTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700645 handleTimerStateChanged(&mFeatures.idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700646 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100647}
648
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700649void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700650 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700651 // Touch event will boost the refresh rate to performance.
652 // Clear layer history to get fresh FPS detection.
653 // NOTE: Instead of checking all the layers, we should be checking the layer
654 // that is currently on top. b/142507166 will give us this capability.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700655 if (handleTimerStateChanged(&mFeatures.touch, touch)) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700656 if (mLayerHistory) {
657 mLayerHistory->clear();
658 }
Ady Abraham1adbb722020-05-15 11:51:48 -0700659 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700660 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700661}
662
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700663void Scheduler::displayPowerTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700664 handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700665 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700666}
667
Dominik Laskowski98041832019-08-01 18:35:59 -0700668void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800669 using base::StringAppendF;
Dominik Laskowski98041832019-08-01 18:35:59 -0700670
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700671 StringAppendF(&result, "+ Idle timer: %s\n", mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Ana Krulec3d367c82020-02-25 15:02:01 -0800672 StringAppendF(&result, "+ Touch timer: %s\n",
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700673 mTouchTimer ? mTouchTimer->dump().c_str() : "off");
674 StringAppendF(&result, "+ Content detection: %s %s\n\n",
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700675 toContentDetectionString(mOptions.useContentDetection,
676 mOptions.useContentDetectionV2),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700677 mLayerHistory ? mLayerHistory->dump().c_str() : "(no layer history)");
Ana Krulecb43429d2019-01-09 14:28:51 -0800678}
679
Ady Abraham8cb21882020-08-26 18:22:05 -0700680void Scheduler::dumpVsync(std::string& s) const {
Ady Abraham8735eac2020-08-12 16:35:04 -0700681 using base::StringAppendF;
682
683 StringAppendF(&s, "VSyncReactor:\n");
Ady Abraham8cb21882020-08-26 18:22:05 -0700684 mVsyncSchedule.controller->dump(s);
Ady Abraham8735eac2020-08-12 16:35:04 -0700685 StringAppendF(&s, "VSyncDispatch:\n");
686 mVsyncSchedule.dispatch->dump(s);
687}
688
Ady Abraham6fe2c172019-07-12 12:37:57 -0700689template <class T>
Ady Abrahamdfd62162020-06-10 16:11:56 -0700690bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
Ady Abraham2139f732019-11-13 18:56:40 -0800691 HwcConfigIndexType newConfigId;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700692 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700693 {
694 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700695 if (*currentState == newState) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700696 return false;
Ady Abraham8532d012019-05-08 14:50:56 -0700697 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700698 *currentState = newState;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700699 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800700 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700701 // We don't need to change the config, but we might need to send an event
702 // about a config change, since it was suppressed due to a previous idleConsidered
703 if (!consideredSignals.idle) {
704 dispatchCachedReportedConfig();
705 }
706 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700707 }
Ady Abraham2139f732019-11-13 18:56:40 -0800708 mFeatures.configId = newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700709 }
Ady Abraham2139f732019-11-13 18:56:40 -0800710 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700711 mSchedulerCallback.changeRefreshRate(newRefreshRate,
712 consideredSignals.idle ? ConfigEvent::None
713 : ConfigEvent::Changed);
714 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700715}
716
Ady Abrahamdfd62162020-06-10 16:11:56 -0700717HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
718 scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800719 ATRACE_CALL();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700720 if (consideredSignals) *consideredSignals = {};
Ady Abraham09bd3922019-04-08 10:44:56 -0700721
Steven Thomasf734df42020-04-13 21:09:28 -0700722 // If Display Power is not in normal operation we want to be in performance mode. When coming
723 // back to normal mode, a grace period is given with DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800724 if (mDisplayPowerTimer &&
725 (!mFeatures.isDisplayPowerStateNormal ||
726 mFeatures.displayPowerTimer == TimerState::Reset)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700727 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800728 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700729
Steven Thomasbb374322020-04-28 22:47:16 -0700730 const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
731 const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
732
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700733 if (!mOptions.useContentDetectionV2) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800734 // As long as touch is active we want to be in performance mode.
Steven Thomasbb374322020-04-28 22:47:16 -0700735 if (touchActive) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700736 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800737 }
Ady Abraham8532d012019-05-08 14:50:56 -0700738
Steven Thomasbb374322020-04-28 22:47:16 -0700739 // If timer has expired as it means there is no new content on the screen.
740 if (idle) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700741 if (consideredSignals) consideredSignals->idle = true;
Steven Thomasbb374322020-04-28 22:47:16 -0700742 return mRefreshRateConfigs.getMinRefreshRateByPolicy().getConfigId();
743 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700744
Ana Krulec3f6a2062020-01-23 15:48:01 -0800745 // If content detection is off we choose performance as we don't know the content fps.
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800746 if (mFeatures.contentDetectionV1 == ContentDetectionState::Off) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800747 // NOTE: V1 always calls this, but this is not a default behavior for V2.
Ady Abrahamabc27602020-04-08 17:20:29 -0700748 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Steven Thomas540730a2020-01-08 20:12:42 -0800749 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800750
751 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abrahamabc27602020-04-08 17:20:29 -0700752 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements)
753 .getConfigId();
Ady Abraham09bd3922019-04-08 10:44:56 -0700754 }
755
Ady Abraham1adbb722020-05-15 11:51:48 -0700756 return mRefreshRateConfigs
Ady Abrahamdfd62162020-06-10 16:11:56 -0700757 .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
758 consideredSignals)
Ady Abraham1adbb722020-05-15 11:51:48 -0700759 .getConfigId();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800760}
761
Ady Abraham2139f732019-11-13 18:56:40 -0800762std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700763 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800764 // Make sure that the default config ID is first updated, before returned.
765 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800766 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800767 }
Ady Abraham2139f732019-11-13 18:56:40 -0800768 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700769}
770
Peiyong Line9d809e2020-04-14 13:10:48 -0700771void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800772 if (timeline.refreshRequired) {
773 mSchedulerCallback.repaintEverythingForHWC();
774 }
775
776 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
777 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
778
779 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
780 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
781 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
782 }
783}
784
785void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
786 bool callRepaint = false;
787 {
788 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
789 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
790 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
791 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
792 } else {
793 // We need to send another refresh as refreshTimeNanos is still in the future
794 callRepaint = true;
795 }
796 }
797 }
798
799 if (callRepaint) {
800 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800801 }
802}
803
Ady Abraham8a82ba62020-01-17 12:43:17 -0800804void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
805 if (mLayerHistory) {
806 mLayerHistory->setDisplayArea(displayArea);
807 }
808}
809
Ana Krulec98b5b242018-08-10 15:03:23 -0700810} // namespace android