blob: 0b645c41c1a56a9f235d3d8003baf0bcbb509f6c [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
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dominik Laskowski98041832019-08-01 18:35:59 -070021#undef LOG_TAG
22#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Ana Krulec98b5b242018-08-10 15:03:23 -070025#include "Scheduler.h"
26
Dominik Laskowski49cea512019-11-12 14:13:23 -080027#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070028#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070030#include <configstore/Utils.h>
Ana Krulecfb772822018-11-30 10:44:07 +010031#include <cutils/properties.h>
Ady Abraham8f1ee7f2019-04-05 10:32:50 -070032#include <input/InputWindow.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080033#include <system/window.h>
Ana Krulece588e312018-09-18 12:32:24 -070034#include <ui/DisplayStatInfo.h>
Ana Krulec3084c052018-11-21 20:27:17 +010035#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010036#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070037
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070038#include <algorithm>
39#include <cinttypes>
40#include <cstdint>
41#include <functional>
42#include <memory>
43#include <numeric>
44
45#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070046#include "DispSync.h"
47#include "DispSyncSource.h"
Ana Krulece588e312018-09-18 12:32:24 -070048#include "EventControlThread.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070049#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070050#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070051#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010052#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090053#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080054#include "Timer.h"
55#include "VSyncDispatchTimerQueue.h"
56#include "VSyncPredictor.h"
57#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070058
Dominik Laskowski98041832019-08-01 18:35:59 -070059#define RETURN_IF_INVALID_HANDLE(handle, ...) \
60 do { \
61 if (mConnections.count(handle) == 0) { \
62 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
63 return __VA_ARGS__; \
64 } \
65 } while (false)
66
Ana Krulec98b5b242018-08-10 15:03:23 -070067namespace android {
68
Kevin DuBois00287382019-11-19 15:11:55 -080069std::unique_ptr<DispSync> createDispSync() {
70 // TODO (140302863) remove this and use the vsync_reactor system.
71 if (property_get_bool("debug.sf.vsync_reactor", false)) {
72 // TODO (144707443) tune Predictor tunables.
73 static constexpr int default_rate = 60;
74 static constexpr auto initial_period =
75 std::chrono::duration<nsecs_t, std::ratio<1, default_rate>>(1);
76 static constexpr size_t vsyncTimestampHistorySize = 20;
77 static constexpr size_t minimumSamplesForPrediction = 6;
78 static constexpr uint32_t discardOutlierPercent = 20;
79 auto tracker = std::make_unique<
80 scheduler::VSyncPredictor>(std::chrono::duration_cast<std::chrono::nanoseconds>(
81 initial_period)
82 .count(),
83 vsyncTimestampHistorySize, minimumSamplesForPrediction,
84 discardOutlierPercent);
85
86 static constexpr auto vsyncMoveThreshold =
87 std::chrono::duration_cast<std::chrono::nanoseconds>(3ms);
88 static constexpr auto timerSlack =
89 std::chrono::duration_cast<std::chrono::nanoseconds>(500us);
90 auto dispatch = std::make_unique<
91 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), *tracker,
92 timerSlack.count(), vsyncMoveThreshold.count());
93
94 static constexpr size_t pendingFenceLimit = 20;
95 return std::make_unique<scheduler::VSyncReactor>(std::make_unique<scheduler::SystemClock>(),
96 std::move(dispatch), std::move(tracker),
97 pendingFenceLimit);
98 } else {
99 return std::make_unique<impl::DispSync>("SchedulerDispSync",
100 sysprop::running_without_sync_framework(true));
101 }
102}
103
Ady Abraham09bd3922019-04-08 10:44:56 -0700104Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800105 const scheduler::RefreshRateConfigs& refreshRateConfig,
106 ISchedulerCallback& schedulerCallback)
Kevin DuBois00287382019-11-19 15:11:55 -0800107 : mPrimaryDispSync(createDispSync()),
Dominik Laskowski98041832019-08-01 18:35:59 -0700108 mEventControlThread(new impl::EventControlThread(std::move(function))),
109 mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800110 mSchedulerCallback(schedulerCallback),
Ady Abraham09bd3922019-04-08 10:44:56 -0700111 mRefreshRateConfigs(refreshRateConfig) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700112 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700113
Dominik Laskowski49cea512019-11-12 14:13:23 -0800114 if (property_get_bool("debug.sf.use_smart_90_for_video", 0) || use_smart_90_for_video(false)) {
Ady Abrahame3ed2f92020-01-06 17:01:28 -0800115 mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800116 }
117
118 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100119
Dominik Laskowski98041832019-08-01 18:35:59 -0700120 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
121 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
122 : &Scheduler::idleTimerCallback;
123
124 mIdleTimer.emplace(
125 std::chrono::milliseconds(millis),
126 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
127 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100128 mIdleTimer->start();
129 }
Ady Abraham8532d012019-05-08 14:50:56 -0700130
Dominik Laskowski98041832019-08-01 18:35:59 -0700131 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700132 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700133 mTouchTimer.emplace(
134 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700135 [this] { touchTimerCallback(TimerState::Reset); },
136 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700137 mTouchTimer->start();
138 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700139
Dominik Laskowski98041832019-08-01 18:35:59 -0700140 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
141 mDisplayPowerTimer.emplace(
142 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700143 [this] { displayPowerTimerCallback(TimerState::Reset); },
144 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700145 mDisplayPowerTimer->start();
146 }
Ana Krulece588e312018-09-18 12:32:24 -0700147}
148
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700149Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
150 std::unique_ptr<EventControlThread> eventControlThread,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800151 const scheduler::RefreshRateConfigs& configs,
152 ISchedulerCallback& schedulerCallback)
Dominik Laskowski98041832019-08-01 18:35:59 -0700153 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700154 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700155 mSupportKernelTimer(false),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800156 mSchedulerCallback(schedulerCallback),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700157 mRefreshRateConfigs(configs) {}
158
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800159Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700160 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700161 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700162 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800163 mIdleTimer.reset();
164}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700165
Dominik Laskowski98041832019-08-01 18:35:59 -0700166DispSync& Scheduler::getPrimaryDispSync() {
167 return *mPrimaryDispSync;
168}
169
Ady Abraham9e16a482019-12-03 17:19:41 -0800170std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
171 nsecs_t phaseOffsetNs) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700172 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
Ady Abraham9e16a482019-12-03 17:19:41 -0800173 true /* traceVsync */, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700174}
175
Dominik Laskowski98041832019-08-01 18:35:59 -0700176Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham9e16a482019-12-03 17:19:41 -0800177 const char* connectionName, nsecs_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700178 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9e16a482019-12-03 17:19:41 -0800179 auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700180 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
181 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700182 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700183}
Ana Krulec98b5b242018-08-10 15:03:23 -0700184
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700185Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700186 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
187 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800188
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700189 auto connection =
190 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700191
192 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
193 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700194}
195
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700196sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700197 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
198 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700199}
200
Ana Krulec98b5b242018-08-10 15:03:23 -0700201sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700202 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700203 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700204 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700205}
206
Dominik Laskowski98041832019-08-01 18:35:59 -0700207sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
208 RETURN_IF_INVALID_HANDLE(handle, nullptr);
209 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700210}
211
Dominik Laskowski98041832019-08-01 18:35:59 -0700212void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
213 bool connected) {
214 RETURN_IF_INVALID_HANDLE(handle);
215 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700216}
217
Dominik Laskowski98041832019-08-01 18:35:59 -0700218void Scheduler::onScreenAcquired(ConnectionHandle handle) {
219 RETURN_IF_INVALID_HANDLE(handle);
220 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700221}
222
Dominik Laskowski98041832019-08-01 18:35:59 -0700223void Scheduler::onScreenReleased(ConnectionHandle handle) {
224 RETURN_IF_INVALID_HANDLE(handle);
225 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700226}
227
Dominik Laskowski98041832019-08-01 18:35:59 -0700228void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700229 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700230 RETURN_IF_INVALID_HANDLE(handle);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700231 mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800232}
233
Dominik Laskowski98041832019-08-01 18:35:59 -0700234void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
235 RETURN_IF_INVALID_HANDLE(handle);
236 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700237}
238
Dominik Laskowski98041832019-08-01 18:35:59 -0700239void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
240 RETURN_IF_INVALID_HANDLE(handle);
241 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700242}
Ana Krulece588e312018-09-18 12:32:24 -0700243
244void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
245 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
246 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
247}
248
Dominik Laskowski6505f792019-09-18 11:10:05 -0700249Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
250 if (mInjectVSyncs == enable) {
251 return {};
252 }
253
254 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
255
256 if (!mInjectorConnectionHandle) {
257 auto vsyncSource = std::make_unique<InjectVSyncSource>();
258 mVSyncInjector = vsyncSource.get();
259
260 auto eventThread =
261 std::make_unique<impl::EventThread>(std::move(vsyncSource),
262 impl::EventThread::InterceptVSyncsCallback());
263
264 mInjectorConnectionHandle = createConnection(std::move(eventThread));
265 }
266
267 mInjectVSyncs = enable;
268 return mInjectorConnectionHandle;
269}
270
271bool Scheduler::injectVSync(nsecs_t when) {
272 if (!mInjectVSyncs || !mVSyncInjector) {
273 return false;
274 }
275
276 mVSyncInjector->onInjectSyncEvent(when);
277 return true;
278}
279
Ana Krulece588e312018-09-18 12:32:24 -0700280void Scheduler::enableHardwareVsync() {
281 std::lock_guard<std::mutex> lock(mHWVsyncLock);
282 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
283 mPrimaryDispSync->beginResync();
284 mEventControlThread->setVsyncEnabled(true);
285 mPrimaryHWVsyncEnabled = true;
286 }
287}
288
289void Scheduler::disableHardwareVsync(bool makeUnavailable) {
290 std::lock_guard<std::mutex> lock(mHWVsyncLock);
291 if (mPrimaryHWVsyncEnabled) {
292 mEventControlThread->setVsyncEnabled(false);
293 mPrimaryDispSync->endResync();
294 mPrimaryHWVsyncEnabled = false;
295 }
296 if (makeUnavailable) {
297 mHWVsyncAvailable = false;
298 }
299}
300
Ana Krulecc2870422019-01-29 19:00:58 -0800301void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
302 {
303 std::lock_guard<std::mutex> lock(mHWVsyncLock);
304 if (makeAvailable) {
305 mHWVsyncAvailable = makeAvailable;
306 } else if (!mHWVsyncAvailable) {
307 // Hardware vsync is not currently available, so abort the resync
308 // attempt for now
309 return;
310 }
311 }
312
313 if (period <= 0) {
314 return;
315 }
316
317 setVsyncPeriod(period);
318}
319
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700320void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700321 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800322
323 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700324 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800325
326 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800327 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800328 }
329}
330
Dominik Laskowski98041832019-08-01 18:35:59 -0700331void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800332 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700333 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800334
335 if (!mPrimaryHWVsyncEnabled) {
336 mPrimaryDispSync->beginResync();
337 mEventControlThread->setVsyncEnabled(true);
338 mPrimaryHWVsyncEnabled = true;
339 }
Ana Krulece588e312018-09-18 12:32:24 -0700340}
341
Dominik Laskowski98041832019-08-01 18:35:59 -0700342void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700343 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700344 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700345 { // Scope for the lock
346 std::lock_guard<std::mutex> lock(mHWVsyncLock);
347 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700348 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700349 }
350 }
351
352 if (needsHwVsync) {
353 enableHardwareVsync();
354 } else {
355 disableHardwareVsync(false);
356 }
357}
358
359void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
360 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
361 enableHardwareVsync();
362 } else {
363 disableHardwareVsync(false);
364 }
365}
366
367void Scheduler::setIgnorePresentFences(bool ignore) {
368 mPrimaryDispSync->setIgnorePresentFences(ignore);
369}
370
Ady Abraham8fe11022019-06-12 17:11:12 -0700371nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800372 return mPrimaryDispSync->expectedPresentTime();
373}
374
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700375void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800376 if (!mLayerHistory) return;
377
Ady Abraham2139f732019-11-13 18:56:40 -0800378 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
379 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
380 ? lowFps
381 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800382
383 mLayerHistory->registerLayer(layer, lowFps, highFps);
Ady Abraham09bd3922019-04-08 10:44:56 -0700384}
385
Ady Abraham2139f732019-11-13 18:56:40 -0800386void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800387 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800388 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800389 }
Ana Krulec3084c052018-11-21 20:27:17 +0100390}
391
Dominik Laskowski49cea512019-11-12 14:13:23 -0800392void Scheduler::chooseRefreshRateForContent() {
393 if (!mLayerHistory) return;
394
Ady Abraham2139f732019-11-13 18:56:40 -0800395 auto [refreshRate] = mLayerHistory->summarize(systemTime());
Ady Abrahama315ce72019-04-24 14:35:20 -0700396 const uint32_t refreshRateRound = std::round(refreshRate);
Ady Abraham2139f732019-11-13 18:56:40 -0800397 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700398 {
399 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800400 if (mFeatures.contentRefreshRate == refreshRateRound) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700401 return;
402 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700403 mFeatures.contentRefreshRate = refreshRateRound;
404 ATRACE_INT("ContentFPS", refreshRateRound);
Ady Abraham6398a0a2019-04-18 19:30:44 -0700405
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700406 mFeatures.contentDetection =
407 refreshRateRound > 0 ? ContentDetectionState::On : ContentDetectionState::Off;
Ady Abraham2139f732019-11-13 18:56:40 -0800408 newConfigId = calculateRefreshRateType();
409 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700410 return;
411 }
Ady Abraham2139f732019-11-13 18:56:40 -0800412 mFeatures.configId = newConfigId;
413 };
414 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800415 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
Ady Abrahama1a49af2019-02-07 14:36:55 -0800416}
417
Ana Krulecfb772822018-11-30 10:44:07 +0100418void Scheduler::resetIdleTimer() {
419 if (mIdleTimer) {
420 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800421 }
422}
423
Ady Abraham8532d012019-05-08 14:50:56 -0700424void Scheduler::notifyTouchEvent() {
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700425 // Touch event will boost the refresh rate to performance.
Steven Thomas540730a2020-01-08 20:12:42 -0800426 // Clear Layer History to get fresh FPS detection.
427 // NOTE: Instead of checking all the layers, we should be checking the layer
428 // that is currently on top. b/142507166 will give us this capability.
429 if (mLayerHistory && !mLayerHistory->hasClientSpecifiedFrameRate()) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800430 mLayerHistory->clear();
Steven Thomas540730a2020-01-08 20:12:42 -0800431
432 if (mTouchTimer) {
433 mTouchTimer->reset();
434 }
435
436 if (mSupportKernelTimer && mIdleTimer) {
437 mIdleTimer->reset();
438 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800439 }
Ady Abraham8532d012019-05-08 14:50:56 -0700440}
441
Ady Abraham6fe2c172019-07-12 12:37:57 -0700442void Scheduler::setDisplayPowerState(bool normal) {
443 {
444 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700445 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700446 }
447
448 if (mDisplayPowerTimer) {
449 mDisplayPowerTimer->reset();
450 }
451
452 // Display Power event will boost the refresh rate to performance.
453 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800454 if (mLayerHistory) {
455 mLayerHistory->clear();
456 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700457}
458
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700459void Scheduler::kernelIdleTimerCallback(TimerState state) {
460 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100461
Ady Abraham2139f732019-11-13 18:56:40 -0800462 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
463 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700464 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800465 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
466 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700467 // If we're not in performance mode then the kernel timer shouldn't do
468 // anything, as the refresh rate during DPU power collapse will be the
469 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800470 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
471 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700472 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
473 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
474 // need to update the DispSync model anyway.
475 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700476 }
477}
478
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700479void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700480 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700481 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100482}
483
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700484void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700485 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
486 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700487 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700488}
489
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700490void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700491 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
492 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700493 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700494}
495
Dominik Laskowski98041832019-08-01 18:35:59 -0700496void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800497 using base::StringAppendF;
498 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700499
Dominik Laskowski49cea512019-11-12 14:13:23 -0800500 const bool supported = mRefreshRateConfigs.refreshRateSwitchingSupported();
501 StringAppendF(&result, "+ Refresh rate switching: %s\n", states[supported]);
Ady Abrahame3ed2f92020-01-06 17:01:28 -0800502 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory != nullptr]);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800503
504 StringAppendF(&result, "+ Idle timer: %s\n",
505 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
506 StringAppendF(&result, "+ Touch timer: %s\n\n",
507 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800508}
509
Ady Abraham6fe2c172019-07-12 12:37:57 -0700510template <class T>
511void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700512 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800513 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700514 {
515 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700516 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700517 return;
518 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700519 *currentState = newState;
Ady Abraham2139f732019-11-13 18:56:40 -0800520 newConfigId = calculateRefreshRateType();
521 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700522 return;
523 }
Ady Abraham2139f732019-11-13 18:56:40 -0800524 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700525 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700526 event = ConfigEvent::Changed;
527 }
528 }
Ady Abraham2139f732019-11-13 18:56:40 -0800529 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800530 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700531}
532
Ady Abraham2139f732019-11-13 18:56:40 -0800533HwcConfigIndexType Scheduler::calculateRefreshRateType() {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700534 if (!mRefreshRateConfigs.refreshRateSwitchingSupported()) {
Ady Abraham2139f732019-11-13 18:56:40 -0800535 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700536 }
537
Steven Thomas540730a2020-01-08 20:12:42 -0800538 // If the layer history doesn't have the frame rate specified, use the old path. NOTE:
539 // if we remove the kernel idle timer, and use our internal idle timer, this code will have to
540 // be refactored.
541 if (!mLayerHistory->hasClientSpecifiedFrameRate()) {
542 // If Display Power is not in normal operation we want to be in performance mode.
543 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
544 if (!mFeatures.isDisplayPowerStateNormal ||
545 mFeatures.displayPowerTimer == TimerState::Reset) {
546 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
547 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700548
Steven Thomas540730a2020-01-08 20:12:42 -0800549 // As long as touch is active we want to be in performance mode
550 if (mFeatures.touch == TouchState::Active) {
551 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
552 }
Ady Abraham8532d012019-05-08 14:50:56 -0700553
Steven Thomas540730a2020-01-08 20:12:42 -0800554 // If timer has expired as it means there is no new content on the screen
555 if (mFeatures.idleTimer == TimerState::Expired) {
556 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
557 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700558
Steven Thomas540730a2020-01-08 20:12:42 -0800559 // If content detection is off we choose performance as we don't know the content fps
560 if (mFeatures.contentDetection == ContentDetectionState::Off) {
561 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
562 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700563 }
564
Wei Wang09be73f2019-07-02 14:29:18 -0700565 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham2139f732019-11-13 18:56:40 -0800566 return mRefreshRateConfigs
567 .getRefreshRateForContent(static_cast<float>(mFeatures.contentRefreshRate))
568 .configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800569}
570
Ady Abraham2139f732019-11-13 18:56:40 -0800571std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700572 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800573 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700574}
575
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800576void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
577 if (timeline.refreshRequired) {
578 mSchedulerCallback.repaintEverythingForHWC();
579 }
580
581 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
582 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
583
584 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
585 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
586 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
587 }
588}
589
590void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
591 bool callRepaint = false;
592 {
593 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
594 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
595 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
596 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
597 } else {
598 // We need to send another refresh as refreshTimeNanos is still in the future
599 callRepaint = true;
600 }
601 }
602 }
603
604 if (callRepaint) {
605 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800606 }
607}
608
Ana Krulec98b5b242018-08-10 15:03:23 -0700609} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800610
611// TODO(b/129481165): remove the #pragma below and fix conversion issues
612#pragma clang diagnostic pop // ignored "-Wconversion"