blob: 55fd6032f2d7a8af166cb3dc3131e2aa84827b87 [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"
Ana Krulec98b5b242018-08-10 15:03:23 -070050
Dominik Laskowski98041832019-08-01 18:35:59 -070051#define RETURN_IF_INVALID_HANDLE(handle, ...) \
52 do { \
53 if (mConnections.count(handle) == 0) { \
54 ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
55 return __VA_ARGS__; \
56 } \
57 } while (false)
58
Ana Krulec98b5b242018-08-10 15:03:23 -070059namespace android {
60
Ady Abraham09bd3922019-04-08 10:44:56 -070061Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
62 const scheduler::RefreshRateConfigs& refreshRateConfig)
Dominik Laskowski98041832019-08-01 18:35:59 -070063 : mPrimaryDispSync(new impl::DispSync("SchedulerDispSync",
64 sysprop::running_without_sync_framework(true))),
65 mEventControlThread(new impl::EventControlThread(std::move(function))),
66 mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
Ady Abraham09bd3922019-04-08 10:44:56 -070067 mRefreshRateConfigs(refreshRateConfig) {
Dominik Laskowski98041832019-08-01 18:35:59 -070068 using namespace sysprop;
Ady Abraham8532d012019-05-08 14:50:56 -070069
Dominik Laskowski49cea512019-11-12 14:13:23 -080070 if (property_get_bool("debug.sf.use_smart_90_for_video", 0) || use_smart_90_for_video(false)) {
71 mLayerHistory.emplace();
72 }
73
74 const int setIdleTimerMs = property_get_int32("debug.sf.set_idle_timer_ms", 0);
Ana Krulecfb772822018-11-30 10:44:07 +010075
Dominik Laskowski98041832019-08-01 18:35:59 -070076 if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
77 const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
78 : &Scheduler::idleTimerCallback;
79
80 mIdleTimer.emplace(
81 std::chrono::milliseconds(millis),
82 [this, callback] { std::invoke(callback, this, TimerState::Reset); },
83 [this, callback] { std::invoke(callback, this, TimerState::Expired); });
Ana Krulecfb772822018-11-30 10:44:07 +010084 mIdleTimer->start();
85 }
Ady Abraham8532d012019-05-08 14:50:56 -070086
Dominik Laskowski98041832019-08-01 18:35:59 -070087 if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
Ady Abraham8532d012019-05-08 14:50:56 -070088 // Touch events are coming to SF every 100ms, so the timer needs to be higher than that
Dominik Laskowski98041832019-08-01 18:35:59 -070089 mTouchTimer.emplace(
90 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070091 [this] { touchTimerCallback(TimerState::Reset); },
92 [this] { touchTimerCallback(TimerState::Expired); });
Ady Abraham8532d012019-05-08 14:50:56 -070093 mTouchTimer->start();
94 }
Ady Abraham6fe2c172019-07-12 12:37:57 -070095
Dominik Laskowski98041832019-08-01 18:35:59 -070096 if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
97 mDisplayPowerTimer.emplace(
98 std::chrono::milliseconds(millis),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -070099 [this] { displayPowerTimerCallback(TimerState::Reset); },
100 [this] { displayPowerTimerCallback(TimerState::Expired); });
Ady Abraham6fe2c172019-07-12 12:37:57 -0700101 mDisplayPowerTimer->start();
102 }
Ana Krulece588e312018-09-18 12:32:24 -0700103}
104
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700105Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
106 std::unique_ptr<EventControlThread> eventControlThread,
107 const scheduler::RefreshRateConfigs& configs)
Dominik Laskowski98041832019-08-01 18:35:59 -0700108 : mPrimaryDispSync(std::move(primaryDispSync)),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700109 mEventControlThread(std::move(eventControlThread)),
Dominik Laskowski98041832019-08-01 18:35:59 -0700110 mSupportKernelTimer(false),
Dominik Laskowski7c9dbf92019-08-01 17:57:31 -0700111 mRefreshRateConfigs(configs) {}
112
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800113Scheduler::~Scheduler() {
Ana Krulecf2c006d2019-06-21 15:37:07 -0700114 // Ensure the OneShotTimer threads are joined before we start destroying state.
Ady Abraham6fe2c172019-07-12 12:37:57 -0700115 mDisplayPowerTimer.reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700116 mTouchTimer.reset();
Lloyd Pique1f9f1a42019-01-31 13:04:00 -0800117 mIdleTimer.reset();
118}
Ana Krulec0c8cd522018-08-31 12:27:28 -0700119
Dominik Laskowski98041832019-08-01 18:35:59 -0700120DispSync& Scheduler::getPrimaryDispSync() {
121 return *mPrimaryDispSync;
122}
123
Dominik Laskowski6505f792019-09-18 11:10:05 -0700124std::unique_ptr<VSyncSource> Scheduler::makePrimaryDispSyncSource(
125 const char* name, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync) {
126 return std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
127 offsetThresholdForNextVsync, true /* traceVsync */,
128 name);
129}
130
Dominik Laskowski98041832019-08-01 18:35:59 -0700131Scheduler::ConnectionHandle Scheduler::createConnection(
Ady Abraham45e4e362019-06-07 18:20:51 -0700132 const char* connectionName, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync,
Ana Krulec98b5b242018-08-10 15:03:23 -0700133 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Dominik Laskowski6505f792019-09-18 11:10:05 -0700134 auto vsyncSource =
135 makePrimaryDispSyncSource(connectionName, phaseOffsetNs, offsetThresholdForNextVsync);
136 auto eventThread = std::make_unique<impl::EventThread>(std::move(vsyncSource),
137 std::move(interceptCallback));
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700138 return createConnection(std::move(eventThread));
Dominik Laskowski98041832019-08-01 18:35:59 -0700139}
Ana Krulec98b5b242018-08-10 15:03:23 -0700140
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700141Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700142 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
143 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
Dominik Laskowskif654d572018-12-20 11:03:06 -0800144
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700145 auto connection =
146 createConnectionInternal(eventThread.get(), ISurfaceComposer::eConfigChangedSuppress);
Dominik Laskowski98041832019-08-01 18:35:59 -0700147
148 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
149 return handle;
Ana Krulec98b5b242018-08-10 15:03:23 -0700150}
151
Ady Abraham0f4a1b12019-06-04 16:04:04 -0700152sp<EventThreadConnection> Scheduler::createConnectionInternal(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700153 EventThread* eventThread, ISurfaceComposer::ConfigChanged configChanged) {
154 return eventThread->createEventConnection([&] { resync(); }, configChanged);
Ana Krulec0c8cd522018-08-31 12:27:28 -0700155}
156
Ana Krulec98b5b242018-08-10 15:03:23 -0700157sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700158 ConnectionHandle handle, ISurfaceComposer::ConfigChanged configChanged) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700159 RETURN_IF_INVALID_HANDLE(handle, nullptr);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700160 return createConnectionInternal(mConnections[handle].thread.get(), configChanged);
Ana Krulec98b5b242018-08-10 15:03:23 -0700161}
162
Dominik Laskowski98041832019-08-01 18:35:59 -0700163sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
164 RETURN_IF_INVALID_HANDLE(handle, nullptr);
165 return mConnections[handle].connection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700166}
167
Dominik Laskowski98041832019-08-01 18:35:59 -0700168void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
169 bool connected) {
170 RETURN_IF_INVALID_HANDLE(handle);
171 mConnections[handle].thread->onHotplugReceived(displayId, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700172}
173
Dominik Laskowski98041832019-08-01 18:35:59 -0700174void Scheduler::onScreenAcquired(ConnectionHandle handle) {
175 RETURN_IF_INVALID_HANDLE(handle);
176 mConnections[handle].thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700177}
178
Dominik Laskowski98041832019-08-01 18:35:59 -0700179void Scheduler::onScreenReleased(ConnectionHandle handle) {
180 RETURN_IF_INVALID_HANDLE(handle);
181 mConnections[handle].thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700182}
183
Dominik Laskowski98041832019-08-01 18:35:59 -0700184void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
Ady Abraham447052e2019-02-13 16:07:27 -0800185 int32_t configId) {
Dominik Laskowski98041832019-08-01 18:35:59 -0700186 RETURN_IF_INVALID_HANDLE(handle);
187 mConnections[handle].thread->onConfigChanged(displayId, configId);
Ady Abraham447052e2019-02-13 16:07:27 -0800188}
189
Dominik Laskowski98041832019-08-01 18:35:59 -0700190void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
191 RETURN_IF_INVALID_HANDLE(handle);
192 mConnections.at(handle).thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700193}
194
Dominik Laskowski98041832019-08-01 18:35:59 -0700195void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
196 RETURN_IF_INVALID_HANDLE(handle);
197 mConnections[handle].thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700198}
Ana Krulece588e312018-09-18 12:32:24 -0700199
200void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
201 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
202 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
203}
204
Dominik Laskowski6505f792019-09-18 11:10:05 -0700205Scheduler::ConnectionHandle Scheduler::enableVSyncInjection(bool enable) {
206 if (mInjectVSyncs == enable) {
207 return {};
208 }
209
210 ALOGV("%s VSYNC injection", enable ? "Enabling" : "Disabling");
211
212 if (!mInjectorConnectionHandle) {
213 auto vsyncSource = std::make_unique<InjectVSyncSource>();
214 mVSyncInjector = vsyncSource.get();
215
216 auto eventThread =
217 std::make_unique<impl::EventThread>(std::move(vsyncSource),
218 impl::EventThread::InterceptVSyncsCallback());
219
220 mInjectorConnectionHandle = createConnection(std::move(eventThread));
221 }
222
223 mInjectVSyncs = enable;
224 return mInjectorConnectionHandle;
225}
226
227bool Scheduler::injectVSync(nsecs_t when) {
228 if (!mInjectVSyncs || !mVSyncInjector) {
229 return false;
230 }
231
232 mVSyncInjector->onInjectSyncEvent(when);
233 return true;
234}
235
Ana Krulece588e312018-09-18 12:32:24 -0700236void Scheduler::enableHardwareVsync() {
237 std::lock_guard<std::mutex> lock(mHWVsyncLock);
238 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
239 mPrimaryDispSync->beginResync();
240 mEventControlThread->setVsyncEnabled(true);
241 mPrimaryHWVsyncEnabled = true;
242 }
243}
244
245void Scheduler::disableHardwareVsync(bool makeUnavailable) {
246 std::lock_guard<std::mutex> lock(mHWVsyncLock);
247 if (mPrimaryHWVsyncEnabled) {
248 mEventControlThread->setVsyncEnabled(false);
249 mPrimaryDispSync->endResync();
250 mPrimaryHWVsyncEnabled = false;
251 }
252 if (makeUnavailable) {
253 mHWVsyncAvailable = false;
254 }
255}
256
Ana Krulecc2870422019-01-29 19:00:58 -0800257void Scheduler::resyncToHardwareVsync(bool makeAvailable, nsecs_t period) {
258 {
259 std::lock_guard<std::mutex> lock(mHWVsyncLock);
260 if (makeAvailable) {
261 mHWVsyncAvailable = makeAvailable;
262 } else if (!mHWVsyncAvailable) {
263 // Hardware vsync is not currently available, so abort the resync
264 // attempt for now
265 return;
266 }
267 }
268
269 if (period <= 0) {
270 return;
271 }
272
273 setVsyncPeriod(period);
274}
275
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700276void Scheduler::resync() {
Long Ling457bef92019-09-11 14:43:11 -0700277 static constexpr nsecs_t kIgnoreDelay = ms2ns(750);
Ana Krulecc2870422019-01-29 19:00:58 -0800278
279 const nsecs_t now = systemTime();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700280 const nsecs_t last = mLastResyncTime.exchange(now);
Ana Krulecc2870422019-01-29 19:00:58 -0800281
282 if (now - last > kIgnoreDelay) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700283 resyncToHardwareVsync(false,
284 mRefreshRateConfigs.getCurrentRefreshRate().second.vsyncPeriod);
Ana Krulecc2870422019-01-29 19:00:58 -0800285 }
286}
287
Dominik Laskowski98041832019-08-01 18:35:59 -0700288void Scheduler::setVsyncPeriod(nsecs_t period) {
Ady Abraham3aff9172019-02-07 19:10:26 -0800289 std::lock_guard<std::mutex> lock(mHWVsyncLock);
Ana Krulece588e312018-09-18 12:32:24 -0700290 mPrimaryDispSync->setPeriod(period);
Ady Abraham3aff9172019-02-07 19:10:26 -0800291
292 if (!mPrimaryHWVsyncEnabled) {
293 mPrimaryDispSync->beginResync();
294 mEventControlThread->setVsyncEnabled(true);
295 mPrimaryHWVsyncEnabled = true;
296 }
Ana Krulece588e312018-09-18 12:32:24 -0700297}
298
Dominik Laskowski98041832019-08-01 18:35:59 -0700299void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
Ana Krulece588e312018-09-18 12:32:24 -0700300 bool needsHwVsync = false;
Alec Mourif8e689c2019-05-20 18:32:22 -0700301 *periodFlushed = false;
Ana Krulece588e312018-09-18 12:32:24 -0700302 { // Scope for the lock
303 std::lock_guard<std::mutex> lock(mHWVsyncLock);
304 if (mPrimaryHWVsyncEnabled) {
Alec Mourif8e689c2019-05-20 18:32:22 -0700305 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp, periodFlushed);
Ana Krulece588e312018-09-18 12:32:24 -0700306 }
307 }
308
309 if (needsHwVsync) {
310 enableHardwareVsync();
311 } else {
312 disableHardwareVsync(false);
313 }
314}
315
316void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
317 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
318 enableHardwareVsync();
319 } else {
320 disableHardwareVsync(false);
321 }
322}
323
324void Scheduler::setIgnorePresentFences(bool ignore) {
325 mPrimaryDispSync->setIgnorePresentFences(ignore);
326}
327
Ady Abraham8fe11022019-06-12 17:11:12 -0700328nsecs_t Scheduler::getDispSyncExpectedPresentTime() {
Ady Abrahamc3e21312019-02-07 14:30:23 -0800329 return mPrimaryDispSync->expectedPresentTime();
330}
331
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700332void Scheduler::registerLayer(Layer* layer) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800333 if (!mLayerHistory) return;
334
335 const auto type = layer->getWindowType() == InputWindowInfo::TYPE_WALLPAPER
336 ? RefreshRateType::DEFAULT
337 : RefreshRateType::PERFORMANCE;
338
339 const auto lowFps = mRefreshRateConfigs.getRefreshRateFromType(RefreshRateType::DEFAULT).fps;
340 const auto highFps = mRefreshRateConfigs.getRefreshRateFromType(type).fps;
341
342 mLayerHistory->registerLayer(layer, lowFps, highFps);
Ady Abraham09bd3922019-04-08 10:44:56 -0700343}
344
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -0700345void Scheduler::recordLayerHistory(Layer* layer, nsecs_t presentTime, bool isHDR) {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800346 if (mLayerHistory) {
347 mLayerHistory->record(layer, presentTime, isHDR, systemTime());
348 }
Ana Krulec3084c052018-11-21 20:27:17 +0100349}
350
Dominik Laskowski49cea512019-11-12 14:13:23 -0800351void Scheduler::chooseRefreshRateForContent() {
352 if (!mLayerHistory) return;
353
354 auto [refreshRate, isHDR] = mLayerHistory->summarize(systemTime());
Ady Abrahama315ce72019-04-24 14:35:20 -0700355 const uint32_t refreshRateRound = std::round(refreshRate);
Ady Abraham6398a0a2019-04-18 19:30:44 -0700356 RefreshRateType newRefreshRateType;
357 {
358 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700359 if (mFeatures.contentRefreshRate == refreshRateRound && mFeatures.isHDRContent == isHDR) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700360 return;
361 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700362 mFeatures.contentRefreshRate = refreshRateRound;
363 ATRACE_INT("ContentFPS", refreshRateRound);
Ady Abraham6398a0a2019-04-18 19:30:44 -0700364
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700365 mFeatures.isHDRContent = isHDR;
366 ATRACE_INT("ContentHDR", isHDR);
Ady Abrahama315ce72019-04-24 14:35:20 -0700367
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700368 mFeatures.contentDetection =
369 refreshRateRound > 0 ? ContentDetectionState::On : ContentDetectionState::Off;
Ady Abraham6398a0a2019-04-18 19:30:44 -0700370 newRefreshRateType = calculateRefreshRateType();
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700371 if (mFeatures.refreshRateType == newRefreshRateType) {
Ady Abraham6398a0a2019-04-18 19:30:44 -0700372 return;
373 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700374 mFeatures.refreshRateType = newRefreshRateType;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800375 }
Ady Abraham6398a0a2019-04-18 19:30:44 -0700376 changeRefreshRate(newRefreshRateType, ConfigEvent::Changed);
Ana Krulec3084c052018-11-21 20:27:17 +0100377}
378
Dominik Laskowski98041832019-08-01 18:35:59 -0700379void Scheduler::setChangeRefreshRateCallback(ChangeRefreshRateCallback&& callback) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800380 std::lock_guard<std::mutex> lock(mCallbackLock);
Dominik Laskowski98041832019-08-01 18:35:59 -0700381 mChangeRefreshRateCallback = std::move(callback);
Ady Abrahama1a49af2019-02-07 14:36:55 -0800382}
383
Ana Krulecfb772822018-11-30 10:44:07 +0100384void Scheduler::resetIdleTimer() {
385 if (mIdleTimer) {
386 mIdleTimer->reset();
Ady Abrahama1a49af2019-02-07 14:36:55 -0800387 }
388}
389
Ady Abraham8532d012019-05-08 14:50:56 -0700390void Scheduler::notifyTouchEvent() {
391 if (mTouchTimer) {
392 mTouchTimer->reset();
393 }
394
Dominik Laskowski98041832019-08-01 18:35:59 -0700395 if (mSupportKernelTimer && mIdleTimer) {
396 mIdleTimer->reset();
Ady Abraham8532d012019-05-08 14:50:56 -0700397 }
Ady Abrahama9bf4ca2019-06-11 19:08:58 -0700398
399 // Touch event will boost the refresh rate to performance.
400 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800401 if (mLayerHistory) {
402 mLayerHistory->clear();
403 }
Ady Abraham8532d012019-05-08 14:50:56 -0700404}
405
Ady Abraham6fe2c172019-07-12 12:37:57 -0700406void Scheduler::setDisplayPowerState(bool normal) {
407 {
408 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700409 mFeatures.isDisplayPowerStateNormal = normal;
Ady Abraham6fe2c172019-07-12 12:37:57 -0700410 }
411
412 if (mDisplayPowerTimer) {
413 mDisplayPowerTimer->reset();
414 }
415
416 // Display Power event will boost the refresh rate to performance.
417 // Clear Layer History to get fresh FPS detection
Dominik Laskowski49cea512019-11-12 14:13:23 -0800418 if (mLayerHistory) {
419 mLayerHistory->clear();
420 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700421}
422
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700423void Scheduler::kernelIdleTimerCallback(TimerState state) {
424 ATRACE_INT("ExpiredKernelIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100425
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700426 const auto refreshRate = mRefreshRateConfigs.getCurrentRefreshRate();
427 if (state == TimerState::Reset && refreshRate.first == RefreshRateType::PERFORMANCE) {
Alec Mouri7f015182019-07-11 13:56:22 -0700428 // If we're not in performance mode then the kernel timer shouldn't do
429 // anything, as the refresh rate during DPU power collapse will be the
430 // same.
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700431 resyncToHardwareVsync(true /* makeAvailable */, refreshRate.second.vsyncPeriod);
432 } else if (state == TimerState::Expired && refreshRate.first != RefreshRateType::PERFORMANCE) {
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700433 // Disable HW VSYNC if the timer expired, as we don't need it enabled if
434 // we're not pushing frames, and if we're in PERFORMANCE mode then we'll
435 // need to update the DispSync model anyway.
436 disableHardwareVsync(false /* makeUnavailable */);
Alec Mouridc28b372019-04-18 21:17:13 -0700437 }
438}
439
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700440void Scheduler::idleTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700441 handleTimerStateChanged(&mFeatures.idleTimer, state, false /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700442 ATRACE_INT("ExpiredIdleTimer", static_cast<int>(state));
Ana Krulecfb772822018-11-30 10:44:07 +0100443}
444
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700445void Scheduler::touchTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700446 const TouchState touch = state == TimerState::Reset ? TouchState::Active : TouchState::Inactive;
447 handleTimerStateChanged(&mFeatures.touch, touch, true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700448 ATRACE_INT("TouchState", static_cast<int>(touch));
Ady Abraham8532d012019-05-08 14:50:56 -0700449}
450
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700451void Scheduler::displayPowerTimerCallback(TimerState state) {
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700452 handleTimerStateChanged(&mFeatures.displayPowerTimer, state,
453 true /* eventOnContentDetection */);
Dominik Laskowski3a80a382019-07-25 11:16:07 -0700454 ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
Alec Mouridc28b372019-04-18 21:17:13 -0700455}
456
Dominik Laskowski98041832019-08-01 18:35:59 -0700457void Scheduler::dump(std::string& result) const {
Dominik Laskowski49cea512019-11-12 14:13:23 -0800458 using base::StringAppendF;
459 const char* const states[] = {"off", "on"};
Dominik Laskowski98041832019-08-01 18:35:59 -0700460
Dominik Laskowski49cea512019-11-12 14:13:23 -0800461 const bool supported = mRefreshRateConfigs.refreshRateSwitchingSupported();
462 StringAppendF(&result, "+ Refresh rate switching: %s\n", states[supported]);
463 StringAppendF(&result, "+ Content detection: %s\n", states[mLayerHistory.has_value()]);
464
465 StringAppendF(&result, "+ Idle timer: %s\n",
466 mIdleTimer ? mIdleTimer->dump().c_str() : states[0]);
467 StringAppendF(&result, "+ Touch timer: %s\n\n",
468 mTouchTimer ? mTouchTimer->dump().c_str() : states[0]);
Ana Krulecb43429d2019-01-09 14:28:51 -0800469}
470
Ady Abraham6fe2c172019-07-12 12:37:57 -0700471template <class T>
472void Scheduler::handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection) {
Ady Abraham8532d012019-05-08 14:50:56 -0700473 ConfigEvent event = ConfigEvent::None;
474 RefreshRateType newRefreshRateType;
475 {
476 std::lock_guard<std::mutex> lock(mFeatureStateLock);
Ady Abraham6fe2c172019-07-12 12:37:57 -0700477 if (*currentState == newState) {
Ady Abraham8532d012019-05-08 14:50:56 -0700478 return;
479 }
Ady Abraham6fe2c172019-07-12 12:37:57 -0700480 *currentState = newState;
Ady Abraham8532d012019-05-08 14:50:56 -0700481 newRefreshRateType = calculateRefreshRateType();
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700482 if (mFeatures.refreshRateType == newRefreshRateType) {
Ady Abraham8532d012019-05-08 14:50:56 -0700483 return;
484 }
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700485 mFeatures.refreshRateType = newRefreshRateType;
486 if (eventOnContentDetection && mFeatures.contentDetection == ContentDetectionState::On) {
Ady Abraham8532d012019-05-08 14:50:56 -0700487 event = ConfigEvent::Changed;
488 }
489 }
490 changeRefreshRate(newRefreshRateType, event);
491}
492
Ady Abraham09bd3922019-04-08 10:44:56 -0700493Scheduler::RefreshRateType Scheduler::calculateRefreshRateType() {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700494 if (!mRefreshRateConfigs.refreshRateSwitchingSupported()) {
495 return RefreshRateType::DEFAULT;
496 }
497
Ady Abraham8532d012019-05-08 14:50:56 -0700498 // HDR content is not supported on PERFORMANCE mode
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700499 if (mForceHDRContentToDefaultRefreshRate && mFeatures.isHDRContent) {
Ady Abraham09bd3922019-04-08 10:44:56 -0700500 return RefreshRateType::DEFAULT;
501 }
502
Ady Abraham6fe2c172019-07-12 12:37:57 -0700503 // If Display Power is not in normal operation we want to be in performance mode.
504 // When coming back to normal mode, a grace period is given with DisplayPowerTimer
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700505 if (!mFeatures.isDisplayPowerStateNormal || mFeatures.displayPowerTimer == TimerState::Reset) {
Ady Abraham6fe2c172019-07-12 12:37:57 -0700506 return RefreshRateType::PERFORMANCE;
507 }
508
Ady Abraham8532d012019-05-08 14:50:56 -0700509 // As long as touch is active we want to be in performance mode
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700510 if (mFeatures.touch == TouchState::Active) {
Ady Abraham8532d012019-05-08 14:50:56 -0700511 return RefreshRateType::PERFORMANCE;
512 }
513
514 // If timer has expired as it means there is no new content on the screen
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700515 if (mFeatures.idleTimer == TimerState::Expired) {
Ady Abrahama315ce72019-04-24 14:35:20 -0700516 return RefreshRateType::DEFAULT;
517 }
518
Ady Abraham09bd3922019-04-08 10:44:56 -0700519 // If content detection is off we choose performance as we don't know the content fps
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700520 if (mFeatures.contentDetection == ContentDetectionState::Off) {
Ady Abraham09bd3922019-04-08 10:44:56 -0700521 return RefreshRateType::PERFORMANCE;
522 }
523
Wei Wang09be73f2019-07-02 14:29:18 -0700524 // Content detection is on, find the appropriate refresh rate with minimal error
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700525 // TODO(b/139751853): Scan allowed refresh rates only (SurfaceFlinger::mAllowedDisplayConfigs)
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700526 const float rate = static_cast<float>(mFeatures.contentRefreshRate);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700527 auto iter = min_element(mRefreshRateConfigs.getRefreshRateMap().cbegin(),
528 mRefreshRateConfigs.getRefreshRateMap().cend(),
Dominik Laskowskidd252cd2019-07-26 09:10:16 -0700529 [rate](const auto& lhs, const auto& rhs) -> bool {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700530 return std::abs(lhs.second.fps - rate) <
531 std::abs(rhs.second.fps - rate);
Wei Wang09be73f2019-07-02 14:29:18 -0700532 });
533 RefreshRateType currRefreshRateType = iter->first;
Ady Abraham09bd3922019-04-08 10:44:56 -0700534
Ady Abraham85b3f012019-04-08 11:04:14 -0700535 // Some content aligns better on higher refresh rate. For example for 45fps we should choose
536 // 90Hz config. However we should still prefer a lower refresh rate if the content doesn't
537 // align well with both
Wei Wang09be73f2019-07-02 14:29:18 -0700538 constexpr float MARGIN = 0.05f;
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700539 float ratio = mRefreshRateConfigs.getRefreshRateFromType(currRefreshRateType).fps / rate;
Ady Abraham85b3f012019-04-08 11:04:14 -0700540 if (std::abs(std::round(ratio) - ratio) > MARGIN) {
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700541 while (iter != mRefreshRateConfigs.getRefreshRateMap().cend()) {
542 ratio = iter->second.fps / rate;
Ady Abraham09bd3922019-04-08 10:44:56 -0700543
Ady Abraham85b3f012019-04-08 11:04:14 -0700544 if (std::abs(std::round(ratio) - ratio) <= MARGIN) {
545 currRefreshRateType = iter->first;
546 break;
547 }
548 ++iter;
549 }
550 }
Ady Abraham09bd3922019-04-08 10:44:56 -0700551
552 return currRefreshRateType;
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800553}
554
Daniel Solomon0f0ddc12019-08-19 19:31:09 -0700555Scheduler::RefreshRateType Scheduler::getPreferredRefreshRateType() {
556 std::lock_guard<std::mutex> lock(mFeatureStateLock);
557 return mFeatures.refreshRateType;
558}
559
Ana Krulecfefd6ae2019-02-13 17:53:08 -0800560void Scheduler::changeRefreshRate(RefreshRateType refreshRateType, ConfigEvent configEvent) {
561 std::lock_guard<std::mutex> lock(mCallbackLock);
562 if (mChangeRefreshRateCallback) {
563 mChangeRefreshRateCallback(refreshRateType, configEvent);
564 }
565}
566
Ana Krulec98b5b242018-08-10 15:03:23 -0700567} // namespace android