blob: 6a437a25ed608555f94b2599fafeb9c010681562 [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
2 * Copyright 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Dominik Laskowski98041832019-08-01 18:35:59 -070021#undef LOG_TAG
22#define LOG_TAG "Scheduler"
Ana Krulec7ab56032018-11-02 20:51:06 +010023#define ATRACE_TAG ATRACE_TAG_GRAPHICS
24
Ana Krulec98b5b242018-08-10 15:03:23 -070025#include "Scheduler.h"
26
Dominik Laskowski49cea512019-11-12 14:13:23 -080027#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070028#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070030#include <configstore/Utils.h>
Ana Krulecfb772822018-11-30 10:44:07 +010031#include <cutils/properties.h>
Ady Abraham8f1ee7f2019-04-05 10:32:50 -070032#include <input/InputWindow.h>
Ana Krulecfefd6ae2019-02-13 17:53:08 -080033#include <system/window.h>
Ana Krulece588e312018-09-18 12:32:24 -070034#include <ui/DisplayStatInfo.h>
Ana Krulec3084c052018-11-21 20:27:17 +010035#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010036#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070037
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070038#include <algorithm>
39#include <cinttypes>
40#include <cstdint>
41#include <functional>
42#include <memory>
43#include <numeric>
44
45#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070046#include "DispSync.h"
47#include "DispSyncSource.h"
Ana Krulece588e312018-09-18 12:32:24 -070048#include "EventControlThread.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070049#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070050#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070051#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010052#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090053#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080054#include "Timer.h"
55#include "VSyncDispatchTimerQueue.h"
56#include "VSyncPredictor.h"
57#include "VSyncReactor.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070058
Dominik Laskowski98041832019-08-01 18:35:59 -070059#define RETURN_IF_INVALID_HANDLE(handle, ...) \
60 do { \
61 if (mConnections.count(handle) == 0) { \
62 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
63 return __VA_ARGS__; \
64 } \
65 } while (false)
66
Ana Krulec98b5b242018-08-10 15:03:23 -070067namespace android {
68
Kevin DuBois00287382019-11-19 15:11:55 -080069std::unique_ptr<DispSync> createDispSync() {
70 // TODO (140302863) remove this and use the vsync_reactor system.
71 if (property_get_bool("debug.sf.vsync_reactor", false)) {
72 // TODO (144707443) tune Predictor tunables.
73 static constexpr int default_rate = 60;
74 static constexpr auto initial_period =
75 std::chrono::duration<nsecs_t, std::ratio<1, default_rate>>(1);
76 static constexpr size_t vsyncTimestampHistorySize = 20;
77 static constexpr size_t minimumSamplesForPrediction = 6;
78 static constexpr uint32_t discardOutlierPercent = 20;
79 auto tracker = std::make_unique<
80 scheduler::VSyncPredictor>(std::chrono::duration_cast<std::chrono::nanoseconds>(
81 initial_period)
82 .count(),
83 vsyncTimestampHistorySize, minimumSamplesForPrediction,
84 discardOutlierPercent);
85
86 static constexpr auto vsyncMoveThreshold =
87 std::chrono::duration_cast<std::chrono::nanoseconds>(3ms);
88 static constexpr auto timerSlack =
89 std::chrono::duration_cast<std::chrono::nanoseconds>(500us);
90 auto dispatch = std::make_unique<
91 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), *tracker,
92 timerSlack.count(), vsyncMoveThreshold.count());
93
94 static constexpr size_t pendingFenceLimit = 20;
95 return std::make_unique<scheduler::VSyncReactor>(std::make_unique<scheduler::SystemClock>(),
96 std::move(dispatch), std::move(tracker),
97 pendingFenceLimit);
98 } else {
99 return std::make_unique<impl::DispSync>("SchedulerDispSync",
100 sysprop::running_without_sync_framework(true));
101 }
102}
103
Ady Abraham09bd3922019-04-08 10:44:56 -0700104Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800105 const scheduler::RefreshRateConfigs& refreshRateConfig,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800106 ISchedulerCallback& schedulerCallback, bool useContentDetectionV2)
Kevin DuBois00287382019-11-19 15:11:55 -0800107 : mPrimaryDispSync(createDispSync()),
Dominik Laskowski98041832019-08-01 18:35:59 -0700108 mEventControlThread(new impl::EventControlThread(std::move(function))),
109 mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800110 mSchedulerCallback(schedulerCallback),
Ady Abraham8a82ba62020-01-17 12:43:17 -0800111 mRefreshRateConfigs(refreshRateConfig),
112 mUseContentDetectionV2(useContentDetectionV2) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700113 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700114
Dominik Laskowski49cea512019-11-12 14:13:23 -0800115 if (property_get_bool("debug.sf.use_smart_90_for_video", 0) || use_smart_90_for_video(false)) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800116 if (mUseContentDetectionV2) {
117 mLayerHistory = std::make_unique<scheduler::impl::LayerHistoryV2>();
118 } else {
119 mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
120 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800121 }
122
123 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100124
Dominik Laskowski98041832019-08-01 18:35:59 -0700125 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
126 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
127 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700128 mIdleTimer.emplace(
129 std::chrono::milliseconds(millis),
130 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
131 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100132 mIdleTimer->start();
133 }
Ady Abraham8532d012019-05-08 14:50:56 -0700134
Dominik Laskowski98041832019-08-01 18:35:59 -0700135 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700136 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700137 mTouchTimer.emplace(
138 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700139 [this] { touchTimerCallback(TimerState::Reset); },
140 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700141 mTouchTimer->start();
142 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700143
Dominik Laskowski98041832019-08-01 18:35:59 -0700144 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
145 mDisplayPowerTimer.emplace(
146 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700147 [this] { displayPowerTimerCallback(TimerState::Reset); },
148 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700149 mDisplayPowerTimer->start();
150 }
Ana Krulece588e312018-09-18 12:32:24 -0700151}
152
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700153Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
154 std::unique_ptr<EventControlThread> eventControlThread,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800155 const scheduler::RefreshRateConfigs& configs,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800156 ISchedulerCallback& schedulerCallback, bool useContentDetectionV2)
Dominik Laskowski98041832019-08-01 18:35:59 -0700157 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700158 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700159 mSupportKernelTimer(false),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800160 mSchedulerCallback(schedulerCallback),
Ady Abraham8a82ba62020-01-17 12:43:17 -0800161 mRefreshRateConfigs(configs),
162 mUseContentDetectionV2(useContentDetectionV2) {}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700163
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800164Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700165 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700166 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700167 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800168 mIdleTimer.reset();
169}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700170
Dominik Laskowski98041832019-08-01 18:35:59 -0700171DispSync& Scheduler::getPrimaryDispSync() {
172 return *mPrimaryDispSync;
173}
174
Ady Abraham9e16a482019-12-03 17:19:41 -0800175std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
176 nsecs_t phaseOffsetNs) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700177 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
Ady Abraham9e16a482019-12-03 17:19:41 -0800178 true /* traceVsync */, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700179}
180
Dominik Laskowski98041832019-08-01 18:35:59 -0700181Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham9e16a482019-12-03 17:19:41 -0800182 const char* connectionName, nsecs_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700183 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9e16a482019-12-03 17:19:41 -0800184 auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700185 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
186 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700187 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700188}
Ana Krulec98b5b242018-08-10 15:03:23 -0700189
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700190Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700191 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
192 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800193
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700194 auto connection =
195 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700196
197 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
198 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700199}
200
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700201sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700202 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
203 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700204}
205
Ana Krulec98b5b242018-08-10 15:03:23 -0700206sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700207 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700208 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700209 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700210}
211
Dominik Laskowski98041832019-08-01 18:35:59 -0700212sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
213 RETURN_IF_INVALID_HANDLE(handle, nullptr);
214 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700215}
216
Dominik Laskowski98041832019-08-01 18:35:59 -0700217void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
218 bool connected) {
219 RETURN_IF_INVALID_HANDLE(handle);
220 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700221}
222
Dominik Laskowski98041832019-08-01 18:35:59 -0700223void Scheduler::onScreenAcquired(ConnectionHandle handle) {
224 RETURN_IF_INVALID_HANDLE(handle);
225 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700226}
227
Dominik Laskowski98041832019-08-01 18:35:59 -0700228void Scheduler::onScreenReleased(ConnectionHandle handle) {
229 RETURN_IF_INVALID_HANDLE(handle);
230 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700231}
232
Dominik Laskowski98041832019-08-01 18:35:59 -0700233void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700234 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700235 RETURN_IF_INVALID_HANDLE(handle);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700236 mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800237}
238
Dominik Laskowski98041832019-08-01 18:35:59 -0700239void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
240 RETURN_IF_INVALID_HANDLE(handle);
241 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700242}
243
Dominik Laskowski98041832019-08-01 18:35:59 -0700244void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
245 RETURN_IF_INVALID_HANDLE(handle);
246 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700247}
Ana Krulece588e312018-09-18 12:32:24 -0700248
249void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
250 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
251 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
252}
253
Dominik Laskowski6505f792019-09-18 11:10:05 -0700254Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
255 if (mInjectVSyncs == enable) {
256 return {};
257 }
258
259 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
260
261 if (!mInjectorConnectionHandle) {
262 auto vsyncSource = std::make_unique<InjectVSyncSource>();
263 mVSyncInjector = vsyncSource.get();
264
265 auto eventThread =
266 std::make_unique<impl::EventThread>(std::move(vsyncSource),
267 impl::EventThread::InterceptVSyncsCallback());
268
269 mInjectorConnectionHandle = createConnection(std::move(eventThread));
270 }
271
272 mInjectVSyncs = enable;
273 return mInjectorConnectionHandle;
274}
275
276bool Scheduler::injectVSync(nsecs_t when) {
277 if (!mInjectVSyncs || !mVSyncInjector) {
278 return false;
279 }
280
281 mVSyncInjector->onInjectSyncEvent(when);
282 return true;
283}
284
Ana Krulece588e312018-09-18 12:32:24 -0700285void Scheduler::enableHardwareVsync() {
286 std::lock_guard<std::mutex> lock(mHWVsyncLock);
287 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
288 mPrimaryDispSync->beginResync();
289 mEventControlThread->setVsyncEnabled(true);
290 mPrimaryHWVsyncEnabled = true;
291 }
292}
293
294void Scheduler::disableHardwareVsync(bool makeUnavailable) {
295 std::lock_guard<std::mutex> lock(mHWVsyncLock);
296 if (mPrimaryHWVsyncEnabled) {
297 mEventControlThread->setVsyncEnabled(false);
298 mPrimaryDispSync->endResync();
299 mPrimaryHWVsyncEnabled = false;
300 }
301 if (makeUnavailable) {
302 mHWVsyncAvailable = false;
303 }
304}
305
Ana Krulecc2870422019-01-29 19:00:58 -0800306void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
307 {
308 std::lock_guard<std::mutex> lock(mHWVsyncLock);
309 if (makeAvailable) {
310 mHWVsyncAvailable = makeAvailable;
311 } else if (!mHWVsyncAvailable) {
312 // Hardware vsync is not currently available, so abort the resync
313 // attempt for now
314 return;
315 }
316 }
317
318 if (period <= 0) {
319 return;
320 }
321
322 setVsyncPeriod(period);
323}
324
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700325void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700326 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800327
328 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700329 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800330
331 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800332 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800333 }
334}
335
Dominik Laskowski98041832019-08-01 18:35:59 -0700336void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800337 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700338 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800339
340 if (!mPrimaryHWVsyncEnabled) {
341 mPrimaryDispSync->beginResync();
342 mEventControlThread->setVsyncEnabled(true);
343 mPrimaryHWVsyncEnabled = true;
344 }
Ana Krulece588e312018-09-18 12:32:24 -0700345}
346
Dominik Laskowski98041832019-08-01 18:35:59 -0700347void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700348 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700349 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700350 { // Scope for the lock
351 std::lock_guard<std::mutex> lock(mHWVsyncLock);
352 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700353 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700354 }
355 }
356
357 if (needsHwVsync) {
358 enableHardwareVsync();
359 } else {
360 disableHardwareVsync(false);
361 }
362}
363
364void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
365 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
366 enableHardwareVsync();
367 } else {
368 disableHardwareVsync(false);
369 }
370}
371
372void Scheduler::setIgnorePresentFences(bool ignore) {
373 mPrimaryDispSync->setIgnorePresentFences(ignore);
374}
375
Ady Abraham8fe11022019-06-12 17:11:12 -0700376nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800377 return mPrimaryDispSync->expectedPresentTime();
378}
379
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700380void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800381 if (!mLayerHistory) return;
382
Ady Abraham8a82ba62020-01-17 12:43:17 -0800383 if (!mUseContentDetectionV2) {
384 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
385 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
386 ? lowFps
387 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800388
Ady Abraham8a82ba62020-01-17 12:43:17 -0800389 mLayerHistory->registerLayer(layer, lowFps, highFps,
390 scheduler::LayerHistory::LayerVoteType::Heuristic);
391 } else {
392 if (layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER) {
393 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
394 mRefreshRateConfigs.getMaxRefreshRate().fps,
395 scheduler::LayerHistory::LayerVoteType::Min);
396 } else if (layer->getWindowType() == InputWindowInfo::TYPE_STATUS_BAR) {
397 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
398 mRefreshRateConfigs.getMaxRefreshRate().fps,
399 scheduler::LayerHistory::LayerVoteType::NoVote);
400 } else {
401 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
402 mRefreshRateConfigs.getMaxRefreshRate().fps,
403 scheduler::LayerHistory::LayerVoteType::Heuristic);
404 }
405
406 // TODO(146935143): Simulate youtube app vote. This should be removed once youtube calls the
407 // API to set desired rate
408 {
409 const auto vote = property_get_int32("experimental.sf.force_youtube_vote", 0);
410 if (vote != 0 &&
411 layer->getName() ==
412 "SurfaceView - "
413 "com.google.android.youtube/"
414 "com.google.android.apps.youtube.app.WatchWhileActivity#0") {
415 layer->setFrameRate(vote);
416 }
417 }
418 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700419}
420
Ady Abraham2139f732019-11-13 18:56:40 -0800421void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800422 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800423 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800424 }
Ana Krulec3084c052018-11-21 20:27:17 +0100425}
426
Dominik Laskowski49cea512019-11-12 14:13:23 -0800427void Scheduler::chooseRefreshRateForContent() {
428 if (!mLayerHistory) return;
429
Ady Abraham8a82ba62020-01-17 12:43:17 -0800430 ATRACE_CALL();
431
432 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800433 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700434 {
435 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800436 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700437 return;
438 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800439 mFeatures.contentRequirements = summary;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700440 mFeatures.contentDetection =
Ady Abraham8a82ba62020-01-17 12:43:17 -0800441 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
442
Ady Abraham2139f732019-11-13 18:56:40 -0800443 newConfigId = calculateRefreshRateType();
444 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700445 return;
446 }
Ady Abraham2139f732019-11-13 18:56:40 -0800447 mFeatures.configId = newConfigId;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800448 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
449 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
450 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800451}
452
Ana Krulecfb772822018-11-30 10:44:07 +0100453void Scheduler::resetIdleTimer() {
454 if (mIdleTimer) {
455 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800456 }
457}
458
Ady Abraham8532d012019-05-08 14:50:56 -0700459void Scheduler::notifyTouchEvent() {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800460 if (!mTouchTimer) return;
461
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700462 // Touch event will boost the refresh rate to performance.
Steven Thomas540730a2020-01-08 20:12:42 -0800463 // Clear Layer History to get fresh FPS detection.
464 // NOTE: Instead of checking all the layers, we should be checking the layer
465 // that is currently on top. b/142507166 will give us this capability.
Ady Abraham8a82ba62020-01-17 12:43:17 -0800466 std::lock_guard<std::mutex> lock(mFeatureStateLock);
467 if (mLayerHistory && !layerHistoryHasClientSpecifiedFrameRate()) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800468 mLayerHistory->clear();
Steven Thomas540730a2020-01-08 20:12:42 -0800469
Ady Abraham8a82ba62020-01-17 12:43:17 -0800470 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800471
472 if (mSupportKernelTimer && mIdleTimer) {
473 mIdleTimer->reset();
474 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800475 }
Ady Abraham8532d012019-05-08 14:50:56 -0700476}
477
Ady Abraham6fe2c172019-07-12 12:37:57 -0700478void Scheduler::setDisplayPowerState(bool normal) {
479 {
480 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700481 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700482 }
483
484 if (mDisplayPowerTimer) {
485 mDisplayPowerTimer->reset();
486 }
487
488 // Display Power event will boost the refresh rate to performance.
489 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800490 if (mLayerHistory) {
491 mLayerHistory->clear();
492 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700493}
494
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700495void Scheduler::kernelIdleTimerCallback(TimerState state) {
496 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100497
Ady Abraham2139f732019-11-13 18:56:40 -0800498 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
499 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700500 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800501 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
502 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700503 // If we're not in performance mode then the kernel timer shouldn't do
504 // anything, as the refresh rate during DPU power collapse will be the
505 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800506 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
507 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700508 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
509 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
510 // need to update the DispSync model anyway.
511 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700512 }
513}
514
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700515void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700516 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700517 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100518}
519
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700520void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700521 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
522 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700523 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700524}
525
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700526void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700527 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
528 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700529 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700530}
531
Dominik Laskowski98041832019-08-01 18:35:59 -0700532void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800533 using base::StringAppendF;
534 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700535
Dominik Laskowski49cea512019-11-12 14:13:23 -0800536 const bool supported = mRefreshRateConfigs.refreshRateSwitchingSupported();
537 StringAppendF(&result, "+ Refresh rate switching: %s\n", states[supported]);
Ady Abrahame3ed2f92020-01-06 17:01:28 -0800538 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory != nullptr]);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800539
540 StringAppendF(&result, "+ Idle timer: %s\n",
541 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
542 StringAppendF(&result, "+ Touch timer: %s\n\n",
543 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800544}
545
Ady Abraham6fe2c172019-07-12 12:37:57 -0700546template <class T>
547void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700548 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800549 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700550 {
551 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700552 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700553 return;
554 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700555 *currentState = newState;
Ady Abraham2139f732019-11-13 18:56:40 -0800556 newConfigId = calculateRefreshRateType();
557 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700558 return;
559 }
Ady Abraham2139f732019-11-13 18:56:40 -0800560 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700561 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700562 event = ConfigEvent::Changed;
563 }
564 }
Ady Abraham2139f732019-11-13 18:56:40 -0800565 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800566 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700567}
568
Ady Abraham8a82ba62020-01-17 12:43:17 -0800569bool Scheduler::layerHistoryHasClientSpecifiedFrameRate() {
570 for (const auto& layer : mFeatures.contentRequirements) {
571 if (layer.vote == scheduler::RefreshRateConfigs::LayerVoteType::Explicit) {
572 return true;
573 }
574 }
575
576 return false;
577}
578
Ady Abraham2139f732019-11-13 18:56:40 -0800579HwcConfigIndexType Scheduler::calculateRefreshRateType() {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700580 if (!mRefreshRateConfigs.refreshRateSwitchingSupported()) {
Ady Abraham2139f732019-11-13 18:56:40 -0800581 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700582 }
583
Steven Thomas540730a2020-01-08 20:12:42 -0800584 // If the layer history doesn't have the frame rate specified, use the old path. NOTE:
585 // if we remove the kernel idle timer, and use our internal idle timer, this code will have to
586 // be refactored.
Ady Abraham8a82ba62020-01-17 12:43:17 -0800587 if (!layerHistoryHasClientSpecifiedFrameRate()) {
Steven Thomas540730a2020-01-08 20:12:42 -0800588 // If Display Power is not in normal operation we want to be in performance mode.
589 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
590 if (!mFeatures.isDisplayPowerStateNormal ||
591 mFeatures.displayPowerTimer == TimerState::Reset) {
592 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
593 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700594
Steven Thomas540730a2020-01-08 20:12:42 -0800595 // As long as touch is active we want to be in performance mode
596 if (mFeatures.touch == TouchState::Active) {
597 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
598 }
Ady Abraham8532d012019-05-08 14:50:56 -0700599
Steven Thomas540730a2020-01-08 20:12:42 -0800600 // If timer has expired as it means there is no new content on the screen
601 if (mFeatures.idleTimer == TimerState::Expired) {
602 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
603 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800604 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700605
Ady Abraham8a82ba62020-01-17 12:43:17 -0800606 if (!mUseContentDetectionV2) {
Steven Thomas540730a2020-01-08 20:12:42 -0800607 // If content detection is off we choose performance as we don't know the content fps
608 if (mFeatures.contentDetection == ContentDetectionState::Off) {
609 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
610 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800611
612 // Content detection is on, find the appropriate refresh rate with minimal error
613 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements).configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700614 }
615
Wei Wang09be73f2019-07-02 14:29:18 -0700616 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham8a82ba62020-01-17 12:43:17 -0800617 if (mFeatures.contentDetection == ContentDetectionState::On) {
618 return mRefreshRateConfigs.getRefreshRateForContentV2(mFeatures.contentRequirements)
619 .configId;
620 }
621
622 // There are no signals for refresh rate, just leave it as is
623 return mRefreshRateConfigs.getCurrentRefreshRate().configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800624}
625
Ady Abraham2139f732019-11-13 18:56:40 -0800626std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700627 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800628 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700629}
630
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800631void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
632 if (timeline.refreshRequired) {
633 mSchedulerCallback.repaintEverythingForHWC();
634 }
635
636 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
637 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
638
639 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
640 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
641 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
642 }
643}
644
645void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
646 bool callRepaint = false;
647 {
648 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
649 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
650 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
651 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
652 } else {
653 // We need to send another refresh as refreshTimeNanos is still in the future
654 callRepaint = true;
655 }
656 }
657 }
658
659 if (callRepaint) {
660 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800661 }
662}
663
Ady Abraham8a82ba62020-01-17 12:43:17 -0800664void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
665 if (mLayerHistory) {
666 mLayerHistory->setDisplayArea(displayArea);
667 }
668}
669
Ana Krulec98b5b242018-08-10 15:03:23 -0700670} // namespace android
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -0800671
672// TODO(b/129481165): remove the #pragma below and fix conversion issues
673#pragma clang diagnostic pop // ignored "-Wconversion"