SF: Clean up Scheduler
Remove dynamic allocation for Scheduler::{Connection,ConnectionHandle},
as well as ref-counting for the latter. Also, remove dead code and make
members private.
Bug: 130554049
Test: libsurfaceflinger_unittest
Change-Id: Ibb9dc8d4cb66451a4172c852a36032bbc0a54411
diff --git a/services/surfaceflinger/Scheduler/DispSync.cpp b/services/surfaceflinger/Scheduler/DispSync.cpp
index ad5eb33..ae776a0 100644
--- a/services/surfaceflinger/Scheduler/DispSync.cpp
+++ b/services/surfaceflinger/Scheduler/DispSync.cpp
@@ -462,22 +462,14 @@
TracedOrdinal<bool> mParity;
};
-DispSync::DispSync(const char* name) : mName(name), mRefreshSkipCount(0) {
+DispSync::DispSync(const char* name, bool hasSyncFramework)
+ : mName(name), mIgnorePresentFences(!hasSyncFramework) {
// This flag offers the ability to turn on systrace logging from the shell.
char value[PROPERTY_VALUE_MAX];
property_get("debug.sf.dispsync_trace_detailed_info", value, "0");
mTraceDetailedInfo = atoi(value);
+
mThread = new DispSyncThread(name, mTraceDetailedInfo);
-}
-
-DispSync::~DispSync() {
- mThread->stop();
- mThread->requestExitAndWait();
-}
-
-void DispSync::init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset) {
- mIgnorePresentFences = !hasSyncFramework;
- mPresentTimeOffset = dispSyncPresentTimeOffset;
mThread->run("DispSync", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
// set DispSync to SCHED_FIFO to minimize jitter
@@ -495,6 +487,11 @@
}
}
+DispSync::~DispSync() {
+ mThread->stop();
+ mThread->requestExitAndWait();
+}
+
void DispSync::reset() {
Mutex::Autolock lock(mMutex);
resetLocked();
diff --git a/services/surfaceflinger/Scheduler/DispSync.h b/services/surfaceflinger/Scheduler/DispSync.h
index 3e33c7e..f5175ba 100644
--- a/services/surfaceflinger/Scheduler/DispSync.h
+++ b/services/surfaceflinger/Scheduler/DispSync.h
@@ -88,11 +88,10 @@
// needed.
class DispSync : public android::DispSync {
public:
- explicit DispSync(const char* name);
+ // hasSyncFramework specifies whether the platform supports present fences.
+ DispSync(const char* name, bool hasSyncFramework);
~DispSync() override;
- void init(bool hasSyncFramework, int64_t dispSyncPresentTimeOffset);
-
// reset clears the resync samples and error value.
void reset() override;
@@ -252,7 +251,7 @@
std::shared_ptr<FenceTime> mPresentFences[NUM_PRESENT_SAMPLES]{FenceTime::NO_FENCE};
size_t mPresentSampleOffset;
- int mRefreshSkipCount;
+ int mRefreshSkipCount = 0;
// mThread is the thread from which all the callbacks are called.
sp<DispSyncThread> mThread;
@@ -260,10 +259,6 @@
// mMutex is used to protect access to all member variables.
mutable Mutex mMutex;
- // This is the offset from the present fence timestamps to the corresponding
- // vsync event.
- int64_t mPresentTimeOffset;
-
// Ignore present (retire) fences if the device doesn't have support for the
// sync framework
bool mIgnorePresentFences;
diff --git a/services/surfaceflinger/Scheduler/EventControlThread.cpp b/services/surfaceflinger/Scheduler/EventControlThread.cpp
index fb6cff5..85a7f82 100644
--- a/services/surfaceflinger/Scheduler/EventControlThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventControlThread.cpp
@@ -31,7 +31,7 @@
namespace impl {
EventControlThread::EventControlThread(EventControlThread::SetVSyncEnabledFunction function)
- : mSetVSyncEnabled(function) {
+ : mSetVSyncEnabled(std::move(function)) {
pthread_setname_np(mThread.native_handle(), "EventControlThread");
pid_t tid = pthread_gettid_np(mThread.native_handle());
diff --git a/services/surfaceflinger/Scheduler/OneShotTimer.h b/services/surfaceflinger/Scheduler/OneShotTimer.h
index fd1aa02..921631e 100644
--- a/services/surfaceflinger/Scheduler/OneShotTimer.h
+++ b/services/surfaceflinger/Scheduler/OneShotTimer.h
@@ -39,6 +39,8 @@
const TimeoutCallback& timeoutCallback);
~OneShotTimer();
+ const Interval& interval() const { return mInterval; }
+
// Initializes and turns on the idle timer.
void start();
// Stops the idle timer and any held resources.
diff --git a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
index 9f8567d..bd25a32 100644
--- a/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
+++ b/services/surfaceflinger/Scheduler/PhaseOffsets.cpp
@@ -63,12 +63,13 @@
void PhaseOffsets::dump(std::string& result) const {
const auto [early, earlyGl, late, threshold] = getCurrentOffsets();
- base::StringAppendF(&result,
- " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
- " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
- "GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
- "threshold for next VSYNC: %" PRId64 " ns\n",
- late.app, late.sf, early.app, early.sf, earlyGl.app, earlyGl.sf, threshold);
+ using base::StringAppendF;
+ StringAppendF(&result,
+ " app phase: %9" PRId64 " ns\t SF phase: %9" PRId64 " ns\n"
+ " early app phase: %9" PRId64 " ns\t early SF phase: %9" PRId64 " ns\n"
+ " GL early app phase: %9" PRId64 " ns\tGL early SF phase: %9" PRId64 " ns\n"
+ "next VSYNC threshold: %9" PRId64 " ns\n",
+ late.app, late.sf, early.app, early.sf, earlyGl.app, earlyGl.sf, threshold);
}
PhaseOffsets::Offsets PhaseOffsets::getDefaultOffsets(nsecs_t thresholdForNextVsync) {
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index d730058..9d47749 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -16,16 +16,23 @@
#pragma once
+#include <android-base/stringprintf.h>
+
#include <algorithm>
#include <numeric>
-
-#include "android-base/stringprintf.h"
+#include <type_traits>
#include "DisplayHardware/HWComposer.h"
#include "Scheduler/SchedulerUtils.h"
-namespace android {
-namespace scheduler {
+namespace android::scheduler {
+
+enum class RefreshRateConfigEvent : unsigned { None = 0b0, Changed = 0b1 };
+
+inline RefreshRateConfigEvent operator|(RefreshRateConfigEvent lhs, RefreshRateConfigEvent rhs) {
+ using T = std::underlying_type_t<RefreshRateConfigEvent>;
+ return static_cast<RefreshRateConfigEvent>(static_cast<T>(lhs) | static_cast<T>(rhs));
+}
/**
* This class is used to encapsulate configuration for refresh rates. It holds information
@@ -134,5 +141,4 @@
std::map<RefreshRateType, std::shared_ptr<RefreshRate>> mRefreshRates;
};
-} // namespace scheduler
-} // namespace android
+} // namespace android::scheduler
diff --git a/services/surfaceflinger/Scheduler/RefreshRateStats.h b/services/surfaceflinger/Scheduler/RefreshRateStats.h
index 7e7c630..1f097db 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateStats.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateStats.h
@@ -94,13 +94,13 @@
// Traverses through the map of config modes and returns how long they've been running in easy
// to read format.
- std::string doDump() const {
- std::ostringstream stream;
- stream << "+ Refresh rate: running time in seconds\n";
+ void dump(std::string& result) const {
+ std::ostringstream stream("+ Refresh rate: running time in seconds\n");
+
for (const auto& [name, time] : const_cast<RefreshRateStats*>(this)->getTotalTimes()) {
stream << name << ": " << getDateFormatFromMs(time) << '\n';
}
- return stream.str();
+ result.append(stream.str());
}
private:
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 3883427..7f1fb3b 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -14,6 +14,8 @@
* limitations under the License.
*/
+#undef LOG_TAG
+#define LOG_TAG "Scheduler"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
#include "Scheduler.h"
@@ -21,6 +23,7 @@
#include <algorithm>
#include <cinttypes>
#include <cstdint>
+#include <functional>
#include <memory>
#include <numeric>
@@ -38,80 +41,56 @@
#include "DispSyncSource.h"
#include "EventControlThread.h"
#include "EventThread.h"
-#include "InjectVSyncSource.h"
-#include "LayerInfo.h"
#include "OneShotTimer.h"
#include "SchedulerUtils.h"
#include "SurfaceFlingerProperties.h"
+#define RETURN_IF_INVALID_HANDLE(handle, ...) \
+ do { \
+ if (mConnections.count(handle) == 0) { \
+ ALOGE("Invalid connection handle %" PRIuPTR, handle.id); \
+ return __VA_ARGS__; \
+ } \
+ } while (false)
+
namespace android {
-using namespace android::hardware::configstore;
-using namespace android::hardware::configstore::V1_0;
-using namespace android::sysprop;
-
-#define RETURN_VALUE_IF_INVALID(value) \
- if (handle == nullptr || mConnections.count(handle->id) == 0) return value
-#define RETURN_IF_INVALID() \
- if (handle == nullptr || mConnections.count(handle->id) == 0) return
-
-std::atomic<int64_t> Scheduler::sNextId = 0;
-
Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
const scheduler::RefreshRateConfigs& refreshRateConfig)
- : mHasSyncFramework(running_without_sync_framework(true)),
- mDispSyncPresentTimeOffset(present_time_offset_from_vsync_ns(0)),
- mPrimaryHWVsyncEnabled(false),
- mHWVsyncAvailable(false),
+ : mPrimaryDispSync(new impl::DispSync("SchedulerDispSync",
+ sysprop::running_without_sync_framework(true))),
+ mEventControlThread(new impl::EventControlThread(std::move(function))),
+ mSupportKernelTimer(sysprop::support_kernel_idle_timer(false)),
mRefreshRateConfigs(refreshRateConfig) {
- // Note: We create a local temporary with the real DispSync implementation
- // type temporarily so we can initialize it with the configured values,
- // before storing it for more generic use using the interface type.
- auto primaryDispSync = std::make_unique<impl::DispSync>("SchedulerDispSync");
- primaryDispSync->init(mHasSyncFramework, mDispSyncPresentTimeOffset);
- mPrimaryDispSync = std::move(primaryDispSync);
- mEventControlThread = std::make_unique<impl::EventControlThread>(function);
-
- mSetIdleTimerMs = set_idle_timer_ms(0);
- mSupportKernelTimer = support_kernel_idle_timer(false);
-
- mSetTouchTimerMs = set_touch_timer_ms(0);
- mSetDisplayPowerTimerMs = set_display_power_timer_ms(0);
+ using namespace sysprop;
char value[PROPERTY_VALUE_MAX];
property_get("debug.sf.set_idle_timer_ms", value, "0");
- int int_value = atoi(value);
- if (int_value) {
- mSetIdleTimerMs = atoi(value);
- }
+ const int setIdleTimerMs = atoi(value);
- if (mSetIdleTimerMs > 0) {
- if (mSupportKernelTimer) {
- mIdleTimer = std::make_unique<scheduler::OneShotTimer>(
- std::chrono::milliseconds(mSetIdleTimerMs),
- [this] { kernelIdleTimerCallback(TimerState::Reset); },
- [this] { kernelIdleTimerCallback(TimerState::Expired); });
- } else {
- mIdleTimer = std::make_unique<scheduler::OneShotTimer>(
- std::chrono::milliseconds(mSetIdleTimerMs),
- [this] { idleTimerCallback(TimerState::Reset); },
- [this] { idleTimerCallback(TimerState::Expired); });
- }
+ if (const auto millis = setIdleTimerMs ? setIdleTimerMs : set_idle_timer_ms(0); millis > 0) {
+ const auto callback = mSupportKernelTimer ? &Scheduler::kernelIdleTimerCallback
+ : &Scheduler::idleTimerCallback;
+
+ mIdleTimer.emplace(
+ std::chrono::milliseconds(millis),
+ [this, callback] { std::invoke(callback, this, TimerState::Reset); },
+ [this, callback] { std::invoke(callback, this, TimerState::Expired); });
mIdleTimer->start();
}
- if (mSetTouchTimerMs > 0) {
+ if (const int64_t millis = set_touch_timer_ms(0); millis > 0) {
// Touch events are coming to SF every 100ms, so the timer needs to be higher than that
- mTouchTimer = std::make_unique<scheduler::OneShotTimer>(
- std::chrono::milliseconds(mSetTouchTimerMs),
+ mTouchTimer.emplace(
+ std::chrono::milliseconds(millis),
[this] { touchTimerCallback(TimerState::Reset); },
[this] { touchTimerCallback(TimerState::Expired); });
mTouchTimer->start();
}
- if (mSetDisplayPowerTimerMs > 0) {
- mDisplayPowerTimer = std::make_unique<scheduler::OneShotTimer>(
- std::chrono::milliseconds(mSetDisplayPowerTimerMs),
+ if (const int64_t millis = set_display_power_timer_ms(0); millis > 0) {
+ mDisplayPowerTimer.emplace(
+ std::chrono::milliseconds(millis),
[this] { displayPowerTimerCallback(TimerState::Reset); },
[this] { displayPowerTimerCallback(TimerState::Expired); });
mDisplayPowerTimer->start();
@@ -121,9 +100,9 @@
Scheduler::Scheduler(std::unique_ptr<DispSync> primaryDispSync,
std::unique_ptr<EventControlThread> eventControlThread,
const scheduler::RefreshRateConfigs& configs)
- : mHasSyncFramework(false),
- mPrimaryDispSync(std::move(primaryDispSync)),
+ : mPrimaryDispSync(std::move(primaryDispSync)),
mEventControlThread(std::move(eventControlThread)),
+ mSupportKernelTimer(false),
mRefreshRateConfigs(configs) {}
Scheduler::~Scheduler() {
@@ -133,36 +112,39 @@
mIdleTimer.reset();
}
-sp<Scheduler::ConnectionHandle> Scheduler::createConnection(
+DispSync& Scheduler::getPrimaryDispSync() {
+ return *mPrimaryDispSync;
+}
+
+Scheduler::ConnectionHandle Scheduler::createConnection(
const char* connectionName, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync,
ResyncCallback resyncCallback,
impl::EventThread::InterceptVSyncsCallback interceptCallback) {
- const int64_t id = sNextId++;
- ALOGV("Creating a connection handle with ID: %" PRId64 "\n", id);
+ auto eventThread = makeEventThread(connectionName, phaseOffsetNs, offsetThresholdForNextVsync,
+ std::move(interceptCallback));
+ return createConnection(std::move(eventThread), std::move(resyncCallback));
+}
- std::unique_ptr<EventThread> eventThread =
- makeEventThread(connectionName, mPrimaryDispSync.get(), phaseOffsetNs,
- offsetThresholdForNextVsync, std::move(interceptCallback));
+Scheduler::ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread,
+ ResyncCallback&& resyncCallback) {
+ const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
+ ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
- auto eventThreadConnection =
- createConnectionInternal(eventThread.get(), std::move(resyncCallback),
- ISurfaceComposer::eConfigChangedSuppress);
- mConnections.emplace(id,
- std::make_unique<Connection>(new ConnectionHandle(id),
- eventThreadConnection,
- std::move(eventThread)));
- return mConnections[id]->handle;
+ auto connection = createConnectionInternal(eventThread.get(), std::move(resyncCallback),
+ ISurfaceComposer::eConfigChangedSuppress);
+
+ mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
+ return handle;
}
std::unique_ptr<EventThread> Scheduler::makeEventThread(
- const char* connectionName, DispSync* dispSync, nsecs_t phaseOffsetNs,
- nsecs_t offsetThresholdForNextVsync,
- impl::EventThread::InterceptVSyncsCallback interceptCallback) {
- std::unique_ptr<VSyncSource> eventThreadSource =
- std::make_unique<DispSyncSource>(dispSync, phaseOffsetNs, offsetThresholdForNextVsync,
- true, connectionName);
- return std::make_unique<impl::EventThread>(std::move(eventThreadSource),
- std::move(interceptCallback), connectionName);
+ const char* connectionName, nsecs_t phaseOffsetNs, nsecs_t offsetThresholdForNextVsync,
+ impl::EventThread::InterceptVSyncsCallback&& interceptCallback) {
+ auto source = std::make_unique<DispSyncSource>(mPrimaryDispSync.get(), phaseOffsetNs,
+ offsetThresholdForNextVsync,
+ true /* traceVsync */, connectionName);
+ return std::make_unique<impl::EventThread>(std::move(source), std::move(interceptCallback),
+ connectionName);
}
sp<EventThreadConnection> Scheduler::createConnectionInternal(
@@ -172,53 +154,53 @@
}
sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
- const sp<Scheduler::ConnectionHandle>& handle, ResyncCallback resyncCallback,
+ ConnectionHandle handle, ResyncCallback resyncCallback,
ISurfaceComposer::ConfigChanged configChanged) {
- RETURN_VALUE_IF_INVALID(nullptr);
- return createConnectionInternal(mConnections[handle->id]->thread.get(),
- std::move(resyncCallback), configChanged);
+ RETURN_IF_INVALID_HANDLE(handle, nullptr);
+ return createConnectionInternal(mConnections[handle].thread.get(), std::move(resyncCallback),
+ configChanged);
}
-EventThread* Scheduler::getEventThread(const sp<Scheduler::ConnectionHandle>& handle) {
- RETURN_VALUE_IF_INVALID(nullptr);
- return mConnections[handle->id]->thread.get();
+EventThread* Scheduler::getEventThread(ConnectionHandle handle) {
+ RETURN_IF_INVALID_HANDLE(handle, nullptr);
+ return mConnections[handle].thread.get();
}
-sp<EventThreadConnection> Scheduler::getEventConnection(const sp<ConnectionHandle>& handle) {
- RETURN_VALUE_IF_INVALID(nullptr);
- return mConnections[handle->id]->eventConnection;
+sp<EventThreadConnection> Scheduler::getEventConnection(ConnectionHandle handle) {
+ RETURN_IF_INVALID_HANDLE(handle, nullptr);
+ return mConnections[handle].connection;
}
-void Scheduler::hotplugReceived(const sp<Scheduler::ConnectionHandle>& handle,
- PhysicalDisplayId displayId, bool connected) {
- RETURN_IF_INVALID();
- mConnections[handle->id]->thread->onHotplugReceived(displayId, connected);
+void Scheduler::onHotplugReceived(ConnectionHandle handle, PhysicalDisplayId displayId,
+ bool connected) {
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections[handle].thread->onHotplugReceived(displayId, connected);
}
-void Scheduler::onScreenAcquired(const sp<Scheduler::ConnectionHandle>& handle) {
- RETURN_IF_INVALID();
- mConnections[handle->id]->thread->onScreenAcquired();
+void Scheduler::onScreenAcquired(ConnectionHandle handle) {
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections[handle].thread->onScreenAcquired();
}
-void Scheduler::onScreenReleased(const sp<Scheduler::ConnectionHandle>& handle) {
- RETURN_IF_INVALID();
- mConnections[handle->id]->thread->onScreenReleased();
+void Scheduler::onScreenReleased(ConnectionHandle handle) {
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections[handle].thread->onScreenReleased();
}
-void Scheduler::onConfigChanged(const sp<ConnectionHandle>& handle, PhysicalDisplayId displayId,
+void Scheduler::onConfigChanged(ConnectionHandle handle, PhysicalDisplayId displayId,
int32_t configId) {
- RETURN_IF_INVALID();
- mConnections[handle->id]->thread->onConfigChanged(displayId, configId);
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections[handle].thread->onConfigChanged(displayId, configId);
}
-void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, std::string& result) const {
- RETURN_IF_INVALID();
- mConnections.at(handle->id)->thread->dump(result);
+void Scheduler::dump(ConnectionHandle handle, std::string& result) const {
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections.at(handle).thread->dump(result);
}
-void Scheduler::setPhaseOffset(const sp<Scheduler::ConnectionHandle>& handle, nsecs_t phaseOffset) {
- RETURN_IF_INVALID();
- mConnections[handle->id]->thread->setPhaseOffset(phaseOffset);
+void Scheduler::setPhaseOffset(ConnectionHandle handle, nsecs_t phaseOffset) {
+ RETURN_IF_INVALID_HANDLE(handle);
+ mConnections[handle].thread->setPhaseOffset(phaseOffset);
}
void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
@@ -290,7 +272,7 @@
mPrimaryDispSync->setRefreshSkipCount(count);
}
-void Scheduler::setVsyncPeriod(const nsecs_t period) {
+void Scheduler::setVsyncPeriod(nsecs_t period) {
std::lock_guard<std::mutex> lock(mHWVsyncLock);
mPrimaryDispSync->setPeriod(period);
@@ -301,7 +283,7 @@
}
}
-void Scheduler::addResyncSample(const nsecs_t timestamp, bool* periodFlushed) {
+void Scheduler::addResyncSample(nsecs_t timestamp, bool* periodFlushed) {
bool needsHwVsync = false;
*periodFlushed = false;
{ // Scope for the lock
@@ -334,10 +316,6 @@
return mPrimaryDispSync->expectedPresentTime();
}
-void Scheduler::dumpPrimaryDispSync(std::string& result) const {
- mPrimaryDispSync->dump(result);
-}
-
std::unique_ptr<scheduler::LayerHistory::LayerHandle> Scheduler::registerLayer(
std::string const& name, int windowType) {
RefreshRateType refreshRateType = (windowType == InputWindowInfo::TYPE_WALLPAPER)
@@ -363,10 +341,6 @@
mLayerHistory.setVisibility(layerHandle, visible);
}
-void Scheduler::withPrimaryDispSync(std::function<void(DispSync&)> const& fn) {
- fn(*mPrimaryDispSync);
-}
-
void Scheduler::updateFpsBasedOnContent() {
auto [refreshRate, isHDR] = mLayerHistory.getDesiredRefreshRateAndHDR();
const uint32_t refreshRateRound = std::round(refreshRate);
@@ -393,30 +367,19 @@
changeRefreshRate(newRefreshRateType, ConfigEvent::Changed);
}
-void Scheduler::setChangeRefreshRateCallback(
- const ChangeRefreshRateCallback&& changeRefreshRateCallback) {
+void Scheduler::setChangeRefreshRateCallback(ChangeRefreshRateCallback&& callback) {
std::lock_guard<std::mutex> lock(mCallbackLock);
- mChangeRefreshRateCallback = changeRefreshRateCallback;
+ mChangeRefreshRateCallback = std::move(callback);
}
-void Scheduler::setGetCurrentRefreshRateTypeCallback(
- const GetCurrentRefreshRateTypeCallback&& getCurrentRefreshRateTypeCallback) {
+void Scheduler::setGetCurrentRefreshRateTypeCallback(GetCurrentRefreshRateTypeCallback&& callback) {
std::lock_guard<std::mutex> lock(mCallbackLock);
- mGetCurrentRefreshRateTypeCallback = getCurrentRefreshRateTypeCallback;
+ mGetCurrentRefreshRateTypeCallback = std::move(callback);
}
-void Scheduler::setGetVsyncPeriodCallback(const GetVsyncPeriod&& getVsyncPeriod) {
+void Scheduler::setGetVsyncPeriodCallback(GetVsyncPeriod&& callback) {
std::lock_guard<std::mutex> lock(mCallbackLock);
- mGetVsyncPeriod = getVsyncPeriod;
-}
-
-void Scheduler::updateFrameSkipping(const int64_t skipCount) {
- ATRACE_INT("FrameSkipCount", skipCount);
- if (mSkipCount != skipCount) {
- // Only update DispSync if it hasn't been updated yet.
- mPrimaryDispSync->setRefreshSkipCount(skipCount);
- mSkipCount = skipCount;
- }
+ mGetVsyncPeriod = std::move(callback);
}
void Scheduler::resetIdleTimer() {
@@ -430,8 +393,8 @@
mTouchTimer->reset();
}
- if (mSupportKernelTimer) {
- resetIdleTimer();
+ if (mSupportKernelTimer && mIdleTimer) {
+ mIdleTimer->reset();
}
// Touch event will boost the refresh rate to performance.
@@ -491,11 +454,16 @@
ATRACE_INT("ExpiredDisplayPowerTimer", static_cast<int>(state));
}
-std::string Scheduler::doDump() {
+void Scheduler::dump(std::string& result) const {
std::ostringstream stream;
- stream << "+ Idle timer interval: " << mSetIdleTimerMs << " ms" << std::endl;
- stream << "+ Touch timer interval: " << mSetTouchTimerMs << " ms" << std::endl;
- return stream.str();
+ if (mIdleTimer) {
+ stream << "+ Idle timer interval: " << mIdleTimer->interval().count() << " ms\n";
+ }
+ if (mTouchTimer) {
+ stream << "+ Touch timer interval: " << mTouchTimer->interval().count() << " ms\n";
+ }
+
+ result.append(stream.str());
}
template <class T>
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 5905ff6..f733317 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -16,17 +16,17 @@
#pragma once
-#include <cstdint>
+#include <atomic>
#include <functional>
#include <memory>
+#include <mutex>
+#include <optional>
+#include <unordered_map>
-#include <ui/DisplayStatInfo.h>
#include <ui/GraphicTypes.h>
-#include "DispSync.h"
#include "EventControlThread.h"
#include "EventThread.h"
-#include "InjectVSyncSource.h"
#include "LayerHistory.h"
#include "OneShotTimer.h"
#include "RefreshRateConfigs.h"
@@ -34,122 +34,67 @@
namespace android {
-class EventControlThread;
+class DispSync;
+class FenceTime;
+struct DisplayStateInfo;
class Scheduler {
public:
- // Enum to keep track of whether we trigger event to notify choreographer of config changes.
- enum class ConfigEvent { None, Changed };
-
- // logical or operator with the semantics of at least one of the events is Changed
- friend ConfigEvent operator|(const ConfigEvent& first, const ConfigEvent& second) {
- if (first == ConfigEvent::Changed) return ConfigEvent::Changed;
- if (second == ConfigEvent::Changed) return ConfigEvent::Changed;
- return ConfigEvent::None;
- }
-
using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
+ using ConfigEvent = scheduler::RefreshRateConfigEvent;
+
using GetCurrentRefreshRateTypeCallback = std::function<RefreshRateType()>;
using ChangeRefreshRateCallback = std::function<void(RefreshRateType, ConfigEvent)>;
using GetVsyncPeriod = std::function<nsecs_t()>;
- // Enum to indicate whether to start the transaction early, or at vsync time.
+ // Indicates whether to start the transaction early, or at vsync time.
enum class TransactionStart { EARLY, NORMAL };
- /* The scheduler handle is a BBinder object passed to the client from which we can extract
- * an ID for subsequent operations.
- */
- class ConnectionHandle : public BBinder {
- public:
- ConnectionHandle(int64_t id) : id(id) {}
-
- ~ConnectionHandle() = default;
-
- const int64_t id;
- };
-
- class Connection {
- public:
- Connection(sp<ConnectionHandle> handle, sp<EventThreadConnection> eventConnection,
- std::unique_ptr<EventThread> eventThread)
- : handle(handle), eventConnection(eventConnection), thread(std::move(eventThread)) {}
-
- ~Connection() = default;
-
- sp<ConnectionHandle> handle;
- sp<EventThreadConnection> eventConnection;
- const std::unique_ptr<EventThread> thread;
- };
-
- // Stores per-display state about VSYNC.
- struct VsyncState {
- explicit VsyncState(Scheduler& scheduler) : scheduler(scheduler) {}
-
- void resync(const GetVsyncPeriod&);
-
- Scheduler& scheduler;
- std::atomic<nsecs_t> lastResyncTime = 0;
- };
-
- explicit Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function,
- const scheduler::RefreshRateConfigs& refreshRateConfig);
+ Scheduler(impl::EventControlThread::SetVSyncEnabledFunction,
+ const scheduler::RefreshRateConfigs&);
virtual ~Scheduler();
- /** Creates an EventThread connection. */
- sp<ConnectionHandle> createConnection(const char* connectionName, nsecs_t phaseOffsetNs,
- nsecs_t offsetThresholdForNextVsync, ResyncCallback,
- impl::EventThread::InterceptVSyncsCallback);
+ DispSync& getPrimaryDispSync();
- sp<IDisplayEventConnection> createDisplayEventConnection(
- const sp<ConnectionHandle>& handle, ResyncCallback,
- ISurfaceComposer::ConfigChanged configChanged);
+ using ConnectionHandle = scheduler::ConnectionHandle;
+ ConnectionHandle createConnection(const char* connectionName, nsecs_t phaseOffsetNs,
+ nsecs_t offsetThresholdForNextVsync, ResyncCallback,
+ impl::EventThread::InterceptVSyncsCallback);
- // Getter methods.
- EventThread* getEventThread(const sp<ConnectionHandle>& handle);
+ sp<IDisplayEventConnection> createDisplayEventConnection(ConnectionHandle, ResyncCallback,
+ ISurfaceComposer::ConfigChanged);
- // Provides access to the DispSync object for the primary display.
- void withPrimaryDispSync(std::function<void(DispSync&)> const& fn);
+ EventThread* getEventThread(ConnectionHandle);
+ sp<EventThreadConnection> getEventConnection(ConnectionHandle);
- sp<EventThreadConnection> getEventConnection(const sp<ConnectionHandle>& handle);
+ void onHotplugReceived(ConnectionHandle, PhysicalDisplayId, bool connected);
+ void onConfigChanged(ConnectionHandle, PhysicalDisplayId, int32_t configId);
- // Should be called when receiving a hotplug event.
- void hotplugReceived(const sp<ConnectionHandle>& handle, PhysicalDisplayId displayId,
- bool connected);
+ void onScreenAcquired(ConnectionHandle);
+ void onScreenReleased(ConnectionHandle);
- // Should be called after the screen is turned on.
- void onScreenAcquired(const sp<ConnectionHandle>& handle);
-
- // Should be called before the screen is turned off.
- void onScreenReleased(const sp<ConnectionHandle>& handle);
-
- // Should be called when display config changed
- void onConfigChanged(const sp<ConnectionHandle>& handle, PhysicalDisplayId displayId,
- int32_t configId);
-
- // Should be called when dumpsys command is received.
- void dump(const sp<ConnectionHandle>& handle, std::string& result) const;
-
- // Offers ability to modify phase offset in the event thread.
- void setPhaseOffset(const sp<ConnectionHandle>& handle, nsecs_t phaseOffset);
+ // Modifies phase offset in the event thread.
+ void setPhaseOffset(ConnectionHandle, nsecs_t phaseOffset);
void getDisplayStatInfo(DisplayStatInfo* stats);
void enableHardwareVsync();
void disableHardwareVsync(bool makeUnavailable);
+
// Resyncs the scheduler to hardware vsync.
// If makeAvailable is true, then hardware vsync will be turned on.
// Otherwise, if hardware vsync is not already enabled then this method will
// no-op.
// The period is the vsync period from the current display configuration.
void resyncToHardwareVsync(bool makeAvailable, nsecs_t period);
- // Creates a callback for resyncing.
- ResyncCallback makeResyncCallback(GetVsyncPeriod&& getVsyncPeriod);
- void setRefreshSkipCount(int count);
+ ResyncCallback makeResyncCallback(GetVsyncPeriod&&);
+
// Passes a vsync sample to DispSync. periodFlushed will be true if
// DispSync detected that the vsync period changed, and false otherwise.
- void addResyncSample(const nsecs_t timestamp, bool* periodFlushed);
- void addPresentFence(const std::shared_ptr<FenceTime>& fenceTime);
+ void addResyncSample(nsecs_t timestamp, bool* periodFlushed);
+ void addPresentFence(const std::shared_ptr<FenceTime>&);
+ void setRefreshSkipCount(int count);
void setIgnorePresentFences(bool ignore);
nsecs_t getDispSyncExpectedPresentTime();
// Registers the layer in the scheduler, and returns the handle for future references.
@@ -165,35 +110,23 @@
const std::unique_ptr<scheduler::LayerHistory::LayerHandle>& layerHandle, bool visible);
// Updates FPS based on the most content presented.
void updateFpsBasedOnContent();
- // Callback that gets invoked when Scheduler wants to change the refresh rate.
- void setChangeRefreshRateCallback(const ChangeRefreshRateCallback&& changeRefreshRateCallback);
- void setGetCurrentRefreshRateTypeCallback(
- const GetCurrentRefreshRateTypeCallback&& getCurrentRefreshRateType);
- void setGetVsyncPeriodCallback(const GetVsyncPeriod&& getVsyncPeriod);
- // Returns whether idle timer is enabled or not
- bool isIdleTimerEnabled() { return mSetIdleTimerMs > 0; }
+ // Called by Scheduler to change refresh rate.
+ void setChangeRefreshRateCallback(ChangeRefreshRateCallback&&);
- // Function that resets the idle timer.
+ void setGetCurrentRefreshRateTypeCallback(GetCurrentRefreshRateTypeCallback&&);
+ void setGetVsyncPeriodCallback(GetVsyncPeriod&&);
+
+ bool isIdleTimerEnabled() const { return mIdleTimer.has_value(); }
void resetIdleTimer();
// Function that resets the touch timer.
void notifyTouchEvent();
- // Function that sets whether display power mode is normal or not.
void setDisplayPowerState(bool normal);
- // Returns relevant information about Scheduler for dumpsys purposes.
- std::string doDump();
-
- // calls DispSync::dump() on primary disp sync
- void dumpPrimaryDispSync(std::string& result) const;
-
-protected:
- virtual std::unique_ptr<EventThread> makeEventThread(
- const char* connectionName, DispSync* dispSync, nsecs_t phaseOffsetNs,
- nsecs_t offsetThresholdForNextVsync,
- impl::EventThread::InterceptVSyncsCallback interceptCallback);
+ void dump(std::string&) const;
+ void dump(ConnectionHandle, std::string&) const;
private:
friend class TestableScheduler;
@@ -209,81 +142,71 @@
const scheduler::RefreshRateConfigs&);
// Creates a connection on the given EventThread and forwards the given callbacks.
+ std::unique_ptr<EventThread> makeEventThread(const char* connectionName, nsecs_t phaseOffsetNs,
+ nsecs_t offsetThresholdForNextVsync,
+ impl::EventThread::InterceptVSyncsCallback&&);
+
+ // Create a connection on the given EventThread and forward the resync callback.
+ ConnectionHandle createConnection(std::unique_ptr<EventThread>, ResyncCallback&&);
sp<EventThreadConnection> createConnectionInternal(EventThread*, ResyncCallback&&,
ISurfaceComposer::ConfigChanged);
- nsecs_t calculateAverage() const;
- void updateFrameSkipping(const int64_t skipCount);
-
// Update feature state machine to given state when corresponding timer resets or expires.
void kernelIdleTimerCallback(TimerState);
void idleTimerCallback(TimerState);
void touchTimerCallback(TimerState);
void displayPowerTimerCallback(TimerState);
- // Sets vsync period.
- void setVsyncPeriod(const nsecs_t period);
// handles various timer features to change the refresh rate.
template <class T>
void handleTimerStateChanged(T* currentState, T newState, bool eventOnContentDetection);
- // Calculate the new refresh rate type
+
+ void setVsyncPeriod(nsecs_t period);
+
RefreshRateType calculateRefreshRateType() REQUIRES(mFeatureStateLock);
- // Acquires a lock and calls the ChangeRefreshRateCallback() with given parameters.
- void changeRefreshRate(RefreshRateType refreshRateType, ConfigEvent configEvent);
+ // Acquires a lock and calls the ChangeRefreshRateCallback with given parameters.
+ void changeRefreshRate(RefreshRateType, ConfigEvent);
- // Helper function to calculate error frames
- float getErrorFrames(float contentFps, float configFps);
+ // Stores EventThread associated with a given VSyncSource, and an initial EventThreadConnection.
+ struct Connection {
+ sp<EventThreadConnection> connection;
+ std::unique_ptr<EventThread> thread;
+ };
- // If fences from sync Framework are supported.
- const bool mHasSyncFramework;
-
- // The offset in nanoseconds to use, when DispSync timestamps present fence
- // signaling time.
- nsecs_t mDispSyncPresentTimeOffset;
-
- // Each connection has it's own ID. This variable keeps track of the count.
- static std::atomic<int64_t> sNextId;
-
- // Connections are stored in a map <connection ID, connection> for easy retrieval.
- std::unordered_map<int64_t, std::unique_ptr<Connection>> mConnections;
+ ConnectionHandle::Id mNextConnectionHandleId = 0;
+ std::unordered_map<ConnectionHandle, Connection> mConnections;
std::mutex mHWVsyncLock;
- bool mPrimaryHWVsyncEnabled GUARDED_BY(mHWVsyncLock);
- bool mHWVsyncAvailable GUARDED_BY(mHWVsyncLock);
+ bool mPrimaryHWVsyncEnabled GUARDED_BY(mHWVsyncLock) = false;
+ bool mHWVsyncAvailable GUARDED_BY(mHWVsyncLock) = false;
+
+ // Stores per-display state about VSYNC.
+ struct VsyncState {
+ explicit VsyncState(Scheduler& scheduler) : scheduler(scheduler) {}
+
+ void resync(const GetVsyncPeriod&);
+
+ Scheduler& scheduler;
+ std::atomic<nsecs_t> lastResyncTime = 0;
+ };
+
const std::shared_ptr<VsyncState> mPrimaryVsyncState{std::make_shared<VsyncState>(*this)};
std::unique_ptr<DispSync> mPrimaryDispSync;
std::unique_ptr<EventControlThread> mEventControlThread;
- // TODO(b/113612090): The following set of variables needs to be revised. For now, this is
- // a proof of concept. We turn on frame skipping if the difference between the timestamps
- // is between 32 and 34ms. We expect this currently for 30fps videos, so we render them at 30Hz.
- nsecs_t mPreviousFrameTimestamp = 0;
- // Keeping track of whether we are skipping the refresh count. If we want to
- // simulate 30Hz rendering, we skip every other frame, and this variable is set
- // to 1.
- int64_t mSkipCount = 0;
- std::array<int64_t, scheduler::ARRAY_SIZE> mTimeDifferences{};
- size_t mCounter = 0;
-
// Historical information about individual layers. Used for predicting the refresh rate.
scheduler::LayerHistory mLayerHistory;
- // Timer that records time between requests for next vsync. If the time is higher than a given
- // interval, a callback is fired. Set this variable to >0 to use this feature.
- int64_t mSetIdleTimerMs = 0;
- std::unique_ptr<scheduler::OneShotTimer> mIdleTimer;
- // Enables whether to use idle timer callbacks that support the kernel
- // timer.
- bool mSupportKernelTimer;
+ // Whether to use idle timer callbacks that support the kernel timer.
+ const bool mSupportKernelTimer;
+ // Timer that records time between requests for next vsync.
+ std::optional<scheduler::OneShotTimer> mIdleTimer;
// Timer used to monitor touch events.
- int64_t mSetTouchTimerMs = 0;
- std::unique_ptr<scheduler::OneShotTimer> mTouchTimer;
-
+ std::optional<scheduler::OneShotTimer> mTouchTimer;
// Timer used to monitor display power mode.
- int64_t mSetDisplayPowerTimerMs = 0;
- std::unique_ptr<scheduler::OneShotTimer> mDisplayPowerTimer;
+ std::optional<scheduler::OneShotTimer> mDisplayPowerTimer;
std::mutex mCallbackLock;
GetCurrentRefreshRateTypeCallback mGetCurrentRefreshRateTypeCallback GUARDED_BY(mCallbackLock);
diff --git a/services/surfaceflinger/Scheduler/SchedulerUtils.h b/services/surfaceflinger/Scheduler/SchedulerUtils.h
index ced1899..ab0c0ff 100644
--- a/services/surfaceflinger/Scheduler/SchedulerUtils.h
+++ b/services/surfaceflinger/Scheduler/SchedulerUtils.h
@@ -22,13 +22,23 @@
#include <unordered_map>
#include <vector>
-namespace android {
-namespace scheduler {
-using namespace std::chrono_literals;
+namespace android::scheduler {
-// This number is used to set the size of the arrays in scheduler that hold information
-// about layers.
-static constexpr size_t ARRAY_SIZE = 30;
+// Opaque handle to scheduler connection.
+struct ConnectionHandle {
+ using Id = std::uintptr_t;
+ static constexpr Id INVALID_ID = static_cast<Id>(-1);
+
+ Id id = INVALID_ID;
+
+ explicit operator bool() const { return id != INVALID_ID; }
+};
+
+inline bool operator==(ConnectionHandle lhs, ConnectionHandle rhs) {
+ return lhs.id == rhs.id;
+}
+
+using namespace std::chrono_literals;
// This number is used to have a place holder for when the screen is not NORMAL/ON. Currently
// the config is not visible to SF, and is completely maintained by HWC. However, we would
@@ -80,5 +90,15 @@
return static_cast<int>(std::max_element(counts.begin(), counts.end(), compareCounts)->first);
}
-} // namespace scheduler
-} // namespace android
\ No newline at end of file
+} // namespace android::scheduler
+
+namespace std {
+
+template <>
+struct hash<android::scheduler::ConnectionHandle> {
+ size_t operator()(android::scheduler::ConnectionHandle handle) const {
+ return hash<android::scheduler::ConnectionHandle::Id>()(handle.id);
+ }
+};
+
+} // namespace std
diff --git a/services/surfaceflinger/Scheduler/VSyncModulator.cpp b/services/surfaceflinger/Scheduler/VSyncModulator.cpp
index f267c99..27fd76c 100644
--- a/services/surfaceflinger/Scheduler/VSyncModulator.cpp
+++ b/services/surfaceflinger/Scheduler/VSyncModulator.cpp
@@ -27,8 +27,8 @@
namespace android::scheduler {
VSyncModulator::VSyncModulator(Scheduler& scheduler,
- const sp<Scheduler::ConnectionHandle>& appConnectionHandle,
- const sp<Scheduler::ConnectionHandle>& sfConnectionHandle,
+ Scheduler::ConnectionHandle appConnectionHandle,
+ Scheduler::ConnectionHandle sfConnectionHandle,
const OffsetsConfig& config)
: mScheduler(scheduler),
mAppConnectionHandle(appConnectionHandle),
diff --git a/services/surfaceflinger/Scheduler/VSyncModulator.h b/services/surfaceflinger/Scheduler/VSyncModulator.h
index 636c8c8..727cef2 100644
--- a/services/surfaceflinger/Scheduler/VSyncModulator.h
+++ b/services/surfaceflinger/Scheduler/VSyncModulator.h
@@ -56,8 +56,8 @@
nsecs_t thresholdForNextVsync;
};
- VSyncModulator(Scheduler&, const sp<Scheduler::ConnectionHandle>& appConnectionHandle,
- const sp<Scheduler::ConnectionHandle>& sfConnectionHandle, const OffsetsConfig&);
+ VSyncModulator(Scheduler&, ConnectionHandle appConnectionHandle,
+ ConnectionHandle sfConnectionHandle, const OffsetsConfig&);
void setPhaseOffsets(const OffsetsConfig&) EXCLUDES(mMutex);
@@ -92,8 +92,8 @@
void updateOffsetsLocked() REQUIRES(mMutex);
Scheduler& mScheduler;
- const sp<Scheduler::ConnectionHandle> mAppConnectionHandle;
- const sp<Scheduler::ConnectionHandle> mSfConnectionHandle;
+ const ConnectionHandle mAppConnectionHandle;
+ const ConnectionHandle mSfConnectionHandle;
mutable std::mutex mMutex;
OffsetsConfig mOffsetsConfig GUARDED_BY(mMutex);