blob: 71ac90e2d362f3fbc9d4d2bfb2e50d66ebdb3086 [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
Ana Krulec3803b8d2020-02-03 16:35:46 -0800111 if (mUseContentDetectionV2) {
112 mLayerHistory = std::make_unique<scheduler::impl::LayerHistoryV2>();
113 } else {
114 mLayerHistory = std::make_unique<scheduler::impl::LayerHistory>();
Dominik Laskowski49cea512019-11-12 14:13:23 -0800115 }
116
117 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100118
Dominik Laskowski98041832019-08-01 18:35:59 -0700119 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
120 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
121 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700122 mIdleTimer.emplace(
123 std::chrono::milliseconds(millis),
124 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
125 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100126 mIdleTimer->start();
127 }
Ady Abraham8532d012019-05-08 14:50:56 -0700128
Dominik Laskowski98041832019-08-01 18:35:59 -0700129 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700130 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700131 mTouchTimer.emplace(
132 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700133 [this] { touchTimerCallback(TimerState::Reset); },
134 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700135 mTouchTimer->start();
136 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700137
Dominik Laskowski98041832019-08-01 18:35:59 -0700138 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
139 mDisplayPowerTimer.emplace(
140 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700141 [this] { displayPowerTimerCallback(TimerState::Reset); },
142 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700143 mDisplayPowerTimer->start();
144 }
Ana Krulece588e312018-09-18 12:32:24 -0700145}
146
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700147Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
148 std::unique_ptr<EventControlThread> eventControlThread,
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800149 const scheduler::RefreshRateConfigs& configs,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800150 ISchedulerCallback& schedulerCallback, bool useContentDetectionV2)
Dominik Laskowski98041832019-08-01 18:35:59 -0700151 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700152 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700153 mSupportKernelTimer(false),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800154 mSchedulerCallback(schedulerCallback),
Ady Abraham8a82ba62020-01-17 12:43:17 -0800155 mRefreshRateConfigs(configs),
156 mUseContentDetectionV2(useContentDetectionV2) {}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700157
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800158Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700159 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700160 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700161 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800162 mIdleTimer.reset();
163}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700164
Dominik Laskowski98041832019-08-01 18:35:59 -0700165DispSync& Scheduler::getPrimaryDispSync() {
166 return *mPrimaryDispSync;
167}
168
Ady Abraham9e16a482019-12-03 17:19:41 -0800169std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(const char* name,
170 nsecs_t phaseOffsetNs) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700171 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
Ady Abraham9e16a482019-12-03 17:19:41 -0800172 true /* traceVsync */, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700173}
174
Dominik Laskowski98041832019-08-01 18:35:59 -0700175Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham9e16a482019-12-03 17:19:41 -0800176 const char* connectionName, nsecs_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700177 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9e16a482019-12-03 17:19:41 -0800178 auto vsyncSource = makePrimaryDispSyncSource(connectionName, phaseOffsetNs);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700179 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
180 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700181 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700182}
Ana Krulec98b5b242018-08-10 15:03:23 -0700183
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700184Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700185 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
186 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800187
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700188 auto connection =
189 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700190
191 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
192 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700193}
194
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700195sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700196 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
197 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700198}
199
Ana Krulec98b5b242018-08-10 15:03:23 -0700200sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700201 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700202 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700203 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700204}
205
Dominik Laskowski98041832019-08-01 18:35:59 -0700206sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
207 RETURN_IF_INVALID_HANDLE(handle, nullptr);
208 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700209}
210
Dominik Laskowski98041832019-08-01 18:35:59 -0700211void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
212 bool connected) {
213 RETURN_IF_INVALID_HANDLE(handle);
214 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700215}
216
Dominik Laskowski98041832019-08-01 18:35:59 -0700217void Scheduler::onScreenAcquired(ConnectionHandle handle) {
218 RETURN_IF_INVALID_HANDLE(handle);
219 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700220}
221
Dominik Laskowski98041832019-08-01 18:35:59 -0700222void Scheduler::onScreenReleased(ConnectionHandle handle) {
223 RETURN_IF_INVALID_HANDLE(handle);
224 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700225}
226
Dominik Laskowski98041832019-08-01 18:35:59 -0700227void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700228 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700229 RETURN_IF_INVALID_HANDLE(handle);
Alec Mouri60aee1c2019-10-28 16:18:59 -0700230 mConnections[handle].thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800231}
232
Alec Mouri717bcb62020-02-10 17:07:19 -0800233size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
234 RETURN_IF_INVALID_HANDLE(handle, 0);
235 return mConnections[handle].thread->getEventThreadConnectionCount();
236}
237
Dominik Laskowski98041832019-08-01 18:35:59 -0700238void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
239 RETURN_IF_INVALID_HANDLE(handle);
240 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700241}
242
Dominik Laskowski98041832019-08-01 18:35:59 -0700243void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
244 RETURN_IF_INVALID_HANDLE(handle);
245 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700246}
Ana Krulece588e312018-09-18 12:32:24 -0700247
248void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
249 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
250 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
251}
252
Dominik Laskowski6505f792019-09-18 11:10:05 -0700253Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
254 if (mInjectVSyncs == enable) {
255 return {};
256 }
257
258 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
259
260 if (!mInjectorConnectionHandle) {
261 auto vsyncSource = std::make_unique<InjectVSyncSource>();
262 mVSyncInjector = vsyncSource.get();
263
264 auto eventThread =
265 std::make_unique<impl::EventThread>(std::move(vsyncSource),
266 impl::EventThread::InterceptVSyncsCallback());
267
268 mInjectorConnectionHandle = createConnection(std::move(eventThread));
269 }
270
271 mInjectVSyncs = enable;
272 return mInjectorConnectionHandle;
273}
274
275bool Scheduler::injectVSync(nsecs_t when) {
276 if (!mInjectVSyncs || !mVSyncInjector) {
277 return false;
278 }
279
280 mVSyncInjector->onInjectSyncEvent(when);
281 return true;
282}
283
Ana Krulece588e312018-09-18 12:32:24 -0700284void Scheduler::enableHardwareVsync() {
285 std::lock_guard<std::mutex> lock(mHWVsyncLock);
286 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
287 mPrimaryDispSync->beginResync();
288 mEventControlThread->setVsyncEnabled(true);
289 mPrimaryHWVsyncEnabled = true;
290 }
291}
292
293void Scheduler::disableHardwareVsync(bool makeUnavailable) {
294 std::lock_guard<std::mutex> lock(mHWVsyncLock);
295 if (mPrimaryHWVsyncEnabled) {
296 mEventControlThread->setVsyncEnabled(false);
297 mPrimaryDispSync->endResync();
298 mPrimaryHWVsyncEnabled = false;
299 }
300 if (makeUnavailable) {
301 mHWVsyncAvailable = false;
302 }
303}
304
Ana Krulecc2870422019-01-29 19:00:58 -0800305void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
306 {
307 std::lock_guard<std::mutex> lock(mHWVsyncLock);
308 if (makeAvailable) {
309 mHWVsyncAvailable = makeAvailable;
310 } else if (!mHWVsyncAvailable) {
311 // Hardware vsync is not currently available, so abort the resync
312 // attempt for now
313 return;
314 }
315 }
316
317 if (period <= 0) {
318 return;
319 }
320
321 setVsyncPeriod(period);
322}
323
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700324void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700325 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800326
327 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700328 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800329
330 if (now - last > kIgnoreDelay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800331 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800332 }
333}
334
Dominik Laskowski98041832019-08-01 18:35:59 -0700335void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800336 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700337 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800338
339 if (!mPrimaryHWVsyncEnabled) {
340 mPrimaryDispSync->beginResync();
341 mEventControlThread->setVsyncEnabled(true);
342 mPrimaryHWVsyncEnabled = true;
343 }
Ana Krulece588e312018-09-18 12:32:24 -0700344}
345
Ady Abraham5dee2f12020-02-05 17:49:47 -0800346void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
347 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) {
Ady Abraham5dee2f12020-02-05 17:49:47 -0800353 needsHwVsync =
354 mPrimaryDispSync->addResyncSample(timestamp, hwcVsyncPeriod, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700355 }
356 }
357
358 if (needsHwVsync) {
359 enableHardwareVsync();
360 } else {
361 disableHardwareVsync(false);
362 }
363}
364
365void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
366 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
367 enableHardwareVsync();
368 } else {
369 disableHardwareVsync(false);
370 }
371}
372
373void Scheduler::setIgnorePresentFences(bool ignore) {
374 mPrimaryDispSync->setIgnorePresentFences(ignore);
375}
376
Ady Abraham8fe11022019-06-12 17:11:12 -0700377nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800378 return mPrimaryDispSync->expectedPresentTime();
379}
380
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700381void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800382 if (!mLayerHistory) return;
383
Ady Abraham8a82ba62020-01-17 12:43:17 -0800384 if (!mUseContentDetectionV2) {
385 const auto lowFps = mRefreshRateConfigs.getMinRefreshRate().fps;
386 const auto highFps = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
387 ? lowFps
388 : mRefreshRateConfigs.getMaxRefreshRate().fps;
Dominik Laskowski49cea512019-11-12 14:13:23 -0800389
Ady Abraham8a82ba62020-01-17 12:43:17 -0800390 mLayerHistory->registerLayer(layer, lowFps, highFps,
391 scheduler::LayerHistory::LayerVoteType::Heuristic);
392 } else {
393 if (layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER) {
394 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
395 mRefreshRateConfigs.getMaxRefreshRate().fps,
396 scheduler::LayerHistory::LayerVoteType::Min);
397 } else if (layer->getWindowType() == InputWindowInfo::TYPE_STATUS_BAR) {
398 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
399 mRefreshRateConfigs.getMaxRefreshRate().fps,
400 scheduler::LayerHistory::LayerVoteType::NoVote);
401 } else {
402 mLayerHistory->registerLayer(layer, mRefreshRateConfigs.getMinRefreshRate().fps,
403 mRefreshRateConfigs.getMaxRefreshRate().fps,
404 scheduler::LayerHistory::LayerVoteType::Heuristic);
405 }
406
407 // TODO(146935143): Simulate youtube app vote. This should be removed once youtube calls the
408 // API to set desired rate
409 {
410 const auto vote = property_get_int32("experimental.sf.force_youtube_vote", 0);
411 if (vote != 0 &&
412 layer->getName() ==
413 "SurfaceView - "
414 "com.google.android.youtube/"
415 "com.google.android.apps.youtube.app.WatchWhileActivity#0") {
Ady Abraham71c437d2020-01-31 15:56:57 -0800416 layer->setFrameRate(
417 Layer::FrameRate(vote, Layer::FrameRateCompatibility::ExactOrMultiple));
Ady Abraham8a82ba62020-01-17 12:43:17 -0800418 }
419 }
420 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700421}
422
Ady Abraham2139f732019-11-13 18:56:40 -0800423void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800424 if (mLayerHistory) {
Ady Abraham2139f732019-11-13 18:56:40 -0800425 mLayerHistory->record(layer, presentTime, systemTime());
Dominik Laskowski49cea512019-11-12 14:13:23 -0800426 }
Ana Krulec3084c052018-11-21 20:27:17 +0100427}
428
Dominik Laskowski49cea512019-11-12 14:13:23 -0800429void Scheduler::chooseRefreshRateForContent() {
430 if (!mLayerHistory) return;
431
Ady Abraham8a82ba62020-01-17 12:43:17 -0800432 ATRACE_CALL();
433
434 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800435 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700436 {
437 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800438 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700439 return;
440 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800441 mFeatures.contentRequirements = summary;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700442 mFeatures.contentDetection =
Ady Abraham8a82ba62020-01-17 12:43:17 -0800443 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
444
Ana Krulec3803b8d2020-02-03 16:35:46 -0800445 newConfigId = calculateRefreshRateConfigIndexType();
Ady Abraham2139f732019-11-13 18:56:40 -0800446 if (mFeatures.configId == newConfigId) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700447 return;
448 }
Ady Abraham2139f732019-11-13 18:56:40 -0800449 mFeatures.configId = newConfigId;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800450 auto newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
451 mSchedulerCallback.changeRefreshRate(newRefreshRate, ConfigEvent::Changed);
452 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800453}
454
Ana Krulecfb772822018-11-30 10:44:07 +0100455void Scheduler::resetIdleTimer() {
456 if (mIdleTimer) {
457 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800458 }
459}
460
Ady Abraham8532d012019-05-08 14:50:56 -0700461void Scheduler::notifyTouchEvent() {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800462 if (!mTouchTimer) return;
463
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700464 // Touch event will boost the refresh rate to performance.
Steven Thomas540730a2020-01-08 20:12:42 -0800465 // Clear Layer History to get fresh FPS detection.
466 // NOTE: Instead of checking all the layers, we should be checking the layer
467 // that is currently on top. b/142507166 will give us this capability.
Ady Abraham8a82ba62020-01-17 12:43:17 -0800468 std::lock_guard<std::mutex> lock(mFeatureStateLock);
469 if (mLayerHistory && !layerHistoryHasClientSpecifiedFrameRate()) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800470 mLayerHistory->clear();
Steven Thomas540730a2020-01-08 20:12:42 -0800471
Ady Abraham8a82ba62020-01-17 12:43:17 -0800472 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800473
474 if (mSupportKernelTimer && mIdleTimer) {
475 mIdleTimer->reset();
476 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800477 }
Ady Abraham8532d012019-05-08 14:50:56 -0700478}
479
Ady Abraham6fe2c172019-07-12 12:37:57 -0700480void Scheduler::setDisplayPowerState(bool normal) {
481 {
482 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700483 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700484 }
485
486 if (mDisplayPowerTimer) {
487 mDisplayPowerTimer->reset();
488 }
489
490 // Display Power event will boost the refresh rate to performance.
491 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800492 if (mLayerHistory) {
493 mLayerHistory->clear();
494 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700495}
496
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700497void Scheduler::kernelIdleTimerCallback(TimerState state) {
498 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100499
Ady Abraham2139f732019-11-13 18:56:40 -0800500 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
501 // magic number
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700502 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800503 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
504 if (state == TimerState::Reset && refreshRate.fps > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700505 // If we're not in performance mode then the kernel timer shouldn't do
506 // anything, as the refresh rate during DPU power collapse will be the
507 // same.
Ady Abraham2139f732019-11-13 18:56:40 -0800508 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.vsyncPeriod);
509 } else if (state == TimerState::Expired && refreshRate.fps <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700510 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
511 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
512 // need to update the DispSync model anyway.
513 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700514 }
515}
516
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700517void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700518 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700519 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100520}
521
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700522void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700523 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
524 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700525 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700526}
527
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700528void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700529 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
530 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700531 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700532}
533
Dominik Laskowski98041832019-08-01 18:35:59 -0700534void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800535 using base::StringAppendF;
536 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700537
Dominik Laskowski49cea512019-11-12 14:13:23 -0800538 StringAppendF(&result, "+ Idle timer: %s\n",
539 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
540 StringAppendF(&result, "+ Touch timer: %s\n\n",
541 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800542}
543
Ady Abraham6fe2c172019-07-12 12:37:57 -0700544template <class T>
545void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700546 ConfigEvent event = ConfigEvent::None;
Ady Abraham2139f732019-11-13 18:56:40 -0800547 HwcConfigIndexType newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700548 {
549 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700550 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700551 return;
552 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700553 *currentState = newState;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800554 newConfigId = calculateRefreshRateConfigIndexType();
Ady Abraham2139f732019-11-13 18:56:40 -0800555 if (mFeatures.configId == newConfigId) {
Ady Abraham8532d012019-05-08 14:50:56 -0700556 return;
557 }
Ady Abraham2139f732019-11-13 18:56:40 -0800558 mFeatures.configId = newConfigId;
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700559 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700560 event = ConfigEvent::Changed;
561 }
562 }
Ady Abraham2139f732019-11-13 18:56:40 -0800563 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800564 mSchedulerCallback.changeRefreshRate(newRefreshRate, event);
Ady Abraham8532d012019-05-08 14:50:56 -0700565}
566
Ady Abraham8a82ba62020-01-17 12:43:17 -0800567bool Scheduler::layerHistoryHasClientSpecifiedFrameRate() {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800568 // Traverse all the layers to see if any of them requested frame rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -0800569 for (const auto& layer : mFeatures.contentRequirements) {
Ady Abraham71c437d2020-01-31 15:56:57 -0800570 if (layer.vote == scheduler::RefreshRateConfigs::LayerVoteType::ExplicitDefault ||
571 layer.vote == scheduler::RefreshRateConfigs::LayerVoteType::ExplicitExactOrMultiple) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800572 return true;
573 }
574 }
575
576 return false;
577}
578
Ana Krulec3803b8d2020-02-03 16:35:46 -0800579HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType() {
Ana Krulec3f6a2062020-01-23 15:48:01 -0800580 // This block of the code checks whether any layers used the SetFrameRate API. If they have,
Ana Krulec3803b8d2020-02-03 16:35:46 -0800581 // their request should be honored depending on other active layers.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800582 if (layerHistoryHasClientSpecifiedFrameRate()) {
583 if (!mUseContentDetectionV2) {
584 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements)
585 .configId;
586 } else {
587 return mRefreshRateConfigs.getRefreshRateForContentV2(mFeatures.contentRequirements)
588 .configId;
589 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700590 }
591
Ana Krulec3803b8d2020-02-03 16:35:46 -0800592 // If the layer history doesn't have the frame rate specified, check for other features and
593 // honor them. NOTE: If we remove the kernel idle timer, and use our internal idle timer, this
594 // code will have to be refactored. If Display Power is not in normal operation we want to be in
595 // performance mode. When coming back to normal mode, a grace period is given with
596 // DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800597 if (mDisplayPowerTimer &&
598 (!mFeatures.isDisplayPowerStateNormal ||
599 mFeatures.displayPowerTimer == TimerState::Reset)) {
600 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
601 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700602
Ana Krulec3803b8d2020-02-03 16:35:46 -0800603 // As long as touch is active we want to be in performance mode.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800604 if (mTouchTimer && mFeatures.touch == TouchState::Active) {
605 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
606 }
Ady Abraham8532d012019-05-08 14:50:56 -0700607
Ana Krulec3803b8d2020-02-03 16:35:46 -0800608 // If timer has expired as it means there is no new content on the screen.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800609 if (mIdleTimer && mFeatures.idleTimer == TimerState::Expired) {
610 return mRefreshRateConfigs.getMinRefreshRateByPolicy().configId;
Ady Abraham8a82ba62020-01-17 12:43:17 -0800611 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700612
Ady Abraham8a82ba62020-01-17 12:43:17 -0800613 if (!mUseContentDetectionV2) {
Ana Krulec3f6a2062020-01-23 15:48:01 -0800614 // If content detection is off we choose performance as we don't know the content fps.
Steven Thomas540730a2020-01-08 20:12:42 -0800615 if (mFeatures.contentDetection == ContentDetectionState::Off) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800616 // NOTE: V1 always calls this, but this is not a default behavior for V2.
Steven Thomas540730a2020-01-08 20:12:42 -0800617 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().configId;
618 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800619
620 // Content detection is on, find the appropriate refresh rate with minimal error
621 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements).configId;
Ady Abraham09bd3922019-04-08 10:44:56 -0700622 }
623
Wei Wang09be73f2019-07-02 14:29:18 -0700624 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abraham8a82ba62020-01-17 12:43:17 -0800625 if (mFeatures.contentDetection == ContentDetectionState::On) {
626 return mRefreshRateConfigs.getRefreshRateForContentV2(mFeatures.contentRequirements)
627 .configId;
628 }
629
Ana Krulec5d477912020-02-07 12:02:38 -0800630 // There are no signals for refresh rate, just leave it as is.
631 return mRefreshRateConfigs.getCurrentRefreshRateByPolicy().configId;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800632}
633
Ady Abraham2139f732019-11-13 18:56:40 -0800634std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700635 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800636 // Make sure that the default config ID is first updated, before returned.
637 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800638 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800639 }
Ady Abraham2139f732019-11-13 18:56:40 -0800640 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700641}
642
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800643void Scheduler::onNewVsyncPeriodChangeTimeline(const HWC2::VsyncPeriodChangeTimeline& timeline) {
644 if (timeline.refreshRequired) {
645 mSchedulerCallback.repaintEverythingForHWC();
646 }
647
648 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
649 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
650
651 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
652 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
653 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
654 }
655}
656
657void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
658 bool callRepaint = false;
659 {
660 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
661 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
662 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
663 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
664 } else {
665 // We need to send another refresh as refreshTimeNanos is still in the future
666 callRepaint = true;
667 }
668 }
669 }
670
671 if (callRepaint) {
672 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800673 }
674}
675
Ady Abraham8a82ba62020-01-17 12:43:17 -0800676void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
677 if (mLayerHistory) {
678 mLayerHistory->setDisplayArea(displayArea);
679 }
680}
681
Ana Krulec98b5b242018-08-10 15:03:23 -0700682} // namespace android