blob: a93bf11301023669050edda3b27e3670cfa70833 [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 Laskowski8b01cc02020-07-14 19:02:41 -070023#include <android-base/properties.h>
Dominik Laskowski49cea512019-11-12 14:13:23 -080024#include <android-base/stringprintf.h>
Ana Krulece588e312018-09-18 12:32:24 -070025#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
26#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Ana Krulece588e312018-09-18 12:32:24 -070027#include <configstore/Utils.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
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -070034#include <FrameTimeline/FrameTimeline.h>
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -070035#include <algorithm>
36#include <cinttypes>
37#include <cstdint>
38#include <functional>
39#include <memory>
40#include <numeric>
41
42#include "../Layer.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070043#include "DispSyncSource.h"
44#include "EventThread.h"
Dominik Laskowski6505f792019-09-18 11:10:05 -070045#include "InjectVSyncSource.h"
Ana Krulecf2c006d2019-06-21 15:37:07 -070046#include "OneShotTimer.h"
Ana Krulec434c22d2018-11-28 13:48:36 +010047#include "SchedulerUtils.h"
Sundong Ahnd5e08f62018-12-12 20:27:28 +090048#include "SurfaceFlingerProperties.h"
Kevin DuBois00287382019-11-19 15:11:55 -080049#include "Timer.h"
50#include "VSyncDispatchTimerQueue.h"
51#include "VSyncPredictor.h"
52#include "VSyncReactor.h"
Ady Abraham8cb21882020-08-26 18:22:05 -070053#include "VsyncController.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
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070063using namespace std::string_literals;
64
Ana Krulec98b5b242018-08-10 15:03:23 -070065namespace android {
Ady Abraham5a858552020-03-31 17:54:56 -070066
Dominik Laskowski983f2b52020-06-25 16:54:06 -070067namespace {
Ana Krulec98b5b242018-08-10 15:03:23 -070068
Ady Abraham5a858552020-03-31 17:54:56 -070069std::unique_ptr<scheduler::VSyncTracker> createVSyncTracker() {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070070 // TODO(b/144707443): Tune constants.
71 constexpr int kDefaultRate = 60;
72 constexpr auto initialPeriod = std::chrono::duration<nsecs_t, std::ratio<1, kDefaultRate>>(1);
73 constexpr nsecs_t idealPeriod =
74 std::chrono::duration_cast<std::chrono::nanoseconds>(initialPeriod).count();
75 constexpr size_t vsyncTimestampHistorySize = 20;
76 constexpr size_t minimumSamplesForPrediction = 6;
77 constexpr uint32_t discardOutlierPercent = 20;
78 return std::make_unique<scheduler::VSyncPredictor>(idealPeriod, vsyncTimestampHistorySize,
79 minimumSamplesForPrediction,
80 discardOutlierPercent);
Ady Abraham5a858552020-03-31 17:54:56 -070081}
82
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070083std::unique_ptr<scheduler::VSyncDispatch> createVSyncDispatch(scheduler::VSyncTracker& tracker) {
84 // TODO(b/144707443): Tune constants.
85 constexpr std::chrono::nanoseconds vsyncMoveThreshold = 3ms;
86 constexpr std::chrono::nanoseconds timerSlack = 500us;
Ady Abraham5a858552020-03-31 17:54:56 -070087 return std::make_unique<
Dominik Laskowski8b01cc02020-07-14 19:02:41 -070088 scheduler::VSyncDispatchTimerQueue>(std::make_unique<scheduler::Timer>(), tracker,
Ady Abraham5a858552020-03-31 17:54:56 -070089 timerSlack.count(), vsyncMoveThreshold.count());
90}
91
Dominik Laskowski983f2b52020-06-25 16:54:06 -070092const char* toContentDetectionString(bool useContentDetection, bool useContentDetectionV2) {
93 if (!useContentDetection) return "off";
94 return useContentDetectionV2 ? "V2" : "V1";
95}
96
97} // namespace
98
Ady Abraham8735eac2020-08-12 16:35:04 -070099class PredictedVsyncTracer {
100public:
101 PredictedVsyncTracer(scheduler::VSyncDispatch& dispatch)
102 : mRegistration(dispatch, std::bind(&PredictedVsyncTracer::callback, this),
103 "PredictedVsyncTracer") {
104 scheduleRegistration();
105 }
106
107private:
108 TracedOrdinal<bool> mParity = {"VSYNC-predicted", 0};
109 scheduler::VSyncCallbackRegistration mRegistration;
110
111 void scheduleRegistration() { mRegistration.schedule({0, 0, 0}); }
112
113 void callback() {
114 mParity = !mParity;
115 scheduleRegistration();
116 }
117};
118
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700119Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback)
120 : Scheduler(configs, callback,
121 {.supportKernelTimer = sysprop::support_kernel_idle_timer(false),
122 .useContentDetection = sysprop::use_content_detection_for_refresh_rate(false),
123 .useContentDetectionV2 =
Ady Abraham49cb7d52020-07-22 18:37:07 -0700124 base::GetBoolProperty("debug.sf.use_content_detection_v2"s, true)}) {}
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700125
126Scheduler::Scheduler(const scheduler::RefreshRateConfigs& configs, ISchedulerCallback& callback,
127 Options options)
Ady Abraham8cb21882020-08-26 18:22:05 -0700128 : Scheduler(createVsyncSchedule(options.supportKernelTimer), configs, callback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700129 createLayerHistory(configs, options.useContentDetectionV2), options) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700130 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -0700131
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700132 const int setIdleTimerMs = base::GetIntProperty("debug.sf.set_idle_timer_ms"s, 0);
Ana Krulecfb772822018-11-30 10:44:07 +0100133
Dominik Laskowski98041832019-08-01 18:35:59 -0700134 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700135 const auto callback = mOptions.supportKernelTimer ? &Scheduler::kernelIdleTimerCallback
136 : &Scheduler::idleTimerCallback;
Dominik Laskowski98041832019-08-01 18:35:59 -0700137 mIdleTimer.emplace(
138 std::chrono::milliseconds(millis),
139 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
140 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +0100141 mIdleTimer->start();
142 }
Ady Abraham8532d012019-05-08 14:50:56 -0700143
Dominik Laskowski98041832019-08-01 18:35:59 -0700144 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -0700145 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -0700146 mTouchTimer.emplace(
147 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700148 [this] { touchTimerCallback(TimerState::Reset); },
149 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -0700150 mTouchTimer->start();
151 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700152
Dominik Laskowski98041832019-08-01 18:35:59 -0700153 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
154 mDisplayPowerTimer.emplace(
155 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700156 [this] { displayPowerTimerCallback(TimerState::Reset); },
157 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700158 mDisplayPowerTimer->start();
159 }
Ana Krulece588e312018-09-18 12:32:24 -0700160}
161
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700162Scheduler::Scheduler(VsyncSchedule schedule, const scheduler::RefreshRateConfigs& configs,
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700163 ISchedulerCallback& schedulerCallback,
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700164 std::unique_ptr<LayerHistory> layerHistory, Options options)
165 : mOptions(options),
166 mVsyncSchedule(std::move(schedule)),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700167 mLayerHistory(std::move(layerHistory)),
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800168 mSchedulerCallback(schedulerCallback),
Ady Abraham8735eac2020-08-12 16:35:04 -0700169 mRefreshRateConfigs(configs),
170 mPredictedVsyncTracer(
171 base::GetBoolProperty("debug.sf.show_predicted_vsync", false)
172 ? std::make_unique<PredictedVsyncTracer>(*mVsyncSchedule.dispatch)
173 : nullptr) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700174 mSchedulerCallback.setVsyncEnabled(false);
175}
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700176
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800177Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700178 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700179 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700180 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800181 mIdleTimer.reset();
182}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700183
Ady Abraham8cb21882020-08-26 18:22:05 -0700184Scheduler::VsyncSchedule Scheduler::createVsyncSchedule(bool supportKernelTimer) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700185 auto clock = std::make_unique<scheduler::SystemClock>();
186 auto tracker = createVSyncTracker();
187 auto dispatch = createVSyncDispatch(*tracker);
188
189 // TODO(b/144707443): Tune constants.
190 constexpr size_t pendingFenceLimit = 20;
Ady Abraham8cb21882020-08-26 18:22:05 -0700191 auto controller =
Ady Abraham8735eac2020-08-12 16:35:04 -0700192 std::make_unique<scheduler::VSyncReactor>(std::move(clock), *tracker, pendingFenceLimit,
Ady Abraham8cb21882020-08-26 18:22:05 -0700193 supportKernelTimer);
194 return {std::move(controller), std::move(tracker), std::move(dispatch)};
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700195}
196
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700197std::unique_ptr<LayerHistory> Scheduler::createLayerHistory(
198 const scheduler::RefreshRateConfigs& configs, bool useContentDetectionV2) {
199 if (!configs.canSwitch()) return nullptr;
200
201 if (useContentDetectionV2) {
202 return std::make_unique<scheduler::impl::LayerHistoryV2>(configs);
203 }
204
205 return std::make_unique<scheduler::impl::LayerHistory>();
206}
207
Ady Abraham9c53ee72020-07-22 21:16:18 -0700208std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
209 const char* name, std::chrono::nanoseconds workDuration,
210 std::chrono::nanoseconds readyDuration, bool traceVsync) {
211 return std::make_unique<scheduler::DispSyncSource>(*mVsyncSchedule.dispatch, workDuration,
212 readyDuration, traceVsync, name);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700213}
214
Ady Abraham0bb6a472020-10-12 10:22:13 -0700215bool Scheduler::isVsyncValid(nsecs_t expectedVsyncTimestamp, uid_t uid) const {
216 const auto divider = mRefreshRateConfigs.getRefreshRateDividerForUid(uid);
217 if (divider <= 1) {
218 return true;
219 }
220
221 return mVsyncSchedule.tracker->isVSyncInPhase(expectedVsyncTimestamp, divider);
222}
223
Dominik Laskowski98041832019-08-01 18:35:59 -0700224Scheduler::ConnectionHandle Scheduler::createConnection(
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700225 const char* connectionName, frametimeline::TokenManager* tokenManager,
226 std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration,
Ana Krulec98b5b242018-08-10 15:03:23 -0700227 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ady Abraham9c53ee72020-07-22 21:16:18 -0700228 auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration);
Ady Abraham0bb6a472020-10-12 10:22:13 -0700229 auto throttleVsync = [this](nsecs_t expectedVsyncTimestamp, uid_t uid) {
230 return !isVsyncValid(expectedVsyncTimestamp, uid);
231 };
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700232 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource), tokenManager,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700233 std::move(interceptCallback),
234 std::move(throttleVsync));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700235 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700236}
Ana Krulec98b5b242018-08-10 15:03:23 -0700237
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700238Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700239 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
240 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800241
Ady Abraham62f216c2020-10-13 19:07:23 -0700242 auto connection = createConnectionInternal(eventThread.get());
Dominik Laskowski98041832019-08-01 18:35:59 -0700243
Ana Krulec6ddd2612020-09-24 13:06:33 -0700244 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700245 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
246 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700247}
248
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700249sp<EventThreadConnection> Scheduler::createConnectionInternal(
Ady Abraham62f216c2020-10-13 19:07:23 -0700250 EventThread* eventThread, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
251 return eventThread->createEventConnection([&] { resync(); }, eventRegistration);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700252}
253
Ana Krulec98b5b242018-08-10 15:03:23 -0700254sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Ady Abraham62f216c2020-10-13 19:07:23 -0700255 ConnectionHandle handle, ISurfaceComposer::EventRegistrationFlags eventRegistration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700256 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700257 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Ady Abraham62f216c2020-10-13 19:07:23 -0700258 return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700259}
260
Dominik Laskowski98041832019-08-01 18:35:59 -0700261sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700262 std::lock_guard<std::mutex> lock(mConnectionsLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700263 RETURN_IF_INVALID_HANDLE(handle, nullptr);
264 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700265}
266
Dominik Laskowski98041832019-08-01 18:35:59 -0700267void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
268 bool connected) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700269 android::EventThread* thread;
270 {
271 std::lock_guard<std::mutex> lock(mConnectionsLock);
272 RETURN_IF_INVALID_HANDLE(handle);
273 thread = mConnections[handle].thread.get();
274 }
275
276 thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700277}
278
Dominik Laskowski98041832019-08-01 18:35:59 -0700279void Scheduler::onScreenAcquired(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700280 android::EventThread* thread;
281 {
282 std::lock_guard<std::mutex> lock(mConnectionsLock);
283 RETURN_IF_INVALID_HANDLE(handle);
284 thread = mConnections[handle].thread.get();
285 }
286 thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700287}
288
Dominik Laskowski98041832019-08-01 18:35:59 -0700289void Scheduler::onScreenReleased(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700290 android::EventThread* thread;
291 {
292 std::lock_guard<std::mutex> lock(mConnectionsLock);
293 RETURN_IF_INVALID_HANDLE(handle);
294 thread = mConnections[handle].thread.get();
295 }
296 thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700297}
298
Ady Abraham62f216c2020-10-13 19:07:23 -0700299void Scheduler::onFrameRateOverridesChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
300 std::vector<FrameRateOverride> overrides) {
301 android::EventThread* thread;
302 {
303 std::lock_guard<std::mutex> lock(mConnectionsLock);
304 RETURN_IF_INVALID_HANDLE(handle);
305 thread = mConnections[handle].thread.get();
306 }
307 thread->onFrameRateOverridesChanged(displayId, std::move(overrides));
308}
309
Ady Abrahamdfd62162020-06-10 16:11:56 -0700310void Scheduler::onPrimaryDisplayConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
311 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
312 std::lock_guard<std::mutex> lock(mFeatureStateLock);
313 // Cache the last reported config for primary display.
314 mFeatures.cachedConfigChangedParams = {handle, displayId, configId, vsyncPeriod};
315 onNonPrimaryDisplayConfigChanged(handle, displayId, configId, vsyncPeriod);
316}
317
318void Scheduler::dispatchCachedReportedConfig() {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700319 // Check optional fields first.
320 if (!mFeatures.configId.has_value()) {
321 ALOGW("No config ID found, not dispatching cached config.");
322 return;
323 }
324 if (!mFeatures.cachedConfigChangedParams.has_value()) {
325 ALOGW("No config changed params found, not dispatching cached config.");
326 return;
327 }
328
Ady Abrahamdfd62162020-06-10 16:11:56 -0700329 const auto configId = *mFeatures.configId;
330 const auto vsyncPeriod =
331 mRefreshRateConfigs.getRefreshRateFromConfigId(configId).getVsyncPeriod();
332
333 // If there is no change from cached config, there is no need to dispatch an event
334 if (configId == mFeatures.cachedConfigChangedParams->configId &&
335 vsyncPeriod == mFeatures.cachedConfigChangedParams->vsyncPeriod) {
336 return;
337 }
338
339 mFeatures.cachedConfigChangedParams->configId = configId;
340 mFeatures.cachedConfigChangedParams->vsyncPeriod = vsyncPeriod;
341 onNonPrimaryDisplayConfigChanged(mFeatures.cachedConfigChangedParams->handle,
342 mFeatures.cachedConfigChangedParams->displayId,
343 mFeatures.cachedConfigChangedParams->configId,
344 mFeatures.cachedConfigChangedParams->vsyncPeriod);
345}
346
347void Scheduler::onNonPrimaryDisplayConfigChanged(ConnectionHandle handle,
348 PhysicalDisplayId displayId,
349 HwcConfigIndexType configId, nsecs_t vsyncPeriod) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700350 android::EventThread* thread;
351 {
352 std::lock_guard<std::mutex> lock(mConnectionsLock);
353 RETURN_IF_INVALID_HANDLE(handle);
354 thread = mConnections[handle].thread.get();
355 }
356 thread->onConfigChanged(displayId, configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800357}
358
Alec Mouri717bcb62020-02-10 17:07:19 -0800359size_t Scheduler::getEventThreadConnectionCount(ConnectionHandle handle) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700360 std::lock_guard<std::mutex> lock(mConnectionsLock);
Alec Mouri717bcb62020-02-10 17:07:19 -0800361 RETURN_IF_INVALID_HANDLE(handle, 0);
362 return mConnections[handle].thread->getEventThreadConnectionCount();
363}
364
Dominik Laskowski98041832019-08-01 18:35:59 -0700365void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700366 android::EventThread* thread;
367 {
368 std::lock_guard<std::mutex> lock(mConnectionsLock);
369 RETURN_IF_INVALID_HANDLE(handle);
370 thread = mConnections.at(handle).thread.get();
371 }
372 thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700373}
374
Ady Abraham9c53ee72020-07-22 21:16:18 -0700375void Scheduler::setDuration(ConnectionHandle handle, std::chrono::nanoseconds workDuration,
376 std::chrono::nanoseconds readyDuration) {
Ana Krulec6ddd2612020-09-24 13:06:33 -0700377 android::EventThread* thread;
378 {
379 std::lock_guard<std::mutex> lock(mConnectionsLock);
380 RETURN_IF_INVALID_HANDLE(handle);
381 thread = mConnections[handle].thread.get();
382 }
383 thread->setDuration(workDuration, readyDuration);
Ana Krulec98b5b242018-08-10 15:03:23 -0700384}
Ana Krulece588e312018-09-18 12:32:24 -0700385
Ady Abraham8cb21882020-08-26 18:22:05 -0700386void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats, nsecs_t now) {
387 stats->vsyncTime = mVsyncSchedule.tracker->nextAnticipatedVSyncTimeFrom(now);
388 stats->vsyncPeriod = mVsyncSchedule.tracker->currentPeriod();
Ana Krulece588e312018-09-18 12:32:24 -0700389}
390
Dominik Laskowski6505f792019-09-18 11:10:05 -0700391Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
392 if (mInjectVSyncs == enable) {
393 return {};
394 }
395
396 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
397
398 if (!mInjectorConnectionHandle) {
399 auto vsyncSource = std::make_unique<InjectVSyncSource>();
400 mVSyncInjector = vsyncSource.get();
401
402 auto eventThread =
403 std::make_unique<impl::EventThread>(std::move(vsyncSource),
Adithya Srinivasan5f683cf2020-09-15 14:21:04 -0700404 /*tokenManager=*/nullptr,
Ady Abraham0bb6a472020-10-12 10:22:13 -0700405 impl::EventThread::InterceptVSyncsCallback(),
406 impl::EventThread::ThrottleVsyncCallback());
Dominik Laskowski6505f792019-09-18 11:10:05 -0700407
408 mInjectorConnectionHandle = createConnection(std::move(eventThread));
409 }
410
411 mInjectVSyncs = enable;
412 return mInjectorConnectionHandle;
413}
414
Ady Abraham9c53ee72020-07-22 21:16:18 -0700415bool Scheduler::injectVSync(nsecs_t when, nsecs_t expectedVSyncTime, nsecs_t deadlineTimestamp) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700416 if (!mInjectVSyncs || !mVSyncInjector) {
417 return false;
418 }
419
Ady Abraham9c53ee72020-07-22 21:16:18 -0700420 mVSyncInjector->onInjectSyncEvent(when, expectedVSyncTime, deadlineTimestamp);
Dominik Laskowski6505f792019-09-18 11:10:05 -0700421 return true;
422}
423
Ana Krulece588e312018-09-18 12:32:24 -0700424void Scheduler::enableHardwareVsync() {
425 std::lock_guard<std::mutex> lock(mHWVsyncLock);
426 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700427 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700428 mSchedulerCallback.setVsyncEnabled(true);
Ana Krulece588e312018-09-18 12:32:24 -0700429 mPrimaryHWVsyncEnabled = true;
430 }
431}
432
433void Scheduler::disableHardwareVsync(bool makeUnavailable) {
434 std::lock_guard<std::mutex> lock(mHWVsyncLock);
435 if (mPrimaryHWVsyncEnabled) {
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700436 mSchedulerCallback.setVsyncEnabled(false);
Ana Krulece588e312018-09-18 12:32:24 -0700437 mPrimaryHWVsyncEnabled = false;
438 }
439 if (makeUnavailable) {
440 mHWVsyncAvailable = false;
441 }
442}
443
Ana Krulecc2870422019-01-29 19:00:58 -0800444void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
445 {
446 std::lock_guard<std::mutex> lock(mHWVsyncLock);
447 if (makeAvailable) {
448 mHWVsyncAvailable = makeAvailable;
449 } else if (!mHWVsyncAvailable) {
450 // Hardware vsync is not currently available, so abort the resync
451 // attempt for now
452 return;
453 }
454 }
455
456 if (period <= 0) {
457 return;
458 }
459
460 setVsyncPeriod(period);
461}
462
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700463void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700464 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800465
466 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700467 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800468
469 if (now - last > kIgnoreDelay) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700470 resyncToHardwareVsync(false, mRefreshRateConfigs.getCurrentRefreshRate().getVsyncPeriod());
Ana Krulecc2870422019-01-29 19:00:58 -0800471 }
472}
473
Dominik Laskowski98041832019-08-01 18:35:59 -0700474void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800475 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ady Abraham8cb21882020-08-26 18:22:05 -0700476 mVsyncSchedule.controller->startPeriodTransition(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800477
478 if (!mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700479 mVsyncSchedule.tracker->resetModel();
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700480 mSchedulerCallback.setVsyncEnabled(true);
Ady Abraham3aff9172019-02-07 19:10:26 -0800481 mPrimaryHWVsyncEnabled = true;
482 }
Ana Krulece588e312018-09-18 12:32:24 -0700483}
484
Ady Abraham5dee2f12020-02-05 17:49:47 -0800485void Scheduler::addResyncSample(nsecs_t timestamp, std::optional<nsecs_t> hwcVsyncPeriod,
486 bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700487 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700488 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700489 { // Scope for the lock
490 std::lock_guard<std::mutex> lock(mHWVsyncLock);
491 if (mPrimaryHWVsyncEnabled) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700492 needsHwVsync = mVsyncSchedule.controller->addHwVsyncTimestamp(timestamp, hwcVsyncPeriod,
493 periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700494 }
495 }
496
497 if (needsHwVsync) {
498 enableHardwareVsync();
499 } else {
500 disableHardwareVsync(false);
501 }
502}
503
504void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700505 if (mVsyncSchedule.controller->addPresentFence(fenceTime)) {
Ana Krulece588e312018-09-18 12:32:24 -0700506 enableHardwareVsync();
507 } else {
508 disableHardwareVsync(false);
509 }
510}
511
512void Scheduler::setIgnorePresentFences(bool ignore) {
Ady Abraham8cb21882020-08-26 18:22:05 -0700513 mVsyncSchedule.controller->setIgnorePresentFences(ignore);
Ady Abrahamc3e21312019-02-07 14:30:23 -0800514}
515
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700516void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800517 if (!mLayerHistory) return;
518
Steven Thomasdebafed2020-05-18 17:30:35 -0700519 const auto minFps = mRefreshRateConfigs.getMinRefreshRate().getFps();
520 const auto maxFps = mRefreshRateConfigs.getMaxRefreshRate().getFps();
521
Michael Wright44753b12020-07-08 13:48:11 +0100522 if (layer->getWindowType() == InputWindowInfo::Type::STATUS_BAR) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700523 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ana Krulec3d367c82020-02-25 15:02:01 -0800524 scheduler::LayerHistory::LayerVoteType::NoVote);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700525 } else if (!mOptions.useContentDetection) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700526 // If the content detection feature is off, all layers are registered at Max. We still keep
527 // the layer history, since we use it for other features (like Frame Rate API), so layers
528 // still need to be registered.
529 mLayerHistory->registerLayer(layer, minFps, maxFps,
530 scheduler::LayerHistory::LayerVoteType::Max);
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700531 } else if (!mOptions.useContentDetectionV2) {
Steven Thomasdebafed2020-05-18 17:30:35 -0700532 // In V1 of content detection, all layers are registered as Heuristic (unless it's
533 // wallpaper).
534 const auto highFps =
Michael Wright44753b12020-07-08 13:48:11 +0100535 layer->getWindowType() == InputWindowInfo::Type::WALLPAPER ? minFps : maxFps;
Ana Krulec3d367c82020-02-25 15:02:01 -0800536
Steven Thomasdebafed2020-05-18 17:30:35 -0700537 mLayerHistory->registerLayer(layer, minFps, highFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800538 scheduler::LayerHistory::LayerVoteType::Heuristic);
539 } else {
Michael Wright44753b12020-07-08 13:48:11 +0100540 if (layer->getWindowType() == InputWindowInfo::Type::WALLPAPER) {
Ana Krulec3d367c82020-02-25 15:02:01 -0800541 // Running Wallpaper at Min is considered as part of content detection.
Steven Thomasdebafed2020-05-18 17:30:35 -0700542 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800543 scheduler::LayerHistory::LayerVoteType::Min);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800544 } else {
Steven Thomasdebafed2020-05-18 17:30:35 -0700545 mLayerHistory->registerLayer(layer, minFps, maxFps,
Ady Abraham8a82ba62020-01-17 12:43:17 -0800546 scheduler::LayerHistory::LayerVoteType::Heuristic);
547 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800548 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700549}
550
Ady Abraham5def7332020-05-29 16:13:47 -0700551void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime,
552 LayerHistory::LayerUpdateType updateType) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800553 if (mLayerHistory) {
Ady Abraham5def7332020-05-29 16:13:47 -0700554 mLayerHistory->record(layer, presentTime, systemTime(), updateType);
Dominik Laskowski49cea512019-11-12 14:13:23 -0800555 }
Ana Krulec3084c052018-11-21 20:27:17 +0100556}
557
Ady Abraham32efd542020-05-19 17:49:26 -0700558void Scheduler::setConfigChangePending(bool pending) {
559 if (mLayerHistory) {
560 mLayerHistory->setConfigChangePending(pending);
561 }
562}
563
Dominik Laskowski49cea512019-11-12 14:13:23 -0800564void Scheduler::chooseRefreshRateForContent() {
565 if (!mLayerHistory) return;
566
Ady Abraham8a82ba62020-01-17 12:43:17 -0800567 ATRACE_CALL();
568
569 scheduler::LayerHistory::Summary summary = mLayerHistory->summarize(systemTime());
Ady Abraham2139f732019-11-13 18:56:40 -0800570 HwcConfigIndexType newConfigId;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700571 {
572 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800573 if (mFeatures.contentRequirements == summary) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700574 return;
575 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800576 mFeatures.contentRequirements = summary;
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800577 mFeatures.contentDetectionV1 =
Ady Abraham8a82ba62020-01-17 12:43:17 -0800578 !summary.empty() ? ContentDetectionState::On : ContentDetectionState::Off;
579
Ady Abrahamdfd62162020-06-10 16:11:56 -0700580 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
581 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800582 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700583 // We don't need to change the config, but we might need to send an event
584 // about a config change, since it was suppressed due to a previous idleConsidered
585 if (!consideredSignals.idle) {
586 dispatchCachedReportedConfig();
587 }
Ady Abraham6398a0a2019-04-18 19:30:44 -0700588 return;
589 }
Ady Abraham2139f732019-11-13 18:56:40 -0800590 mFeatures.configId = newConfigId;
Ady Abraham2e1dd892020-03-05 13:48:36 -0800591 auto& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700592 mSchedulerCallback.changeRefreshRate(newRefreshRate,
593 consideredSignals.idle ? ConfigEvent::None
594 : ConfigEvent::Changed);
Ady Abraham8a82ba62020-01-17 12:43:17 -0800595 }
Ady Abrahama1a49af2019-02-07 14:36:55 -0800596}
597
Ana Krulecfb772822018-11-30 10:44:07 +0100598void Scheduler::resetIdleTimer() {
599 if (mIdleTimer) {
600 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800601 }
602}
603
Ady Abraham8532d012019-05-08 14:50:56 -0700604void Scheduler::notifyTouchEvent() {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700605 if (mTouchTimer) {
Ady Abraham8a82ba62020-01-17 12:43:17 -0800606 mTouchTimer->reset();
Steven Thomas540730a2020-01-08 20:12:42 -0800607
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700608 if (mOptions.supportKernelTimer && mIdleTimer) {
Steven Thomas540730a2020-01-08 20:12:42 -0800609 mIdleTimer->reset();
610 }
Dominik Laskowski49cea512019-11-12 14:13:23 -0800611 }
Ady Abraham8532d012019-05-08 14:50:56 -0700612}
613
Ady Abraham6fe2c172019-07-12 12:37:57 -0700614void Scheduler::setDisplayPowerState(bool normal) {
615 {
616 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700617 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700618 }
619
620 if (mDisplayPowerTimer) {
621 mDisplayPowerTimer->reset();
622 }
623
624 // Display Power event will boost the refresh rate to performance.
625 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800626 if (mLayerHistory) {
627 mLayerHistory->clear();
628 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700629}
630
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700631void Scheduler::kernelIdleTimerCallback(TimerState state) {
632 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100633
Ady Abraham2139f732019-11-13 18:56:40 -0800634 // TODO(145561154): cleanup the kernel idle timer implementation and the refresh rate
635 // magic number
Ady Abraham2e1dd892020-03-05 13:48:36 -0800636 const auto& refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -0800637 constexpr float FPS_THRESHOLD_FOR_KERNEL_TIMER = 65.0f;
Ady Abrahamabc27602020-04-08 17:20:29 -0700638 if (state == TimerState::Reset && refreshRate.getFps() > FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Alec Mouri7f015182019-07-11 13:56:22 -0700639 // If we're not in performance mode then the kernel timer shouldn't do
640 // anything, as the refresh rate during DPU power collapse will be the
641 // same.
Ady Abrahamabc27602020-04-08 17:20:29 -0700642 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.getVsyncPeriod());
643 } else if (state == TimerState::Expired &&
644 refreshRate.getFps() <= FPS_THRESHOLD_FOR_KERNEL_TIMER) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700645 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
646 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
Ady Abraham8cb21882020-08-26 18:22:05 -0700647 // need to update the VsyncController model anyway.
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700648 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700649 }
Ady Abrahama09852a2020-02-20 14:23:42 -0800650
651 mSchedulerCallback.kernelTimerChanged(state == TimerState::Expired);
Alec Mouridc28b372019-04-18 21:17:13 -0700652}
653
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700654void Scheduler::idleTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700655 handleTimerStateChanged(&mFeatures.idleTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700656 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100657}
658
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700659void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700660 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700661 // Touch event will boost the refresh rate to performance.
662 // Clear layer history to get fresh FPS detection.
663 // NOTE: Instead of checking all the layers, we should be checking the layer
664 // that is currently on top. b/142507166 will give us this capability.
Ady Abrahamdfd62162020-06-10 16:11:56 -0700665 if (handleTimerStateChanged(&mFeatures.touch, touch)) {
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700666 if (mLayerHistory) {
667 mLayerHistory->clear();
668 }
Ady Abraham1adbb722020-05-15 11:51:48 -0700669 }
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700670 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700671}
672
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700673void Scheduler::displayPowerTimerCallback(TimerState state) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700674 handleTimerStateChanged(&mFeatures.displayPowerTimer, state);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700675 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700676}
677
Dominik Laskowski98041832019-08-01 18:35:59 -0700678void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800679 using base::StringAppendF;
Dominik Laskowski98041832019-08-01 18:35:59 -0700680
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700681 StringAppendF(&result, "+ Idle timer: %s\n", mIdleTimer ? mIdleTimer->dump().c_str() : "off");
Ana Krulec3d367c82020-02-25 15:02:01 -0800682 StringAppendF(&result, "+ Touch timer: %s\n",
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700683 mTouchTimer ? mTouchTimer->dump().c_str() : "off");
684 StringAppendF(&result, "+ Content detection: %s %s\n\n",
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700685 toContentDetectionString(mOptions.useContentDetection,
686 mOptions.useContentDetectionV2),
Dominik Laskowski983f2b52020-06-25 16:54:06 -0700687 mLayerHistory ? mLayerHistory->dump().c_str() : "(no layer history)");
Ana Krulecb43429d2019-01-09 14:28:51 -0800688}
689
Ady Abraham8cb21882020-08-26 18:22:05 -0700690void Scheduler::dumpVsync(std::string& s) const {
Ady Abraham8735eac2020-08-12 16:35:04 -0700691 using base::StringAppendF;
692
693 StringAppendF(&s, "VSyncReactor:\n");
Ady Abraham8cb21882020-08-26 18:22:05 -0700694 mVsyncSchedule.controller->dump(s);
Ady Abraham8735eac2020-08-12 16:35:04 -0700695 StringAppendF(&s, "VSyncDispatch:\n");
696 mVsyncSchedule.dispatch->dump(s);
697}
698
Ady Abraham6fe2c172019-07-12 12:37:57 -0700699template <class T>
Ady Abrahamdfd62162020-06-10 16:11:56 -0700700bool Scheduler::handleTimerStateChanged(T* currentState, T newState) {
Ady Abraham2139f732019-11-13 18:56:40 -0800701 HwcConfigIndexType newConfigId;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700702 scheduler::RefreshRateConfigs::GlobalSignals consideredSignals;
Ady Abraham8532d012019-05-08 14:50:56 -0700703 {
704 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700705 if (*currentState == newState) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700706 return false;
Ady Abraham8532d012019-05-08 14:50:56 -0700707 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700708 *currentState = newState;
Ady Abrahamdfd62162020-06-10 16:11:56 -0700709 newConfigId = calculateRefreshRateConfigIndexType(&consideredSignals);
Ady Abraham2139f732019-11-13 18:56:40 -0800710 if (mFeatures.configId == newConfigId) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700711 // We don't need to change the config, but we might need to send an event
712 // about a config change, since it was suppressed due to a previous idleConsidered
713 if (!consideredSignals.idle) {
714 dispatchCachedReportedConfig();
715 }
716 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700717 }
Ady Abraham2139f732019-11-13 18:56:40 -0800718 mFeatures.configId = newConfigId;
Ady Abraham8532d012019-05-08 14:50:56 -0700719 }
Ady Abraham2139f732019-11-13 18:56:40 -0800720 const RefreshRate& newRefreshRate = mRefreshRateConfigs.getRefreshRateFromConfigId(newConfigId);
Ady Abrahamdfd62162020-06-10 16:11:56 -0700721 mSchedulerCallback.changeRefreshRate(newRefreshRate,
722 consideredSignals.idle ? ConfigEvent::None
723 : ConfigEvent::Changed);
724 return consideredSignals.touch;
Ady Abraham8532d012019-05-08 14:50:56 -0700725}
726
Ady Abrahamdfd62162020-06-10 16:11:56 -0700727HwcConfigIndexType Scheduler::calculateRefreshRateConfigIndexType(
728 scheduler::RefreshRateConfigs::GlobalSignals* consideredSignals) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800729 ATRACE_CALL();
Ady Abrahamdfd62162020-06-10 16:11:56 -0700730 if (consideredSignals) *consideredSignals = {};
Ady Abraham09bd3922019-04-08 10:44:56 -0700731
Steven Thomasf734df42020-04-13 21:09:28 -0700732 // If Display Power is not in normal operation we want to be in performance mode. When coming
733 // back to normal mode, a grace period is given with DisplayPowerTimer.
Ana Krulec3f6a2062020-01-23 15:48:01 -0800734 if (mDisplayPowerTimer &&
735 (!mFeatures.isDisplayPowerStateNormal ||
736 mFeatures.displayPowerTimer == TimerState::Reset)) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700737 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800738 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700739
Steven Thomasbb374322020-04-28 22:47:16 -0700740 const bool touchActive = mTouchTimer && mFeatures.touch == TouchState::Active;
741 const bool idle = mIdleTimer && mFeatures.idleTimer == TimerState::Expired;
742
Dominik Laskowski8b01cc02020-07-14 19:02:41 -0700743 if (!mOptions.useContentDetectionV2) {
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800744 // As long as touch is active we want to be in performance mode.
Steven Thomasbb374322020-04-28 22:47:16 -0700745 if (touchActive) {
Ady Abrahamabc27602020-04-08 17:20:29 -0700746 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800747 }
Ady Abraham8532d012019-05-08 14:50:56 -0700748
Steven Thomasbb374322020-04-28 22:47:16 -0700749 // If timer has expired as it means there is no new content on the screen.
750 if (idle) {
Ady Abrahamdfd62162020-06-10 16:11:56 -0700751 if (consideredSignals) consideredSignals->idle = true;
Steven Thomasbb374322020-04-28 22:47:16 -0700752 return mRefreshRateConfigs.getMinRefreshRateByPolicy().getConfigId();
753 }
Ady Abrahama315ce72019-04-24 14:35:20 -0700754
Ana Krulec3f6a2062020-01-23 15:48:01 -0800755 // If content detection is off we choose performance as we don't know the content fps.
Ady Abraham4ccdcb42020-02-11 17:34:34 -0800756 if (mFeatures.contentDetectionV1 == ContentDetectionState::Off) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800757 // NOTE: V1 always calls this, but this is not a default behavior for V2.
Ady Abrahamabc27602020-04-08 17:20:29 -0700758 return mRefreshRateConfigs.getMaxRefreshRateByPolicy().getConfigId();
Steven Thomas540730a2020-01-08 20:12:42 -0800759 }
Ady Abraham8a82ba62020-01-17 12:43:17 -0800760
761 // Content detection is on, find the appropriate refresh rate with minimal error
Ady Abrahamabc27602020-04-08 17:20:29 -0700762 return mRefreshRateConfigs.getRefreshRateForContent(mFeatures.contentRequirements)
763 .getConfigId();
Ady Abraham09bd3922019-04-08 10:44:56 -0700764 }
765
Ady Abraham1adbb722020-05-15 11:51:48 -0700766 return mRefreshRateConfigs
Ady Abrahamdfd62162020-06-10 16:11:56 -0700767 .getBestRefreshRate(mFeatures.contentRequirements, {.touch = touchActive, .idle = idle},
768 consideredSignals)
Ady Abraham1adbb722020-05-15 11:51:48 -0700769 .getConfigId();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800770}
771
Ady Abraham2139f732019-11-13 18:56:40 -0800772std::optional<HwcConfigIndexType> Scheduler::getPreferredConfigId() {
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700773 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ana Krulec3f6a2062020-01-23 15:48:01 -0800774 // Make sure that the default config ID is first updated, before returned.
775 if (mFeatures.configId.has_value()) {
Ana Krulec3803b8d2020-02-03 16:35:46 -0800776 mFeatures.configId = calculateRefreshRateConfigIndexType();
Ana Krulec3f6a2062020-01-23 15:48:01 -0800777 }
Ady Abraham2139f732019-11-13 18:56:40 -0800778 return mFeatures.configId;
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700779}
780
Peiyong Line9d809e2020-04-14 13:10:48 -0700781void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -0800782 if (timeline.refreshRequired) {
783 mSchedulerCallback.repaintEverythingForHWC();
784 }
785
786 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
787 mLastVsyncPeriodChangeTimeline = std::make_optional(timeline);
788
789 const auto maxAppliedTime = systemTime() + MAX_VSYNC_APPLIED_TIME.count();
790 if (timeline.newVsyncAppliedTimeNanos > maxAppliedTime) {
791 mLastVsyncPeriodChangeTimeline->newVsyncAppliedTimeNanos = maxAppliedTime;
792 }
793}
794
795void Scheduler::onDisplayRefreshed(nsecs_t timestamp) {
796 bool callRepaint = false;
797 {
798 std::lock_guard<std::mutex> lock(mVsyncTimelineLock);
799 if (mLastVsyncPeriodChangeTimeline && mLastVsyncPeriodChangeTimeline->refreshRequired) {
800 if (mLastVsyncPeriodChangeTimeline->refreshTimeNanos < timestamp) {
801 mLastVsyncPeriodChangeTimeline->refreshRequired = false;
802 } else {
803 // We need to send another refresh as refreshTimeNanos is still in the future
804 callRepaint = true;
805 }
806 }
807 }
808
809 if (callRepaint) {
810 mSchedulerCallback.repaintEverythingForHWC();
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800811 }
812}
813
Ady Abraham8a82ba62020-01-17 12:43:17 -0800814void Scheduler::onPrimaryDisplayAreaChanged(uint32_t displayArea) {
815 if (mLayerHistory) {
816 mLayerHistory->setDisplayArea(displayArea);
817 }
818}
819
Ana Krulec98b5b242018-08-10 15:03:23 -0700820} // namespace android