blob: 3119bde5391482dec5ae2e76020fe293f8651f18 [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)) {
111 mLayerHistory.emplace();
112 }
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
Dominik Laskowski6505f792019-09-18 11:10:05 -0700166std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
167 const char* name, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync) {
168 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
169 offsetThresholdForNextVsync, true /* traceVsync */,
170 name);
171}
172
Dominik Laskowski98041832019-08-01 18:35:59 -0700173Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham45e4e362019-06-07 18:20:51 -0700174 const char* connectionName, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync,
Ana Krulec98b5b242018-08-10 15:03:23 -0700175 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700176 auto vsyncSource =
177 makePrimaryDispSyncSource(connectionName, phaseOffsetNs, offsetThresholdForNextVsync);
178 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
179 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700180 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700181}
Ana Krulec98b5b242018-08-10 15:03:23 -0700182
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700183Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700184 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
185 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800186
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700187 auto connection =
188 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700189
190 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
191 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700192}
193
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700194sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700195 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
196 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700197}
198
Ana Krulec98b5b242018-08-10 15:03:23 -0700199sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700200 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700201 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700202 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700203}
204
Dominik Laskowski98041832019-08-01 18:35:59 -0700205sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
206 RETURN_IF_INVALID_HANDLE(handle, nullptr);
207 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700208}
209
Dominik Laskowski98041832019-08-01 18:35:59 -0700210void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
211 bool connected) {
212 RETURN_IF_INVALID_HANDLE(handle);
213 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700214}
215
Dominik Laskowski98041832019-08-01 18:35:59 -0700216void Scheduler::onScreenAcquired(ConnectionHandle handle) {
217 RETURN_IF_INVALID_HANDLE(handle);
218 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700219}
220
Dominik Laskowski98041832019-08-01 18:35:59 -0700221void Scheduler::onScreenReleased(ConnectionHandle handle) {
222 RETURN_IF_INVALID_HANDLE(handle);
223 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700224}
225
Dominik Laskowski98041832019-08-01 18:35:59 -0700226void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Ady Abraham2139f732019-11-13 18:56:40 -0800227 HwcConfigIndexType configId) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700228 RETURN_IF_INVALID_HANDLE(handle);
229 mConnections[handle].thread->onConfigChanged(displayId, configId);
Ady Abraham447052e2019-02-13 16:07:27 -0800230}
231
Dominik Laskowski98041832019-08-01 18:35:59 -0700232void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
233 RETURN_IF_INVALID_HANDLE(handle);
234 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700235}
236
Dominik Laskowski98041832019-08-01 18:35:59 -0700237void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
238 RETURN_IF_INVALID_HANDLE(handle);
239 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700240}
Ana Krulece588e312018-09-18 12:32:24 -0700241
242void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
243 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
244 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
245}
246
Dominik Laskowski6505f792019-09-18 11:10:05 -0700247Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
248 if (mInjectVSyncs == enable) {
249 return {};
250 }
251
252 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
253
254 if (!mInjectorConnectionHandle) {
255 auto vsyncSource = std::make_unique<InjectVSyncSource>();
256 mVSyncInjector = vsyncSource.get();
257
258 auto eventThread =
259 std::make_unique<impl::EventThread>(std::move(vsyncSource),
260 impl::EventThread::InterceptVSyncsCallback());
261
262 mInjectorConnectionHandle = createConnection(std::move(eventThread));
263 }
264
265 mInjectVSyncs = enable;
266 return mInjectorConnectionHandle;
267}
268
269bool Scheduler::injectVSync(nsecs_t when) {
270 if (!mInjectVSyncs || !mVSyncInjector) {
271 return false;
272 }
273
274 mVSyncInjector->onInjectSyncEvent(when);
275 return true;
276}
277
Ana Krulece588e312018-09-18 12:32:24 -0700278void Scheduler::enableHardwareVsync() {
279 std::lock_guard<std::mutex> lock(mHWVsyncLock);
280 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
281 mPrimaryDispSync->beginResync();
282 mEventControlThread->setVsyncEnabled(true);
283 mPrimaryHWVsyncEnabled = true;
284 }
285}
286
287void Scheduler::disableHardwareVsync(bool makeUnavailable) {
288 std::lock_guard<std::mutex> lock(mHWVsyncLock);
289 if (mPrimaryHWVsyncEnabled) {
290 mEventControlThread->setVsyncEnabled(false);
291 mPrimaryDispSync->endResync();
292 mPrimaryHWVsyncEnabled = false;
293 }
294 if (makeUnavailable) {
295 mHWVsyncAvailable = false;
296 }
297}
298
Ana Krulecc2870422019-01-29 19:00:58 -0800299void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
300 {
301 std::lock_guard<std::mutex> lock(mHWVsyncLock);
302 if (makeAvailable) {
303 mHWVsyncAvailable = makeAvailable;
304 } else if (!mHWVsyncAvailable) {
305 // Hardware vsync is not currently available, so abort the resync
306 // attempt for now
307 return;
308 }
309 }
310
311 if (period <= 0) {
312 return;
313 }
314
315 setVsyncPeriod(period);
316}
317
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700318void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700319 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800320
321 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700322 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800323
324 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800325 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800326 }
327}
328
Dominik Laskowski98041832019-08-01 18:35:59 -0700329void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800330 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700331 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800332
333 if (!mPrimaryHWVsyncEnabled) {
334 mPrimaryDispSync->beginResync();
335 mEventControlThread->setVsyncEnabled(true);
336 mPrimaryHWVsyncEnabled = true;
337 }
Ana Krulece588e312018-09-18 12:32:24 -0700338}
339
Dominik Laskowski98041832019-08-01 18:35:59 -0700340void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700341 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700342 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700343 { // Scope for the lock
344 std::lock_guard<std::mutex> lock(mHWVsyncLock);
345 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700346 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700347 }
348 }
349
350 if (needsHwVsync) {
351 enableHardwareVsync();
352 } else {
353 disableHardwareVsync(false);
354 }
355}
356
357void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
358 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
359 enableHardwareVsync();
360 } else {
361 disableHardwareVsync(false);
362 }
363}
364
365void Scheduler::setIgnorePresentFences(bool ignore) {
366 mPrimaryDispSync->setIgnorePresentFences(ignore);
367}
368
Ady Abraham8fe11022019-06-12 17:11:12 -0700369nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800370 return mPrimaryDispSync->expectedPresentTime();
371}
372
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700373void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800374 if (!mLayerHistory) return;
375
Ady Abraham2139f732019-11-13 18:56:40 -0800376 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
377 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
378 ? lowFps
379 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800380
381 mLayerHistory->registerLayer(layer, lowFps, highFps);
Ady Abraham09bd3922019-04-08 10:44:56 -0700382}
383
Ady Abraham2139f732019-11-13 18:56:40 -0800384void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800385 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800386 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800387 }
Ana Krulec3084c052018-11-21 20:27:17 +0100388}
389
Dominik Laskowski49cea512019-11-12 14:13:23 -0800390void Scheduler::chooseRefreshRateForContent() {
391 if (!mLayerHistory) return;
392
Ady Abraham2139f732019-11-13 18:56:40 -0800393 auto [refreshRate] = mLayerHistory->summarize(systemTime());
Ady Abrahama315ce72019-04-24 14:35:20 -0700394 const uint32_t refreshRateRound = std::round(refreshRate);
Ady Abraham2139f732019-11-13 18:56:40 -0800395 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700396 {
397 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800398 if (mFeatures.contentRefreshRate == refreshRateRound) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700399 return;
400 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700401 mFeatures.contentRefreshRate = refreshRateRound;
402 ATRACE_INT("ContentFPS", refreshRateRound);
Ady Abraham6398a0a2019-04-18 19:30:44 -0700403
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700404 mFeatures.contentDetection =
405 refreshRateRound > 0 ? ContentDetectionState::On : ContentDetectionState::Off;
Ady Abraham2139f732019-11-13 18:56:40 -0800406 newConfigId = calculateRefreshRateType();
407 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700408 return;
409 }
Ady Abraham2139f732019-11-13 18:56:40 -0800410 mFeatures.configId = newConfigId;
411 };
412 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800413 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
Ady Abrahama1a49af2019-02-07 14:36:55 -0800414}
415
Ana Krulecfb772822018-11-30 10:44:07 +0100416void Scheduler::resetIdleTimer() {
417 if (mIdleTimer) {
418 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800419 }
420}
421
Ady Abraham8532d012019-05-08 14:50:56 -0700422void Scheduler::notifyTouchEvent() {
423 if (mTouchTimer) {
424 mTouchTimer->reset();
425 }
426
Dominik Laskowski98041832019-08-01 18:35:59 -0700427 if (mSupportKernelTimer && mIdleTimer) {
428 mIdleTimer->reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700429 }
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700430
431 // Touch event will boost the refresh rate to performance.
432 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800433 if (mLayerHistory) {
434 mLayerHistory->clear();
435 }
Ady Abraham8532d012019-05-08 14:50:56 -0700436}
437
Ady Abraham6fe2c172019-07-12 12:37:57 -0700438void Scheduler::setDisplayPowerState(bool normal) {
439 {
440 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700441 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700442 }
443
444 if (mDisplayPowerTimer) {
445 mDisplayPowerTimer->reset();
446 }
447
448 // Display Power event will boost the refresh rate to performance.
449 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800450 if (mLayerHistory) {
451 mLayerHistory->clear();
452 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700453}
454
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700455void Scheduler::kernelIdleTimerCallback(TimerState state) {
456 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100457
Ady Abraham2139f732019-11-13 18:56:40 -0800458 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
459 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700460 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800461 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
462 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700463 // If we're not in performance mode then the kernel timer shouldn't do
464 // anything, as the refresh rate during DPU power collapse will be the
465 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800466 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
467 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700468 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
469 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
470 // need to update the DispSync model anyway.
471 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700472 }
473}
474
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700475void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700476 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700477 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100478}
479
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700480void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700481 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
482 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700483 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700484}
485
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700486void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700487 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
488 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700489 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700490}
491
Dominik Laskowski98041832019-08-01 18:35:59 -0700492void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800493 using base::StringAppendF;
494 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700495
Dominik Laskowski49cea512019-11-12 14:13:23 -0800496 const bool supported = mRefreshRateConfigs.refreshRateSwitchingSupported();
497 StringAppendF(&result, "+ Refresh rate switching: %s\n", states[supported]);
498 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory.has_value()]);
499
500 StringAppendF(&result, "+ Idle timer: %s\n",
501 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
502 StringAppendF(&result, "+ Touch timer: %s\n\n",
503 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800504}
505
Ady Abraham6fe2c172019-07-12 12:37:57 -0700506template <class T>
507void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700508 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800509 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700510 {
511 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700512 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700513 return;
514 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700515 *currentState = newState;
Ady Abraham2139f732019-11-13 18:56:40 -0800516 newConfigId = calculateRefreshRateType();
517 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700518 return;
519 }
Ady Abraham2139f732019-11-13 18:56:40 -0800520 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700521 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700522 event = ConfigEvent::Changed;
523 }
524 }
Ady Abraham2139f732019-11-13 18:56:40 -0800525 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800526 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700527}
528
Ady Abraham2139f732019-11-13 18:56:40 -0800529HwcConfigIndexType Scheduler::calculateRefreshRateType() {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700530 if (!mRefreshRateConfigs.refreshRateSwitchingSupported()) {
Ady Abraham2139f732019-11-13 18:56:40 -0800531 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700532 }
533
Ady Abraham6fe2c172019-07-12 12:37:57 -0700534 // If Display Power is not in normal operation we want to be in performance mode.
535 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700536 if (!mFeatures.isDisplayPowerStateNormal || mFeatures.displayPowerTimer == TimerState::Reset) {
Ady Abraham2139f732019-11-13 18:56:40 -0800537 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700538 }
539
Ady Abraham8532d012019-05-08 14:50:56 -0700540 // As long as touch is active we want to be in performance mode
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700541 if (mFeatures.touch == TouchState::Active) {
Ady Abraham2139f732019-11-13 18:56:40 -0800542 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham8532d012019-05-08 14:50:56 -0700543 }
544
545 // If timer has expired as it means there is no new content on the screen
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700546 if (mFeatures.idleTimer == TimerState::Expired) {
Ady Abraham2139f732019-11-13 18:56:40 -0800547 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
Ady Abrahama315ce72019-04-24 14:35:20 -0700548 }
549
Ady Abraham09bd3922019-04-08 10:44:56 -0700550 // If content detection is off we choose performance as we don't know the content fps
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700551 if (mFeatures.contentDetection == ContentDetectionState::Off) {
Ady Abraham2139f732019-11-13 18:56:40 -0800552 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700553 }
554
Wei Wang09be73f2019-07-02 14:29:18 -0700555 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham2139f732019-11-13 18:56:40 -0800556 return mRefreshRateConfigs
557 .getRefreshRateForContent(static_cast<float>(mFeatures.contentRefreshRate))
558 .configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800559}
560
Ady Abraham2139f732019-11-13 18:56:40 -0800561std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700562 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800563 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700564}
565
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800566void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
567 if (timeline.refreshRequired) {
568 mSchedulerCallback.repaintEverythingForHWC();
569 }
570
571 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
572 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
573
574 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
575 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
576 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
577 }
578}
579
580void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
581 bool callRepaint = false;
582 {
583 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
584 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
585 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
586 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
587 } else {
588 // We need to send another refresh as refreshTimeNanos is still in the future
589 callRepaint = true;
590 }
591 }
592 }
593
594 if (callRepaint) {
595 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800596 }
597}
598
Ana Krulec98b5b242018-08-10 15:03:23 -0700599} // namespace android