blob: 73dc753c7e25b3b846bc714336d5a443511c6f6f [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 Laskowski49cea512019-11-12 14:13:23 -080023#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070024#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
25#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070026#include <configstore/Utils.h>
Ana Krulecfb772822018-11-30 10:44:07 +010027#include <cutils/properties.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
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070034#include <algorithm>
35#include <cinttypes>
36#include <cstdint>
37#include <functional>
38#include <memory>
39#include <numeric>
40
41#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070042#include "DispSync.h"
43#include "DispSyncSource.h"
Ana Krulece588e312018-09-18 12:32:24 -070044#include "EventControlThread.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070045#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070046#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070047#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010048#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090049#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080050#include "Timer.h"
51#include "VSyncDispatchTimerQueue.h"
52#include "VSyncPredictor.h"
53#include "VSyncReactor.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
Ana Krulec98b5b242018-08-10 15:03:23 -070063namespace android {
64
Kevin DuBois00287382019-11-19 15:11:55 -080065std::unique_ptr<DispSync> createDispSync() {
66 // TODO (140302863) remove this and use the vsync_reactor system.
67 if (property_get_bool("debug.sf.vsync_reactor", false)) {
68 // TODO (144707443) tune Predictor tunables.
69 static constexpr int default_rate = 60;
70 static constexpr auto initial_period =
71 std::chrono::duration<nsecs_t, std::ratio<1, default_rate>>(1);
72 static constexpr size_t vsyncTimestampHistorySize = 20;
73 static constexpr size_t minimumSamplesForPrediction = 6;
74 static constexpr uint32_t discardOutlierPercent = 20;
75 auto tracker = std::make_unique<
76 scheduler::VSyncPredictor>(std::chrono::duration_cast<std::chrono::nanoseconds>(
77 initial_period)
78 .count(),
79 vsyncTimestampHistorySize, minimumSamplesForPrediction,
80 discardOutlierPercent);
81
82 static constexpr auto vsyncMoveThreshold =
83 std::chrono::duration_cast<std::chrono::nanoseconds>(3ms);
84 static constexpr auto timerSlack =
85 std::chrono::duration_cast<std::chrono::nanoseconds>(500us);
86 auto dispatch = std::make_unique<
87 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), *tracker,
88 timerSlack.count(), vsyncMoveThreshold.count());
89
90 static constexpr size_t pendingFenceLimit = 20;
91 return std::make_unique<scheduler::VSyncReactor>(std::make_unique<scheduler::SystemClock>(),
92 std::move(dispatch), std::move(tracker),
93 pendingFenceLimit);
94 } else {
95 return std::make_unique<impl::DispSync>("SchedulerDispSync",
96 sysprop::running_without_sync_framework(true));
97 }
98}
99
Ady Abraham09bd3922019-04-08 10:44:56 -0700100Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800101 const scheduler::RefreshRateConfigs& refreshRateConfig,
102 ISchedulerCallback& schedulerCallback)
Kevin DuBois00287382019-11-19 15:11:55 -0800103 : mPrimaryDispSync(createDispSync()),
Dominik Laskowski98041832019-08-01 18:35:59 -0700104 mEventControlThread(new impl::EventControlThread(std::move(function))),
105 mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800106 mSchedulerCallback(schedulerCallback),
Ady Abraham09bd3922019-04-08 10:44:56 -0700107 mRefreshRateConfigs(refreshRateConfig) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700108 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700109
Dominik Laskowski49cea512019-11-12 14:13:23 -0800110 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 -0800111 mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800112 }
113
114 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100115
Dominik Laskowski98041832019-08-01 18:35:59 -0700116 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
117 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
118 : &Scheduler::idleTimerCallback;
119
120 mIdleTimer.emplace(
121 std::chrono::milliseconds(millis),
122 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
123 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100124 mIdleTimer->start();
125 }
Ady Abraham8532d012019-05-08 14:50:56 -0700126
Dominik Laskowski98041832019-08-01 18:35:59 -0700127 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700128 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700129 mTouchTimer.emplace(
130 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700131 [this] { touchTimerCallback(TimerState::Reset); },
132 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700133 mTouchTimer->start();
134 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700135
Dominik Laskowski98041832019-08-01 18:35:59 -0700136 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
137 mDisplayPowerTimer.emplace(
138 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700139 [this] { displayPowerTimerCallback(TimerState::Reset); },
140 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700141 mDisplayPowerTimer->start();
142 }
Ana Krulece588e312018-09-18 12:32:24 -0700143}
144
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700145Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
146 std::unique_ptr<EventControlThread> eventControlThread,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800147 const scheduler::RefreshRateConfigs& configs,
148 ISchedulerCallback& schedulerCallback)
Dominik Laskowski98041832019-08-01 18:35:59 -0700149 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700150 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700151 mSupportKernelTimer(false),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800152 mSchedulerCallback(schedulerCallback),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700153 mRefreshRateConfigs(configs) {}
154
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800155Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700156 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700157 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700158 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800159 mIdleTimer.reset();
160}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700161
Dominik Laskowski98041832019-08-01 18:35:59 -0700162DispSync& Scheduler::getPrimaryDispSync() {
163 return *mPrimaryDispSync;
164}
165
Ady Abraham9e16a482019-12-03 17:19:41 -0800166std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
167 nsecs_t phaseOffsetNs) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700168 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
Ady Abraham9e16a482019-12-03 17:19:41 -0800169 true /* traceVsync */, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700170}
171
Dominik Laskowski98041832019-08-01 18:35:59 -0700172Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham9e16a482019-12-03 17:19:41 -0800173 const char* connectionName, nsecs_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700174 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9e16a482019-12-03 17:19:41 -0800175 auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700176 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
177 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700178 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700179}
Ana Krulec98b5b242018-08-10 15:03:23 -0700180
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700181Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700182 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
183 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800184
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700185 auto connection =
186 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700187
188 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
189 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700190}
191
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700192sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700193 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
194 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700195}
196
Ana Krulec98b5b242018-08-10 15:03:23 -0700197sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700198 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700199 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700200 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700201}
202
Dominik Laskowski98041832019-08-01 18:35:59 -0700203sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
204 RETURN_IF_INVALID_HANDLE(handle, nullptr);
205 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700206}
207
Dominik Laskowski98041832019-08-01 18:35:59 -0700208void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
209 bool connected) {
210 RETURN_IF_INVALID_HANDLE(handle);
211 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700212}
213
Dominik Laskowski98041832019-08-01 18:35:59 -0700214void Scheduler::onScreenAcquired(ConnectionHandle handle) {
215 RETURN_IF_INVALID_HANDLE(handle);
216 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700217}
218
Dominik Laskowski98041832019-08-01 18:35:59 -0700219void Scheduler::onScreenReleased(ConnectionHandle handle) {
220 RETURN_IF_INVALID_HANDLE(handle);
221 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700222}
223
Dominik Laskowski98041832019-08-01 18:35:59 -0700224void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700225 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700226 RETURN_IF_INVALID_HANDLE(handle);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700227 mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800228}
229
Dominik Laskowski98041832019-08-01 18:35:59 -0700230void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
231 RETURN_IF_INVALID_HANDLE(handle);
232 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700233}
234
Dominik Laskowski98041832019-08-01 18:35:59 -0700235void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
236 RETURN_IF_INVALID_HANDLE(handle);
237 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700238}
Ana Krulece588e312018-09-18 12:32:24 -0700239
240void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
241 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
242 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
243}
244
Dominik Laskowski6505f792019-09-18 11:10:05 -0700245Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
246 if (mInjectVSyncs == enable) {
247 return {};
248 }
249
250 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
251
252 if (!mInjectorConnectionHandle) {
253 auto vsyncSource = std::make_unique<InjectVSyncSource>();
254 mVSyncInjector = vsyncSource.get();
255
256 auto eventThread =
257 std::make_unique<impl::EventThread>(std::move(vsyncSource),
258 impl::EventThread::InterceptVSyncsCallback());
259
260 mInjectorConnectionHandle = createConnection(std::move(eventThread));
261 }
262
263 mInjectVSyncs = enable;
264 return mInjectorConnectionHandle;
265}
266
267bool Scheduler::injectVSync(nsecs_t when) {
268 if (!mInjectVSyncs || !mVSyncInjector) {
269 return false;
270 }
271
272 mVSyncInjector->onInjectSyncEvent(when);
273 return true;
274}
275
Ana Krulece588e312018-09-18 12:32:24 -0700276void Scheduler::enableHardwareVsync() {
277 std::lock_guard<std::mutex> lock(mHWVsyncLock);
278 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
279 mPrimaryDispSync->beginResync();
280 mEventControlThread->setVsyncEnabled(true);
281 mPrimaryHWVsyncEnabled = true;
282 }
283}
284
285void Scheduler::disableHardwareVsync(bool makeUnavailable) {
286 std::lock_guard<std::mutex> lock(mHWVsyncLock);
287 if (mPrimaryHWVsyncEnabled) {
288 mEventControlThread->setVsyncEnabled(false);
289 mPrimaryDispSync->endResync();
290 mPrimaryHWVsyncEnabled = false;
291 }
292 if (makeUnavailable) {
293 mHWVsyncAvailable = false;
294 }
295}
296
Ana Krulecc2870422019-01-29 19:00:58 -0800297void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
298 {
299 std::lock_guard<std::mutex> lock(mHWVsyncLock);
300 if (makeAvailable) {
301 mHWVsyncAvailable = makeAvailable;
302 } else if (!mHWVsyncAvailable) {
303 // Hardware vsync is not currently available, so abort the resync
304 // attempt for now
305 return;
306 }
307 }
308
309 if (period <= 0) {
310 return;
311 }
312
313 setVsyncPeriod(period);
314}
315
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700316void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700317 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800318
319 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700320 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800321
322 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800323 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800324 }
325}
326
Dominik Laskowski98041832019-08-01 18:35:59 -0700327void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800328 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700329 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800330
331 if (!mPrimaryHWVsyncEnabled) {
332 mPrimaryDispSync->beginResync();
333 mEventControlThread->setVsyncEnabled(true);
334 mPrimaryHWVsyncEnabled = true;
335 }
Ana Krulece588e312018-09-18 12:32:24 -0700336}
337
Dominik Laskowski98041832019-08-01 18:35:59 -0700338void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700339 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700340 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700341 { // Scope for the lock
342 std::lock_guard<std::mutex> lock(mHWVsyncLock);
343 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700344 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700345 }
346 }
347
348 if (needsHwVsync) {
349 enableHardwareVsync();
350 } else {
351 disableHardwareVsync(false);
352 }
353}
354
355void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
356 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
357 enableHardwareVsync();
358 } else {
359 disableHardwareVsync(false);
360 }
361}
362
363void Scheduler::setIgnorePresentFences(bool ignore) {
364 mPrimaryDispSync->setIgnorePresentFences(ignore);
365}
366
Ady Abraham8fe11022019-06-12 17:11:12 -0700367nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800368 return mPrimaryDispSync->expectedPresentTime();
369}
370
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700371void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800372 if (!mLayerHistory) return;
373
Ady Abraham2139f732019-11-13 18:56:40 -0800374 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
375 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
376 ? lowFps
377 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800378
379 mLayerHistory->registerLayer(layer, lowFps, highFps);
Ady Abraham09bd3922019-04-08 10:44:56 -0700380}
381
Ady Abraham2139f732019-11-13 18:56:40 -0800382void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800383 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800384 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800385 }
Ana Krulec3084c052018-11-21 20:27:17 +0100386}
387
Dominik Laskowski49cea512019-11-12 14:13:23 -0800388void Scheduler::chooseRefreshRateForContent() {
389 if (!mLayerHistory) return;
390
Ady Abraham2139f732019-11-13 18:56:40 -0800391 auto [refreshRate] = mLayerHistory->summarize(systemTime());
Ady Abrahama315ce72019-04-24 14:35:20 -0700392 const uint32_t refreshRateRound = std::round(refreshRate);
Ady Abraham2139f732019-11-13 18:56:40 -0800393 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700394 {
395 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800396 if (mFeatures.contentRefreshRate == refreshRateRound) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700397 return;
398 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700399 mFeatures.contentRefreshRate = refreshRateRound;
400 ATRACE_INT("ContentFPS", refreshRateRound);
Ady Abraham6398a0a2019-04-18 19:30:44 -0700401
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700402 mFeatures.contentDetection =
403 refreshRateRound > 0 ? ContentDetectionState::On : ContentDetectionState::Off;
Ady Abraham2139f732019-11-13 18:56:40 -0800404 newConfigId = calculateRefreshRateType();
405 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700406 return;
407 }
Ady Abraham2139f732019-11-13 18:56:40 -0800408 mFeatures.configId = newConfigId;
409 };
410 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800411 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
Ady Abrahama1a49af2019-02-07 14:36:55 -0800412}
413
Ana Krulecfb772822018-11-30 10:44:07 +0100414void Scheduler::resetIdleTimer() {
415 if (mIdleTimer) {
416 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800417 }
418}
419
Ady Abraham8532d012019-05-08 14:50:56 -0700420void Scheduler::notifyTouchEvent() {
421 if (mTouchTimer) {
422 mTouchTimer->reset();
423 }
424
Dominik Laskowski98041832019-08-01 18:35:59 -0700425 if (mSupportKernelTimer && mIdleTimer) {
426 mIdleTimer->reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700427 }
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700428
429 // Touch event will boost the refresh rate to performance.
430 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800431 if (mLayerHistory) {
432 mLayerHistory->clear();
433 }
Ady Abraham8532d012019-05-08 14:50:56 -0700434}
435
Ady Abraham6fe2c172019-07-12 12:37:57 -0700436void Scheduler::setDisplayPowerState(bool normal) {
437 {
438 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700439 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700440 }
441
442 if (mDisplayPowerTimer) {
443 mDisplayPowerTimer->reset();
444 }
445
446 // Display Power event will boost the refresh rate to performance.
447 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800448 if (mLayerHistory) {
449 mLayerHistory->clear();
450 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700451}
452
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700453void Scheduler::kernelIdleTimerCallback(TimerState state) {
454 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100455
Ady Abraham2139f732019-11-13 18:56:40 -0800456 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
457 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700458 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800459 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
460 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700461 // If we're not in performance mode then the kernel timer shouldn't do
462 // anything, as the refresh rate during DPU power collapse will be the
463 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800464 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
465 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700466 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
467 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
468 // need to update the DispSync model anyway.
469 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700470 }
471}
472
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700473void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700474 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700475 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100476}
477
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700478void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700479 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
480 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700481 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700482}
483
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700484void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700485 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
486 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700487 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700488}
489
Dominik Laskowski98041832019-08-01 18:35:59 -0700490void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800491 using base::StringAppendF;
492 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700493
Dominik Laskowski49cea512019-11-12 14:13:23 -0800494 const bool supported = mRefreshRateConfigs.refreshRateSwitchingSupported();
495 StringAppendF(&result, "+ Refresh rate switching: %s\n", states[supported]);
Ady Abrahame3ed2f92020-01-06 17:01:28 -0800496 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory != nullptr]);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800497
498 StringAppendF(&result, "+ Idle timer: %s\n",
499 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
500 StringAppendF(&result, "+ Touch timer: %s\n\n",
501 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800502}
503
Ady Abraham6fe2c172019-07-12 12:37:57 -0700504template <class T>
505void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700506 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800507 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700508 {
509 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700510 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700511 return;
512 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700513 *currentState = newState;
Ady Abraham2139f732019-11-13 18:56:40 -0800514 newConfigId = calculateRefreshRateType();
515 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700516 return;
517 }
Ady Abraham2139f732019-11-13 18:56:40 -0800518 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700519 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700520 event = ConfigEvent::Changed;
521 }
522 }
Ady Abraham2139f732019-11-13 18:56:40 -0800523 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800524 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700525}
526
Ady Abraham2139f732019-11-13 18:56:40 -0800527HwcConfigIndexType Scheduler::calculateRefreshRateType() {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700528 if (!mRefreshRateConfigs.refreshRateSwitchingSupported()) {
Ady Abraham2139f732019-11-13 18:56:40 -0800529 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700530 }
531
Ady Abraham6fe2c172019-07-12 12:37:57 -0700532 // If Display Power is not in normal operation we want to be in performance mode.
533 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700534 if (!mFeatures.isDisplayPowerStateNormal || mFeatures.displayPowerTimer == TimerState::Reset) {
Ady Abraham2139f732019-11-13 18:56:40 -0800535 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700536 }
537
Ady Abraham8532d012019-05-08 14:50:56 -0700538 // As long as touch is active we want to be in performance mode
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700539 if (mFeatures.touch == TouchState::Active) {
Ady Abraham2139f732019-11-13 18:56:40 -0800540 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham8532d012019-05-08 14:50:56 -0700541 }
542
543 // If timer has expired as it means there is no new content on the screen
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700544 if (mFeatures.idleTimer == TimerState::Expired) {
Ady Abraham2139f732019-11-13 18:56:40 -0800545 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
Ady Abrahama315ce72019-04-24 14:35:20 -0700546 }
547
Ady Abraham09bd3922019-04-08 10:44:56 -0700548 // If content detection is off we choose performance as we don't know the content fps
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700549 if (mFeatures.contentDetection == ContentDetectionState::Off) {
Ady Abraham2139f732019-11-13 18:56:40 -0800550 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700551 }
552
Wei Wang09be73f2019-07-02 14:29:18 -0700553 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham2139f732019-11-13 18:56:40 -0800554 return mRefreshRateConfigs
555 .getRefreshRateForContent(static_cast<float>(mFeatures.contentRefreshRate))
556 .configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800557}
558
Ady Abraham2139f732019-11-13 18:56:40 -0800559std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700560 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800561 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700562}
563
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800564void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
565 if (timeline.refreshRequired) {
566 mSchedulerCallback.repaintEverythingForHWC();
567 }
568
569 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
570 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
571
572 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
573 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
574 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
575 }
576}
577
578void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
579 bool callRepaint = false;
580 {
581 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
582 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
583 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
584 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
585 } else {
586 // We need to send another refresh as refreshTimeNanos is still in the future
587 callRepaint = true;
588 }
589 }
590 }
591
592 if (callRepaint) {
593 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800594 }
595}
596
Ana Krulec98b5b242018-08-10 15:03:23 -0700597} // namespace android