blob: dd5d2ac7bfb16c7a4b723bf2a353869aa625774c [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.
Kevin DuBoisc57f2c32019-12-20 16:32:29 -080067 if (property_get_bool("debug.sf.vsync_reactor", true)) {
Kevin DuBois00287382019-11-19 15:11:55 -080068 // 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,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800102 ISchedulerCallback& schedulerCallback, bool useContentDetectionV2)
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 Abraham8a82ba62020-01-17 12:43:17 -0800107 mRefreshRateConfigs(refreshRateConfig),
108 mUseContentDetectionV2(useContentDetectionV2) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700109 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700110
Ady Abraham48da0702020-02-04 15:59:25 -0800111 if (property_get_bool("debug.sf.use_content_detection_for_refresh_rate", 0) ||
112 use_content_detection_for_refresh_rate(false)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800113 if (mUseContentDetectionV2) {
114 mLayerHistory = std::make_unique<scheduler::impl::LayerHistoryV2>();
115 } else {
116 mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
117 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800118 }
119
120 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100121
Dominik Laskowski98041832019-08-01 18:35:59 -0700122 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
123 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
124 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700125 mIdleTimer.emplace(
126 std::chrono::milliseconds(millis),
127 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
128 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100129 mIdleTimer->start();
130 }
Ady Abraham8532d012019-05-08 14:50:56 -0700131
Dominik Laskowski98041832019-08-01 18:35:59 -0700132 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700133 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700134 mTouchTimer.emplace(
135 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700136 [this] { touchTimerCallback(TimerState::Reset); },
137 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700138 mTouchTimer->start();
139 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700140
Dominik Laskowski98041832019-08-01 18:35:59 -0700141 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
142 mDisplayPowerTimer.emplace(
143 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700144 [this] { displayPowerTimerCallback(TimerState::Reset); },
145 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700146 mDisplayPowerTimer->start();
147 }
Ana Krulece588e312018-09-18 12:32:24 -0700148}
149
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700150Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
151 std::unique_ptr<EventControlThread> eventControlThread,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800152 const scheduler::RefreshRateConfigs& configs,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800153 ISchedulerCallback& schedulerCallback, bool useContentDetectionV2)
Dominik Laskowski98041832019-08-01 18:35:59 -0700154 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700155 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700156 mSupportKernelTimer(false),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800157 mSchedulerCallback(schedulerCallback),
Ady Abraham8a82ba62020-01-17 12:43:17 -0800158 mRefreshRateConfigs(configs),
159 mUseContentDetectionV2(useContentDetectionV2) {}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700160
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800161Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700162 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700163 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700164 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800165 mIdleTimer.reset();
166}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700167
Dominik Laskowski98041832019-08-01 18:35:59 -0700168DispSync& Scheduler::getPrimaryDispSync() {
169 return *mPrimaryDispSync;
170}
171
Ady Abraham9e16a482019-12-03 17:19:41 -0800172std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
173 nsecs_t phaseOffsetNs) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700174 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
Ady Abraham9e16a482019-12-03 17:19:41 -0800175 true /* traceVsync */, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700176}
177
Dominik Laskowski98041832019-08-01 18:35:59 -0700178Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham9e16a482019-12-03 17:19:41 -0800179 const char* connectionName, nsecs_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700180 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9e16a482019-12-03 17:19:41 -0800181 auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700182 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
183 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700184 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700185}
Ana Krulec98b5b242018-08-10 15:03:23 -0700186
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700187Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700188 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
189 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800190
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700191 auto connection =
192 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700193
194 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
195 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700196}
197
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700198sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700199 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
200 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700201}
202
Ana Krulec98b5b242018-08-10 15:03:23 -0700203sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700204 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700205 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700206 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700207}
208
Dominik Laskowski98041832019-08-01 18:35:59 -0700209sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
210 RETURN_IF_INVALID_HANDLE(handle, nullptr);
211 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700212}
213
Dominik Laskowski98041832019-08-01 18:35:59 -0700214void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
215 bool connected) {
216 RETURN_IF_INVALID_HANDLE(handle);
217 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700218}
219
Dominik Laskowski98041832019-08-01 18:35:59 -0700220void Scheduler::onScreenAcquired(ConnectionHandle handle) {
221 RETURN_IF_INVALID_HANDLE(handle);
222 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700223}
224
Dominik Laskowski98041832019-08-01 18:35:59 -0700225void Scheduler::onScreenReleased(ConnectionHandle handle) {
226 RETURN_IF_INVALID_HANDLE(handle);
227 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700228}
229
Dominik Laskowski98041832019-08-01 18:35:59 -0700230void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700231 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700232 RETURN_IF_INVALID_HANDLE(handle);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700233 mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800234}
235
Dominik Laskowski98041832019-08-01 18:35:59 -0700236void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
237 RETURN_IF_INVALID_HANDLE(handle);
238 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700239}
240
Dominik Laskowski98041832019-08-01 18:35:59 -0700241void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
242 RETURN_IF_INVALID_HANDLE(handle);
243 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700244}
Ana Krulece588e312018-09-18 12:32:24 -0700245
246void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
247 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
248 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
249}
250
Dominik Laskowski6505f792019-09-18 11:10:05 -0700251Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
252 if (mInjectVSyncs == enable) {
253 return {};
254 }
255
256 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
257
258 if (!mInjectorConnectionHandle) {
259 auto vsyncSource = std::make_unique<InjectVSyncSource>();
260 mVSyncInjector = vsyncSource.get();
261
262 auto eventThread =
263 std::make_unique<impl::EventThread>(std::move(vsyncSource),
264 impl::EventThread::InterceptVSyncsCallback());
265
266 mInjectorConnectionHandle = createConnection(std::move(eventThread));
267 }
268
269 mInjectVSyncs = enable;
270 return mInjectorConnectionHandle;
271}
272
273bool Scheduler::injectVSync(nsecs_t when) {
274 if (!mInjectVSyncs || !mVSyncInjector) {
275 return false;
276 }
277
278 mVSyncInjector->onInjectSyncEvent(when);
279 return true;
280}
281
Ana Krulece588e312018-09-18 12:32:24 -0700282void Scheduler::enableHardwareVsync() {
283 std::lock_guard<std::mutex> lock(mHWVsyncLock);
284 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
285 mPrimaryDispSync->beginResync();
286 mEventControlThread->setVsyncEnabled(true);
287 mPrimaryHWVsyncEnabled = true;
288 }
289}
290
291void Scheduler::disableHardwareVsync(bool makeUnavailable) {
292 std::lock_guard<std::mutex> lock(mHWVsyncLock);
293 if (mPrimaryHWVsyncEnabled) {
294 mEventControlThread->setVsyncEnabled(false);
295 mPrimaryDispSync->endResync();
296 mPrimaryHWVsyncEnabled = false;
297 }
298 if (makeUnavailable) {
299 mHWVsyncAvailable = false;
300 }
301}
302
Ana Krulecc2870422019-01-29 19:00:58 -0800303void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
304 {
305 std::lock_guard<std::mutex> lock(mHWVsyncLock);
306 if (makeAvailable) {
307 mHWVsyncAvailable = makeAvailable;
308 } else if (!mHWVsyncAvailable) {
309 // Hardware vsync is not currently available, so abort the resync
310 // attempt for now
311 return;
312 }
313 }
314
315 if (period <= 0) {
316 return;
317 }
318
319 setVsyncPeriod(period);
320}
321
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700322void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700323 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800324
325 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700326 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800327
328 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800329 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800330 }
331}
332
Dominik Laskowski98041832019-08-01 18:35:59 -0700333void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800334 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700335 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800336
337 if (!mPrimaryHWVsyncEnabled) {
338 mPrimaryDispSync->beginResync();
339 mEventControlThread->setVsyncEnabled(true);
340 mPrimaryHWVsyncEnabled = true;
341 }
Ana Krulece588e312018-09-18 12:32:24 -0700342}
343
Dominik Laskowski98041832019-08-01 18:35:59 -0700344void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700345 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700346 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700347 { // Scope for the lock
348 std::lock_guard<std::mutex> lock(mHWVsyncLock);
349 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700350 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700351 }
352 }
353
354 if (needsHwVsync) {
355 enableHardwareVsync();
356 } else {
357 disableHardwareVsync(false);
358 }
359}
360
361void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
362 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
363 enableHardwareVsync();
364 } else {
365 disableHardwareVsync(false);
366 }
367}
368
369void Scheduler::setIgnorePresentFences(bool ignore) {
370 mPrimaryDispSync->setIgnorePresentFences(ignore);
371}
372
Ady Abraham8fe11022019-06-12 17:11:12 -0700373nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800374 return mPrimaryDispSync->expectedPresentTime();
375}
376
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700377void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800378 if (!mLayerHistory) return;
379
Ady Abraham8a82ba62020-01-17 12:43:17 -0800380 if (!mUseContentDetectionV2) {
381 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
382 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
383 ? lowFps
384 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800385
Ady Abraham8a82ba62020-01-17 12:43:17 -0800386 mLayerHistory->registerLayer(layer, lowFps, highFps,
387 scheduler::LayerHistory::LayerVoteType::Heuristic);
388 } else {
389 if (layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER) {
390 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
391 mRefreshRateConfigs.getMaxRefreshRate().fps,
392 scheduler::LayerHistory::LayerVoteType::Min);
393 } else if (layer->getWindowType() == InputWindowInfo::TYPE_STATUS_BAR) {
394 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
395 mRefreshRateConfigs.getMaxRefreshRate().fps,
396 scheduler::LayerHistory::LayerVoteType::NoVote);
397 } else {
398 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
399 mRefreshRateConfigs.getMaxRefreshRate().fps,
400 scheduler::LayerHistory::LayerVoteType::Heuristic);
401 }
402
403 // TODO(146935143): Simulate youtube app vote. This should be removed once youtube calls the
404 // API to set desired rate
405 {
406 const auto vote = property_get_int32("experimental.sf.force_youtube_vote", 0);
407 if (vote != 0 &&
408 layer->getName() ==
409 "SurfaceView - "
410 "com.google.android.youtube/"
411 "com.google.android.apps.youtube.app.WatchWhileActivity#0") {
Ady Abraham71c437d2020-01-31 15:56:57 -0800412 layer->setFrameRate(
413 Layer::FrameRate(vote, Layer::FrameRateCompatibility::ExactOrMultiple));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800414 }
415 }
416 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700417}
418
Ady Abraham2139f732019-11-13 18:56:40 -0800419void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800420 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800421 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800422 }
Ana Krulec3084c052018-11-21 20:27:17 +0100423}
424
Dominik Laskowski49cea512019-11-12 14:13:23 -0800425void Scheduler::chooseRefreshRateForContent() {
426 if (!mLayerHistory) return;
427
Ady Abraham8a82ba62020-01-17 12:43:17 -0800428 ATRACE_CALL();
429
430 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800431 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700432 {
433 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800434 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700435 return;
436 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800437 mFeatures.contentRequirements = summary;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700438 mFeatures.contentDetection =
Ady Abraham8a82ba62020-01-17 12:43:17 -0800439 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
440
Ady Abraham2139f732019-11-13 18:56:40 -0800441 newConfigId = calculateRefreshRateType();
442 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700443 return;
444 }
Ady Abraham2139f732019-11-13 18:56:40 -0800445 mFeatures.configId = newConfigId;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800446 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
447 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
448 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800449}
450
Ana Krulecfb772822018-11-30 10:44:07 +0100451void Scheduler::resetIdleTimer() {
452 if (mIdleTimer) {
453 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800454 }
455}
456
Ady Abraham8532d012019-05-08 14:50:56 -0700457void Scheduler::notifyTouchEvent() {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800458 if (!mTouchTimer) return;
459
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700460 // Touch event will boost the refresh rate to performance.
Steven Thomas540730a2020-01-08 20:12:42 -0800461 // Clear Layer History to get fresh FPS detection.
462 // NOTE: Instead of checking all the layers, we should be checking the layer
463 // that is currently on top. b/142507166 will give us this capability.
Ady Abraham8a82ba62020-01-17 12:43:17 -0800464 std::lock_guard<std::mutex> lock(mFeatureStateLock);
465 if (mLayerHistory && !layerHistoryHasClientSpecifiedFrameRate()) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800466 mLayerHistory->clear();
Steven Thomas540730a2020-01-08 20:12:42 -0800467
Ady Abraham8a82ba62020-01-17 12:43:17 -0800468 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800469
470 if (mSupportKernelTimer && mIdleTimer) {
471 mIdleTimer->reset();
472 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800473 }
Ady Abraham8532d012019-05-08 14:50:56 -0700474}
475
Ady Abraham6fe2c172019-07-12 12:37:57 -0700476void Scheduler::setDisplayPowerState(bool normal) {
477 {
478 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700479 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700480 }
481
482 if (mDisplayPowerTimer) {
483 mDisplayPowerTimer->reset();
484 }
485
486 // Display Power event will boost the refresh rate to performance.
487 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800488 if (mLayerHistory) {
489 mLayerHistory->clear();
490 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700491}
492
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700493void Scheduler::kernelIdleTimerCallback(TimerState state) {
494 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100495
Ady Abraham2139f732019-11-13 18:56:40 -0800496 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
497 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700498 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800499 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
500 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700501 // If we're not in performance mode then the kernel timer shouldn't do
502 // anything, as the refresh rate during DPU power collapse will be the
503 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800504 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
505 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700506 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
507 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
508 // need to update the DispSync model anyway.
509 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700510 }
511}
512
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700513void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700514 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700515 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100516}
517
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700518void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700519 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
520 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700521 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700522}
523
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700524void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700525 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
526 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700527 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700528}
529
Dominik Laskowski98041832019-08-01 18:35:59 -0700530void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800531 using base::StringAppendF;
532 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700533
Ady Abrahame3ed2f92020-01-06 17:01:28 -0800534 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory != nullptr]);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800535
536 StringAppendF(&result, "+ Idle timer: %s\n",
537 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
538 StringAppendF(&result, "+ Touch timer: %s\n\n",
539 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800540}
541
Ady Abraham6fe2c172019-07-12 12:37:57 -0700542template <class T>
543void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700544 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800545 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700546 {
547 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700548 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700549 return;
550 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700551 *currentState = newState;
Ady Abraham2139f732019-11-13 18:56:40 -0800552 newConfigId = calculateRefreshRateType();
553 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700554 return;
555 }
Ady Abraham2139f732019-11-13 18:56:40 -0800556 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700557 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700558 event = ConfigEvent::Changed;
559 }
560 }
Ady Abraham2139f732019-11-13 18:56:40 -0800561 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800562 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700563}
564
Ady Abraham8a82ba62020-01-17 12:43:17 -0800565bool Scheduler::layerHistoryHasClientSpecifiedFrameRate() {
566 for (const auto& layer : mFeatures.contentRequirements) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800567 if (layer.vote == scheduler::RefreshRateConfigs::LayerVoteType::ExplicitDefault ||
568 layer.vote == scheduler::RefreshRateConfigs::LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800569 return true;
570 }
571 }
572
573 return false;
574}
575
Ady Abraham2139f732019-11-13 18:56:40 -0800576HwcConfigIndexType Scheduler::calculateRefreshRateType() {
Ana Krulec3f6a2062020-01-23 15:48:01 -0800577 // This block of the code checks whether any layers used the SetFrameRate API. If they have,
578 // their request should be honored regardless of whether the device has refresh rate switching
579 // turned off.
580 if (layerHistoryHasClientSpecifiedFrameRate()) {
581 if (!mUseContentDetectionV2) {
582 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements)
583 .configId;
584 } else {
585 return mRefreshRateConfigs.getRefreshRateForContentV2(mFeatures.contentRequirements)
586 .configId;
587 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700588 }
589
Steven Thomas540730a2020-01-08 20:12:42 -0800590 // If the layer history doesn't have the frame rate specified, use the old path. NOTE:
591 // if we remove the kernel idle timer, and use our internal idle timer, this code will have to
592 // be refactored.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800593 // If Display Power is not in normal operation we want to be in performance mode.
594 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
595 if (mDisplayPowerTimer &&
596 (!mFeatures.isDisplayPowerStateNormal ||
597 mFeatures.displayPowerTimer == TimerState::Reset)) {
598 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
599 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700600
Ana Krulec3f6a2062020-01-23 15:48:01 -0800601 // As long as touch is active we want to be in performance mode
602 if (mTouchTimer && mFeatures.touch == TouchState::Active) {
603 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
604 }
Ady Abraham8532d012019-05-08 14:50:56 -0700605
Ana Krulec3f6a2062020-01-23 15:48:01 -0800606 // If timer has expired as it means there is no new content on the screen
607 if (mIdleTimer && mFeatures.idleTimer == TimerState::Expired) {
608 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800609 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700610
Ady Abraham8a82ba62020-01-17 12:43:17 -0800611 if (!mUseContentDetectionV2) {
Ana Krulec3f6a2062020-01-23 15:48:01 -0800612 // If content detection is off we choose performance as we don't know the content fps.
Steven Thomas540730a2020-01-08 20:12:42 -0800613 if (mFeatures.contentDetection == ContentDetectionState::Off) {
Ana Krulec3f6a2062020-01-23 15:48:01 -0800614 // TODO(b/148428554): Be careful to not always call this.
Steven Thomas540730a2020-01-08 20:12:42 -0800615 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
616 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800617
618 // Content detection is on, find the appropriate refresh rate with minimal error
619 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements).configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700620 }
621
Wei Wang09be73f2019-07-02 14:29:18 -0700622 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham8a82ba62020-01-17 12:43:17 -0800623 if (mFeatures.contentDetection == ContentDetectionState::On) {
624 return mRefreshRateConfigs.getRefreshRateForContentV2(mFeatures.contentRequirements)
625 .configId;
626 }
627
628 // There are no signals for refresh rate, just leave it as is
629 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800630}
631
Ady Abraham2139f732019-11-13 18:56:40 -0800632std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700633 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800634 // Make sure that the default config ID is first updated, before returned.
635 if (mFeatures.configId.has_value()) {
636 mFeatures.configId = calculateRefreshRateType();
637 }
Ady Abraham2139f732019-11-13 18:56:40 -0800638 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700639}
640
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800641void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
642 if (timeline.refreshRequired) {
643 mSchedulerCallback.repaintEverythingForHWC();
644 }
645
646 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
647 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
648
649 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
650 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
651 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
652 }
653}
654
655void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
656 bool callRepaint = false;
657 {
658 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
659 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
660 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
661 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
662 } else {
663 // We need to send another refresh as refreshTimeNanos is still in the future
664 callRepaint = true;
665 }
666 }
667 }
668
669 if (callRepaint) {
670 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800671 }
672}
673
Ady Abraham8a82ba62020-01-17 12:43:17 -0800674void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
675 if (mLayerHistory) {
676 mLayerHistory->setDisplayArea(displayArea);
677 }
678}
679
Ana Krulec98b5b242018-08-10 15:03:23 -0700680} // namespace android