Merge "Turn down GLESRenderEngine tests"
diff --git a/cmds/dumpstate/TEST_MAPPING b/cmds/dumpstate/TEST_MAPPING
index 839a2c3..649a13e 100644
--- a/cmds/dumpstate/TEST_MAPPING
+++ b/cmds/dumpstate/TEST_MAPPING
@@ -9,15 +9,15 @@
]
},
{
- "name": "dumpstate_smoke_test"
- },
- {
"name": "dumpstate_test"
}
],
"postsubmit": [
{
"name": "BugreportManagerTestCases"
+ },
+ {
+ "name": "dumpstate_smoke_test"
}
],
"imports": [
diff --git a/cmds/installd/Android.bp b/cmds/installd/Android.bp
index 0f7c489..ac101ec 100644
--- a/cmds/installd/Android.bp
+++ b/cmds/installd/Android.bp
@@ -25,6 +25,7 @@
"CrateManager.cpp",
"InstalldNativeService.cpp",
"QuotaUtils.cpp",
+ "SysTrace.cpp",
"dexopt.cpp",
"execv_helper.cpp",
"globals.cpp",
@@ -173,7 +174,7 @@
// Needs to be wherever installd is as it's execed by
// installd.
- required: ["migrate_legacy_obb_data.sh"],
+ required: ["migrate_legacy_obb_data"],
}
// OTA chroot tool
@@ -299,6 +300,6 @@
// Script to migrate legacy obb data.
sh_binary {
- name: "migrate_legacy_obb_data.sh",
+ name: "migrate_legacy_obb_data",
src: "migrate_legacy_obb_data.sh",
}
diff --git a/cmds/installd/InstalldNativeService.cpp b/cmds/installd/InstalldNativeService.cpp
index 6ee3070..a278a48 100644
--- a/cmds/installd/InstalldNativeService.cpp
+++ b/cmds/installd/InstalldNativeService.cpp
@@ -16,8 +16,6 @@
#include "InstalldNativeService.h"
-#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
-
#include <errno.h>
#include <fts.h>
#include <inttypes.h>
@@ -75,6 +73,7 @@
#include "CrateManager.h"
#include "MatchExtensionGen.h"
#include "QuotaUtils.h"
+#include "SysTrace.h"
#ifndef LOG_TAG
#define LOG_TAG "installd"
@@ -100,6 +99,8 @@
static constexpr const char* kDataMirrorCePath = "/data_mirror/data_ce";
static constexpr const char* kDataMirrorDePath = "/data_mirror/data_de";
+static constexpr const char* kMiscMirrorCePath = "/data_mirror/misc_ce";
+static constexpr const char* kMiscMirrorDePath = "/data_mirror/misc_de";
static constexpr const int MIN_RESTRICTED_HOME_SDK_VERSION = 24; // > M
@@ -1327,7 +1328,7 @@
const char* uuid_ = uuid ? uuid->c_str() : nullptr;
for (auto userId : get_known_users(uuid_)) {
LOCK_USER();
- ATRACE_BEGIN("fixup user");
+ atrace_pm_begin("fixup user");
FTS* fts;
FTSENT* p;
auto ce_path = create_data_user_ce_path(uuid_, userId);
@@ -1417,7 +1418,7 @@
}
}
fts_close(fts);
- ATRACE_END();
+ atrace_pm_end();
}
return ok();
}
@@ -1955,7 +1956,6 @@
return error("Failed to determine free space for " + data_path);
}
- int64_t cleared = 0;
int64_t needed = targetFreeBytes - free;
if (!defy_target) {
LOG(DEBUG) << "Device " << data_path << " has " << free << " free; requested "
@@ -1971,7 +1971,7 @@
// files from the UIDs which are most over their allocated quota
// 1. Create trackers for every known UID
- ATRACE_BEGIN("create");
+ atrace_pm_begin("create");
const auto users = get_known_users(uuid_);
#ifdef GRANULAR_LOCKS
std::vector<UserLock> userLocks;
@@ -2052,11 +2052,10 @@
}
fts_close(fts);
}
- ATRACE_END();
+ atrace_pm_end();
// 2. Populate tracker stats and insert into priority queue
- ATRACE_BEGIN("populate");
- int64_t cacheTotal = 0;
+ atrace_pm_begin("populate");
auto cmp = [](std::shared_ptr<CacheTracker> left, std::shared_ptr<CacheTracker> right) {
return (left->getCacheRatio() < right->getCacheRatio());
};
@@ -2065,13 +2064,12 @@
for (const auto& it : trackers) {
it.second->loadStats();
queue.push(it.second);
- cacheTotal += it.second->cacheUsed;
}
- ATRACE_END();
+ atrace_pm_end();
// 3. Bounce across the queue, freeing items from whichever tracker is
// the most over their assigned quota
- ATRACE_BEGIN("bounce");
+ atrace_pm_begin("bounce");
std::shared_ptr<CacheTracker> active;
while (active || !queue.empty()) {
// Only look at apps under quota when explicitly requested
@@ -2111,7 +2109,6 @@
}
active->cacheUsed -= item->size;
needed -= item->size;
- cleared += item->size;
}
if (!defy_target) {
@@ -2128,7 +2125,7 @@
}
}
}
- ATRACE_END();
+ atrace_pm_end();
} else {
return error("Legacy cache logic no longer supported");
@@ -2473,84 +2470,84 @@
flags &= ~FLAG_USE_QUOTA;
}
- ATRACE_BEGIN("obb");
+ atrace_pm_begin("obb");
for (const auto& packageName : packageNames) {
auto obbCodePath = create_data_media_package_path(uuid_, userId,
"obb", packageName.c_str());
calculate_tree_size(obbCodePath, &extStats.codeSize);
}
- ATRACE_END();
+ atrace_pm_end();
// Calculating the app size of the external storage owning app in a manual way, since
// calculating it through quota apis also includes external media storage in the app storage
// numbers
if (flags & FLAG_USE_QUOTA && appId >= AID_APP_START && !ownsExternalStorage(appId)) {
- ATRACE_BEGIN("code");
+ atrace_pm_begin("code");
for (const auto& codePath : codePaths) {
calculate_tree_size(codePath, &stats.codeSize, -1,
multiuser_get_shared_gid(0, appId));
}
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("quota");
+ atrace_pm_begin("quota");
collectQuotaStats(uuidString, userId, appId, &stats, &extStats);
- ATRACE_END();
+ atrace_pm_end();
} else {
- ATRACE_BEGIN("code");
+ atrace_pm_begin("code");
for (const auto& codePath : codePaths) {
calculate_tree_size(codePath, &stats.codeSize);
}
- ATRACE_END();
+ atrace_pm_end();
for (size_t i = 0; i < packageNames.size(); i++) {
const char* pkgname = packageNames[i].c_str();
- ATRACE_BEGIN("data");
+ atrace_pm_begin("data");
auto cePath = create_data_user_ce_package_path(uuid_, userId, pkgname, ceDataInodes[i]);
collectManualStats(cePath, &stats);
auto dePath = create_data_user_de_package_path(uuid_, userId, pkgname);
collectManualStats(dePath, &stats);
- ATRACE_END();
+ atrace_pm_end();
// In case of sdk sandbox storage (e.g. /data/misc_ce/0/sdksandbox/<package-name>),
// collect individual stats of each subdirectory (shared, storage of each sdk etc.)
if (appId >= AID_APP_START && appId <= AID_APP_END) {
- ATRACE_BEGIN("sdksandbox");
+ atrace_pm_begin("sdksandbox");
auto sdkSandboxCePath =
create_data_misc_sdk_sandbox_package_path(uuid_, true, userId, pkgname);
collectManualStatsForSubDirectories(sdkSandboxCePath, &stats);
auto sdkSandboxDePath =
create_data_misc_sdk_sandbox_package_path(uuid_, false, userId, pkgname);
collectManualStatsForSubDirectories(sdkSandboxDePath, &stats);
- ATRACE_END();
+ atrace_pm_end();
}
if (!uuid) {
- ATRACE_BEGIN("profiles");
+ atrace_pm_begin("profiles");
calculate_tree_size(
create_primary_current_profile_package_dir_path(userId, pkgname),
&stats.dataSize);
calculate_tree_size(
create_primary_reference_profile_package_dir_path(pkgname),
&stats.codeSize);
- ATRACE_END();
+ atrace_pm_end();
}
- ATRACE_BEGIN("external");
+ atrace_pm_begin("external");
auto extPath = create_data_media_package_path(uuid_, userId, "data", pkgname);
collectManualStats(extPath, &extStats);
auto mediaPath = create_data_media_package_path(uuid_, userId, "media", pkgname);
calculate_tree_size(mediaPath, &extStats.dataSize);
- ATRACE_END();
+ atrace_pm_end();
}
if (!uuid) {
- ATRACE_BEGIN("dalvik");
+ atrace_pm_begin("dalvik");
int32_t sharedGid = multiuser_get_shared_gid(0, appId);
if (sharedGid != -1) {
calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
sharedGid, -1);
}
- ATRACE_END();
+ atrace_pm_end();
}
}
@@ -2696,41 +2693,41 @@
}
if (flags & FLAG_USE_QUOTA) {
- ATRACE_BEGIN("code");
+ atrace_pm_begin("code");
calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize, -1, -1, true);
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("data");
+ atrace_pm_begin("data");
auto cePath = create_data_user_ce_path(uuid_, userId);
collectManualStatsForUser(cePath, &stats, true);
auto dePath = create_data_user_de_path(uuid_, userId);
collectManualStatsForUser(dePath, &stats, true);
- ATRACE_END();
+ atrace_pm_end();
if (!uuid) {
- ATRACE_BEGIN("profile");
+ atrace_pm_begin("profile");
auto userProfilePath = create_primary_cur_profile_dir_path(userId);
calculate_tree_size(userProfilePath, &stats.dataSize, -1, -1, true);
auto refProfilePath = create_primary_ref_profile_dir_path();
calculate_tree_size(refProfilePath, &stats.codeSize, -1, -1, true);
- ATRACE_END();
+ atrace_pm_end();
}
- ATRACE_BEGIN("external");
+ atrace_pm_begin("external");
auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
extStats.dataSize += sizes.totalSize;
extStats.codeSize += sizes.obbSize;
- ATRACE_END();
+ atrace_pm_end();
if (!uuid) {
- ATRACE_BEGIN("dalvik");
+ atrace_pm_begin("dalvik");
calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize,
-1, -1, true);
calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize,
-1, -1, true);
- ATRACE_END();
+ atrace_pm_end();
}
- ATRACE_BEGIN("quota");
+ atrace_pm_begin("quota");
int64_t dataSize = extStats.dataSize;
for (auto appId : appIds) {
if (appId >= AID_APP_START) {
@@ -2742,54 +2739,54 @@
}
}
extStats.dataSize = dataSize;
- ATRACE_END();
+ atrace_pm_end();
} else {
- ATRACE_BEGIN("obb");
+ atrace_pm_begin("obb");
auto obbPath = create_data_path(uuid_) + "/media/obb";
calculate_tree_size(obbPath, &extStats.codeSize);
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("code");
+ atrace_pm_begin("code");
calculate_tree_size(create_data_app_path(uuid_), &stats.codeSize);
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("data");
+ atrace_pm_begin("data");
auto cePath = create_data_user_ce_path(uuid_, userId);
collectManualStatsForUser(cePath, &stats);
auto dePath = create_data_user_de_path(uuid_, userId);
collectManualStatsForUser(dePath, &stats);
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("sdksandbox");
+ atrace_pm_begin("sdksandbox");
auto sdkSandboxCePath = create_data_misc_sdk_sandbox_path(uuid_, true, userId);
collectManualStatsForUser(sdkSandboxCePath, &stats, false, true);
auto sdkSandboxDePath = create_data_misc_sdk_sandbox_path(uuid_, false, userId);
collectManualStatsForUser(sdkSandboxDePath, &stats, false, true);
- ATRACE_END();
+ atrace_pm_end();
if (!uuid) {
- ATRACE_BEGIN("profile");
+ atrace_pm_begin("profile");
auto userProfilePath = create_primary_cur_profile_dir_path(userId);
calculate_tree_size(userProfilePath, &stats.dataSize);
auto refProfilePath = create_primary_ref_profile_dir_path();
calculate_tree_size(refProfilePath, &stats.codeSize);
- ATRACE_END();
+ atrace_pm_end();
}
- ATRACE_BEGIN("external");
+ atrace_pm_begin("external");
auto dataMediaPath = create_data_media_path(uuid_, userId);
collectManualExternalStatsForUser(dataMediaPath, &extStats);
#if MEASURE_DEBUG
LOG(DEBUG) << "Measured external data " << extStats.dataSize << " cache "
<< extStats.cacheSize;
#endif
- ATRACE_END();
+ atrace_pm_end();
if (!uuid) {
- ATRACE_BEGIN("dalvik");
+ atrace_pm_begin("dalvik");
calculate_tree_size(create_data_dalvik_cache_path(), &stats.codeSize);
calculate_tree_size(create_primary_cur_profile_dir_path(userId), &stats.dataSize);
- ATRACE_END();
+ atrace_pm_end();
}
}
@@ -2837,16 +2834,16 @@
}
if (flags & FLAG_USE_QUOTA) {
- ATRACE_BEGIN("quota");
+ atrace_pm_begin("quota");
auto sizes = getExternalSizesForUserWithQuota(uuidString, userId, appIds);
totalSize = sizes.totalSize;
audioSize = sizes.audioSize;
videoSize = sizes.videoSize;
imageSize = sizes.imageSize;
obbSize = sizes.obbSize;
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("apps");
+ atrace_pm_begin("apps");
struct stats extStats;
memset(&extStats, 0, sizeof(extStats));
for (auto appId : appIds) {
@@ -2855,9 +2852,9 @@
}
}
appSize = extStats.dataSize;
- ATRACE_END();
+ atrace_pm_end();
} else {
- ATRACE_BEGIN("manual");
+ atrace_pm_begin("manual");
FTS *fts;
FTSENT *p;
auto path = create_data_media_path(uuid_, userId);
@@ -2900,16 +2897,16 @@
}
}
fts_close(fts);
- ATRACE_END();
+ atrace_pm_end();
- ATRACE_BEGIN("obb");
+ atrace_pm_begin("obb");
auto obbPath = StringPrintf("%s/Android/obb",
create_data_media_path(uuid_, userId).c_str());
calculate_tree_size(obbPath, &obbSize);
if (!(flags & FLAG_USE_QUOTA)) {
totalSize -= obbSize;
}
- ATRACE_END();
+ atrace_pm_end();
}
std::vector<int64_t> ret;
@@ -3584,16 +3581,28 @@
std::string mirrorVolCePath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
if (fs_prepare_dir(mirrorVolCePath.c_str(), 0711, AID_SYSTEM, AID_SYSTEM) != 0) {
- return error("Failed to create CE mirror");
+ return error("Failed to create CE data mirror");
}
std::string mirrorVolDePath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
if (fs_prepare_dir(mirrorVolDePath.c_str(), 0711, AID_SYSTEM, AID_SYSTEM) != 0) {
- return error("Failed to create DE mirror");
+ return error("Failed to create DE data mirror");
+ }
+
+ std::string mirrorVolMiscCePath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
+ if (fs_prepare_dir(mirrorVolMiscCePath.c_str(), 0711, AID_SYSTEM, AID_SYSTEM) != 0) {
+ return error("Failed to create CE misc mirror");
+ }
+
+ std::string mirrorVolMiscDePath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
+ if (fs_prepare_dir(mirrorVolMiscDePath.c_str(), 0711, AID_SYSTEM, AID_SYSTEM) != 0) {
+ return error("Failed to create DE misc mirror");
}
auto cePath = StringPrintf("%s/user", create_data_path(uuid_).c_str());
auto dePath = StringPrintf("%s/user_de", create_data_path(uuid_).c_str());
+ auto miscCePath = StringPrintf("%s/misc_ce", create_data_path(uuid_).c_str());
+ auto miscDePath = StringPrintf("%s/misc_de", create_data_path(uuid_).c_str());
if (access(cePath.c_str(), F_OK) != 0) {
return error("Cannot access CE path: " + cePath);
@@ -3601,6 +3610,12 @@
if (access(dePath.c_str(), F_OK) != 0) {
return error("Cannot access DE path: " + dePath);
}
+ if (access(miscCePath.c_str(), F_OK) != 0) {
+ return error("Cannot access misc CE path: " + cePath);
+ }
+ if (access(miscDePath.c_str(), F_OK) != 0) {
+ return error("Cannot access misc DE path: " + dePath);
+ }
struct stat ceStat, mirrorCeStat;
if (stat(cePath.c_str(), &ceStat) != 0) {
@@ -3628,6 +3643,21 @@
MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC, nullptr)) == -1) {
return error("Failed to mount " + mirrorVolDePath);
}
+
+ // Mount misc CE mirror
+ if (TEMP_FAILURE_RETRY(mount(miscCePath.c_str(), mirrorVolMiscCePath.c_str(), NULL,
+ MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
+ nullptr)) == -1) {
+ return error("Failed to mount " + mirrorVolMiscCePath);
+ }
+
+ // Mount misc DE mirror
+ if (TEMP_FAILURE_RETRY(mount(miscDePath.c_str(), mirrorVolMiscDePath.c_str(), NULL,
+ MS_NOSUID | MS_NODEV | MS_NOATIME | MS_BIND | MS_NOEXEC,
+ nullptr)) == -1) {
+ return error("Failed to mount " + mirrorVolMiscDePath);
+ }
+
return ok();
}
@@ -3650,6 +3680,8 @@
std::string mirrorCeVolPath(StringPrintf("%s/%s", kDataMirrorCePath, uuid_));
std::string mirrorDeVolPath(StringPrintf("%s/%s", kDataMirrorDePath, uuid_));
+ std::string mirrorMiscCeVolPath(StringPrintf("%s/%s", kMiscMirrorCePath, uuid_));
+ std::string mirrorMiscDeVolPath(StringPrintf("%s/%s", kMiscMirrorDePath, uuid_));
std::lock_guard<std::recursive_mutex> lock(mMountsLock);
@@ -3674,6 +3706,29 @@
if (delete_dir_contents_and_dir(mirrorDeVolPath, true) != 0) {
res = error("Failed to delete " + mirrorDeVolPath);
}
+
+ // Unmount misc CE storage
+ if (TEMP_FAILURE_RETRY(umount(mirrorMiscCeVolPath.c_str())) != 0) {
+ if (errno != ENOENT) {
+ res = error(StringPrintf("Failed to umount %s %s", mirrorMiscCeVolPath.c_str(),
+ strerror(errno)));
+ }
+ }
+ if (delete_dir_contents_and_dir(mirrorMiscCeVolPath, true) != 0) {
+ res = error("Failed to delete " + mirrorMiscCeVolPath);
+ }
+
+ // Unmount misc DE storage
+ if (TEMP_FAILURE_RETRY(umount(mirrorMiscDeVolPath.c_str())) != 0) {
+ if (errno != ENOENT) {
+ res = error(StringPrintf("Failed to umount %s %s", mirrorMiscDeVolPath.c_str(),
+ strerror(errno)));
+ }
+ }
+ if (delete_dir_contents_and_dir(mirrorMiscDeVolPath, true) != 0) {
+ res = error("Failed to delete " + mirrorMiscDeVolPath);
+ }
+
return res;
}
@@ -3713,7 +3768,7 @@
ENFORCE_UID(AID_SYSTEM);
// NOTE: The lint warning doesn't apply to the use of system(3) with
// absolute parse and no command line arguments.
- if (system("/system/bin/migrate_legacy_obb_data.sh") != 0) { // NOLINT(cert-env33-c)
+ if (system("/system/bin/migrate_legacy_obb_data") != 0) { // NOLINT(cert-env33-c)
LOG(ERROR) << "Unable to migrate legacy obb data";
}
diff --git a/cmds/installd/SysTrace.cpp b/cmds/installd/SysTrace.cpp
new file mode 100644
index 0000000..fa65c77
--- /dev/null
+++ b/cmds/installd/SysTrace.cpp
@@ -0,0 +1,30 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#define ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
+
+#include "SysTrace.h"
+#include <utils/Trace.h>
+
+namespace android::installd {
+void atrace_pm_begin(const char* name) {
+ ATRACE_BEGIN(name);
+}
+
+void atrace_pm_end() {
+ ATRACE_END();
+}
+} /* namespace android::installd */
diff --git a/cmds/installd/SysTrace.h b/cmds/installd/SysTrace.h
new file mode 100644
index 0000000..18506a9
--- /dev/null
+++ b/cmds/installd/SysTrace.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+namespace android::installd {
+void atrace_pm_begin(const char*);
+void atrace_pm_end();
+} /* namespace android::installd */
diff --git a/cmds/installd/utils.cpp b/cmds/installd/utils.cpp
index 4d9b710..ffc082d 100644
--- a/cmds/installd/utils.cpp
+++ b/cmds/installd/utils.cpp
@@ -523,7 +523,6 @@
*/
bool is_valid_package_name(const std::string& packageName) {
// This logic is borrowed from PackageParser.java
- bool hasSep = false;
bool front = true;
auto it = packageName.begin();
@@ -539,7 +538,6 @@
}
}
if (c == '.') {
- hasSep = true;
front = true;
continue;
}
diff --git a/cmds/servicemanager/ServiceManagerFuzzer.cpp b/cmds/servicemanager/ServiceManagerFuzzer.cpp
index 39f8522..bc48fa9 100644
--- a/cmds/servicemanager/ServiceManagerFuzzer.cpp
+++ b/cmds/servicemanager/ServiceManagerFuzzer.cpp
@@ -26,9 +26,15 @@
using ::android::sp;
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
+ FuzzedDataProvider provider(data, size);
+
+ // Adding this random abort to check bug pipeline.
+ bool shouldAbort = provider.ConsumeBool();
+ if (shouldAbort) abort();
+
auto accessPtr = std::make_unique<Access>();
auto serviceManager = sp<ServiceManager>::make(std::move(accessPtr));
- fuzzService(serviceManager, FuzzedDataProvider(data, size));
+ fuzzService(serviceManager, std::move(provider));
return 0;
}
diff --git a/include/android/choreographer.h b/include/android/choreographer.h
index 63aa7ff..cd8e63d 100644
--- a/include/android/choreographer.h
+++ b/include/android/choreographer.h
@@ -16,6 +16,28 @@
/**
* @addtogroup Choreographer
+ *
+ * Choreographer coordinates the timing of frame rendering. This is the C version of the
+ * android.view.Choreographer object in Java.
+ *
+ * As of API level 33, apps can follow proper frame pacing and even choose a future frame to render.
+ * The API is used as follows:
+ * 1. The app posts an {@link AChoreographer_vsyncCallback} to Choreographer to run on the next
+ * frame.
+ * 2. The callback is called when it is the time to start the frame with an {@link
+ * AChoreographerFrameCallbackData} payload: information about multiple possible frame
+ * timelines.
+ * 3. Apps can choose a frame timeline from the {@link
+ * AChoreographerFrameCallbackData} payload, depending on the frame deadline they can meet when
+ * rendering the frame and their desired presentation time, and subsequently
+ * {@link ASurfaceTransaction_setFrameTimeline notify SurfaceFlinger}
+ * of the choice. Alternatively, for apps that do not choose a frame timeline, their frame would be
+ * presented at the earliest possible timeline.
+ * - The preferred frame timeline is the default frame
+ * timeline that the platform scheduled for the app, based on device configuration.
+ * 4. SurfaceFlinger attempts to follow the chosen frame timeline, by not applying transactions or
+ * latching buffers before the desired presentation time.
+ *
* @{
*/
@@ -47,7 +69,8 @@
struct AChoreographerFrameCallbackData;
/**
- * Opaque type that provides access to an AChoreographerFrameCallbackData object.
+ * Opaque type that provides access to an AChoreographerFrameCallbackData object, which contains
+ * various methods to extract frame information.
*/
typedef struct AChoreographerFrameCallbackData AChoreographerFrameCallbackData;
@@ -73,8 +96,9 @@
/**
* Prototype of the function that is called when a new frame is being rendered.
- * It's passed the frame data that should not outlive the callback, as well as the data pointer
- * provided by the application that registered a callback.
+ * It is called with \c callbackData describing multiple frame timelines, as well as the \c data
+ * pointer provided by the application that registered a callback. The \c callbackData does not
+ * outlive the callback.
*/
typedef void (*AChoreographer_vsyncCallback)(
const AChoreographerFrameCallbackData* callbackData, void* data);
@@ -110,7 +134,7 @@
__DEPRECATED_IN(29);
/**
- * Power a callback to be run on the next frame. The data pointer provided will
+ * Post a callback to be run on the next frame. The data pointer provided will
* be passed to the callback function when it's called.
*
* Available since API level 29.
@@ -131,8 +155,10 @@
uint32_t delayMillis) __INTRODUCED_IN(29);
/**
- * Posts a callback to run on the next frame. The data pointer provided will
+ * Posts a callback to be run on the next frame. The data pointer provided will
* be passed to the callback function when it's called.
+ *
+ * Available since API level 33.
*/
void AChoreographer_postVsyncCallback(AChoreographer* choreographer,
AChoreographer_vsyncCallback callback, void* data)
@@ -189,7 +215,10 @@
__INTRODUCED_IN(30);
/**
- * The time in nanoseconds when the frame started being rendered.
+ * The time in nanoseconds at which the frame started being rendered.
+ *
+ * Note that this time should \b not be used to advance animation clocks.
+ * Instead, see AChoreographerFrameCallbackData_getFrameTimelineExpectedPresentationTimeNanos().
*/
int64_t AChoreographerFrameCallbackData_getFrameTimeNanos(
const AChoreographerFrameCallbackData* data) __INTRODUCED_IN(33);
@@ -201,25 +230,38 @@
const AChoreographerFrameCallbackData* data) __INTRODUCED_IN(33);
/**
- * Get index of the platform-preferred FrameTimeline.
+ * Gets the index of the platform-preferred frame timeline.
+ * The preferred frame timeline is the default
+ * by which the platform scheduled the app, based on the device configuration.
*/
size_t AChoreographerFrameCallbackData_getPreferredFrameTimelineIndex(
const AChoreographerFrameCallbackData* data) __INTRODUCED_IN(33);
/**
- * The vsync ID token used to map Choreographer data.
+ * Gets the token used by the platform to identify the frame timeline at the given \c index.
+ *
+ * \param index index of a frame timeline, in \f( [0, FrameTimelinesLength) \f). See
+ * AChoreographerFrameCallbackData_getFrameTimelinesLength()
*/
AVsyncId AChoreographerFrameCallbackData_getFrameTimelineVsyncId(
const AChoreographerFrameCallbackData* data, size_t index) __INTRODUCED_IN(33);
/**
- * The time in nanoseconds which the frame at given index is expected to be presented.
+ * Gets the time in nanoseconds at which the frame described at the given \c index is expected to
+ * be presented. This time should be used to advance any animation clocks.
+ *
+ * \param index index of a frame timeline, in \f( [0, FrameTimelinesLength) \f). See
+ * AChoreographerFrameCallbackData_getFrameTimelinesLength()
*/
int64_t AChoreographerFrameCallbackData_getFrameTimelineExpectedPresentationTimeNanos(
const AChoreographerFrameCallbackData* data, size_t index) __INTRODUCED_IN(33);
/**
- * The time in nanoseconds which the frame at given index needs to be ready by.
+ * Gets the time in nanoseconds at which the frame described at the given \c index needs to be
+ * ready by in order to be presented on time.
+ *
+ * \param index index of a frame timeline, in \f( [0, FrameTimelinesLength) \f). See
+ * AChoreographerFrameCallbackData_getFrameTimelinesLength()
*/
int64_t AChoreographerFrameCallbackData_getFrameTimelineDeadlineNanos(
const AChoreographerFrameCallbackData* data, size_t index) __INTRODUCED_IN(33);
diff --git a/include/android/keycodes.h b/include/android/keycodes.h
index 214559d..16a13d6 100644
--- a/include/android/keycodes.h
+++ b/include/android/keycodes.h
@@ -776,7 +776,48 @@
AKEYCODE_THUMBS_DOWN = 287,
/** Used to switch current account that is consuming content.
* May be consumed by system to switch current viewer profile. */
- AKEYCODE_PROFILE_SWITCH = 288
+ AKEYCODE_PROFILE_SWITCH = 288,
+ /** Video Application key #1. */
+ AKEYCODE_VIDEO_APP_1 = 289,
+ /** Video Application key #2. */
+ AKEYCODE_VIDEO_APP_2 = 290,
+ /** Video Application key #3. */
+ AKEYCODE_VIDEO_APP_3 = 291,
+ /** Video Application key #4. */
+ AKEYCODE_VIDEO_APP_4 = 292,
+ /** Video Application key #5. */
+ AKEYCODE_VIDEO_APP_5 = 293,
+ /** Video Application key #6. */
+ AKEYCODE_VIDEO_APP_6 = 294,
+ /** Video Application key #7. */
+ AKEYCODE_VIDEO_APP_7 = 295,
+ /** Video Application key #8. */
+ AKEYCODE_VIDEO_APP_8 = 296,
+ /** Featured Application key #1. */
+ AKEYCODE_FEATURED_APP_1 = 297,
+ /** Featured Application key #2. */
+ AKEYCODE_FEATURED_APP_2 = 298,
+ /** Featured Application key #3. */
+ AKEYCODE_FEATURED_APP_3 = 299,
+ /** Featured Application key #4. */
+ AKEYCODE_FEATURED_APP_4 = 300,
+ /** Demo Application key #1. */
+ AKEYCODE_DEMO_APP_1 = 301,
+ /** Demo Application key #2. */
+ AKEYCODE_DEMO_APP_2 = 302,
+ /** Demo Application key #3. */
+ AKEYCODE_DEMO_APP_3 = 303,
+ /** Demo Application key #4. */
+ AKEYCODE_DEMO_APP_4 = 304,
+ /** Keyboard backlight Down key.
+ * Adjusts the keyboard backlight brightness down. */
+ AKEYCODE_KEYBOARD_BACKLIGHT_DOWN = 305,
+ /** Keyboard backlight Up key.
+ * Adjusts the keyboard backlight brightness up. */
+ AKEYCODE_KEYBOARD_BACKLIGHT_UP = 306,
+ /** Keyboard backlight Toggle key.
+ * Toggles the keyboard backlight on/off. */
+ AKEYCODE_KEYBOARD_BACKLIGHT_TOGGLE = 307,
// NOTE: If you add a new keycode here you must also add it to several other files.
// Refer to frameworks/base/core/java/android/view/KeyEvent.java for the full list.
diff --git a/include/android/surface_control.h b/include/android/surface_control.h
index 9a36ecb..f76e73d 100644
--- a/include/android/surface_control.h
+++ b/include/android/surface_control.h
@@ -545,6 +545,8 @@
* You can register for changes in the refresh rate using
* \a AChoreographer_registerRefreshRateCallback.
*
+ * See ASurfaceTransaction_clearFrameRate().
+ *
* \param frameRate is the intended frame rate of this surface, in frames per second. 0 is a special
* value that indicates the app will accept the system's choice for the display frame rate, which is
* the default behavior if this function isn't called. The frameRate param does <em>not</em> need to
@@ -568,6 +570,31 @@
__INTRODUCED_IN(31);
/**
+ * Clears the frame rate which is set for \a surface_control.
+ *
+ * This is equivalent to calling
+ * ASurfaceTransaction_setFrameRateWithChangeStrategy(
+ * transaction, 0, compatibility, changeFrameRateStrategy).
+ *
+ * Usage of this API won't directly affect the application's frame production pipeline. However,
+ * because the system may change the display refresh rate, calls to this function may result in
+ * changes to Choreographer callback timings, and changes to the time interval at which the system
+ * releases buffers back to the application.
+ *
+ * See ASurfaceTransaction_setFrameRateWithChangeStrategy()
+ *
+ * You can register for changes in the refresh rate using
+ * \a AChoreographer_registerRefreshRateCallback.
+ *
+ * See ASurfaceTransaction_setFrameRateWithChangeStrategy().
+ *
+ * Available since API level 34.
+ */
+void ASurfaceTransaction_clearFrameRate(ASurfaceTransaction* transaction,
+ ASurfaceControl* surface_control)
+ __INTRODUCED_IN(__ANDROID_API_U__);
+
+/**
* Indicate whether to enable backpressure for buffer submission to a given SurfaceControl.
*
* By default backpressure is disabled, which means submitting a buffer prior to receiving
@@ -597,20 +624,20 @@
__INTRODUCED_IN(31);
/**
- * Sets the frame timeline to use in Surface Flinger.
+ * Sets the frame timeline to use in SurfaceFlinger.
*
- * A frame timeline should be chosen based on what frame deadline the application
- * can meet when rendering the frame and the application's desired present time.
- * By setting a frame timeline, Surface Flinger tries to present the frame at the corresponding
- * expected present time.
+ * A frame timeline should be chosen based on the frame deadline the application
+ * can meet when rendering the frame and the application's desired presentation time.
+ * By setting a frame timeline, SurfaceFlinger tries to present the frame at the corresponding
+ * expected presentation time.
*
* To receive frame timelines, a callback must be posted to Choreographer using
- * AChoreographer_postExtendedFrameCallback(). The \a vsnycId can then be extracted from the
+ * AChoreographer_postVsyncCallback(). The \c vsyncId can then be extracted from the
* callback payload using AChoreographerFrameCallbackData_getFrameTimelineVsyncId().
*
- * \param vsyncId The vsync ID received from AChoreographer, setting the frame's present target to
- * the corresponding expected present time and deadline from the frame to be rendered. A stale or
- * invalid value will be ignored.
+ * \param vsyncId The vsync ID received from AChoreographer, setting the frame's presentation target
+ * to the corresponding expected presentation time and deadline from the frame to be rendered. A
+ * stale or invalid value will be ignored.
*/
void ASurfaceTransaction_setFrameTimeline(ASurfaceTransaction* transaction,
AVsyncId vsyncId) __INTRODUCED_IN(33);
diff --git a/include/ftl/algorithm.h b/include/ftl/algorithm.h
new file mode 100644
index 0000000..c5ff03b
--- /dev/null
+++ b/include/ftl/algorithm.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <algorithm>
+#include <functional>
+#include <utility>
+
+#include <ftl/optional.h>
+
+namespace android::ftl {
+
+// Adapter for std::find_if that converts the return value from iterator to optional.
+//
+// const ftl::StaticVector vector = {"upside"sv, "down"sv, "cake"sv};
+// assert(ftl::find_if(vector, [](const auto& str) { return str.front() == 'c'; }) == "cake"sv);
+//
+template <typename Container, typename Predicate, typename V = typename Container::value_type>
+constexpr auto find_if(const Container& container, Predicate&& predicate)
+ -> Optional<std::reference_wrapper<const V>> {
+ const auto it = std::find_if(std::cbegin(container), std::cend(container),
+ std::forward<Predicate>(predicate));
+ if (it == std::cend(container)) return {};
+ return std::cref(*it);
+}
+
+// Transformers for ftl::find_if on a map-like `Container` that contains key-value pairs.
+//
+// const ftl::SmallMap map = ftl::init::map<int, ftl::StaticVector<std::string_view, 3>>(
+// 12, "snow"sv, "cone"sv)(13, "tiramisu"sv)(14, "upside"sv, "down"sv, "cake"sv);
+//
+// using Map = decltype(map);
+//
+// assert(14 == ftl::find_if(map, [](const auto& pair) {
+// return pair.second.size() == 3;
+// }).transform(ftl::to_key<Map>));
+//
+// const auto opt = ftl::find_if(map, [](const auto& pair) {
+// return pair.second.size() == 1;
+// }).transform(ftl::to_mapped_ref<Map>);
+//
+// assert(opt);
+// assert(opt->get() == ftl::StaticVector("tiramisu"sv));
+//
+template <typename Map, typename Pair = typename Map::value_type,
+ typename Key = typename Map::key_type>
+constexpr auto to_key(const Pair& pair) -> Key {
+ return pair.first;
+}
+
+template <typename Map, typename Pair = typename Map::value_type,
+ typename Mapped = typename Map::mapped_type>
+constexpr auto to_mapped_ref(const Pair& pair) -> std::reference_wrapper<const Mapped> {
+ return std::cref(pair.second);
+}
+
+} // namespace android::ftl
diff --git a/include/ftl/details/optional.h b/include/ftl/details/optional.h
new file mode 100644
index 0000000..bff7c1e
--- /dev/null
+++ b/include/ftl/details/optional.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <functional>
+#include <optional>
+
+#include <ftl/details/type_traits.h>
+
+namespace android::ftl {
+
+template <typename>
+struct Optional;
+
+namespace details {
+
+template <typename>
+struct is_optional : std::false_type {};
+
+template <typename T>
+struct is_optional<std::optional<T>> : std::true_type {};
+
+template <typename T>
+struct is_optional<Optional<T>> : std::true_type {};
+
+template <typename F, typename T>
+struct transform_result {
+ using type = Optional<std::remove_cv_t<std::invoke_result_t<F, T>>>;
+};
+
+template <typename F, typename T>
+using transform_result_t = typename transform_result<F, T>::type;
+
+template <typename F, typename T>
+struct and_then_result {
+ using type = remove_cvref_t<std::invoke_result_t<F, T>>;
+ static_assert(is_optional<type>{}, "and_then function must return an optional");
+};
+
+template <typename F, typename T>
+using and_then_result_t = typename and_then_result<F, T>::type;
+
+} // namespace details
+} // namespace android::ftl
diff --git a/include/ftl/details/type_traits.h b/include/ftl/details/type_traits.h
new file mode 100644
index 0000000..7092ec5
--- /dev/null
+++ b/include/ftl/details/type_traits.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <type_traits>
+
+namespace android::ftl::details {
+
+// TODO: Replace with std::remove_cvref_t in C++20.
+template <typename U>
+using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<U>>;
+
+} // namespace android::ftl::details
diff --git a/include/ftl/optional.h b/include/ftl/optional.h
index daf4502..626507f 100644
--- a/include/ftl/optional.h
+++ b/include/ftl/optional.h
@@ -18,9 +18,10 @@
#include <functional>
#include <optional>
-#include <type_traits>
#include <utility>
+#include <ftl/details/optional.h>
+
namespace android::ftl {
// Superset of std::optional<T> with monadic operations, as proposed in https://wg21.link/P0798R8.
@@ -31,41 +32,76 @@
struct Optional final : std::optional<T> {
using std::optional<T>::optional;
+ // Implicit downcast.
+ Optional(std::optional<T> other) : std::optional<T>(std::move(other)) {}
+
using std::optional<T>::has_value;
using std::optional<T>::value;
// Returns Optional<U> where F is a function that maps T to U.
template <typename F>
constexpr auto transform(F&& f) const& {
- using U = std::remove_cv_t<std::invoke_result_t<F, decltype(value())>>;
- if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), value()));
- return Optional<U>();
+ using R = details::transform_result_t<F, decltype(value())>;
+ if (has_value()) return R(std::invoke(std::forward<F>(f), value()));
+ return R();
}
template <typename F>
constexpr auto transform(F&& f) & {
- using U = std::remove_cv_t<std::invoke_result_t<F, decltype(value())>>;
- if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), value()));
- return Optional<U>();
+ using R = details::transform_result_t<F, decltype(value())>;
+ if (has_value()) return R(std::invoke(std::forward<F>(f), value()));
+ return R();
}
template <typename F>
constexpr auto transform(F&& f) const&& {
- using U = std::invoke_result_t<F, decltype(std::move(value()))>;
- if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), std::move(value())));
- return Optional<U>();
+ using R = details::transform_result_t<F, decltype(std::move(value()))>;
+ if (has_value()) return R(std::invoke(std::forward<F>(f), std::move(value())));
+ return R();
}
template <typename F>
constexpr auto transform(F&& f) && {
- using U = std::invoke_result_t<F, decltype(std::move(value()))>;
- if (has_value()) return Optional<U>(std::invoke(std::forward<F>(f), std::move(value())));
- return Optional<U>();
+ using R = details::transform_result_t<F, decltype(std::move(value()))>;
+ if (has_value()) return R(std::invoke(std::forward<F>(f), std::move(value())));
+ return R();
+ }
+
+ // Returns Optional<U> where F is a function that maps T to Optional<U>.
+ template <typename F>
+ constexpr auto and_then(F&& f) const& {
+ using R = details::and_then_result_t<F, decltype(value())>;
+ if (has_value()) return std::invoke(std::forward<F>(f), value());
+ return R();
+ }
+
+ template <typename F>
+ constexpr auto and_then(F&& f) & {
+ using R = details::and_then_result_t<F, decltype(value())>;
+ if (has_value()) return std::invoke(std::forward<F>(f), value());
+ return R();
+ }
+
+ template <typename F>
+ constexpr auto and_then(F&& f) const&& {
+ using R = details::and_then_result_t<F, decltype(std::move(value()))>;
+ if (has_value()) return std::invoke(std::forward<F>(f), std::move(value()));
+ return R();
+ }
+
+ template <typename F>
+ constexpr auto and_then(F&& f) && {
+ using R = details::and_then_result_t<F, decltype(std::move(value()))>;
+ if (has_value()) return std::invoke(std::forward<F>(f), std::move(value()));
+ return R();
}
};
-// Deduction guide.
+// Deduction guides.
template <typename T>
Optional(T) -> Optional<T>;
+template <typename T>
+Optional(std::optional<T>) -> Optional<T>;
+
} // namespace android::ftl
diff --git a/include/ftl/small_vector.h b/include/ftl/small_vector.h
index 339726e..11294c3 100644
--- a/include/ftl/small_vector.h
+++ b/include/ftl/small_vector.h
@@ -21,11 +21,12 @@
#include <algorithm>
#include <iterator>
-#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
+#include <ftl/details/type_traits.h>
+
namespace android::ftl {
template <typename>
@@ -80,10 +81,6 @@
using Static = StaticVector<T, N>;
using Dynamic = SmallVector<T, 0>;
- // TODO: Replace with std::remove_cvref_t in C++20.
- template <typename U>
- using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<U>>;
-
public:
FTL_ARRAY_TRAIT(T, value_type);
FTL_ARRAY_TRAIT(T, size_type);
@@ -104,7 +101,7 @@
// Constructs at most N elements. See StaticVector for underlying constructors.
template <typename Arg, typename... Args,
- typename = std::enable_if_t<!is_small_vector<remove_cvref_t<Arg>>{}>>
+ typename = std::enable_if_t<!is_small_vector<details::remove_cvref_t<Arg>>{}>>
SmallVector(Arg&& arg, Args&&... args)
: vector_(std::in_place_type<Static>, std::forward<Arg>(arg), std::forward<Args>(args)...) {}
diff --git a/include/input/DisplayViewport.h b/include/input/DisplayViewport.h
index 9148fee..98a18c9 100644
--- a/include/input/DisplayViewport.h
+++ b/include/input/DisplayViewport.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_DISPLAY_VIEWPORT_H
-#define _LIBINPUT_DISPLAY_VIEWPORT_H
+#pragma once
#include <android-base/stringprintf.h>
#include <ftl/enum.h>
@@ -144,5 +143,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_DISPLAY_VIEWPORT_H
diff --git a/include/input/Input.h b/include/input/Input.h
index a3c9f33..2dd651e 100644
--- a/include/input/Input.h
+++ b/include/input/Input.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_INPUT_H
-#define _LIBINPUT_INPUT_H
+#pragma once
#pragma GCC system_header
@@ -1104,5 +1103,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_INPUT_H
diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h
index 3585392..415080d 100644
--- a/include/input/InputDevice.h
+++ b/include/input/InputDevice.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_INPUT_DEVICE_H
-#define _LIBINPUT_INPUT_DEVICE_H
+#pragma once
#include <android/sensor.h>
#include <input/Input.h>
@@ -23,6 +22,8 @@
#include <unordered_map>
#include <vector>
+#include "android/hardware/input/InputDeviceCountryCode.h"
+
namespace android {
/*
@@ -210,8 +211,10 @@
};
void initialize(int32_t id, int32_t generation, int32_t controllerNumber,
- const InputDeviceIdentifier& identifier, const std::string& alias, bool isExternal,
- bool hasMic);
+ const InputDeviceIdentifier& identifier, const std::string& alias,
+ bool isExternal, bool hasMic,
+ hardware::input::InputDeviceCountryCode countryCode =
+ hardware::input::InputDeviceCountryCode::INVALID);
inline int32_t getId() const { return mId; }
inline int32_t getControllerNumber() const { return mControllerNumber; }
@@ -223,6 +226,7 @@
}
inline bool isExternal() const { return mIsExternal; }
inline bool hasMic() const { return mHasMic; }
+ inline hardware::input::InputDeviceCountryCode getCountryCode() const { return mCountryCode; }
inline uint32_t getSources() const { return mSources; }
const MotionRange* getMotionRange(int32_t axis, uint32_t source) const;
@@ -274,9 +278,11 @@
std::string mAlias;
bool mIsExternal;
bool mHasMic;
+ hardware::input::InputDeviceCountryCode mCountryCode;
uint32_t mSources;
int32_t mKeyboardType;
std::shared_ptr<KeyCharacterMap> mKeyCharacterMap;
+
bool mHasVibrator;
bool mHasBattery;
bool mHasButtonUnderPad;
@@ -334,5 +340,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_INPUT_DEVICE_H
diff --git a/include/input/InputEventLabels.h b/include/input/InputEventLabels.h
index 2a742f9..b4374ac 100644
--- a/include/input/InputEventLabels.h
+++ b/include/input/InputEventLabels.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_INPUT_EVENT_LABELS_H
-#define _LIBINPUT_INPUT_EVENT_LABELS_H
+#pragma once
#include <input/Input.h>
#include <android/keycodes.h>
@@ -68,4 +67,3 @@
};
} // namespace android
-#endif // _LIBINPUT_INPUT_EVENT_LABELS_H
diff --git a/include/input/InputTransport.h b/include/input/InputTransport.h
index dbc7bfa..1c52792 100644
--- a/include/input/InputTransport.h
+++ b/include/input/InputTransport.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_INPUT_TRANSPORT_H
-#define _LIBINPUT_INPUT_TRANSPORT_H
+#pragma once
#pragma GCC system_header
@@ -674,5 +673,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_INPUT_TRANSPORT_H
diff --git a/include/input/KeyCharacterMap.h b/include/input/KeyCharacterMap.h
index 1c9a5ea..dc928b8 100644
--- a/include/input/KeyCharacterMap.h
+++ b/include/input/KeyCharacterMap.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_KEY_CHARACTER_MAP_H
-#define _LIBINPUT_KEY_CHARACTER_MAP_H
+#pragma once
#include <stdint.h>
#include <list>
@@ -270,5 +269,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
diff --git a/include/input/KeyLayoutMap.h b/include/input/KeyLayoutMap.h
index a6c696d..e203d19 100644
--- a/include/input/KeyLayoutMap.h
+++ b/include/input/KeyLayoutMap.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_KEY_LAYOUT_MAP_H
-#define _LIBINPUT_KEY_LAYOUT_MAP_H
+#pragma once
#include <android-base/result.h>
#include <stdint.h>
@@ -131,5 +130,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_KEY_LAYOUT_MAP_H
diff --git a/include/input/Keyboard.h b/include/input/Keyboard.h
index 9a3e15f..f7f960f 100644
--- a/include/input/Keyboard.h
+++ b/include/input/Keyboard.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_KEYBOARD_H
-#define _LIBINPUT_KEYBOARD_H
+#pragma once
#include <input/Input.h>
#include <input/InputDevice.h>
@@ -88,5 +87,3 @@
extern bool isMetaKey(int32_t keyCode);
} // namespace android
-
-#endif // _LIBINPUT_KEYBOARD_H
diff --git a/include/input/PrintTools.h b/include/input/PrintTools.h
index 0a75278..55f730b 100644
--- a/include/input/PrintTools.h
+++ b/include/input/PrintTools.h
@@ -17,6 +17,7 @@
#pragma once
#include <map>
+#include <optional>
#include <set>
#include <string>
@@ -28,6 +29,15 @@
}
/**
+ * Convert an optional type to string.
+ */
+template <typename T>
+std::string toString(const std::optional<T>& optional,
+ std::string (*toString)(const T&) = constToString) {
+ return optional ? toString(*optional) : "<not set>";
+}
+
+/**
* Convert a set of integral types to string.
*/
template <typename T>
diff --git a/include/input/PropertyMap.h b/include/input/PropertyMap.h
index b1e3f85..28e4816 100644
--- a/include/input/PropertyMap.h
+++ b/include/input/PropertyMap.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UTILS_PROPERTY_MAP_H
-#define _UTILS_PROPERTY_MAP_H
+#pragma once
#include <android-base/result.h>
#include <utils/Tokenizer.h>
@@ -98,5 +97,3 @@
};
} // namespace android
-
-#endif // _UTILS_PROPERTY_MAP_H
diff --git a/include/input/TouchVideoFrame.h b/include/input/TouchVideoFrame.h
index eda628e..a616a95 100644
--- a/include/input/TouchVideoFrame.h
+++ b/include/input/TouchVideoFrame.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_TOUCHVIDEOFRAME_H
-#define _LIBINPUT_TOUCHVIDEOFRAME_H
+#pragma once
#include <stdint.h>
#include <sys/time.h>
@@ -75,5 +74,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_TOUCHVIDEOFRAME_H
diff --git a/include/input/VelocityControl.h b/include/input/VelocityControl.h
index 1acc2ae..f72a1bd 100644
--- a/include/input/VelocityControl.h
+++ b/include/input/VelocityControl.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_VELOCITY_CONTROL_H
-#define _LIBINPUT_VELOCITY_CONTROL_H
+#pragma once
#include <input/Input.h>
#include <input/VelocityTracker.h>
@@ -98,10 +97,8 @@
VelocityControlParameters mParameters;
nsecs_t mLastMovementTime;
- VelocityTracker::Position mRawPosition;
+ float mRawPositionX, mRawPositionY;
VelocityTracker mVelocityTracker;
};
} // namespace android
-
-#endif // _LIBINPUT_VELOCITY_CONTROL_H
diff --git a/include/input/VelocityTracker.h b/include/input/VelocityTracker.h
index 886f1f7..6144f5b 100644
--- a/include/input/VelocityTracker.h
+++ b/include/input/VelocityTracker.h
@@ -14,12 +14,13 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_VELOCITY_TRACKER_H
-#define _LIBINPUT_VELOCITY_TRACKER_H
+#pragma once
#include <input/Input.h>
#include <utils/BitSet.h>
#include <utils/Timers.h>
+#include <map>
+#include <set>
namespace android {
@@ -46,18 +47,14 @@
MAX = LEGACY,
};
- struct Position {
- float x, y;
- };
-
struct Estimator {
static const size_t MAX_DEGREE = 4;
// Estimator time base.
nsecs_t time;
- // Polynomial coefficients describing motion in X and Y.
- float xCoeff[MAX_DEGREE + 1], yCoeff[MAX_DEGREE + 1];
+ // Polynomial coefficients describing motion.
+ float coeff[MAX_DEGREE + 1];
// Polynomial degree (number of coefficients), or zero if no information is
// available.
@@ -71,14 +68,40 @@
degree = 0;
confidence = 0;
for (size_t i = 0; i <= MAX_DEGREE; i++) {
- xCoeff[i] = 0;
- yCoeff[i] = 0;
+ coeff[i] = 0;
}
}
};
- // Creates a velocity tracker using the specified strategy.
+ /*
+ * Contains all available velocity data from a VelocityTracker.
+ */
+ struct ComputedVelocity {
+ inline std::optional<float> getVelocity(int32_t axis, uint32_t id) const {
+ const auto& axisVelocities = mVelocities.find(axis);
+ if (axisVelocities == mVelocities.end()) {
+ return {};
+ }
+
+ const auto& axisIdVelocity = axisVelocities->second.find(id);
+ if (axisIdVelocity == axisVelocities->second.end()) {
+ return {};
+ }
+
+ return axisIdVelocity->second;
+ }
+
+ inline void addVelocity(int32_t axis, uint32_t id, float velocity) {
+ mVelocities[axis][id] = velocity;
+ }
+
+ private:
+ std::map<int32_t /*axis*/, std::map<int32_t /*pointerId*/, float /*velocity*/>> mVelocities;
+ };
+
+ // Creates a velocity tracker using the specified strategy for each supported axis.
// If strategy is not provided, uses the default strategy for the platform.
+ // TODO(b/32830165): support axis-specific strategies.
VelocityTracker(const Strategy strategy = Strategy::DEFAULT);
~VelocityTracker();
@@ -92,45 +115,56 @@
void clearPointers(BitSet32 idBits);
// Adds movement information for a set of pointers.
- // The idBits bitfield specifies the pointer ids of the pointers whose positions
+ // The idBits bitfield specifies the pointer ids of the pointers whose data points
// are included in the movement.
- // The positions array contains position information for each pointer in order by
- // increasing id. Its size should be equal to the number of one bits in idBits.
- void addMovement(nsecs_t eventTime, BitSet32 idBits, const std::vector<Position>& positions);
+ // The positions map contains a mapping of an axis to positions array.
+ // The positions arrays contain information for each pointer in order by increasing id.
+ // Each array's size should be equal to the number of one bits in idBits.
+ void addMovement(nsecs_t eventTime, BitSet32 idBits,
+ const std::map<int32_t, std::vector<float>>& positions);
// Adds movement information for all pointers in a MotionEvent, including historical samples.
void addMovement(const MotionEvent* event);
- // Gets the velocity of the specified pointer id in position units per second.
- // Returns false and sets the velocity components to zero if there is
- // insufficient movement information for the pointer.
- bool getVelocity(uint32_t id, float* outVx, float* outVy) const;
+ // Returns the velocity of the specified pointer id and axis in position units per second.
+ // Returns empty optional if there is insufficient movement information for the pointer, or if
+ // the given axis is not supported for velocity tracking.
+ std::optional<float> getVelocity(int32_t axis, uint32_t id) const;
- // Gets an estimator for the recent movements of the specified pointer id.
+ // Returns a ComputedVelocity instance with all available velocity data, using the given units
+ // (reference: units == 1 means "per millisecond"), and clamping each velocity between
+ // [-maxVelocity, maxVelocity], inclusive.
+ ComputedVelocity getComputedVelocity(int32_t units, float maxVelocity);
+
+ // Gets an estimator for the recent movements of the specified pointer id for the given axis.
// Returns false and clears the estimator if there is no information available
// about the pointer.
- bool getEstimator(uint32_t id, Estimator* outEstimator) const;
+ bool getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const;
// Gets the active pointer id, or -1 if none.
inline int32_t getActivePointerId() const { return mActivePointerId; }
- // Gets a bitset containing all pointer ids from the most recent movement.
- inline BitSet32 getCurrentPointerIdBits() const { return mCurrentPointerIdBits; }
-
private:
// The default velocity tracker strategy.
// Although other strategies are available for testing and comparison purposes,
// this is the strategy that applications will actually use. Be very careful
// when adjusting the default strategy because it can dramatically affect
// (often in a bad way) the user experience.
+ // TODO(b/32830165): define default strategy per axis.
static const Strategy DEFAULT_STRATEGY = Strategy::LSQ2;
+ // Set of all axes supported for velocity tracking.
+ static const std::set<int32_t> SUPPORTED_AXES;
+
+ // Axes specifying location on a 2D plane (i.e. X and Y).
+ static const std::set<int32_t> PLANAR_AXES;
+
nsecs_t mLastEventTime;
BitSet32 mCurrentPointerIdBits;
int32_t mActivePointerId;
- std::unique_ptr<VelocityTrackerStrategy> mStrategy;
+ std::map<int32_t /*axis*/, std::unique_ptr<VelocityTrackerStrategy>> mStrategies;
- bool configureStrategy(const Strategy strategy);
+ void configureStrategy(int32_t axis, const Strategy strategy);
static std::unique_ptr<VelocityTrackerStrategy> createStrategy(const Strategy strategy);
};
@@ -149,7 +183,7 @@
virtual void clear() = 0;
virtual void clearPointers(BitSet32 idBits) = 0;
virtual void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) = 0;
+ const std::vector<float>& positions) = 0;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const = 0;
};
@@ -181,7 +215,7 @@
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) override;
+ const std::vector<float>& positions) override;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
@@ -196,11 +230,9 @@
struct Movement {
nsecs_t eventTime;
BitSet32 idBits;
- VelocityTracker::Position positions[MAX_POINTERS];
+ float positions[MAX_POINTERS];
- inline const VelocityTracker::Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
+ inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
};
float chooseWeight(uint32_t index) const;
@@ -224,7 +256,7 @@
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) override;
+ const std::vector<float>& positions) override;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
@@ -233,16 +265,15 @@
nsecs_t updateTime;
uint32_t degree;
- float xpos, xvel, xaccel;
- float ypos, yvel, yaccel;
+ float pos, vel, accel;
};
const uint32_t mDegree;
BitSet32 mPointerIdBits;
State mPointerState[MAX_POINTER_ID + 1];
- void initState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
- void updateState(State& state, nsecs_t eventTime, float xpos, float ypos) const;
+ void initState(State& state, nsecs_t eventTime, float pos) const;
+ void updateState(State& state, nsecs_t eventTime, float pos) const;
void populateEstimator(const State& state, VelocityTracker::Estimator* outEstimator) const;
};
@@ -258,7 +289,7 @@
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) override;
+ const std::vector<float>& positions) override;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
@@ -274,11 +305,9 @@
struct Movement {
nsecs_t eventTime;
BitSet32 idBits;
- VelocityTracker::Position positions[MAX_POINTERS];
+ float positions[MAX_POINTERS];
- inline const VelocityTracker::Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
+ inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
};
uint32_t mIndex;
@@ -293,7 +322,7 @@
virtual void clear();
virtual void clearPointers(BitSet32 idBits);
void addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) override;
+ const std::vector<float>& positions) override;
virtual bool getEstimator(uint32_t id, VelocityTracker::Estimator* outEstimator) const;
private:
@@ -308,11 +337,9 @@
struct Movement {
nsecs_t eventTime;
BitSet32 idBits;
- VelocityTracker::Position positions[MAX_POINTERS];
+ float positions[MAX_POINTERS];
- inline const VelocityTracker::Position& getPosition(uint32_t id) const {
- return positions[idBits.getIndexOfBit(id)];
- }
+ inline float getPosition(uint32_t id) const { return positions[idBits.getIndexOfBit(id)]; }
};
size_t mIndex;
@@ -320,5 +347,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_VELOCITY_TRACKER_H
diff --git a/include/input/VirtualKeyMap.h b/include/input/VirtualKeyMap.h
index 6e8e2c9..a4381ea 100644
--- a/include/input/VirtualKeyMap.h
+++ b/include/input/VirtualKeyMap.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _LIBINPUT_VIRTUAL_KEY_MAP_H
-#define _LIBINPUT_VIRTUAL_KEY_MAP_H
+#pragma once
#include <stdint.h>
@@ -77,5 +76,3 @@
};
} // namespace android
-
-#endif // _LIBINPUT_KEY_CHARACTER_MAP_H
diff --git a/libs/arect/include/android/rect.h b/libs/arect/include/android/rect.h
index b36728e..d52861a 100644
--- a/libs/arect/include/android/rect.h
+++ b/libs/arect/include/android/rect.h
@@ -57,7 +57,7 @@
} ARect;
#ifdef __cplusplus
-};
+}
#endif
#endif // ANDROID_RECT_H
diff --git a/libs/binder/Android.bp b/libs/binder/Android.bp
index 66b03b0..c4bb6d0 100644
--- a/libs/binder/Android.bp
+++ b/libs/binder/Android.bp
@@ -71,9 +71,46 @@
}
cc_defaults {
- name: "libbinder_defaults",
+ name: "libbinder_common_defaults",
host_supported: true,
+ srcs: [
+ "Binder.cpp",
+ "BinderRecordReplay.cpp",
+ "BpBinder.cpp",
+ "Debug.cpp",
+ "FdTrigger.cpp",
+ "IInterface.cpp",
+ "IResultReceiver.cpp",
+ "Parcel.cpp",
+ "ParcelFileDescriptor.cpp",
+ "RpcSession.cpp",
+ "RpcServer.cpp",
+ "RpcState.cpp",
+ "Stability.cpp",
+ "Status.cpp",
+ "TextOutput.cpp",
+ "Trace.cpp",
+ "Utils.cpp",
+ ],
+
+ shared_libs: [
+ "libcutils",
+ "libutils",
+ ],
+
+ static_libs: [
+ "libbase",
+ ],
+
+ header_libs: [
+ "libbinder_headers",
+ ],
+}
+
+cc_defaults {
+ name: "libbinder_android_defaults",
+
// TODO(b/31559095): get headers from bionic on host
include_dirs: [
"bionic/libc/kernel/android/uapi/",
@@ -81,23 +118,8 @@
],
srcs: [
- "Binder.cpp",
- "BpBinder.cpp",
- "Debug.cpp",
- "FdTrigger.cpp",
- "IInterface.cpp",
- "IResultReceiver.cpp",
"OS.cpp",
- "Parcel.cpp",
- "ParcelFileDescriptor.cpp",
- "RpcSession.cpp",
- "RpcServer.cpp",
- "RpcState.cpp",
"RpcTransportRaw.cpp",
- "Stability.cpp",
- "Status.cpp",
- "TextOutput.cpp",
- "Utils.cpp",
],
target: {
@@ -127,22 +149,18 @@
},
debuggable: {
- cflags: ["-DBINDER_RPC_DEV_SERVERS"],
+ cflags: [
+ "-DBINDER_RPC_DEV_SERVERS",
+ "-DBINDER_ENABLE_RECORDING",
+ ],
},
},
shared_libs: [
"liblog",
- "libcutils",
- "libutils",
- ],
-
- static_libs: [
- "libbase",
],
header_libs: [
- "libbinder_headers",
"libandroid_runtime_vm_headers",
],
@@ -177,6 +195,48 @@
],
}
+cc_library_shared {
+ name: "libbinder_on_trusty_mock",
+ defaults: ["libbinder_common_defaults"],
+
+ srcs: [
+ // Trusty-specific files
+ "trusty/logging.cpp",
+ "trusty/OS.cpp",
+ "trusty/RpcServerTrusty.cpp",
+ "trusty/RpcTransportTipcTrusty.cpp",
+ "trusty/TrustyStatus.cpp",
+ "trusty/socket.cpp",
+ ],
+
+ cflags: [
+ "-DBINDER_RPC_SINGLE_THREADED",
+ // Trusty libbinder uses vendor stability for its binders
+ "-D__ANDROID_VNDK__",
+ "-U__ANDROID__",
+ "-D__TRUSTY__",
+ "-DTRUSTY_USERSPACE",
+ // Flags from the Trusty build system
+ "-Werror",
+ "-Wsign-compare",
+ "-Wno-unused-function",
+ "-Wno-unused-label",
+ "-fno-common",
+ "-fno-omit-frame-pointer",
+ "-fno-threadsafe-statics",
+ ],
+ rtti: false,
+
+ local_include_dirs: [
+ "trusty/include",
+ "trusty/include_mock",
+ ],
+
+ visibility: [
+ ":__subpackages__",
+ ],
+}
+
cc_defaults {
name: "libbinder_kernel_defaults",
srcs: [
@@ -208,7 +268,8 @@
cc_library {
name: "libbinder",
defaults: [
- "libbinder_defaults",
+ "libbinder_common_defaults",
+ "libbinder_android_defaults",
"libbinder_kernel_defaults",
],
@@ -264,7 +325,10 @@
cc_library_static {
name: "libbinder_rpc_no_kernel",
- defaults: ["libbinder_defaults"],
+ defaults: [
+ "libbinder_common_defaults",
+ "libbinder_android_defaults",
+ ],
visibility: [
":__subpackages__",
],
@@ -273,7 +337,8 @@
cc_library_static {
name: "libbinder_rpc_single_threaded",
defaults: [
- "libbinder_defaults",
+ "libbinder_common_defaults",
+ "libbinder_android_defaults",
"libbinder_kernel_defaults",
],
cflags: [
@@ -286,7 +351,10 @@
cc_library_static {
name: "libbinder_rpc_single_threaded_no_kernel",
- defaults: ["libbinder_defaults"],
+ defaults: [
+ "libbinder_common_defaults",
+ "libbinder_android_defaults",
+ ],
cflags: [
"-DBINDER_RPC_SINGLE_THREADED",
],
@@ -416,6 +484,9 @@
java: {
enabled: false,
},
+ cpp: {
+ gen_trace: false,
+ },
},
}
diff --git a/libs/binder/Binder.cpp b/libs/binder/Binder.cpp
index 4029957..481d704 100644
--- a/libs/binder/Binder.cpp
+++ b/libs/binder/Binder.cpp
@@ -21,6 +21,7 @@
#include <android-base/logging.h>
#include <android-base/unique_fd.h>
+#include <binder/BinderRecordReplay.h>
#include <binder/BpBinder.h>
#include <binder/IInterface.h>
#include <binder/IPCThreadState.h>
@@ -28,7 +29,9 @@
#include <binder/IShellCallback.h>
#include <binder/Parcel.h>
#include <binder/RpcServer.h>
+#include <cutils/compiler.h>
#include <private/android_filesystem_config.h>
+#include <pthread.h>
#include <utils/misc.h>
#include <inttypes.h>
@@ -60,6 +63,12 @@
bool kEnableRpcDevServers = false;
#endif
+#ifdef BINDER_ENABLE_RECORDING
+bool kEnableRecording = true;
+#else
+bool kEnableRecording = false;
+#endif
+
// Log any reply transactions for which the data exceeds this size
#define LOG_REPLIES_OVER_SIZE (300 * 1024)
// ---------------------------------------------------------------------------
@@ -265,11 +274,13 @@
Mutex mLock;
std::set<sp<RpcServerLink>> mRpcServerLinks;
BpBinder::ObjectManager mObjects;
+
+ android::base::unique_fd mRecordingFd;
};
// ---------------------------------------------------------------------------
-BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false) {}
+BBinder::BBinder() : mExtras(nullptr), mStability(0), mParceled(false), mRecordingOn(false) {}
bool BBinder::isBinderAlive() const
{
@@ -281,6 +292,63 @@
return NO_ERROR;
}
+status_t BBinder::startRecordingTransactions(const Parcel& data) {
+ if (!kEnableRecording) {
+ ALOGW("Binder recording disallowed because recording is not enabled");
+ return INVALID_OPERATION;
+ }
+ if (!kEnableKernelIpc) {
+ ALOGW("Binder recording disallowed because kernel binder is not enabled");
+ return INVALID_OPERATION;
+ }
+ uid_t uid = IPCThreadState::self()->getCallingUid();
+ if (uid != AID_ROOT) {
+ ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
+ return PERMISSION_DENIED;
+ }
+ Extras* e = getOrCreateExtras();
+ AutoMutex lock(e->mLock);
+ if (mRecordingOn) {
+ LOG(INFO) << "Could not start Binder recording. Another is already in progress.";
+ return INVALID_OPERATION;
+ } else {
+ status_t readStatus = data.readUniqueFileDescriptor(&(e->mRecordingFd));
+ if (readStatus != OK) {
+ return readStatus;
+ }
+ mRecordingOn = true;
+ LOG(INFO) << "Started Binder recording.";
+ return NO_ERROR;
+ }
+}
+
+status_t BBinder::stopRecordingTransactions() {
+ if (!kEnableRecording) {
+ ALOGW("Binder recording disallowed because recording is not enabled");
+ return INVALID_OPERATION;
+ }
+ if (!kEnableKernelIpc) {
+ ALOGW("Binder recording disallowed because kernel binder is not enabled");
+ return INVALID_OPERATION;
+ }
+ uid_t uid = IPCThreadState::self()->getCallingUid();
+ if (uid != AID_ROOT) {
+ ALOGE("Binder recording not allowed because client %" PRIu32 " is not root", uid);
+ return PERMISSION_DENIED;
+ }
+ Extras* e = getOrCreateExtras();
+ AutoMutex lock(e->mLock);
+ if (mRecordingOn) {
+ e->mRecordingFd.reset();
+ mRecordingOn = false;
+ LOG(INFO) << "Stopped Binder recording.";
+ return NO_ERROR;
+ } else {
+ LOG(INFO) << "Could not stop Binder recording. One is not in progress.";
+ return INVALID_OPERATION;
+ }
+}
+
const String16& BBinder::getInterfaceDescriptor() const
{
static StaticString16 sBBinder(u"BBinder");
@@ -303,6 +371,12 @@
case PING_TRANSACTION:
err = pingBinder();
break;
+ case START_RECORDING_TRANSACTION:
+ err = startRecordingTransactions(data);
+ break;
+ case STOP_RECORDING_TRANSACTION:
+ err = stopRecordingTransactions();
+ break;
case EXTENSION_TRANSACTION:
CHECK(reply != nullptr);
err = reply->writeStrongBinder(getExtension());
@@ -329,6 +403,26 @@
}
}
+ if (CC_UNLIKELY(kEnableKernelIpc && mRecordingOn && code != START_RECORDING_TRANSACTION)) {
+ Extras* e = mExtras.load(std::memory_order_acquire);
+ AutoMutex lock(e->mLock);
+ if (mRecordingOn) {
+ Parcel emptyReply;
+ auto transaction =
+ android::binder::debug::RecordedTransaction::fromDetails(code, flags, data,
+ reply ? *reply
+ : emptyReply,
+ err);
+ if (transaction) {
+ if (status_t err = transaction->dumpToFile(e->mRecordingFd); err != NO_ERROR) {
+ LOG(INFO) << "Failed to dump RecordedTransaction to file with error " << err;
+ }
+ } else {
+ LOG(INFO) << "Failed to create RecordedTransaction object.";
+ }
+ }
+ }
+
return err;
}
diff --git a/libs/binder/BinderRecordReplay.cpp b/libs/binder/BinderRecordReplay.cpp
new file mode 100644
index 0000000..90c02a8
--- /dev/null
+++ b/libs/binder/BinderRecordReplay.cpp
@@ -0,0 +1,185 @@
+/*
+ * Copyright (C) 2022, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android-base/file.h>
+#include <android-base/logging.h>
+#include <binder/BinderRecordReplay.h>
+#include <algorithm>
+
+using android::Parcel;
+using android::base::unique_fd;
+using android::binder::debug::RecordedTransaction;
+
+#define PADDING8(s) ((8 - (s) % 8) % 8)
+
+static_assert(PADDING8(0) == 0);
+static_assert(PADDING8(1) == 7);
+static_assert(PADDING8(7) == 1);
+static_assert(PADDING8(8) == 0);
+
+// Transactions are sequentially recorded to the file descriptor in the following format:
+//
+// RecordedTransaction.TransactionHeader (32 bytes)
+// Sent Parcel data (getDataSize() bytes)
+// padding (enough bytes to align the reply Parcel data to 8 bytes)
+// Reply Parcel data (getReplySize() bytes)
+// padding (enough bytes to align the next header to 8 bytes)
+// [repeats with next transaction]
+//
+// Warning: This format is non-stable
+
+RecordedTransaction::RecordedTransaction(RecordedTransaction&& t) noexcept {
+ mHeader = {t.getCode(), t.getFlags(), t.getDataSize(),
+ t.getReplySize(), t.getReturnedStatus(), t.getVersion()};
+ mSent.setData(t.getDataParcel().data(), t.getDataSize());
+ mReply.setData(t.getReplyParcel().data(), t.getReplySize());
+}
+
+std::optional<RecordedTransaction> RecordedTransaction::fromDetails(uint32_t code, uint32_t flags,
+ const Parcel& dataParcel,
+ const Parcel& replyParcel,
+ status_t err) {
+ RecordedTransaction t;
+ t.mHeader = {code,
+ flags,
+ static_cast<uint64_t>(dataParcel.dataSize()),
+ static_cast<uint64_t>(replyParcel.dataSize()),
+ static_cast<int32_t>(err),
+ dataParcel.isForRpc() ? static_cast<uint32_t>(1) : static_cast<uint32_t>(0)};
+
+ if (t.mSent.setData(dataParcel.data(), t.getDataSize()) != android::NO_ERROR) {
+ LOG(INFO) << "Failed to set sent parcel data.";
+ return std::nullopt;
+ }
+
+ if (t.mReply.setData(replyParcel.data(), t.getReplySize()) != android::NO_ERROR) {
+ LOG(INFO) << "Failed to set reply parcel data.";
+ return std::nullopt;
+ }
+
+ return std::optional<RecordedTransaction>(std::move(t));
+}
+
+std::optional<RecordedTransaction> RecordedTransaction::fromFile(const unique_fd& fd) {
+ RecordedTransaction t;
+ if (!android::base::ReadFully(fd, &t.mHeader, sizeof(mHeader))) {
+ LOG(INFO) << "Failed to read transactionHeader from fd " << fd.get();
+ return std::nullopt;
+ }
+ if (t.getVersion() != 0) {
+ LOG(INFO) << "File corrupted: transaction version is not 0.";
+ return std::nullopt;
+ }
+
+ std::vector<uint8_t> bytes;
+ bytes.resize(t.getDataSize());
+ if (!android::base::ReadFully(fd, bytes.data(), t.getDataSize())) {
+ LOG(INFO) << "Failed to read sent parcel data from fd " << fd.get();
+ return std::nullopt;
+ }
+ if (t.mSent.setData(bytes.data(), t.getDataSize()) != android::NO_ERROR) {
+ LOG(INFO) << "Failed to set sent parcel data.";
+ return std::nullopt;
+ }
+
+ uint8_t padding[7];
+ if (!android::base::ReadFully(fd, padding, PADDING8(t.getDataSize()))) {
+ LOG(INFO) << "Failed to read sent parcel padding from fd " << fd.get();
+ return std::nullopt;
+ }
+ if (std::any_of(padding, padding + 7, [](uint8_t i) { return i != 0; })) {
+ LOG(INFO) << "File corrupted: padding isn't 0.";
+ return std::nullopt;
+ }
+
+ bytes.resize(t.getReplySize());
+ if (!android::base::ReadFully(fd, bytes.data(), t.getReplySize())) {
+ LOG(INFO) << "Failed to read reply parcel data from fd " << fd.get();
+ return std::nullopt;
+ }
+ if (t.mReply.setData(bytes.data(), t.getReplySize()) != android::NO_ERROR) {
+ LOG(INFO) << "Failed to set reply parcel data.";
+ return std::nullopt;
+ }
+
+ if (!android::base::ReadFully(fd, padding, PADDING8(t.getReplySize()))) {
+ LOG(INFO) << "Failed to read parcel padding from fd " << fd.get();
+ return std::nullopt;
+ }
+ if (std::any_of(padding, padding + 7, [](uint8_t i) { return i != 0; })) {
+ LOG(INFO) << "File corrupted: padding isn't 0.";
+ return std::nullopt;
+ }
+
+ return std::optional<RecordedTransaction>(std::move(t));
+}
+
+android::status_t RecordedTransaction::dumpToFile(const unique_fd& fd) const {
+ if (!android::base::WriteFully(fd, &mHeader, sizeof(mHeader))) {
+ LOG(INFO) << "Failed to write transactionHeader to fd " << fd.get();
+ return UNKNOWN_ERROR;
+ }
+ if (!android::base::WriteFully(fd, mSent.data(), getDataSize())) {
+ LOG(INFO) << "Failed to write sent parcel data to fd " << fd.get();
+ return UNKNOWN_ERROR;
+ }
+ const uint8_t zeros[7] = {0};
+ if (!android::base::WriteFully(fd, zeros, PADDING8(getDataSize()))) {
+ LOG(INFO) << "Failed to write sent parcel padding to fd " << fd.get();
+ return UNKNOWN_ERROR;
+ }
+ if (!android::base::WriteFully(fd, mReply.data(), getReplySize())) {
+ LOG(INFO) << "Failed to write reply parcel data to fd " << fd.get();
+ return UNKNOWN_ERROR;
+ }
+ if (!android::base::WriteFully(fd, zeros, PADDING8(getReplySize()))) {
+ LOG(INFO) << "Failed to write reply parcel padding to fd " << fd.get();
+ return UNKNOWN_ERROR;
+ }
+ return NO_ERROR;
+}
+
+uint32_t RecordedTransaction::getCode() const {
+ return mHeader.code;
+}
+
+uint32_t RecordedTransaction::getFlags() const {
+ return mHeader.flags;
+}
+
+uint64_t RecordedTransaction::getDataSize() const {
+ return mHeader.dataSize;
+}
+
+uint64_t RecordedTransaction::getReplySize() const {
+ return mHeader.replySize;
+}
+
+int32_t RecordedTransaction::getReturnedStatus() const {
+ return mHeader.statusReturned;
+}
+
+uint32_t RecordedTransaction::getVersion() const {
+ return mHeader.version;
+}
+
+const Parcel& RecordedTransaction::getDataParcel() const {
+ return mSent;
+}
+
+const Parcel& RecordedTransaction::getReplyParcel() const {
+ return mReply;
+}
diff --git a/libs/binder/BpBinder.cpp b/libs/binder/BpBinder.cpp
index d9b7231..54d2445 100644
--- a/libs/binder/BpBinder.cpp
+++ b/libs/binder/BpBinder.cpp
@@ -30,6 +30,8 @@
#include "BuildFlags.h"
+#include <android-base/file.h>
+
//#undef ALOGV
//#define ALOGV(...) fprintf(stderr, __VA_ARGS__)
@@ -299,6 +301,18 @@
return transact(PING_TRANSACTION, data, &reply);
}
+status_t BpBinder::startRecordingBinder(const android::base::unique_fd& fd) {
+ Parcel send, reply;
+ send.writeUniqueFileDescriptor(fd);
+ return transact(START_RECORDING_TRANSACTION, send, &reply);
+}
+
+status_t BpBinder::stopRecordingBinder() {
+ Parcel data, reply;
+ data.markForBinder(sp<BpBinder>::fromExisting(this));
+ return transact(STOP_RECORDING_TRANSACTION, data, &reply);
+}
+
status_t BpBinder::dump(int fd, const Vector<String16>& args)
{
Parcel send;
diff --git a/libs/binder/FdTrigger.cpp b/libs/binder/FdTrigger.cpp
index d123fd1..8ee6cb0 100644
--- a/libs/binder/FdTrigger.cpp
+++ b/libs/binder/FdTrigger.cpp
@@ -22,6 +22,7 @@
#include <poll.h>
#include <android-base/macros.h>
+#include <android-base/scopeguard.h>
#include "RpcState.h"
namespace android {
@@ -53,25 +54,34 @@
#endif
}
-status_t FdTrigger::triggerablePoll(base::borrowed_fd fd, int16_t event) {
+status_t FdTrigger::triggerablePoll(const android::RpcTransportFd& transportFd, int16_t event) {
#ifdef BINDER_RPC_SINGLE_THREADED
if (mTriggered) {
return DEAD_OBJECT;
}
#endif
- LOG_ALWAYS_FATAL_IF(event == 0, "triggerablePoll %d with event 0 is not allowed", fd.get());
+ LOG_ALWAYS_FATAL_IF(event == 0, "triggerablePoll %d with event 0 is not allowed",
+ transportFd.fd.get());
pollfd pfd[]{
- {.fd = fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
+ {.fd = transportFd.fd.get(), .events = static_cast<int16_t>(event), .revents = 0},
#ifndef BINDER_RPC_SINGLE_THREADED
{.fd = mRead.get(), .events = 0, .revents = 0},
#endif
};
+
+ LOG_ALWAYS_FATAL_IF(transportFd.isInPollingState() == true,
+ "Only one thread should be polling on Fd!");
+
+ transportFd.setPollingState(true);
+ auto pollingStateGuard =
+ android::base::make_scope_guard([&]() { transportFd.setPollingState(false); });
+
int ret = TEMP_FAILURE_RETRY(poll(pfd, arraysize(pfd), -1));
if (ret < 0) {
return -errno;
}
- LOG_ALWAYS_FATAL_IF(ret == 0, "poll(%d) returns 0 with infinite timeout", fd.get());
+ LOG_ALWAYS_FATAL_IF(ret == 0, "poll(%d) returns 0 with infinite timeout", transportFd.fd.get());
// At least one FD has events. Check them.
diff --git a/libs/binder/FdTrigger.h b/libs/binder/FdTrigger.h
index a25dc11..5fbf290 100644
--- a/libs/binder/FdTrigger.h
+++ b/libs/binder/FdTrigger.h
@@ -21,6 +21,8 @@
#include <android-base/unique_fd.h>
#include <utils/Errors.h>
+#include <binder/RpcTransport.h>
+
namespace android {
/** This is not a pipe. */
@@ -53,7 +55,8 @@
* true - time to read!
* false - trigger happened
*/
- [[nodiscard]] status_t triggerablePoll(base::borrowed_fd fd, int16_t event);
+ [[nodiscard]] status_t triggerablePoll(const android::RpcTransportFd& transportFd,
+ int16_t event);
private:
#ifdef BINDER_RPC_SINGLE_THREADED
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index b50cfb3..bfcf39a 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -1318,6 +1318,13 @@
LOG_ONEWAY("Sending reply to %d!", mCallingPid);
if (error < NO_ERROR) reply.setError(error);
+ // b/238777741: clear buffer before we send the reply.
+ // Otherwise, there is a race where the client may
+ // receive the reply and send another transaction
+ // here and the space used by this transaction won't
+ // be freed for the client.
+ buffer.setDataSize(0);
+
constexpr uint32_t kForwardReplyFlags = TF_CLEAR_BUF;
sendReply(reply, (tr.flags & kForwardReplyFlags));
} else {
diff --git a/libs/binder/IServiceManager.cpp b/libs/binder/IServiceManager.cpp
index c0a8d74..5db3eef 100644
--- a/libs/binder/IServiceManager.cpp
+++ b/libs/binder/IServiceManager.cpp
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#define LOG_TAG "ServiceManager"
+#define LOG_TAG "ServiceManagerCppClient"
#include <binder/IServiceManager.h>
diff --git a/libs/binder/OS.cpp b/libs/binder/OS.cpp
index cc4a03b..24ce2bb 100644
--- a/libs/binder/OS.cpp
+++ b/libs/binder/OS.cpp
@@ -17,6 +17,7 @@
#include "OS.h"
#include <android-base/file.h>
+#include <binder/RpcTransportRaw.h>
#include <string.h>
using android::base::ErrnoError;
@@ -58,4 +59,8 @@
return OK;
}
+std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory() {
+ return RpcTransportCtxFactoryRaw::make();
+}
+
} // namespace android
diff --git a/libs/binder/OS.h b/libs/binder/OS.h
index d6e1c78..5ab8bab 100644
--- a/libs/binder/OS.h
+++ b/libs/binder/OS.h
@@ -20,6 +20,7 @@
#include <android-base/result.h>
#include <android-base/unique_fd.h>
+#include <binder/RpcTransport.h>
#include <utils/Errors.h>
namespace android {
@@ -30,4 +31,6 @@
status_t dupFileDescriptor(int oldFd, int* newFd);
+std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory();
+
} // namespace android
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index 49be4dd..e581d0b 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -55,7 +55,7 @@
sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
// Default is without TLS.
if (rpcTransportCtxFactory == nullptr)
- rpcTransportCtxFactory = RpcTransportCtxFactoryRaw::make();
+ rpcTransportCtxFactory = makeDefaultRpcTransportCtxFactory();
auto ctx = rpcTransportCtxFactory->newServerCtx();
if (ctx == nullptr) return nullptr;
return sp<RpcServer>::make(std::move(ctx));
@@ -86,7 +86,7 @@
LOG_ALWAYS_FATAL_IF(socketAddress.addr()->sa_family != AF_INET, "expecting inet");
sockaddr_in addr{};
socklen_t len = sizeof(addr);
- if (0 != getsockname(mServer.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
+ if (0 != getsockname(mServer.fd.get(), reinterpret_cast<sockaddr*>(&addr), &len)) {
int savedErrno = errno;
ALOGE("Could not getsockname at %s: %s", socketAddress.toString().c_str(),
strerror(savedErrno));
@@ -181,7 +181,7 @@
{
RpcMutexLockGuard _l(mLock);
- LOG_ALWAYS_FATAL_IF(!mServer.ok(), "RpcServer must be setup to join.");
+ LOG_ALWAYS_FATAL_IF(!mServer.fd.ok(), "RpcServer must be setup to join.");
LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
mJoinThreadRunning = true;
mShutdownTrigger = FdTrigger::make();
@@ -194,24 +194,24 @@
static_assert(addr.size() >= sizeof(sockaddr_storage), "kRpcAddressSize is too small");
socklen_t addrLen = addr.size();
- unique_fd clientFd(
- TEMP_FAILURE_RETRY(accept4(mServer.get(), reinterpret_cast<sockaddr*>(addr.data()),
- &addrLen, SOCK_CLOEXEC | SOCK_NONBLOCK)));
+ RpcTransportFd clientSocket(unique_fd(TEMP_FAILURE_RETRY(
+ accept4(mServer.fd.get(), reinterpret_cast<sockaddr*>(addr.data()), &addrLen,
+ SOCK_CLOEXEC | SOCK_NONBLOCK))));
LOG_ALWAYS_FATAL_IF(addrLen > static_cast<socklen_t>(sizeof(sockaddr_storage)),
"Truncated address");
- if (clientFd < 0) {
+ if (clientSocket.fd < 0) {
ALOGE("Could not accept4 socket: %s", strerror(errno));
continue;
}
- LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.get(), clientFd.get());
+ LOG_RPC_DETAIL("accept4 on fd %d yields fd %d", mServer.fd.get(), clientSocket.fd.get());
{
RpcMutexLockGuard _l(mLock);
RpcMaybeThread thread =
RpcMaybeThread(&RpcServer::establishConnection,
- sp<RpcServer>::fromExisting(this), std::move(clientFd), addr,
+ sp<RpcServer>::fromExisting(this), std::move(clientSocket), addr,
addrLen, RpcSession::join);
auto& threadRef = mConnectingThreads[thread.get_id()];
@@ -296,7 +296,7 @@
}
void RpcServer::establishConnection(
- sp<RpcServer>&& server, base::unique_fd clientFd, std::array<uint8_t, kRpcAddressSize> addr,
+ sp<RpcServer>&& server, RpcTransportFd clientFd, std::array<uint8_t, kRpcAddressSize> addr,
size_t addrLen,
std::function<void(sp<RpcSession>&&, RpcSession::PreJoinSetupResult&&)>&& joinFn) {
// mShutdownTrigger can only be cleared once connection threads have joined.
@@ -306,7 +306,7 @@
status_t status = OK;
- int clientFdForLog = clientFd.get();
+ int clientFdForLog = clientFd.fd.get();
auto client = server->mCtx->newTransport(std::move(clientFd), server->mShutdownTrigger.get());
if (client == nullptr) {
ALOGE("Dropping accept4()-ed socket because sslAccept fails");
@@ -488,15 +488,15 @@
LOG_RPC_DETAIL("Setting up socket server %s", addr.toString().c_str());
LOG_ALWAYS_FATAL_IF(hasServer(), "Each RpcServer can only have one server.");
- unique_fd serverFd(TEMP_FAILURE_RETRY(
- socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0)));
- if (serverFd == -1) {
+ RpcTransportFd transportFd(unique_fd(TEMP_FAILURE_RETRY(
+ socket(addr.addr()->sa_family, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0))));
+ if (!transportFd.fd.ok()) {
int savedErrno = errno;
ALOGE("Could not create socket: %s", strerror(savedErrno));
return -savedErrno;
}
- if (0 != TEMP_FAILURE_RETRY(bind(serverFd.get(), addr.addr(), addr.addrSize()))) {
+ if (0 != TEMP_FAILURE_RETRY(bind(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
int savedErrno = errno;
ALOGE("Could not bind socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
return -savedErrno;
@@ -506,7 +506,7 @@
// the backlog is increased to a large number.
// TODO(b/189955605): Once we create threads dynamically & lazily, the backlog can be reduced
// to 1.
- if (0 != TEMP_FAILURE_RETRY(listen(serverFd.get(), 50 /*backlog*/))) {
+ if (0 != TEMP_FAILURE_RETRY(listen(transportFd.fd.get(), 50 /*backlog*/))) {
int savedErrno = errno;
ALOGE("Could not listen socket at %s: %s", addr.toString().c_str(), strerror(savedErrno));
return -savedErrno;
@@ -514,7 +514,7 @@
LOG_RPC_DETAIL("Successfully setup socket server %s", addr.toString().c_str());
- if (status_t status = setupExternalServer(std::move(serverFd)); status != OK) {
+ if (status_t status = setupExternalServer(std::move(transportFd.fd)); status != OK) {
ALOGE("Another thread has set up server while calling setupSocketServer. Race?");
return status;
}
@@ -542,17 +542,17 @@
bool RpcServer::hasServer() {
RpcMutexLockGuard _l(mLock);
- return mServer.ok();
+ return mServer.fd.ok();
}
unique_fd RpcServer::releaseServer() {
RpcMutexLockGuard _l(mLock);
- return std::move(mServer);
+ return std::move(mServer.fd);
}
status_t RpcServer::setupExternalServer(base::unique_fd serverFd) {
RpcMutexLockGuard _l(mLock);
- if (mServer.ok()) {
+ if (mServer.fd.ok()) {
ALOGE("Each RpcServer can only have one server.");
return INVALID_OPERATION;
}
@@ -560,4 +560,14 @@
return OK;
}
+bool RpcServer::hasActiveRequests() {
+ RpcMutexLockGuard _l(mLock);
+ for (const auto& [_, session] : mSessions) {
+ if (session->hasActiveRequests()) {
+ return true;
+ }
+ }
+ return !mServer.isInPollingState();
+}
+
} // namespace android
diff --git a/libs/binder/RpcSession.cpp b/libs/binder/RpcSession.cpp
index 8ddfa93..49843e5 100644
--- a/libs/binder/RpcSession.cpp
+++ b/libs/binder/RpcSession.cpp
@@ -68,7 +68,7 @@
sp<RpcSession> RpcSession::make() {
// Default is without TLS.
- return make(RpcTransportCtxFactoryRaw::make());
+ return make(makeDefaultRpcTransportCtxFactory());
}
sp<RpcSession> RpcSession::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
@@ -162,7 +162,8 @@
return NAME_NOT_FOUND;
}
-status_t RpcSession::setupPreconnectedClient(unique_fd fd, std::function<unique_fd()>&& request) {
+status_t RpcSession::setupPreconnectedClient(base::unique_fd fd,
+ std::function<unique_fd()>&& request) {
return setupClient([&](const std::vector<uint8_t>& sessionId, bool incoming) -> status_t {
if (!fd.ok()) {
fd = request();
@@ -172,7 +173,9 @@
ALOGE("setupPreconnectedClient: %s", res.error().message().c_str());
return res.error().code() == 0 ? UNKNOWN_ERROR : -res.error().code();
}
- status_t status = initAndAddConnection(std::move(fd), sessionId, incoming);
+
+ RpcTransportFd transportFd(std::move(fd));
+ status_t status = initAndAddConnection(std::move(transportFd), sessionId, incoming);
fd = unique_fd(); // Explicitly reset after move to avoid analyzer warning.
return status;
});
@@ -190,7 +193,8 @@
return -savedErrno;
}
- auto server = mCtx->newTransport(std::move(serverFd), mShutdownTrigger.get());
+ RpcTransportFd transportFd(std::move(serverFd));
+ auto server = mCtx->newTransport(std::move(transportFd), mShutdownTrigger.get());
if (server == nullptr) {
ALOGE("Unable to set up RpcTransport");
return UNKNOWN_ERROR;
@@ -572,12 +576,14 @@
return -savedErrno;
}
- if (0 != TEMP_FAILURE_RETRY(connect(serverFd.get(), addr.addr(), addr.addrSize()))) {
+ RpcTransportFd transportFd(std::move(serverFd));
+
+ if (0 != TEMP_FAILURE_RETRY(connect(transportFd.fd.get(), addr.addr(), addr.addrSize()))) {
int connErrno = errno;
if (connErrno == EAGAIN || connErrno == EINPROGRESS) {
// For non-blocking sockets, connect() may return EAGAIN (for unix domain socket) or
// EINPROGRESS (for others). Call poll() and getsockopt() to get the error.
- status_t pollStatus = mShutdownTrigger->triggerablePoll(serverFd, POLLOUT);
+ status_t pollStatus = mShutdownTrigger->triggerablePoll(transportFd, POLLOUT);
if (pollStatus != OK) {
ALOGE("Could not POLLOUT after connect() on non-blocking socket: %s",
statusToString(pollStatus).c_str());
@@ -585,8 +591,8 @@
}
// Set connErrno to the errno that connect() would have set if the fd were blocking.
socklen_t connErrnoLen = sizeof(connErrno);
- int ret =
- getsockopt(serverFd.get(), SOL_SOCKET, SO_ERROR, &connErrno, &connErrnoLen);
+ int ret = getsockopt(transportFd.fd.get(), SOL_SOCKET, SO_ERROR, &connErrno,
+ &connErrnoLen);
if (ret == -1) {
int savedErrno = errno;
ALOGE("Could not getsockopt() after connect() on non-blocking socket: %s. "
@@ -608,16 +614,17 @@
return -connErrno;
}
}
- LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(), serverFd.get());
+ LOG_RPC_DETAIL("Socket at %s client with fd %d", addr.toString().c_str(),
+ transportFd.fd.get());
- return initAndAddConnection(std::move(serverFd), sessionId, incoming);
+ return initAndAddConnection(std::move(transportFd), sessionId, incoming);
}
ALOGE("Ran out of retries to connect to %s", addr.toString().c_str());
return UNKNOWN_ERROR;
}
-status_t RpcSession::initAndAddConnection(unique_fd fd, const std::vector<uint8_t>& sessionId,
+status_t RpcSession::initAndAddConnection(RpcTransportFd fd, const std::vector<uint8_t>& sessionId,
bool incoming) {
LOG_ALWAYS_FATAL_IF(mShutdownTrigger == nullptr);
auto server = mCtx->newTransport(std::move(fd), mShutdownTrigger.get());
@@ -945,4 +952,24 @@
}
}
+bool RpcSession::hasActiveConnection(const std::vector<sp<RpcConnection>>& connections) {
+ for (const auto& connection : connections) {
+ if (connection->exclusiveTid != std::nullopt && !connection->rpcTransport->isWaiting()) {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool RpcSession::hasActiveRequests() {
+ RpcMutexUniqueLock _l(mMutex);
+ if (hasActiveConnection(mConnections.mIncoming)) {
+ return true;
+ }
+ if (hasActiveConnection(mConnections.mOutgoing)) {
+ return true;
+ }
+ return mConnections.mWaitingThreads != 0;
+}
+
} // namespace android
diff --git a/libs/binder/RpcTransportRaw.cpp b/libs/binder/RpcTransportRaw.cpp
index 51326f6..65e8fac 100644
--- a/libs/binder/RpcTransportRaw.cpp
+++ b/libs/binder/RpcTransportRaw.cpp
@@ -36,11 +36,11 @@
// RpcTransport with TLS disabled.
class RpcTransportRaw : public RpcTransport {
public:
- explicit RpcTransportRaw(android::base::unique_fd socket) : mSocket(std::move(socket)) {}
+ explicit RpcTransportRaw(android::RpcTransportFd socket) : mSocket(std::move(socket)) {}
status_t pollRead(void) override {
uint8_t buf;
ssize_t ret = TEMP_FAILURE_RETRY(
- ::recv(mSocket.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT));
+ ::recv(mSocket.fd.get(), &buf, sizeof(buf), MSG_PEEK | MSG_DONTWAIT));
if (ret < 0) {
int savedErrno = errno;
if (savedErrno == EAGAIN || savedErrno == EWOULDBLOCK) {
@@ -100,7 +100,7 @@
msg.msg_controllen = CMSG_SPACE(fdsByteSize);
ssize_t processedSize = TEMP_FAILURE_RETRY(
- sendmsg(mSocket.get(), &msg, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC));
+ sendmsg(mSocket.fd.get(), &msg, MSG_NOSIGNAL | MSG_CMSG_CLOEXEC));
if (processedSize > 0) {
sentFds = true;
}
@@ -113,10 +113,10 @@
// non-negative int and can be cast to either.
.msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
};
- return TEMP_FAILURE_RETRY(sendmsg(mSocket.get(), &msg, MSG_NOSIGNAL));
+ return TEMP_FAILURE_RETRY(sendmsg(mSocket.fd.get(), &msg, MSG_NOSIGNAL));
};
- return interruptableReadOrWrite(mSocket.get(), fdTrigger, iovs, niovs, send, "sendmsg",
- POLLOUT, altPoll);
+ return interruptableReadOrWrite(mSocket, fdTrigger, iovs, niovs, send, "sendmsg", POLLOUT,
+ altPoll);
}
status_t interruptableReadFully(
@@ -135,7 +135,7 @@
.msg_controllen = sizeof(msgControlBuf),
};
ssize_t processSize =
- TEMP_FAILURE_RETRY(recvmsg(mSocket.get(), &msg, MSG_NOSIGNAL));
+ TEMP_FAILURE_RETRY(recvmsg(mSocket.fd.get(), &msg, MSG_NOSIGNAL));
if (processSize < 0) {
return -1;
}
@@ -171,21 +171,23 @@
// non-negative int and can be cast to either.
.msg_iovlen = static_cast<decltype(msg.msg_iovlen)>(niovs),
};
- return TEMP_FAILURE_RETRY(recvmsg(mSocket.get(), &msg, MSG_NOSIGNAL));
+ return TEMP_FAILURE_RETRY(recvmsg(mSocket.fd.get(), &msg, MSG_NOSIGNAL));
};
- return interruptableReadOrWrite(mSocket.get(), fdTrigger, iovs, niovs, recv, "recvmsg",
- POLLIN, altPoll);
+ return interruptableReadOrWrite(mSocket, fdTrigger, iovs, niovs, recv, "recvmsg", POLLIN,
+ altPoll);
}
+ virtual bool isWaiting() { return mSocket.isInPollingState(); }
+
private:
- base::unique_fd mSocket;
+ android::RpcTransportFd mSocket;
};
// RpcTransportCtx with TLS disabled.
class RpcTransportCtxRaw : public RpcTransportCtx {
public:
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd, FdTrigger*) const {
- return std::make_unique<RpcTransportRaw>(std::move(fd));
+ std::unique_ptr<RpcTransport> newTransport(android::RpcTransportFd socket, FdTrigger*) const {
+ return std::make_unique<RpcTransportRaw>(std::move(socket));
}
std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override { return {}; }
};
diff --git a/libs/binder/RpcTransportTipcAndroid.cpp b/libs/binder/RpcTransportTipcAndroid.cpp
index c82201b..453279c 100644
--- a/libs/binder/RpcTransportTipcAndroid.cpp
+++ b/libs/binder/RpcTransportTipcAndroid.cpp
@@ -36,8 +36,7 @@
// RpcTransport for writing Trusty IPC clients in Android.
class RpcTransportTipcAndroid : public RpcTransport {
public:
- explicit RpcTransportTipcAndroid(android::base::unique_fd socket)
- : mSocket(std::move(socket)) {}
+ explicit RpcTransportTipcAndroid(android::RpcTransportFd socket) : mSocket(std::move(socket)) {}
status_t pollRead() override {
if (mReadBufferPos < mReadBufferSize) {
@@ -46,7 +45,7 @@
}
// Trusty IPC device is not a socket, so MSG_PEEK is not available
- pollfd pfd{.fd = mSocket.get(), .events = static_cast<int16_t>(POLLIN), .revents = 0};
+ pollfd pfd{.fd = mSocket.fd.get(), .events = static_cast<int16_t>(POLLIN), .revents = 0};
ssize_t ret = TEMP_FAILURE_RETRY(::poll(&pfd, 1, 0));
if (ret < 0) {
int savedErrno = errno;
@@ -84,9 +83,9 @@
// to send any.
LOG_ALWAYS_FATAL_IF(ancillaryFds != nullptr && !ancillaryFds->empty(),
"File descriptors are not supported on Trusty yet");
- return TEMP_FAILURE_RETRY(tipc_send(mSocket.get(), iovs, niovs, nullptr, 0));
+ return TEMP_FAILURE_RETRY(tipc_send(mSocket.fd.get(), iovs, niovs, nullptr, 0));
};
- return interruptableReadOrWrite(mSocket.get(), fdTrigger, iovs, niovs, writeFn, "tipc_send",
+ return interruptableReadOrWrite(mSocket, fdTrigger, iovs, niovs, writeFn, "tipc_send",
POLLOUT, altPoll);
}
@@ -120,10 +119,12 @@
return processSize;
};
- return interruptableReadOrWrite(mSocket.get(), fdTrigger, iovs, niovs, readFn, "read",
- POLLIN, altPoll);
+ return interruptableReadOrWrite(mSocket, fdTrigger, iovs, niovs, readFn, "read", POLLIN,
+ altPoll);
}
+ bool isWaiting() override { return mSocket.isInPollingState(); }
+
private:
status_t fillReadBuffer() {
if (mReadBufferPos < mReadBufferSize) {
@@ -146,8 +147,8 @@
mReadBufferSize = 0;
while (true) {
- ssize_t processSize =
- TEMP_FAILURE_RETRY(read(mSocket.get(), mReadBuffer.get(), mReadBufferCapacity));
+ ssize_t processSize = TEMP_FAILURE_RETRY(
+ read(mSocket.fd.get(), mReadBuffer.get(), mReadBufferCapacity));
if (processSize == 0) {
return DEAD_OBJECT;
} else if (processSize < 0) {
@@ -173,7 +174,7 @@
}
}
- base::unique_fd mSocket;
+ RpcTransportFd mSocket;
// For now, we copy all the input data into a temporary buffer because
// we might get multiple interruptableReadFully calls per message, but
@@ -192,7 +193,7 @@
// RpcTransportCtx for Trusty.
class RpcTransportCtxTipcAndroid : public RpcTransportCtx {
public:
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
+ std::unique_ptr<RpcTransport> newTransport(android::RpcTransportFd fd,
FdTrigger*) const override {
return std::make_unique<RpcTransportTipcAndroid>(std::move(fd));
}
diff --git a/libs/binder/RpcTransportTls.cpp b/libs/binder/RpcTransportTls.cpp
index 09b5c17..3e98ecc 100644
--- a/libs/binder/RpcTransportTls.cpp
+++ b/libs/binder/RpcTransportTls.cpp
@@ -182,8 +182,8 @@
// If |sslError| is WANT_READ / WANT_WRITE, poll for POLLIN / POLLOUT respectively. Otherwise
// return error. Also return error if |fdTrigger| is triggered before or during poll().
status_t pollForSslError(
- android::base::borrowed_fd fd, int sslError, FdTrigger* fdTrigger, const char* fnString,
- int additionalEvent,
+ const android::RpcTransportFd& fd, int sslError, FdTrigger* fdTrigger,
+ const char* fnString, int additionalEvent,
const std::optional<android::base::function_ref<status_t()>>& altPoll) {
switch (sslError) {
case SSL_ERROR_WANT_READ:
@@ -198,7 +198,7 @@
private:
bool mHandled = false;
- status_t handlePoll(int event, android::base::borrowed_fd fd, FdTrigger* fdTrigger,
+ status_t handlePoll(int event, const android::RpcTransportFd& fd, FdTrigger* fdTrigger,
const char* fnString,
const std::optional<android::base::function_ref<status_t()>>& altPoll) {
status_t ret;
@@ -277,7 +277,7 @@
class RpcTransportTls : public RpcTransport {
public:
- RpcTransportTls(android::base::unique_fd socket, Ssl ssl)
+ RpcTransportTls(RpcTransportFd socket, Ssl ssl)
: mSocket(std::move(socket)), mSsl(std::move(ssl)) {}
status_t pollRead(void) override;
status_t interruptableWriteFully(
@@ -290,8 +290,10 @@
const std::optional<android::base::function_ref<status_t()>>& altPoll,
std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) override;
+ bool isWaiting() { return mSocket.isInPollingState(); };
+
private:
- android::base::unique_fd mSocket;
+ android::RpcTransportFd mSocket;
Ssl mSsl;
};
@@ -350,7 +352,7 @@
int sslError = mSsl.getError(writeSize);
// TODO(b/195788248): BIO should contain the FdTrigger, and send(2) / recv(2) should be
// triggerablePoll()-ed. Then additionalEvent is no longer necessary.
- status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
+ status_t pollStatus = errorQueue.pollForSslError(mSocket, sslError, fdTrigger,
"SSL_write", POLLIN, altPoll);
if (pollStatus != OK) return pollStatus;
// Do not advance buffer. Try SSL_write() again.
@@ -398,7 +400,7 @@
return DEAD_OBJECT;
}
int sslError = mSsl.getError(readSize);
- status_t pollStatus = errorQueue.pollForSslError(mSocket.get(), sslError, fdTrigger,
+ status_t pollStatus = errorQueue.pollForSslError(mSocket, sslError, fdTrigger,
"SSL_read", 0, altPoll);
if (pollStatus != OK) return pollStatus;
// Do not advance buffer. Try SSL_read() again.
@@ -409,8 +411,8 @@
}
// For |ssl|, set internal FD to |fd|, and do handshake. Handshake is triggerable by |fdTrigger|.
-bool setFdAndDoHandshake(Ssl* ssl, android::base::borrowed_fd fd, FdTrigger* fdTrigger) {
- bssl::UniquePtr<BIO> bio = newSocketBio(fd);
+bool setFdAndDoHandshake(Ssl* ssl, const android::RpcTransportFd& socket, FdTrigger* fdTrigger) {
+ bssl::UniquePtr<BIO> bio = newSocketBio(socket.fd);
TEST_AND_RETURN(false, bio != nullptr);
auto [_, errorQueue] = ssl->call(SSL_set_bio, bio.get(), bio.get());
(void)bio.release(); // SSL_set_bio takes ownership.
@@ -430,7 +432,7 @@
return false;
}
int sslError = ssl->getError(ret);
- status_t pollStatus = errorQueue.pollForSslError(fd, sslError, fdTrigger,
+ status_t pollStatus = errorQueue.pollForSslError(socket, sslError, fdTrigger,
"SSL_do_handshake", 0, std::nullopt);
if (pollStatus != OK) return false;
}
@@ -442,7 +444,7 @@
typename = std::enable_if_t<std::is_base_of_v<RpcTransportCtxTls, Impl>>>
static std::unique_ptr<RpcTransportCtxTls> create(
std::shared_ptr<RpcCertificateVerifier> verifier, RpcAuth* auth);
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
+ std::unique_ptr<RpcTransport> newTransport(RpcTransportFd fd,
FdTrigger* fdTrigger) const override;
std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override;
@@ -513,15 +515,15 @@
return ret;
}
-std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::base::unique_fd fd,
+std::unique_ptr<RpcTransport> RpcTransportCtxTls::newTransport(android::RpcTransportFd socket,
FdTrigger* fdTrigger) const {
bssl::UniquePtr<SSL> ssl(SSL_new(mCtx.get()));
TEST_AND_RETURN(nullptr, ssl != nullptr);
Ssl wrapped(std::move(ssl));
preHandshake(&wrapped);
- TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, fd, fdTrigger));
- return std::make_unique<RpcTransportTls>(std::move(fd), std::move(wrapped));
+ TEST_AND_RETURN(nullptr, setFdAndDoHandshake(&wrapped, socket, fdTrigger));
+ return std::make_unique<RpcTransportTls>(std::move(socket), std::move(wrapped));
}
class RpcTransportCtxTlsServer : public RpcTransportCtxTls {
diff --git a/libs/binder/RpcTransportUtils.h b/libs/binder/RpcTransportUtils.h
index 00cb2af..32f0db8 100644
--- a/libs/binder/RpcTransportUtils.h
+++ b/libs/binder/RpcTransportUtils.h
@@ -25,8 +25,8 @@
template <typename SendOrReceive>
status_t interruptableReadOrWrite(
- int socketFd, FdTrigger* fdTrigger, iovec* iovs, int niovs, SendOrReceive sendOrReceiveFun,
- const char* funName, int16_t event,
+ const android::RpcTransportFd& socket, FdTrigger* fdTrigger, iovec* iovs, int niovs,
+ SendOrReceive sendOrReceiveFun, const char* funName, int16_t event,
const std::optional<android::base::function_ref<status_t()>>& altPoll) {
MAYBE_WAIT_IN_FLAKE_MODE;
@@ -99,7 +99,7 @@
return DEAD_OBJECT;
}
} else {
- if (status_t status = fdTrigger->triggerablePoll(socketFd, event); status != OK)
+ if (status_t status = fdTrigger->triggerablePoll(socket, event); status != OK)
return status;
if (!havePolled) havePolled = true;
}
diff --git a/libs/binder/Trace.cpp b/libs/binder/Trace.cpp
new file mode 100644
index 0000000..1ebfa1a
--- /dev/null
+++ b/libs/binder/Trace.cpp
@@ -0,0 +1,32 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <binder/Trace.h>
+#include <cutils/trace.h>
+
+namespace android {
+namespace binder {
+
+void atrace_begin(uint64_t tag, const char* name) {
+ ::atrace_begin(tag, name);
+}
+
+void atrace_end(uint64_t tag) {
+ ::atrace_end(tag);
+}
+
+} // namespace binder
+} // namespace android
diff --git a/libs/binder/include/binder/Binder.h b/libs/binder/include/binder/Binder.h
index 88d9ca1..08dbd13 100644
--- a/libs/binder/include/binder/Binder.h
+++ b/libs/binder/include/binder/Binder.h
@@ -105,6 +105,12 @@
[[nodiscard]] status_t setRpcClientDebug(android::base::unique_fd clientFd,
const sp<IBinder>& keepAliveBinder);
+ // Start recording transactions to the unique_fd in data.
+ // See BinderRecordReplay.h for more details.
+ [[nodiscard]] status_t startRecordingTransactions(const Parcel& data);
+ // Stop the current recording.
+ [[nodiscard]] status_t stopRecordingTransactions();
+
protected:
virtual ~BBinder();
@@ -131,7 +137,7 @@
friend ::android::internal::Stability;
int16_t mStability;
bool mParceled;
- uint8_t mReserved0;
+ bool mRecordingOn;
#ifdef __LP64__
int32_t mReserved1;
diff --git a/libs/binder/include/binder/BinderRecordReplay.h b/libs/binder/include/binder/BinderRecordReplay.h
new file mode 100644
index 0000000..25ed5e5
--- /dev/null
+++ b/libs/binder/include/binder/BinderRecordReplay.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2022, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android-base/unique_fd.h>
+#include <binder/Parcel.h>
+#include <mutex>
+
+namespace android {
+
+namespace binder::debug {
+
+// Warning: Transactions are sequentially recorded to the file descriptor in a
+// non-stable format. A detailed description of the recording format can be found in
+// BinderRecordReplay.cpp.
+
+class RecordedTransaction {
+public:
+ // Filled with the first transaction from fd.
+ static std::optional<RecordedTransaction> fromFile(const android::base::unique_fd& fd);
+ // Filled with the arguments.
+ static std::optional<RecordedTransaction> fromDetails(uint32_t code, uint32_t flags,
+ const Parcel& data, const Parcel& reply,
+ status_t err);
+ RecordedTransaction(RecordedTransaction&& t) noexcept;
+
+ [[nodiscard]] status_t dumpToFile(const android::base::unique_fd& fd) const;
+
+ uint32_t getCode() const;
+ uint32_t getFlags() const;
+ uint64_t getDataSize() const;
+ uint64_t getReplySize() const;
+ int32_t getReturnedStatus() const;
+ uint32_t getVersion() const;
+ const Parcel& getDataParcel() const;
+ const Parcel& getReplyParcel() const;
+
+private:
+ RecordedTransaction() = default;
+
+#pragma clang diagnostic push
+#pragma clang diagnostic error "-Wpadded"
+ struct TransactionHeader {
+ uint32_t code = 0;
+ uint32_t flags = 0;
+ uint64_t dataSize = 0;
+ uint64_t replySize = 0;
+ int32_t statusReturned = 0;
+ uint32_t version = 0; // !0 iff Rpc
+ };
+#pragma clang diagnostic pop
+ static_assert(sizeof(TransactionHeader) == 32);
+ static_assert(sizeof(TransactionHeader) % 8 == 0);
+
+ TransactionHeader mHeader;
+ Parcel mSent;
+ Parcel mReply;
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wunused-private-field"
+ uint8_t mReserved[40];
+#pragma clang diagnostic pop
+};
+
+} // namespace binder::debug
+
+} // namespace android
diff --git a/libs/binder/include/binder/BpBinder.h b/libs/binder/include/binder/BpBinder.h
index 4172cc5..57e103d 100644
--- a/libs/binder/include/binder/BpBinder.h
+++ b/libs/binder/include/binder/BpBinder.h
@@ -16,6 +16,7 @@
#pragma once
+#include <android-base/unique_fd.h>
#include <binder/IBinder.h>
#include <utils/Mutex.h>
@@ -89,6 +90,12 @@
std::optional<int32_t> getDebugBinderHandle() const;
+ // Start recording transactions to the unique_fd.
+ // See BinderRecordReplay.h for more details.
+ status_t startRecordingBinder(const android::base::unique_fd& fd);
+ // Stop the current recording.
+ status_t stopRecordingBinder();
+
class ObjectManager {
public:
ObjectManager();
diff --git a/libs/binder/include/binder/IBinder.h b/libs/binder/include/binder/IBinder.h
index 83aaca7..e75d548 100644
--- a/libs/binder/include/binder/IBinder.h
+++ b/libs/binder/include/binder/IBinder.h
@@ -56,6 +56,8 @@
LAST_CALL_TRANSACTION = 0x00ffffff,
PING_TRANSACTION = B_PACK_CHARS('_', 'P', 'N', 'G'),
+ START_RECORDING_TRANSACTION = B_PACK_CHARS('_', 'S', 'R', 'D'),
+ STOP_RECORDING_TRANSACTION = B_PACK_CHARS('_', 'E', 'R', 'D'),
DUMP_TRANSACTION = B_PACK_CHARS('_', 'D', 'M', 'P'),
SHELL_COMMAND_TRANSACTION = B_PACK_CHARS('_', 'C', 'M', 'D'),
INTERFACE_TRANSACTION = B_PACK_CHARS('_', 'N', 'T', 'F'),
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index 52bda0e..2c99334 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -187,6 +187,11 @@
std::vector<sp<RpcSession>> listSessions();
size_t numUninitializedSessions();
+ /**
+ * Whether any requests are currently being processed.
+ */
+ bool hasActiveRequests();
+
~RpcServer();
private:
@@ -199,7 +204,7 @@
static constexpr size_t kRpcAddressSize = 128;
static void establishConnection(
- sp<RpcServer>&& server, base::unique_fd clientFd,
+ sp<RpcServer>&& server, RpcTransportFd clientFd,
std::array<uint8_t, kRpcAddressSize> addr, size_t addrLen,
std::function<void(sp<RpcSession>&&, RpcSession::PreJoinSetupResult&&)>&& joinFn);
[[nodiscard]] status_t setupSocketServer(const RpcSocketAddress& address);
@@ -210,7 +215,7 @@
// A mode is supported if the N'th bit is on, where N is the mode enum's value.
std::bitset<8> mSupportedFileDescriptorTransportModes = std::bitset<8>().set(
static_cast<size_t>(RpcSession::FileDescriptorTransportMode::NONE));
- base::unique_fd mServer; // socket we are accepting sessions on
+ RpcTransportFd mServer; // socket we are accepting sessions on
RpcMutex mLock; // for below
std::unique_ptr<RpcMaybeThread> mJoinThread;
diff --git a/libs/binder/include/binder/RpcSession.h b/libs/binder/include/binder/RpcSession.h
index 428e272..a25ba98 100644
--- a/libs/binder/include/binder/RpcSession.h
+++ b/libs/binder/include/binder/RpcSession.h
@@ -189,6 +189,11 @@
*/
[[nodiscard]] status_t sendDecStrong(const BpBinder* binder);
+ /**
+ * Whether any requests are currently being processed.
+ */
+ bool hasActiveRequests();
+
~RpcSession();
/**
@@ -269,7 +274,7 @@
[[nodiscard]] status_t setupOneSocketConnection(const RpcSocketAddress& address,
const std::vector<uint8_t>& sessionId,
bool incoming);
- [[nodiscard]] status_t initAndAddConnection(base::unique_fd fd,
+ [[nodiscard]] status_t initAndAddConnection(RpcTransportFd fd,
const std::vector<uint8_t>& sessionId,
bool incoming);
[[nodiscard]] status_t addIncomingConnection(std::unique_ptr<RpcTransport> rpcTransport);
@@ -286,6 +291,11 @@
[[nodiscard]] status_t initShutdownTrigger();
+ /**
+ * Checks whether any connection is active (Not polling on fd)
+ */
+ bool hasActiveConnection(const std::vector<sp<RpcConnection>>& connections);
+
enum class ConnectionUse {
CLIENT,
CLIENT_ASYNC,
diff --git a/libs/binder/include/binder/RpcTransport.h b/libs/binder/include/binder/RpcTransport.h
index 5197ef9..fd52a3a 100644
--- a/libs/binder/include/binder/RpcTransport.h
+++ b/libs/binder/include/binder/RpcTransport.h
@@ -30,12 +30,14 @@
#include <utils/Errors.h>
#include <binder/RpcCertificateFormat.h>
+#include <binder/RpcThreads.h>
#include <sys/uio.h>
namespace android {
class FdTrigger;
+struct RpcTransportFd;
// Represents a socket connection.
// No thread-safety is guaranteed for these APIs.
@@ -81,6 +83,15 @@
const std::optional<android::base::function_ref<status_t()>> &altPoll,
std::vector<std::variant<base::unique_fd, base::borrowed_fd>> *ancillaryFds) = 0;
+ /**
+ * Check whether any threads are blocked while polling the transport
+ * for read operations
+ * Return:
+ * True - Specifies that there is active polling on transport.
+ * False - No active polling on transport
+ */
+ [[nodiscard]] virtual bool isWaiting() = 0;
+
protected:
RpcTransport() = default;
};
@@ -96,7 +107,7 @@
// Implementation details: for TLS, this function may incur I/O. |fdTrigger| may be used
// to interrupt I/O. This function blocks until handshake is finished.
[[nodiscard]] virtual std::unique_ptr<RpcTransport> newTransport(
- android::base::unique_fd fd, FdTrigger *fdTrigger) const = 0;
+ android::RpcTransportFd fd, FdTrigger *fdTrigger) const = 0;
// Return the preconfigured certificate of this context.
//
@@ -129,4 +140,36 @@
RpcTransportCtxFactory() = default;
};
+struct RpcTransportFd {
+private:
+ mutable bool isPolling{false};
+
+ void setPollingState(bool state) const { isPolling = state; }
+
+public:
+ base::unique_fd fd;
+
+ RpcTransportFd() = default;
+ explicit RpcTransportFd(base::unique_fd &&descriptor)
+ : isPolling(false), fd(std::move(descriptor)) {}
+
+ RpcTransportFd(RpcTransportFd &&transportFd) noexcept
+ : isPolling(transportFd.isPolling), fd(std::move(transportFd.fd)) {}
+
+ RpcTransportFd &operator=(RpcTransportFd &&transportFd) noexcept {
+ fd = std::move(transportFd.fd);
+ isPolling = transportFd.isPolling;
+ return *this;
+ }
+
+ RpcTransportFd &operator=(base::unique_fd &&descriptor) noexcept {
+ fd = std::move(descriptor);
+ isPolling = false;
+ return *this;
+ }
+
+ bool isInPollingState() const { return isPolling; }
+ friend class FdTrigger;
+};
+
} // namespace android
diff --git a/libs/binder/include/binder/Trace.h b/libs/binder/include/binder/Trace.h
new file mode 100644
index 0000000..9937842
--- /dev/null
+++ b/libs/binder/include/binder/Trace.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <cutils/trace.h>
+#include <stdint.h>
+
+namespace android {
+namespace binder {
+
+// Trampoline functions allowing generated aidls to trace binder transactions without depending on
+// libcutils/libutils
+void atrace_begin(uint64_t tag, const char* name);
+void atrace_end(uint64_t tag);
+
+class ScopedTrace {
+public:
+ inline ScopedTrace(uint64_t tag, const char* name) : mTag(tag) { atrace_begin(mTag, name); }
+
+ inline ~ScopedTrace() { atrace_end(mTag); }
+
+private:
+ uint64_t mTag;
+};
+
+} // namespace binder
+} // namespace android
diff --git a/libs/binder/ndk/Android.bp b/libs/binder/ndk/Android.bp
index 32e018d..33d28e6 100644
--- a/libs/binder/ndk/Android.bp
+++ b/libs/binder/ndk/Android.bp
@@ -57,6 +57,7 @@
srcs: [
"ibinder.cpp",
"ibinder_jni.cpp",
+ "libbinder.cpp",
"parcel.cpp",
"parcel_jni.cpp",
"process.cpp",
diff --git a/libs/binder/ndk/ibinder.cpp b/libs/binder/ndk/ibinder.cpp
index 9778ec0..28d1f16 100644
--- a/libs/binder/ndk/ibinder.cpp
+++ b/libs/binder/ndk/ibinder.cpp
@@ -14,21 +14,19 @@
* limitations under the License.
*/
+#include <android-base/logging.h>
#include <android/binder_ibinder.h>
#include <android/binder_ibinder_platform.h>
-#include <android/binder_libbinder.h>
-#include "ibinder_internal.h"
-
#include <android/binder_stability.h>
#include <android/binder_status.h>
-#include "parcel_internal.h"
-#include "status_internal.h"
-
-#include <android-base/logging.h>
#include <binder/IPCThreadState.h>
#include <binder/IResultReceiver.h>
#include <private/android_filesystem_config.h>
+#include "ibinder_internal.h"
+#include "parcel_internal.h"
+#include "status_internal.h"
+
using DeathRecipient = ::android::IBinder::DeathRecipient;
using ::android::IBinder;
@@ -782,17 +780,6 @@
return ::android::IPCThreadState::self()->getCallingSid();
}
-android::sp<android::IBinder> AIBinder_toPlatformBinder(AIBinder* binder) {
- if (binder == nullptr) return nullptr;
- return binder->getBinder();
-}
-
-AIBinder* AIBinder_fromPlatformBinder(const android::sp<android::IBinder>& binder) {
- sp<AIBinder> ndkBinder = ABpBinder::lookupOrCreateFromBinder(binder);
- AIBinder_incStrong(ndkBinder.get());
- return ndkBinder.get();
-}
-
void AIBinder_setMinSchedulerPolicy(AIBinder* binder, int policy, int priority) {
binder->asABBinder()->setMinSchedulerPolicy(policy, priority);
}
diff --git a/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h b/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
index 0bf1e3d..95eee26 100644
--- a/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
+++ b/libs/binder/ndk/include_cpp/android/binder_parcel_utils.h
@@ -1639,7 +1639,6 @@
return AParcel_writeParcelable(parcel, value);
} else {
static_assert(dependent_false_v<T>, "unrecognized type");
- return STATUS_OK;
}
}
@@ -1707,7 +1706,6 @@
return AParcel_readParcelable(parcel, value);
} else {
static_assert(dependent_false_v<T>, "unrecognized type");
- return STATUS_OK;
}
}
diff --git a/libs/binder/ndk/include_cpp/android/binder_to_string.h b/libs/binder/ndk/include_cpp/android/binder_to_string.h
index ef71a81..d7840ec 100644
--- a/libs/binder/ndk/include_cpp/android/binder_to_string.h
+++ b/libs/binder/ndk/include_cpp/android/binder_to_string.h
@@ -162,7 +162,12 @@
} else if constexpr (std::is_same_v<bool, _T>) {
return t ? "true" : "false";
} else if constexpr (std::is_same_v<char16_t, _T>) {
+ // TODO(b/244494451): codecvt is deprecated in C++17 -- suppress the
+ // warnings. There's no replacement in the standard library yet.
+ _Pragma("clang diagnostic push")
+ _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"");
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>().to_bytes(t);
+ _Pragma("clang diagnostic pop");
} else if constexpr (std::is_arithmetic_v<_T>) {
return std::to_string(t);
} else if constexpr (std::is_same_v<std::string, _T>) {
diff --git a/libs/binder/ndk/include_platform/android/binder_libbinder.h b/libs/binder/ndk/include_platform/android/binder_libbinder.h
index f0c00e8..dfe12a1 100644
--- a/libs/binder/ndk/include_platform/android/binder_libbinder.h
+++ b/libs/binder/ndk/include_platform/android/binder_libbinder.h
@@ -19,7 +19,9 @@
#if !defined(__ANDROID_APEX__) && !defined(__ANDROID_VNDK__)
#include <android/binder_ibinder.h>
+#include <android/binder_parcel.h>
#include <binder/IBinder.h>
+#include <binder/Parcel.h>
/**
* Get libbinder version of binder from AIBinder.
@@ -47,4 +49,26 @@
*/
AIBinder* AIBinder_fromPlatformBinder(const android::sp<android::IBinder>& binder);
+/**
+ * View libbinder version of parcel from AParcel (mutable).
+ *
+ * The lifetime of the returned parcel is the lifetime of the input AParcel.
+ * Do not ues this reference after dropping the AParcel.
+ *
+ * \param parcel non-null parcel with ownership retained by client
+ * \return platform parcel object
+ */
+android::Parcel* AParcel_viewPlatformParcel(AParcel* parcel);
+
+/**
+ * View libbinder version of parcel from AParcel (const version).
+ *
+ * The lifetime of the returned parcel is the lifetime of the input AParcel.
+ * Do not ues this reference after dropping the AParcel.
+ *
+ * \param parcel non-null parcel with ownership retained by client
+ * \return platform parcel object
+ */
+const android::Parcel* AParcel_viewPlatformParcel(const AParcel* parcel);
+
#endif
diff --git a/libs/binder/ndk/libbinder.cpp b/libs/binder/ndk/libbinder.cpp
new file mode 100644
index 0000000..f94d81d
--- /dev/null
+++ b/libs/binder/ndk/libbinder.cpp
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <android/binder_libbinder.h>
+
+#include "ibinder_internal.h"
+#include "parcel_internal.h"
+
+using ::android::IBinder;
+using ::android::Parcel;
+using ::android::sp;
+
+sp<IBinder> AIBinder_toPlatformBinder(AIBinder* binder) {
+ if (binder == nullptr) return nullptr;
+ return binder->getBinder();
+}
+
+AIBinder* AIBinder_fromPlatformBinder(const sp<IBinder>& binder) {
+ sp<AIBinder> ndkBinder = ABpBinder::lookupOrCreateFromBinder(binder);
+ AIBinder_incStrong(ndkBinder.get());
+ return ndkBinder.get();
+}
+
+Parcel* AParcel_viewPlatformParcel(AParcel* parcel) {
+ return parcel->get();
+}
+
+const Parcel* AParcel_viewPlatformParcel(const AParcel* parcel) {
+ return parcel->get();
+}
diff --git a/libs/binder/ndk/libbinder_ndk.map.txt b/libs/binder/ndk/libbinder_ndk.map.txt
index 6bc9814..259a736 100644
--- a/libs/binder/ndk/libbinder_ndk.map.txt
+++ b/libs/binder/ndk/libbinder_ndk.map.txt
@@ -158,6 +158,7 @@
extern "C++" {
AIBinder_fromPlatformBinder*;
AIBinder_toPlatformBinder*;
+ AParcel_viewPlatformParcel*;
};
local:
*;
diff --git a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
index 1b136dc..6d29238 100644
--- a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
+++ b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
@@ -661,6 +661,15 @@
}
}
+TEST(NdkBinder, ConvertToPlatformParcel) {
+ ndk::ScopedAParcel parcel = ndk::ScopedAParcel(AParcel_create());
+ EXPECT_EQ(OK, AParcel_writeInt32(parcel.get(), 42));
+
+ android::Parcel* pparcel = AParcel_viewPlatformParcel(parcel.get());
+ pparcel->setDataPosition(0);
+ EXPECT_EQ(42, pparcel->readInt32());
+}
+
class MyResultReceiver : public BnResultReceiver {
public:
Mutex mMutex;
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index 1babfd5..92d132f 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -341,6 +341,11 @@
"binderRpcTest_shared_defaults",
"libbinder_tls_shared_deps",
],
+
+ // Add the Trusty mock library as a fake dependency so it gets built
+ required: [
+ "libbinder_on_trusty_mock",
+ ],
}
cc_test {
@@ -600,6 +605,7 @@
shared_libs: [
"libbinder",
"liblog",
+ "libcutils",
"libutils",
"libutilscallstack",
"libbase",
diff --git a/libs/binder/tests/binderAllocationLimits.cpp b/libs/binder/tests/binderAllocationLimits.cpp
index a2ab8ab..55a3916 100644
--- a/libs/binder/tests/binderAllocationLimits.cpp
+++ b/libs/binder/tests/binderAllocationLimits.cpp
@@ -20,6 +20,7 @@
#include <binder/Parcel.h>
#include <binder/RpcServer.h>
#include <binder/RpcSession.h>
+#include <cutils/trace.h>
#include <gtest/gtest.h>
#include <utils/CallStack.h>
@@ -223,5 +224,10 @@
return 1;
}
::testing::InitGoogleTest(&argc, argv);
+
+ // if tracing is enabled, take in one-time cost
+ (void)ATRACE_INIT();
+ (void)ATRACE_GET_ENABLED_TAGS();
+
return RUN_ALL_TESTS();
}
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index 5de08bd..6e1c8ac 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -1161,8 +1161,7 @@
// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
// This value is not exposed, but some code in the framework relies on being able to use
// buffers near the cap size.
-// TODO(b/238777741): why do larger values, like 300K fail sometimes
-constexpr size_t kSizeBytesAlmostFull = 100'000;
+constexpr size_t kSizeBytesAlmostFull = 950'000;
constexpr size_t kSizeBytesOverFull = 1'050'000;
TEST_F(BinderLibTest, GargantuanVectorSent) {
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 4c037b7..21b0354 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -1773,7 +1773,7 @@
}
}
mFd = rpcServer->releaseServer();
- if (!mFd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
+ if (!mFd.fd.ok()) return AssertionFailure() << "releaseServer returns invalid fd";
mCtx = newFactory(rpcSecurity, mCertVerifier, std::move(auth))->newServerCtx();
if (mCtx == nullptr) return AssertionFailure() << "newServerCtx";
mSetup = true;
@@ -1794,7 +1794,7 @@
std::vector<std::thread> threads;
while (OK == mFdTrigger->triggerablePoll(mFd, POLLIN)) {
base::unique_fd acceptedFd(
- TEMP_FAILURE_RETRY(accept4(mFd.get(), nullptr, nullptr /*length*/,
+ TEMP_FAILURE_RETRY(accept4(mFd.fd.get(), nullptr, nullptr /*length*/,
SOCK_CLOEXEC | SOCK_NONBLOCK)));
threads.emplace_back(&Server::handleOne, this, std::move(acceptedFd));
}
@@ -1803,7 +1803,8 @@
}
void handleOne(android::base::unique_fd acceptedFd) {
ASSERT_TRUE(acceptedFd.ok());
- auto serverTransport = mCtx->newTransport(std::move(acceptedFd), mFdTrigger.get());
+ RpcTransportFd transportFd(std::move(acceptedFd));
+ auto serverTransport = mCtx->newTransport(std::move(transportFd), mFdTrigger.get());
if (serverTransport == nullptr) return; // handshake failed
ASSERT_TRUE(mPostConnect(serverTransport.get(), mFdTrigger.get()));
}
@@ -1822,7 +1823,7 @@
std::unique_ptr<std::thread> mThread;
ConnectToServer mConnectToServer;
std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
- base::unique_fd mFd;
+ RpcTransportFd mFd;
std::unique_ptr<RpcTransportCtx> mCtx;
std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
std::make_shared<RpcCertificateVerifierSimple>();
@@ -1869,7 +1870,7 @@
// connect() and do handshake
bool setUpTransport() {
mFd = mConnectToServer();
- if (!mFd.ok()) return AssertionFailure() << "Cannot connect to server";
+ if (!mFd.fd.ok()) return AssertionFailure() << "Cannot connect to server";
mClientTransport = mCtx->newTransport(std::move(mFd), mFdTrigger.get());
return mClientTransport != nullptr;
}
@@ -1898,9 +1899,11 @@
ASSERT_EQ(readOk, readMessage());
}
+ bool isTransportWaiting() { return mClientTransport->isWaiting(); }
+
private:
ConnectToServer mConnectToServer;
- base::unique_fd mFd;
+ RpcTransportFd mFd;
std::unique_ptr<FdTrigger> mFdTrigger = FdTrigger::make();
std::unique_ptr<RpcTransportCtx> mCtx;
std::shared_ptr<RpcCertificateVerifierSimple> mCertVerifier =
@@ -2147,6 +2150,56 @@
ASSERT_FALSE(client.readMessage(msg2));
}
+TEST_P(RpcTransportTest, CheckWaitingForRead) {
+ std::mutex readMutex;
+ std::condition_variable readCv;
+ bool shouldContinueReading = false;
+ // Server will write data on transport once its started
+ auto serverPostConnect = [&](RpcTransport* serverTransport, FdTrigger* fdTrigger) {
+ std::string message(RpcTransportTestUtils::kMessage);
+ iovec messageIov{message.data(), message.size()};
+ auto status = serverTransport->interruptableWriteFully(fdTrigger, &messageIov, 1,
+ std::nullopt, nullptr);
+ if (status != OK) return AssertionFailure() << statusToString(status);
+
+ {
+ std::unique_lock<std::mutex> lock(readMutex);
+ shouldContinueReading = true;
+ lock.unlock();
+ readCv.notify_all();
+ }
+ return AssertionSuccess();
+ };
+
+ // Setup Server and client
+ auto server = std::make_unique<Server>();
+ ASSERT_TRUE(server->setUp(GetParam()));
+
+ Client client(server->getConnectToServerFn());
+ ASSERT_TRUE(client.setUp(GetParam()));
+
+ ASSERT_EQ(OK, trust(&client, server));
+ ASSERT_EQ(OK, trust(server, &client));
+ server->setPostConnect(serverPostConnect);
+
+ server->start();
+ ASSERT_TRUE(client.setUpTransport());
+ {
+ // Wait till server writes data
+ std::unique_lock<std::mutex> lock(readMutex);
+ ASSERT_TRUE(readCv.wait_for(lock, 3s, [&] { return shouldContinueReading; }));
+ }
+
+ // Since there is no read polling here, we will get polling count 0
+ ASSERT_FALSE(client.isTransportWaiting());
+ ASSERT_TRUE(client.readMessage(RpcTransportTestUtils::kMessage));
+ // Thread should increment polling count, read and decrement polling count
+ // Again, polling count should be zero here
+ ASSERT_FALSE(client.isTransportWaiting());
+
+ server->shutdown();
+}
+
INSTANTIATE_TEST_CASE_P(BinderRpc, RpcTransportTest,
::testing::ValuesIn(RpcTransportTest::getRpcTranportTestParams()),
RpcTransportTest::PrintParamInfo);
diff --git a/libs/binder/tests/parcel_fuzzer/binder_ndk.h b/libs/binder/tests/parcel_fuzzer/binder_ndk.h
index 81e79b5..d19f25b 100644
--- a/libs/binder/tests/parcel_fuzzer/binder_ndk.h
+++ b/libs/binder/tests/parcel_fuzzer/binder_ndk.h
@@ -18,29 +18,27 @@
#include <android/binder_auto_utils.h>
#include <vector>
+#include <android/binder_libbinder.h>
#include <android/binder_parcel.h>
#include "parcel_fuzzer.h"
-// libbinder_ndk doesn't export this header which breaks down its API for NDK
-// and APEX users, but we need access to it to fuzz.
-#include "../../ndk/parcel_internal.h"
-
class NdkParcelAdapter {
public:
- NdkParcelAdapter() : mParcel(new AParcel(nullptr /*binder*/)) {}
+ NdkParcelAdapter() : mParcel(AParcel_create()) {}
const AParcel* aParcel() const { return mParcel.get(); }
AParcel* aParcel() { return mParcel.get(); }
- android::Parcel* parcel() { return aParcel()->get(); }
+ const android::Parcel* parcel() const { return AParcel_viewPlatformParcel(aParcel()); }
+ android::Parcel* parcel() { return AParcel_viewPlatformParcel(aParcel()); }
- const uint8_t* data() const { return aParcel()->get()->data(); }
- size_t dataSize() const { return aParcel()->get()->dataSize(); }
- size_t dataAvail() const { return aParcel()->get()->dataAvail(); }
- size_t dataPosition() const { return aParcel()->get()->dataPosition(); }
- size_t dataCapacity() const { return aParcel()->get()->dataCapacity(); }
+ const uint8_t* data() const { return parcel()->data(); }
+ size_t dataSize() const { return parcel()->dataSize(); }
+ size_t dataAvail() const { return parcel()->dataAvail(); }
+ size_t dataPosition() const { return parcel()->dataPosition(); }
+ size_t dataCapacity() const { return parcel()->dataCapacity(); }
android::status_t setData(const uint8_t* buffer, size_t len) {
- return aParcel()->get()->setData(buffer, len);
+ return parcel()->setData(buffer, len);
}
android::status_t appendFrom(const NdkParcelAdapter* parcel, int32_t start, int32_t len) {
diff --git a/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp b/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
index 32494e3..25f6096 100644
--- a/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
+++ b/libs/binder/tests/parcel_fuzzer/libbinder_driver.cpp
@@ -17,6 +17,9 @@
#include <fuzzbinder/random_parcel.h>
+#include <android-base/logging.h>
+#include <binder/ProcessState.h>
+
namespace android {
void fuzzService(const sp<IBinder>& binder, FuzzedDataProvider&& provider) {
@@ -60,6 +63,15 @@
options.extraFds.push_back(base::unique_fd(dup(retFds[i])));
}
}
+
+ // invariants
+
+ auto ps = ProcessState::selfOrNull();
+ if (ps) {
+ CHECK_EQ(0, ps->getThreadPoolMaxTotalThreadCount())
+ << "Binder threadpool should not be started by fuzzer because coverage can only "
+ "cover in-process calls.";
+ }
}
} // namespace android
diff --git a/libs/binder/tests/rpc_fuzzer/main.cpp b/libs/binder/tests/rpc_fuzzer/main.cpp
index a8713a2..f68a561 100644
--- a/libs/binder/tests/rpc_fuzzer/main.cpp
+++ b/libs/binder/tests/rpc_fuzzer/main.cpp
@@ -157,8 +157,6 @@
}
}
- usleep(10000);
-
if (hangupBeforeShutdown) {
connections.clear();
while (!server->listSessions().empty() || server->numUninitializedSessions()) {
@@ -167,6 +165,10 @@
}
}
+ while (server->hasActiveRequests()) {
+ usleep(10);
+ }
+
while (!server->shutdown()) usleep(1);
serverThread.join();
diff --git a/libs/binder/trusty/OS.cpp b/libs/binder/trusty/OS.cpp
index b21fe6a..46346bb 100644
--- a/libs/binder/trusty/OS.cpp
+++ b/libs/binder/trusty/OS.cpp
@@ -20,13 +20,15 @@
#include <lib/rand/rand.h>
#endif
+#include <binder/RpcTransportTipcTrusty.h>
+
#include "../OS.h"
using android::base::Result;
namespace android {
-Result<void> setNonBlocking(android::base::borrowed_fd fd) {
+Result<void> setNonBlocking(android::base::borrowed_fd /*fd*/) {
// Trusty IPC syscalls are all non-blocking by default.
return {};
}
@@ -41,9 +43,13 @@
#endif // TRUSTY_USERSPACE
}
-status_t dupFileDescriptor(int oldFd, int* newFd) {
+status_t dupFileDescriptor(int /*oldFd*/, int* /*newFd*/) {
// TODO: implement separately
return INVALID_OPERATION;
}
+std::unique_ptr<RpcTransportCtxFactory> makeDefaultRpcTransportCtxFactory() {
+ return RpcTransportCtxFactoryTipcTrusty::make();
+}
+
} // namespace android
diff --git a/libs/binder/trusty/RpcServerTrusty.cpp b/libs/binder/trusty/RpcServerTrusty.cpp
index c789614..18ce316 100644
--- a/libs/binder/trusty/RpcServerTrusty.cpp
+++ b/libs/binder/trusty/RpcServerTrusty.cpp
@@ -118,16 +118,18 @@
};
base::unique_fd clientFd(chan);
+ android::RpcTransportFd transportFd(std::move(clientFd));
+
std::array<uint8_t, RpcServer::kRpcAddressSize> addr;
constexpr size_t addrLen = sizeof(*peer);
memcpy(addr.data(), peer, addrLen);
- RpcServer::establishConnection(sp(server->mRpcServer), std::move(clientFd), addr, addrLen,
+ RpcServer::establishConnection(sp(server->mRpcServer), std::move(transportFd), addr, addrLen,
joinFn);
return rc;
}
-int RpcServerTrusty::handleMessage(const tipc_port* port, handle_t chan, void* ctx) {
+int RpcServerTrusty::handleMessage(const tipc_port* /*port*/, handle_t /*chan*/, void* ctx) {
auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
LOG_ALWAYS_FATAL_IF(channelContext == nullptr,
"bad state: message received on uninitialized channel");
@@ -144,7 +146,8 @@
return NO_ERROR;
}
-void RpcServerTrusty::handleDisconnect(const tipc_port* port, handle_t chan, void* ctx) {}
+void RpcServerTrusty::handleDisconnect(const tipc_port* /*port*/, handle_t /*chan*/,
+ void* /*ctx*/) {}
void RpcServerTrusty::handleChannelCleanup(void* ctx) {
auto* channelContext = reinterpret_cast<ChannelContext*>(ctx);
diff --git a/libs/binder/trusty/RpcTransportTipcTrusty.cpp b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
index dc27eb9..0b67b9f 100644
--- a/libs/binder/trusty/RpcTransportTipcTrusty.cpp
+++ b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
@@ -33,7 +33,7 @@
// RpcTransport for Trusty.
class RpcTransportTipcTrusty : public RpcTransport {
public:
- explicit RpcTransportTipcTrusty(android::base::unique_fd socket) : mSocket(std::move(socket)) {}
+ explicit RpcTransportTipcTrusty(android::RpcTransportFd socket) : mSocket(std::move(socket)) {}
~RpcTransportTipcTrusty() { releaseMessage(); }
status_t pollRead() override {
@@ -45,9 +45,9 @@
}
status_t interruptableWriteFully(
- FdTrigger* fdTrigger, iovec* iovs, int niovs,
- const std::optional<android::base::function_ref<status_t()>>& altPoll,
- const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds)
+ FdTrigger* /*fdTrigger*/, iovec* iovs, int niovs,
+ const std::optional<android::base::function_ref<status_t()>>& /*altPoll*/,
+ const std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* /*ancillaryFds*/)
override {
if (niovs < 0) {
return BAD_VALUE;
@@ -64,7 +64,7 @@
.num_handles = 0, // TODO: add ancillaryFds
.handles = nullptr,
};
- ssize_t rc = send_msg(mSocket.get(), &msg);
+ ssize_t rc = send_msg(mSocket.fd.get(), &msg);
if (rc == ERR_NOT_ENOUGH_BUFFER) {
// Peer is blocked, wait until it unblocks.
// TODO: when tipc supports a send-unblocked handler,
@@ -72,7 +72,7 @@
// when the handler gets called by the library
uevent uevt;
do {
- rc = ::wait(mSocket.get(), &uevt, INFINITE_TIME);
+ rc = ::wait(mSocket.fd.get(), &uevt, INFINITE_TIME);
if (rc < 0) {
return statusFromTrusty(rc);
}
@@ -83,7 +83,7 @@
// Retry the send, it should go through this time because
// sending is now unblocked
- rc = send_msg(mSocket.get(), &msg);
+ rc = send_msg(mSocket.fd.get(), &msg);
}
if (rc < 0) {
return statusFromTrusty(rc);
@@ -95,9 +95,10 @@
}
status_t interruptableReadFully(
- FdTrigger* fdTrigger, iovec* iovs, int niovs,
- const std::optional<android::base::function_ref<status_t()>>& altPoll,
- std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* ancillaryFds) override {
+ FdTrigger* /*fdTrigger*/, iovec* iovs, int niovs,
+ const std::optional<android::base::function_ref<status_t()>>& /*altPoll*/,
+ std::vector<std::variant<base::unique_fd, base::borrowed_fd>>* /*ancillaryFds*/)
+ override {
if (niovs < 0) {
return BAD_VALUE;
}
@@ -129,7 +130,7 @@
.num_handles = 0, // TODO: support ancillaryFds
.handles = nullptr,
};
- ssize_t rc = read_msg(mSocket.get(), mMessageInfo.id, mMessageOffset, &msg);
+ ssize_t rc = read_msg(mSocket.fd.get(), mMessageInfo.id, mMessageOffset, &msg);
if (rc < 0) {
return statusFromTrusty(rc);
}
@@ -169,6 +170,8 @@
}
}
+ bool isWaiting() override { return mSocket.isInPollingState(); }
+
private:
status_t ensureMessage(bool wait) {
int rc;
@@ -179,7 +182,7 @@
/* TODO: interruptible wait, maybe with a timeout??? */
uevent uevt;
- rc = ::wait(mSocket.get(), &uevt, wait ? INFINITE_TIME : 0);
+ rc = ::wait(mSocket.fd.get(), &uevt, wait ? INFINITE_TIME : 0);
if (rc < 0) {
if (rc == ERR_TIMED_OUT && !wait) {
// If we timed out with wait==false, then there's no message
@@ -192,7 +195,7 @@
return OK;
}
- rc = get_msg(mSocket.get(), &mMessageInfo);
+ rc = get_msg(mSocket.fd.get(), &mMessageInfo);
if (rc < 0) {
return statusFromTrusty(rc);
}
@@ -204,12 +207,12 @@
void releaseMessage() {
if (mHaveMessage) {
- put_msg(mSocket.get(), mMessageInfo.id);
+ put_msg(mSocket.fd.get(), mMessageInfo.id);
mHaveMessage = false;
}
}
- base::unique_fd mSocket;
+ android::RpcTransportFd mSocket;
bool mHaveMessage = false;
ipc_msg_info mMessageInfo;
@@ -219,9 +222,9 @@
// RpcTransportCtx for Trusty.
class RpcTransportCtxTipcTrusty : public RpcTransportCtx {
public:
- std::unique_ptr<RpcTransport> newTransport(android::base::unique_fd fd,
+ std::unique_ptr<RpcTransport> newTransport(android::RpcTransportFd socket,
FdTrigger*) const override {
- return std::make_unique<RpcTransportTipcTrusty>(std::move(fd));
+ return std::make_unique<RpcTransportTipcTrusty>(std::move(socket));
}
std::vector<uint8_t> getCertificate(RpcCertificateFormat) const override { return {}; }
};
diff --git a/libs/binder/trusty/include_mock/lib/tipc/tipc_srv.h b/libs/binder/trusty/include_mock/lib/tipc/tipc_srv.h
new file mode 100644
index 0000000..2747314
--- /dev/null
+++ b/libs/binder/trusty/include_mock/lib/tipc/tipc_srv.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <stddef.h>
+#include <trusty_ipc.h>
+#include <uapi/trusty_uuid.h>
+
+struct tipc_port_acl {
+ uint32_t flags;
+ uint32_t uuid_num;
+ const struct uuid** uuids;
+ const void* extra_data;
+};
+
+struct tipc_port {
+ const char* name;
+ uint32_t msg_max_size;
+ uint32_t msg_queue_len;
+ const struct tipc_port_acl* acl;
+ const void* priv;
+};
+
+struct tipc_srv_ops {
+ int (*on_connect)(const struct tipc_port* port, handle_t chan, const struct uuid* peer,
+ void** ctx_p);
+
+ int (*on_message)(const struct tipc_port* port, handle_t chan, void* ctx);
+
+ void (*on_disconnect)(const struct tipc_port* port, handle_t chan, void* ctx);
+
+ void (*on_channel_cleanup)(void* ctx);
+};
+
+static inline int tipc_add_service(struct tipc_hset*, const struct tipc_port*, uint32_t, uint32_t,
+ const struct tipc_srv_ops*) {
+ return 0;
+}
diff --git a/libs/binder/trusty/include_mock/openssl/rand.h b/libs/binder/trusty/include_mock/openssl/rand.h
new file mode 100644
index 0000000..07dcc1c
--- /dev/null
+++ b/libs/binder/trusty/include_mock/openssl/rand.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+static inline int RAND_bytes(unsigned char*, int) {
+ return 0;
+}
diff --git a/libs/binder/trusty/include_mock/trusty_ipc.h b/libs/binder/trusty/include_mock/trusty_ipc.h
new file mode 100644
index 0000000..a2170ce
--- /dev/null
+++ b/libs/binder/trusty/include_mock/trusty_ipc.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <stddef.h>
+#include <stdint.h>
+#include <sys/types.h>
+#include <sys/uio.h>
+#include <uapi/trusty_uuid.h>
+
+#define INFINITE_TIME 1
+#define IPC_MAX_MSG_HANDLES 8
+
+#define IPC_HANDLE_POLL_HUP 0x1
+#define IPC_HANDLE_POLL_MSG 0x2
+#define IPC_HANDLE_POLL_SEND_UNBLOCKED 0x4
+
+typedef int handle_t;
+
+typedef struct ipc_msg {
+ uint32_t num_iov;
+ iovec* iov;
+ uint32_t num_handles;
+ handle_t* handles;
+} ipc_msg_t;
+
+typedef struct ipc_msg_info {
+ size_t len;
+ uint32_t id;
+ uint32_t num_handles;
+} ipc_msg_info_t;
+
+typedef struct uevent {
+ uint32_t event;
+} uevent_t;
+
+static inline handle_t port_create(const char*, uint32_t, uint32_t, uint32_t) {
+ return 0;
+}
+static inline handle_t connect(const char*, uint32_t) {
+ return 0;
+}
+static inline handle_t accept(handle_t, uuid_t*) {
+ return 0;
+}
+static inline int set_cookie(handle_t, void*) {
+ return 0;
+}
+static inline handle_t handle_set_create(void) {
+ return 0;
+}
+static inline int handle_set_ctrl(handle_t, uint32_t, struct uevent*) {
+ return 0;
+}
+static inline int wait(handle_t, uevent_t*, uint32_t) {
+ return 0;
+}
+static inline int wait_any(uevent_t*, uint32_t) {
+ return 0;
+}
+static inline int get_msg(handle_t, ipc_msg_info_t*) {
+ return 0;
+}
+static inline ssize_t read_msg(handle_t, uint32_t, uint32_t, ipc_msg_t*) {
+ return 0;
+}
+static inline int put_msg(handle_t, uint32_t) {
+ return 0;
+}
+static inline ssize_t send_msg(handle_t, ipc_msg_t*) {
+ return 0;
+}
diff --git a/libs/binder/trusty/include_mock/trusty_log.h b/libs/binder/trusty/include_mock/trusty_log.h
new file mode 100644
index 0000000..d51e752
--- /dev/null
+++ b/libs/binder/trusty/include_mock/trusty_log.h
@@ -0,0 +1,26 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+#include <stdio.h>
+
+// Mock definitions for the Trusty logging macros. These are not
+// meant to be run, just compiled successfully.
+#define TLOGD(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#define TLOGI(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#define TLOGW(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#define TLOGE(fmt, ...) printf(fmt, ##__VA_ARGS__)
+#define TLOGC(fmt, ...) printf(fmt, ##__VA_ARGS__)
diff --git a/libs/binder/trusty/include_mock/uapi/err.h b/libs/binder/trusty/include_mock/uapi/err.h
new file mode 100644
index 0000000..c7e117e
--- /dev/null
+++ b/libs/binder/trusty/include_mock/uapi/err.h
@@ -0,0 +1,40 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+enum {
+ NO_ERROR,
+ ERR_ACCESS_DENIED,
+ ERR_ALREADY_EXISTS,
+ ERR_BAD_HANDLE,
+ ERR_BAD_LEN,
+ ERR_BAD_STATE,
+ ERR_CHANNEL_CLOSED,
+ ERR_CMD_UNKNOWN,
+ ERR_GENERIC,
+ ERR_INVALID_ARGS,
+ ERR_NO_MEMORY,
+ ERR_NO_MSG,
+ ERR_NOT_ALLOWED,
+ ERR_NOT_CONFIGURED,
+ ERR_NOT_ENOUGH_BUFFER,
+ ERR_NOT_FOUND,
+ ERR_NOT_READY,
+ ERR_NOT_SUPPORTED,
+ ERR_NOT_VALID,
+ ERR_TIMED_OUT,
+ ERR_TOO_BIG,
+};
diff --git a/libs/binder/trusty/include_mock/uapi/trusty_uuid.h b/libs/binder/trusty/include_mock/uapi/trusty_uuid.h
new file mode 100644
index 0000000..f636826
--- /dev/null
+++ b/libs/binder/trusty/include_mock/uapi/trusty_uuid.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+#pragma once
+
+typedef struct uuid {
+ int placeholder;
+} uuid_t;
diff --git a/libs/binder/trusty/logging.cpp b/libs/binder/trusty/logging.cpp
index fd54744..b4243af 100644
--- a/libs/binder/trusty/logging.cpp
+++ b/libs/binder/trusty/logging.cpp
@@ -54,7 +54,7 @@
abort();
}
-static void TrustyLogLine(const char* msg, int length, android::base::LogSeverity severity,
+static void TrustyLogLine(const char* msg, int /*length*/, android::base::LogSeverity severity,
const char* tag) {
switch (severity) {
case VERBOSE:
@@ -157,7 +157,7 @@
TrustyLogger(DEFAULT, severity, tag ?: "<unknown>", file, line, message);
}
-bool ShouldLog(LogSeverity severity, const char* tag) {
+bool ShouldLog(LogSeverity /*severity*/, const char* /*tag*/) {
// This is controlled by Trusty's log level.
return true;
}
diff --git a/libs/binder/trusty/rules.mk b/libs/binder/trusty/rules.mk
index d0d0861..4e5cd18 100644
--- a/libs/binder/trusty/rules.mk
+++ b/libs/binder/trusty/rules.mk
@@ -76,7 +76,6 @@
$(LIBBINDER_DIR)/ndk/include_cpp \
MODULE_EXPORT_COMPILEFLAGS += \
- -DBINDER_NO_KERNEL_IPC \
-DBINDER_RPC_SINGLE_THREADED \
-D__ANDROID_VNDK__ \
diff --git a/libs/binderthreadstate/test.cpp b/libs/binderthreadstate/test.cpp
index 44e2fd1..2f73137 100644
--- a/libs/binderthreadstate/test.cpp
+++ b/libs/binderthreadstate/test.cpp
@@ -68,8 +68,13 @@
static void callAidl(size_t id, int32_t idx) {
sp<IAidlStuff> stuff;
- CHECK(OK == android::getService<IAidlStuff>(String16(id2name(id).c_str()), &stuff));
- CHECK(stuff->call(idx).isOk());
+ CHECK_EQ(OK, android::getService<IAidlStuff>(String16(id2name(id).c_str()), &stuff));
+ auto ret = stuff->call(idx);
+ CHECK(ret.isOk()) << ret;
+}
+
+static inline std::ostream& operator<<(std::ostream& o, const BinderCallType& s) {
+ return o << static_cast<std::underlying_type_t<BinderCallType>>(s);
}
class HidlServer : public IHidlStuff {
@@ -79,13 +84,13 @@
size_t otherId;
Return<void> callLocal() {
- CHECK(BinderCallType::NONE == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::NONE, getCurrentServingCall());
return android::hardware::Status::ok();
}
Return<void> call(int32_t idx) {
LOG(INFO) << "HidlServer CALL " << thisId << " to " << otherId << " at idx: " << idx
<< " with tid: " << gettid();
- CHECK(BinderCallType::HWBINDER == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::HWBINDER, getCurrentServingCall());
if (idx > 0) {
if (thisId == kP1Id && idx % 4 < 2) {
callHidl(otherId, idx - 1);
@@ -93,7 +98,7 @@
callAidl(otherId, idx - 1);
}
}
- CHECK(BinderCallType::HWBINDER == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::HWBINDER, getCurrentServingCall());
return android::hardware::Status::ok();
}
};
@@ -104,13 +109,13 @@
size_t otherId;
Status callLocal() {
- CHECK(BinderCallType::NONE == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::NONE, getCurrentServingCall());
return Status::ok();
}
Status call(int32_t idx) {
LOG(INFO) << "AidlServer CALL " << thisId << " to " << otherId << " at idx: " << idx
<< " with tid: " << gettid();
- CHECK(BinderCallType::BINDER == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::BINDER, getCurrentServingCall());
if (idx > 0) {
if (thisId == kP2Id && idx % 4 < 2) {
callHidl(otherId, idx - 1);
@@ -118,7 +123,7 @@
callAidl(otherId, idx - 1);
}
}
- CHECK(BinderCallType::BINDER == getCurrentServingCall());
+ CHECK_EQ(BinderCallType::BINDER, getCurrentServingCall());
return Status::ok();
}
};
@@ -161,13 +166,14 @@
// AIDL
android::ProcessState::self()->setThreadPoolMaxThreadCount(1);
sp<AidlServer> aidlServer = new AidlServer(thisId, otherId);
- CHECK(OK == defaultServiceManager()->addService(String16(id2name(thisId).c_str()), aidlServer));
+ CHECK_EQ(OK,
+ defaultServiceManager()->addService(String16(id2name(thisId).c_str()), aidlServer));
android::ProcessState::self()->startThreadPool();
// HIDL
android::hardware::configureRpcThreadpool(1, true /*callerWillJoin*/);
sp<IHidlStuff> hidlServer = new HidlServer(thisId, otherId);
- CHECK(OK == hidlServer->registerAsService(id2name(thisId).c_str()));
+ CHECK_EQ(OK, hidlServer->registerAsService(id2name(thisId).c_str()));
android::hardware::joinRpcThreadpool();
return EXIT_FAILURE;
diff --git a/libs/fakeservicemanager/Android.bp b/libs/fakeservicemanager/Android.bp
index 47c0657..29924ff 100644
--- a/libs/fakeservicemanager/Android.bp
+++ b/libs/fakeservicemanager/Android.bp
@@ -28,6 +28,7 @@
cc_library {
name: "libfakeservicemanager",
defaults: ["fakeservicemanager_defaults"],
+ export_include_dirs: ["include/fakeservicemanager"],
}
cc_test_host {
@@ -37,4 +38,5 @@
"test_sm.cpp",
],
static_libs: ["libgmock"],
+ local_include_dirs: ["include/fakeservicemanager"],
}
diff --git a/libs/fakeservicemanager/ServiceManager.h b/libs/fakeservicemanager/include/fakeservicemanager/ServiceManager.h
similarity index 100%
rename from libs/fakeservicemanager/ServiceManager.h
rename to libs/fakeservicemanager/include/fakeservicemanager/ServiceManager.h
diff --git a/libs/ftl/Android.bp b/libs/ftl/Android.bp
index 8f89e7d..a25a493 100644
--- a/libs/ftl/Android.bp
+++ b/libs/ftl/Android.bp
@@ -14,6 +14,7 @@
address: true,
},
srcs: [
+ "algorithm_test.cpp",
"cast_test.cpp",
"concat_test.cpp",
"enum_test.cpp",
diff --git a/libs/ftl/algorithm_test.cpp b/libs/ftl/algorithm_test.cpp
new file mode 100644
index 0000000..8052caf
--- /dev/null
+++ b/libs/ftl/algorithm_test.cpp
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <ftl/algorithm.h>
+#include <ftl/small_map.h>
+#include <ftl/static_vector.h>
+#include <gtest/gtest.h>
+
+#include <string_view>
+
+namespace android::test {
+
+// Keep in sync with example usage in header file.
+TEST(Algorithm, FindIf) {
+ using namespace std::string_view_literals;
+
+ const ftl::StaticVector vector = {"upside"sv, "down"sv, "cake"sv};
+ EXPECT_EQ(ftl::find_if(vector, [](const auto& str) { return str.front() == 'c'; }), "cake"sv);
+
+ const ftl::SmallMap map = ftl::init::map<int, ftl::StaticVector<std::string_view, 3>>(
+ 12, "snow"sv, "cone"sv)(13, "tiramisu"sv)(14, "upside"sv, "down"sv, "cake"sv);
+
+ using Map = decltype(map);
+
+ EXPECT_EQ(14, ftl::find_if(map, [](const auto& pair) {
+ return pair.second.size() == 3;
+ }).transform(ftl::to_key<Map>));
+
+ const auto opt = ftl::find_if(map, [](const auto& pair) {
+ return pair.second.size() == 1;
+ }).transform(ftl::to_mapped_ref<Map>);
+
+ ASSERT_TRUE(opt);
+ EXPECT_EQ(opt->get(), ftl::StaticVector("tiramisu"sv));
+}
+
+} // namespace android::test
diff --git a/libs/ftl/optional_test.cpp b/libs/ftl/optional_test.cpp
index ede159a..f7410c2 100644
--- a/libs/ftl/optional_test.cpp
+++ b/libs/ftl/optional_test.cpp
@@ -20,6 +20,7 @@
#include <ftl/unit.h>
#include <gtest/gtest.h>
+#include <cstdlib>
#include <functional>
#include <numeric>
#include <utility>
@@ -32,6 +33,29 @@
using ftl::Optional;
using ftl::StaticVector;
+TEST(Optional, Construct) {
+ // Empty.
+ EXPECT_EQ(std::nullopt, Optional<int>());
+ EXPECT_EQ(std::nullopt, Optional<std::string>(std::nullopt));
+
+ // Value.
+ EXPECT_EQ('?', Optional('?'));
+ EXPECT_EQ(""s, Optional(std::string()));
+
+ // In place.
+ EXPECT_EQ("???"s, Optional<std::string>(std::in_place, 3u, '?'));
+ EXPECT_EQ("abc"s, Optional<std::string>(std::in_place, {'a', 'b', 'c'}));
+
+ // Implicit downcast.
+ {
+ Optional opt = std::optional("test"s);
+ static_assert(std::is_same_v<decltype(opt), Optional<std::string>>);
+
+ ASSERT_TRUE(opt);
+ EXPECT_EQ(opt.value(), "test"s);
+ }
+}
+
TEST(Optional, Transform) {
// Empty.
EXPECT_EQ(std::nullopt, Optional<int>().transform([](int) { return 0; }));
@@ -82,4 +106,62 @@
.transform([](const std::string& s) { return s.length(); }));
}
+namespace {
+
+Optional<int> parse_int(const std::string& str) {
+ if (const int i = std::atoi(str.c_str())) return i;
+ return std::nullopt;
+}
+
+} // namespace
+
+TEST(Optional, AndThen) {
+ // Empty.
+ EXPECT_EQ(std::nullopt, Optional<int>().and_then([](int) -> Optional<int> { return 0; }));
+ EXPECT_EQ(std::nullopt, Optional<int>().and_then([](int) { return Optional<int>(); }));
+
+ // By value.
+ EXPECT_EQ(0, Optional(0).and_then([](int x) { return Optional(x); }));
+ EXPECT_EQ(123, Optional("123").and_then(parse_int));
+ EXPECT_EQ(std::nullopt, Optional("abc").and_then(parse_int));
+
+ // By reference.
+ {
+ Optional opt = 'x';
+ EXPECT_EQ('z', opt.and_then([](char& c) {
+ c = 'y';
+ return Optional('z');
+ }));
+
+ EXPECT_EQ('y', opt);
+ }
+
+ // By rvalue reference.
+ {
+ std::string out;
+ EXPECT_EQ("xyz"s, Optional("abc"s).and_then([&out](std::string&& str) {
+ out = std::move(str);
+ return Optional("xyz"s);
+ }));
+
+ EXPECT_EQ(out, "abc"s);
+ }
+
+ // Chaining.
+ using StringVector = StaticVector<std::string, 3>;
+ EXPECT_EQ(14u, Optional(StaticVector{"-"s, "1"s})
+ .and_then([](StringVector&& v) -> Optional<StringVector> {
+ if (v.push_back("4"s)) return v;
+ return {};
+ })
+ .and_then([](const StringVector& v) -> Optional<std::string> {
+ if (v.full()) return std::accumulate(v.begin(), v.end(), std::string());
+ return {};
+ })
+ .and_then(parse_int)
+ .and_then([](int i) {
+ return i > 0 ? std::nullopt : std::make_optional(static_cast<unsigned>(-i));
+ }));
+}
+
} // namespace android::test
diff --git a/libs/gralloc/types/Android.bp b/libs/gralloc/types/Android.bp
index bd21fba..3d81c32 100644
--- a/libs/gralloc/types/Android.bp
+++ b/libs/gralloc/types/Android.bp
@@ -23,6 +23,7 @@
cc_library {
name: "libgralloctypes",
+ defaults: ["android.hardware.graphics.common-ndk_shared"],
cflags: [
"-Wall",
"-Werror",
@@ -51,7 +52,6 @@
],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
"android.hardware.graphics.mapper@4.0",
"libhidlbase",
"liblog",
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index e138212..d3144bb 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -336,6 +336,8 @@
cc_defaults {
name: "libgui_bufferqueue-defaults",
+ defaults: ["android.hardware.graphics.common-ndk_shared"],
+
cflags: [
"-Wall",
"-Werror",
@@ -364,7 +366,6 @@
"android.hardware.graphics.bufferqueue@2.0",
"android.hardware.graphics.common@1.1",
"android.hardware.graphics.common@1.2",
- "android.hardware.graphics.common-V3-ndk",
"android.hidl.token@1.0-utils",
"libbase",
"libcutils",
diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp
index 3bf2e19..3afa339 100644
--- a/libs/gui/BLASTBufferQueue.cpp
+++ b/libs/gui/BLASTBufferQueue.cpp
@@ -1083,50 +1083,6 @@
return mLastAcquiredFrameNumber;
}
-void BLASTBufferQueue::abandon() {
- std::unique_lock _lock{mMutex};
- // flush out the shadow queue
- while (mNumFrameAvailable > 0) {
- acquireAndReleaseBuffer();
- }
-
- // Clear submitted buffer states
- mNumAcquired = 0;
- mSubmitted.clear();
- mPendingRelease.clear();
-
- if (!mPendingTransactions.empty()) {
- BQA_LOGD("Applying pending transactions on abandon %d",
- static_cast<uint32_t>(mPendingTransactions.size()));
- SurfaceComposerClient::Transaction t;
- mergePendingTransactions(&t, std::numeric_limits<uint64_t>::max() /* frameNumber */);
- // All transactions on our apply token are one-way. See comment on mAppliedLastTransaction
- t.setApplyToken(mApplyToken).apply(false, true);
- }
-
- // Clear sync states
- if (!mSyncedFrameNumbers.empty()) {
- BQA_LOGD("mSyncedFrameNumbers cleared");
- mSyncedFrameNumbers.clear();
- }
-
- if (mSyncTransaction != nullptr) {
- BQA_LOGD("mSyncTransaction cleared mAcquireSingleBuffer=%s",
- mAcquireSingleBuffer ? "true" : "false");
- mSyncTransaction = nullptr;
- mAcquireSingleBuffer = false;
- }
-
- // abandon buffer queue
- if (mBufferItemConsumer != nullptr) {
- mBufferItemConsumer->abandon();
- mBufferItemConsumer->setFrameAvailableListener(nullptr);
- }
- mBufferItemConsumer = nullptr;
- mConsumer = nullptr;
- mProducer = nullptr;
-}
-
bool BLASTBufferQueue::isSameSurfaceControl(const sp<SurfaceControl>& surfaceControl) const {
std::unique_lock _lock{mMutex};
return SurfaceControl::isSameSurface(mSurfaceControl, surfaceControl);
diff --git a/libs/gui/OWNERS b/libs/gui/OWNERS
index 31bf895..05b5533 100644
--- a/libs/gui/OWNERS
+++ b/libs/gui/OWNERS
@@ -2,8 +2,9 @@
alecmouri@google.com
chaviw@google.com
chrisforbes@google.com
-lpy@google.com
jreck@google.com
+lpy@google.com
+pdwilliams@google.com
racarr@google.com
vishnun@google.com
diff --git a/libs/gui/ScreenCaptureResults.cpp b/libs/gui/ScreenCaptureResults.cpp
index fe38706..601a5f9 100644
--- a/libs/gui/ScreenCaptureResults.cpp
+++ b/libs/gui/ScreenCaptureResults.cpp
@@ -17,6 +17,7 @@
#include <gui/ScreenCaptureResults.h>
#include <private/gui/ParcelUtils.h>
+#include <ui/FenceResult.h>
namespace android::gui {
@@ -28,17 +29,17 @@
SAFE_PARCEL(parcel->writeBool, false);
}
- if (fence != Fence::NO_FENCE) {
+ if (fenceResult.ok() && fenceResult.value() != Fence::NO_FENCE) {
SAFE_PARCEL(parcel->writeBool, true);
- SAFE_PARCEL(parcel->write, *fence);
+ SAFE_PARCEL(parcel->write, *fenceResult.value());
} else {
SAFE_PARCEL(parcel->writeBool, false);
+ SAFE_PARCEL(parcel->writeInt32, fenceStatus(fenceResult));
}
SAFE_PARCEL(parcel->writeBool, capturedSecureLayers);
SAFE_PARCEL(parcel->writeBool, capturedHdrLayers);
SAFE_PARCEL(parcel->writeUint32, static_cast<uint32_t>(capturedDataspace));
- SAFE_PARCEL(parcel->writeInt32, result);
return NO_ERROR;
}
@@ -53,8 +54,13 @@
bool hasFence;
SAFE_PARCEL(parcel->readBool, &hasFence);
if (hasFence) {
- fence = new Fence();
- SAFE_PARCEL(parcel->read, *fence);
+ fenceResult = sp<Fence>::make();
+ SAFE_PARCEL(parcel->read, *fenceResult.value());
+ } else {
+ status_t status;
+ SAFE_PARCEL(parcel->readInt32, &status);
+ fenceResult = status == NO_ERROR ? FenceResult(Fence::NO_FENCE)
+ : FenceResult(base::unexpected(status));
}
SAFE_PARCEL(parcel->readBool, &capturedSecureLayers);
@@ -62,7 +68,6 @@
uint32_t dataspace = 0;
SAFE_PARCEL(parcel->readUint32, &dataspace);
capturedDataspace = static_cast<ui::Dataspace>(dataspace);
- SAFE_PARCEL(parcel->readInt32, &result);
return NO_ERROR;
}
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index 34edd65..751721e 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -915,9 +915,8 @@
uncacheBuffer.token = BufferCache::getInstance().getToken();
uncacheBuffer.id = cacheId;
- sp<IBinder> applyToken = IInterface::asBinder(TransactionCompletedListener::getIInstance());
- sf->setTransactionState(FrameTimelineInfo{}, {}, {}, 0, applyToken, {}, systemTime(), true,
- uncacheBuffer, false, {}, generateId());
+ sf->setTransactionState(FrameTimelineInfo{}, {}, {}, 0, Transaction::getDefaultApplyToken(), {},
+ systemTime(), true, uncacheBuffer, false, {}, generateId());
}
void SurfaceComposerClient::Transaction::cacheBuffers() {
@@ -2715,12 +2714,16 @@
ComposerServiceAIDL::getComposerService()->getDisplayDecorationSupport(displayToken,
&gsupport);
std::optional<DisplayDecorationSupport> support;
- if (status.isOk() && gsupport.has_value()) {
- support->format = static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
- gsupport->format);
- support->alphaInterpretation =
+ // TODO (b/241277093): Remove `false && ` once b/241278870 is fixed.
+ if (false && status.isOk() && gsupport.has_value()) {
+ support.emplace(DisplayDecorationSupport{
+ .format =
+ static_cast<aidl::android::hardware::graphics::common::PixelFormat>(
+ gsupport->format),
+ .alphaInterpretation =
static_cast<aidl::android::hardware::graphics::common::AlphaInterpretation>(
- gsupport->alphaInterpretation);
+ gsupport->alphaInterpretation)
+ });
}
return support;
}
diff --git a/libs/gui/include/gui/BLASTBufferQueue.h b/libs/gui/include/gui/BLASTBufferQueue.h
index 95df811..4535c98 100644
--- a/libs/gui/include/gui/BLASTBufferQueue.h
+++ b/libs/gui/include/gui/BLASTBufferQueue.h
@@ -108,7 +108,6 @@
uint32_t getLastTransformHint() const;
uint64_t getLastAcquiredFrameNum();
- void abandon();
/**
* Set a callback to be invoked when we are hung. The boolean parameter
diff --git a/libs/gui/include/gui/ScreenCaptureResults.h b/libs/gui/include/gui/ScreenCaptureResults.h
index 724c11c..6e17791 100644
--- a/libs/gui/include/gui/ScreenCaptureResults.h
+++ b/libs/gui/include/gui/ScreenCaptureResults.h
@@ -19,6 +19,7 @@
#include <binder/Parcel.h>
#include <binder/Parcelable.h>
#include <ui/Fence.h>
+#include <ui/FenceResult.h>
#include <ui/GraphicBuffer.h>
namespace android::gui {
@@ -31,11 +32,10 @@
status_t readFromParcel(const android::Parcel* parcel) override;
sp<GraphicBuffer> buffer;
- sp<Fence> fence = Fence::NO_FENCE;
+ FenceResult fenceResult = Fence::NO_FENCE;
bool capturedSecureLayers{false};
bool capturedHdrLayers{false};
ui::Dataspace capturedDataspace{ui::Dataspace::V0_SRGB};
- status_t result = OK;
};
} // namespace android::gui
diff --git a/libs/gui/include/gui/SyncScreenCaptureListener.h b/libs/gui/include/gui/SyncScreenCaptureListener.h
index 0784fbc..bcf565a 100644
--- a/libs/gui/include/gui/SyncScreenCaptureListener.h
+++ b/libs/gui/include/gui/SyncScreenCaptureListener.h
@@ -34,7 +34,9 @@
ScreenCaptureResults waitForResults() {
std::future<ScreenCaptureResults> resultsFuture = resultsPromise.get_future();
const auto screenCaptureResults = resultsFuture.get();
- screenCaptureResults.fence->waitForever("");
+ if (screenCaptureResults.fenceResult.ok()) {
+ screenCaptureResults.fenceResult.value()->waitForever("");
+ }
return screenCaptureResults;
}
@@ -42,4 +44,4 @@
std::promise<ScreenCaptureResults> resultsPromise;
};
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/libs/gui/tests/BLASTBufferQueue_test.cpp b/libs/gui/tests/BLASTBufferQueue_test.cpp
index 3e563b2..c4c2fa5 100644
--- a/libs/gui/tests/BLASTBufferQueue_test.cpp
+++ b/libs/gui/tests/BLASTBufferQueue_test.cpp
@@ -311,7 +311,7 @@
return err;
}
captureResults = captureListener->waitForResults();
- return captureResults.result;
+ return fenceStatus(captureResults.fenceResult);
}
void queueBuffer(sp<IGraphicBufferProducer> igbp, uint8_t r, uint8_t g, uint8_t b,
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index 71f2ad4..b9358e7 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -218,7 +218,7 @@
return err;
}
captureResults = captureListener->waitForResults();
- return captureResults.result;
+ return fenceStatus(captureResults.fenceResult);
}
sp<Surface> mSurface;
diff --git a/libs/input/Android.bp b/libs/input/Android.bp
index 5030d60..29e02cf 100644
--- a/libs/input/Android.bp
+++ b/libs/input/Android.bp
@@ -26,6 +26,7 @@
filegroup {
name: "inputconstants_aidl",
srcs: [
+ "android/hardware/input/InputDeviceCountryCode.aidl",
"android/os/IInputConstants.aidl",
"android/os/InputEventInjectionResult.aidl",
"android/os/InputEventInjectionSync.aidl",
diff --git a/libs/input/Input.cpp b/libs/input/Input.cpp
index 155cb04..2b7483d 100644
--- a/libs/input/Input.cpp
+++ b/libs/input/Input.cpp
@@ -949,6 +949,8 @@
out << ", actionButton=" << std::to_string(event.getActionButton());
}
const size_t pointerCount = event.getPointerCount();
+ LOG_ALWAYS_FATAL_IF(pointerCount > MAX_POINTERS, "Too many pointers : pointerCount = %zu",
+ pointerCount);
for (size_t i = 0; i < pointerCount; i++) {
out << ", id[" << i << "]=" << event.getPointerId(i);
float x = event.getX(i);
diff --git a/libs/input/InputDevice.cpp b/libs/input/InputDevice.cpp
index a908969..3fe03c7 100644
--- a/libs/input/InputDevice.cpp
+++ b/libs/input/InputDevice.cpp
@@ -26,6 +26,7 @@
#include <input/InputEventLabels.h>
using android::base::StringPrintf;
+using android::hardware::input::InputDeviceCountryCode;
namespace android {
@@ -177,6 +178,7 @@
mAlias(other.mAlias),
mIsExternal(other.mIsExternal),
mHasMic(other.mHasMic),
+ mCountryCode(other.mCountryCode),
mSources(other.mSources),
mKeyboardType(other.mKeyboardType),
mKeyCharacterMap(other.mKeyCharacterMap),
@@ -192,8 +194,8 @@
}
void InputDeviceInfo::initialize(int32_t id, int32_t generation, int32_t controllerNumber,
- const InputDeviceIdentifier& identifier, const std::string& alias, bool isExternal,
- bool hasMic) {
+ const InputDeviceIdentifier& identifier, const std::string& alias,
+ bool isExternal, bool hasMic, InputDeviceCountryCode countryCode) {
mId = id;
mGeneration = generation;
mControllerNumber = controllerNumber;
@@ -201,6 +203,7 @@
mAlias = alias;
mIsExternal = isExternal;
mHasMic = hasMic;
+ mCountryCode = countryCode;
mSources = 0;
mKeyboardType = AINPUT_KEYBOARD_TYPE_NONE;
mHasVibrator = false;
diff --git a/libs/input/InputEventLabels.cpp b/libs/input/InputEventLabels.cpp
index c0aa2e2..5990ee0 100644
--- a/libs/input/InputEventLabels.cpp
+++ b/libs/input/InputEventLabels.cpp
@@ -314,7 +314,26 @@
DEFINE_KEYCODE(REFRESH), \
DEFINE_KEYCODE(THUMBS_UP), \
DEFINE_KEYCODE(THUMBS_DOWN), \
- DEFINE_KEYCODE(PROFILE_SWITCH)
+ DEFINE_KEYCODE(PROFILE_SWITCH), \
+ DEFINE_KEYCODE(VIDEO_APP_1), \
+ DEFINE_KEYCODE(VIDEO_APP_2), \
+ DEFINE_KEYCODE(VIDEO_APP_3), \
+ DEFINE_KEYCODE(VIDEO_APP_4), \
+ DEFINE_KEYCODE(VIDEO_APP_5), \
+ DEFINE_KEYCODE(VIDEO_APP_6), \
+ DEFINE_KEYCODE(VIDEO_APP_7), \
+ DEFINE_KEYCODE(VIDEO_APP_8), \
+ DEFINE_KEYCODE(FEATURED_APP_1), \
+ DEFINE_KEYCODE(FEATURED_APP_2), \
+ DEFINE_KEYCODE(FEATURED_APP_3), \
+ DEFINE_KEYCODE(FEATURED_APP_4), \
+ DEFINE_KEYCODE(DEMO_APP_1), \
+ DEFINE_KEYCODE(DEMO_APP_2), \
+ DEFINE_KEYCODE(DEMO_APP_3), \
+ DEFINE_KEYCODE(DEMO_APP_4), \
+ DEFINE_KEYCODE(KEYBOARD_BACKLIGHT_DOWN), \
+ DEFINE_KEYCODE(KEYBOARD_BACKLIGHT_UP), \
+ DEFINE_KEYCODE(KEYBOARD_BACKLIGHT_TOGGLE)
// NOTE: If you add a new axis here you must also add it to several other files.
// Refer to frameworks/base/core/java/android/view/MotionEvent.java for the full list.
diff --git a/libs/input/PropertyMap.cpp b/libs/input/PropertyMap.cpp
index 662e568..16ffa10 100644
--- a/libs/input/PropertyMap.cpp
+++ b/libs/input/PropertyMap.cpp
@@ -75,7 +75,7 @@
}
char* end;
- int value = strtol(stringValue.c_str(), &end, 10);
+ int32_t value = static_cast<int32_t>(strtol(stringValue.c_str(), &end, 10));
if (*end != '\0') {
ALOGW("Property key '%s' has invalid value '%s'. Expected an integer.", key.c_str(),
stringValue.c_str());
diff --git a/libs/input/VelocityControl.cpp b/libs/input/VelocityControl.cpp
index 6e991e9..e2bfb50 100644
--- a/libs/input/VelocityControl.cpp
+++ b/libs/input/VelocityControl.cpp
@@ -44,8 +44,8 @@
void VelocityControl::reset() {
mLastMovementTime = LLONG_MIN;
- mRawPosition.x = 0;
- mRawPosition.y = 0;
+ mRawPositionX = 0;
+ mRawPositionY = 0;
mVelocityTracker.clear();
}
@@ -61,17 +61,20 @@
mLastMovementTime = eventTime;
if (deltaX) {
- mRawPosition.x += *deltaX;
+ mRawPositionX += *deltaX;
}
if (deltaY) {
- mRawPosition.y += *deltaY;
+ mRawPositionY += *deltaY;
}
- mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)), {mRawPosition});
+ mVelocityTracker.addMovement(eventTime, BitSet32(BitSet32::valueForBit(0)),
+ {{AMOTION_EVENT_AXIS_X, {mRawPositionX}},
+ {AMOTION_EVENT_AXIS_Y, {mRawPositionY}}});
- float vx, vy;
+ std::optional<float> vx = mVelocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, 0);
+ std::optional<float> vy = mVelocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, 0);
float scale = mParameters.scale;
- if (mVelocityTracker.getVelocity(0, &vx, &vy)) {
- float speed = hypotf(vx, vy) * scale;
+ if (vx && vy) {
+ float speed = hypotf(*vx, *vy) * scale;
if (speed >= mParameters.highThreshold) {
// Apply full acceleration above the high speed threshold.
scale *= mParameters.acceleration;
@@ -85,10 +88,9 @@
if (DEBUG_ACCELERATION) {
ALOGD("VelocityControl(%0.3f, %0.3f, %0.3f, %0.3f): "
- "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
- mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
- mParameters.acceleration,
- vx, vy, speed, scale / mParameters.scale);
+ "vx=%0.3f, vy=%0.3f, speed=%0.3f, accel=%0.3f",
+ mParameters.scale, mParameters.lowThreshold, mParameters.highThreshold,
+ mParameters.acceleration, *vx, *vy, speed, scale / mParameters.scale);
}
} else {
diff --git a/libs/input/VelocityTracker.cpp b/libs/input/VelocityTracker.cpp
index 76aaf61..6f88a38 100644
--- a/libs/input/VelocityTracker.cpp
+++ b/libs/input/VelocityTracker.cpp
@@ -125,29 +125,39 @@
// --- VelocityTracker ---
+const std::set<int32_t> VelocityTracker::SUPPORTED_AXES = {AMOTION_EVENT_AXIS_X,
+ AMOTION_EVENT_AXIS_Y};
+
+const std::set<int32_t> VelocityTracker::PLANAR_AXES = {AMOTION_EVENT_AXIS_X, AMOTION_EVENT_AXIS_Y};
+
VelocityTracker::VelocityTracker(const Strategy strategy)
: mLastEventTime(0), mCurrentPointerIdBits(0), mActivePointerId(-1) {
- // Configure the strategy.
- if (!configureStrategy(strategy)) {
- ALOGE("Unrecognized velocity tracker strategy %" PRId32 ".", strategy);
- if (!configureStrategy(VelocityTracker::DEFAULT_STRATEGY)) {
- LOG_ALWAYS_FATAL("Could not create the default velocity tracker strategy '%" PRId32
- "'!",
- strategy);
- }
+ // Configure the strategy for each axis.
+ for (int32_t axis : SUPPORTED_AXES) {
+ configureStrategy(axis, strategy);
}
}
VelocityTracker::~VelocityTracker() {
}
-bool VelocityTracker::configureStrategy(Strategy strategy) {
+void VelocityTracker::configureStrategy(int32_t axis, const Strategy strategy) {
+ std::unique_ptr<VelocityTrackerStrategy> createdStrategy;
+
if (strategy == VelocityTracker::Strategy::DEFAULT) {
- mStrategy = createStrategy(VelocityTracker::DEFAULT_STRATEGY);
+ createdStrategy = createStrategy(VelocityTracker::DEFAULT_STRATEGY);
} else {
- mStrategy = createStrategy(strategy);
+ createdStrategy = createStrategy(strategy);
}
- return mStrategy != nullptr;
+
+ if (createdStrategy == nullptr) {
+ ALOGE("Unrecognized velocity tracker strategy %" PRId32 ".", strategy);
+ createdStrategy = createStrategy(VelocityTracker::DEFAULT_STRATEGY);
+ LOG_ALWAYS_FATAL_IF(createdStrategy == nullptr,
+ "Could not create the default velocity tracker strategy '%" PRId32 "'!",
+ strategy);
+ }
+ mStrategies[axis] = std::move(createdStrategy);
}
std::unique_ptr<VelocityTrackerStrategy> VelocityTracker::createStrategy(
@@ -201,8 +211,9 @@
void VelocityTracker::clear() {
mCurrentPointerIdBits.clear();
mActivePointerId = -1;
-
- mStrategy->clear();
+ for (int32_t axis : SUPPORTED_AXES) {
+ mStrategies[axis]->clear();
+ }
}
void VelocityTracker::clearPointers(BitSet32 idBits) {
@@ -213,14 +224,13 @@
mActivePointerId = !remainingIdBits.isEmpty() ? remainingIdBits.firstMarkedBit() : -1;
}
- mStrategy->clearPointers(idBits);
+ for (int32_t axis : SUPPORTED_AXES) {
+ mStrategies[axis]->clearPointers(idBits);
+ }
}
void VelocityTracker::addMovement(nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) {
- LOG_ALWAYS_FATAL_IF(idBits.count() != positions.size(),
- "Mismatching number of pointers, idBits=%" PRIu32 ", positions=%zu",
- idBits.count(), positions.size());
+ const std::map<int32_t /*axis*/, std::vector<float>>& positions) {
while (idBits.count() > MAX_POINTERS) {
idBits.clearLastMarkedBit();
}
@@ -232,7 +242,9 @@
// We have not received any movements for too long. Assume that all pointers
// have stopped.
- mStrategy->clear();
+ for (const auto& [_, strategy] : mStrategies) {
+ strategy->clear();
+ }
}
mLastEventTime = eventTime;
@@ -241,29 +253,37 @@
mActivePointerId = idBits.isEmpty() ? -1 : idBits.firstMarkedBit();
}
- mStrategy->addMovement(eventTime, idBits, positions);
+ for (const auto& [axis, positionValues] : positions) {
+ LOG_ALWAYS_FATAL_IF(idBits.count() != positionValues.size(),
+ "Mismatching number of pointers, idBits=%" PRIu32 ", positions=%zu",
+ idBits.count(), positionValues.size());
+ mStrategies[axis]->addMovement(eventTime, idBits, positionValues);
+ }
if (DEBUG_VELOCITY) {
ALOGD("VelocityTracker: addMovement eventTime=%" PRId64
", idBits=0x%08x, activePointerId=%d",
eventTime, idBits.value, mActivePointerId);
- for (BitSet32 iterBits(idBits); !iterBits.isEmpty();) {
- uint32_t id = iterBits.firstMarkedBit();
- uint32_t index = idBits.getIndexOfBit(id);
- iterBits.clearBit(id);
- Estimator estimator;
- getEstimator(id, &estimator);
- ALOGD(" %d: position (%0.3f, %0.3f), "
- "estimator (degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f)",
- id, positions[index].x, positions[index].y, int(estimator.degree),
- vectorToString(estimator.xCoeff, estimator.degree + 1).c_str(),
- vectorToString(estimator.yCoeff, estimator.degree + 1).c_str(),
- estimator.confidence);
+ for (const auto& positionsEntry : positions) {
+ for (BitSet32 iterBits(idBits); !iterBits.isEmpty();) {
+ uint32_t id = iterBits.firstMarkedBit();
+ uint32_t index = idBits.getIndexOfBit(id);
+ iterBits.clearBit(id);
+ Estimator estimator;
+ getEstimator(positionsEntry.first, id, &estimator);
+ ALOGD(" %d: axis=%d, position=%0.3f, "
+ "estimator (degree=%d, coeff=%s, confidence=%f)",
+ id, positionsEntry.first, positionsEntry.second[index], int(estimator.degree),
+ vectorToString(estimator.coeff, estimator.degree + 1).c_str(),
+ estimator.confidence);
+ }
}
}
}
void VelocityTracker::addMovement(const MotionEvent* event) {
+ // Stores data about which axes to process based on the incoming motion event.
+ std::set<int32_t> axesToProcess;
int32_t actionMasked = event->getActionMasked();
switch (actionMasked) {
@@ -271,6 +291,9 @@
case AMOTION_EVENT_ACTION_HOVER_ENTER:
// Clear all pointers on down before adding the new movement.
clear();
+ for (int32_t axis : PLANAR_AXES) {
+ axesToProcess.insert(axis);
+ }
break;
case AMOTION_EVENT_ACTION_POINTER_DOWN: {
// Start a new movement trace for a pointer that just went down.
@@ -279,10 +302,16 @@
BitSet32 downIdBits;
downIdBits.markBit(event->getPointerId(event->getActionIndex()));
clearPointers(downIdBits);
+ for (int32_t axis : PLANAR_AXES) {
+ axesToProcess.insert(axis);
+ }
break;
}
case AMOTION_EVENT_ACTION_MOVE:
case AMOTION_EVENT_ACTION_HOVER_MOVE:
+ for (int32_t axis : PLANAR_AXES) {
+ axesToProcess.insert(axis);
+ }
break;
case AMOTION_EVENT_ACTION_POINTER_UP:
case AMOTION_EVENT_ACTION_UP: {
@@ -293,7 +322,9 @@
toString(delaySinceLastEvent).c_str());
// We have not received any movements for too long. Assume that all pointers
// have stopped.
- mStrategy->clear();
+ for (int32_t axis : PLANAR_AXES) {
+ mStrategies[axis]->clear();
+ }
}
// These actions because they do not convey any new information about
// pointer movement. We also want to preserve the last known velocity of the pointers.
@@ -325,37 +356,56 @@
pointerIndex[i] = idBits.getIndexOfBit(event->getPointerId(i));
}
- std::vector<Position> positions;
- positions.resize(pointerCount);
+ std::map<int32_t, std::vector<float>> positions;
+ for (int32_t axis : axesToProcess) {
+ positions[axis].resize(pointerCount);
+ }
size_t historySize = event->getHistorySize();
for (size_t h = 0; h <= historySize; h++) {
nsecs_t eventTime = event->getHistoricalEventTime(h);
- for (size_t i = 0; i < pointerCount; i++) {
- uint32_t index = pointerIndex[i];
- positions[index].x = event->getHistoricalX(i, h);
- positions[index].y = event->getHistoricalY(i, h);
+ for (int32_t axis : axesToProcess) {
+ for (size_t i = 0; i < pointerCount; i++) {
+ positions[axis][pointerIndex[i]] = event->getHistoricalAxisValue(axis, i, h);
+ }
}
addMovement(eventTime, idBits, positions);
}
}
-bool VelocityTracker::getVelocity(uint32_t id, float* outVx, float* outVy) const {
+std::optional<float> VelocityTracker::getVelocity(int32_t axis, uint32_t id) const {
Estimator estimator;
- if (getEstimator(id, &estimator) && estimator.degree >= 1) {
- *outVx = estimator.xCoeff[1];
- *outVy = estimator.yCoeff[1];
- return true;
+ bool validVelocity = getEstimator(axis, id, &estimator) && estimator.degree >= 1;
+ if (validVelocity) {
+ return estimator.coeff[1];
}
- *outVx = 0;
- *outVy = 0;
- return false;
+ return {};
}
-bool VelocityTracker::getEstimator(uint32_t id, Estimator* outEstimator) const {
- return mStrategy->getEstimator(id, outEstimator);
+VelocityTracker::ComputedVelocity VelocityTracker::getComputedVelocity(int32_t units,
+ float maxVelocity) {
+ ComputedVelocity computedVelocity;
+ for (int32_t axis : SUPPORTED_AXES) {
+ BitSet32 copyIdBits = BitSet32(mCurrentPointerIdBits);
+ while (!copyIdBits.isEmpty()) {
+ uint32_t id = copyIdBits.clearFirstMarkedBit();
+ std::optional<float> velocity = getVelocity(axis, id);
+ if (velocity) {
+ float adjustedVelocity =
+ std::clamp(*velocity * units / 1000, -maxVelocity, maxVelocity);
+ computedVelocity.addVelocity(axis, id, adjustedVelocity);
+ }
+ }
+ }
+ return computedVelocity;
}
+bool VelocityTracker::getEstimator(int32_t axis, uint32_t id, Estimator* outEstimator) const {
+ if (SUPPORTED_AXES.find(axis) == SUPPORTED_AXES.end()) {
+ return false;
+ }
+ return mStrategies.at(axis)->getEstimator(id, outEstimator);
+}
// --- LeastSquaresVelocityTrackerStrategy ---
@@ -378,9 +428,8 @@
mMovements[mIndex].idBits = remainingIdBits;
}
-void LeastSquaresVelocityTrackerStrategy::addMovement(
- nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) {
+void LeastSquaresVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
+ const std::vector<float>& positions) {
if (mMovements[mIndex].eventTime != eventTime) {
// When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
// of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
@@ -627,8 +676,7 @@
outEstimator->clear();
// Iterate over movement samples in reverse time order and collect samples.
- std::vector<float> x;
- std::vector<float> y;
+ std::vector<float> positions;
std::vector<float> w;
std::vector<float> time;
@@ -645,15 +693,13 @@
break;
}
- const VelocityTracker::Position& position = movement.getPosition(id);
- x.push_back(position.x);
- y.push_back(position.y);
+ positions.push_back(movement.getPosition(id));
w.push_back(chooseWeight(index));
time.push_back(-age * 0.000000001f);
index = (index == 0 ? HISTORY_SIZE : index) - 1;
- } while (x.size() < HISTORY_SIZE);
+ } while (positions.size() < HISTORY_SIZE);
- const size_t m = x.size();
+ const size_t m = positions.size();
if (m == 0) {
return false; // no data
}
@@ -666,39 +712,36 @@
if (degree == 2 && mWeighting == WEIGHTING_NONE) {
// Optimize unweighted, quadratic polynomial fit
- std::optional<std::array<float, 3>> xCoeff = solveUnweightedLeastSquaresDeg2(time, x);
- std::optional<std::array<float, 3>> yCoeff = solveUnweightedLeastSquaresDeg2(time, y);
- if (xCoeff && yCoeff) {
+ std::optional<std::array<float, 3>> coeff =
+ solveUnweightedLeastSquaresDeg2(time, positions);
+ if (coeff) {
outEstimator->time = newestMovement.eventTime;
outEstimator->degree = 2;
outEstimator->confidence = 1;
for (size_t i = 0; i <= outEstimator->degree; i++) {
- outEstimator->xCoeff[i] = (*xCoeff)[i];
- outEstimator->yCoeff[i] = (*yCoeff)[i];
+ outEstimator->coeff[i] = (*coeff)[i];
}
return true;
}
} else if (degree >= 1) {
// General case for an Nth degree polynomial fit
- float xdet, ydet;
+ float det;
uint32_t n = degree + 1;
- if (solveLeastSquares(time, x, w, n, outEstimator->xCoeff, &xdet) &&
- solveLeastSquares(time, y, w, n, outEstimator->yCoeff, &ydet)) {
+ if (solveLeastSquares(time, positions, w, n, outEstimator->coeff, &det)) {
outEstimator->time = newestMovement.eventTime;
outEstimator->degree = degree;
- outEstimator->confidence = xdet * ydet;
+ outEstimator->confidence = det;
- ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, xCoeff=%s, yCoeff=%s, confidence=%f",
- int(outEstimator->degree), vectorToString(outEstimator->xCoeff, n).c_str(),
- vectorToString(outEstimator->yCoeff, n).c_str(), outEstimator->confidence);
+ ALOGD_IF(DEBUG_STRATEGY, "estimate: degree=%d, coeff=%s, confidence=%f",
+ int(outEstimator->degree), vectorToString(outEstimator->coeff, n).c_str(),
+ outEstimator->confidence);
return true;
}
}
// No velocity data available for this pointer, but we do have its current position.
- outEstimator->xCoeff[0] = x[0];
- outEstimator->yCoeff[0] = y[0];
+ outEstimator->coeff[0] = positions[0];
outEstimator->time = newestMovement.eventTime;
outEstimator->degree = 0;
outEstimator->confidence = 1;
@@ -790,18 +833,17 @@
mPointerIdBits.value &= ~idBits.value;
}
-void IntegratingVelocityTrackerStrategy::addMovement(
- nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) {
+void IntegratingVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
+ const std::vector<float>& positions) {
uint32_t index = 0;
for (BitSet32 iterIdBits(idBits); !iterIdBits.isEmpty();) {
uint32_t id = iterIdBits.clearFirstMarkedBit();
State& state = mPointerState[id];
- const VelocityTracker::Position& position = positions[index++];
+ const float position = positions[index++];
if (mPointerIdBits.hasBit(id)) {
- updateState(state, eventTime, position.x, position.y);
+ updateState(state, eventTime, position);
} else {
- initState(state, eventTime, position.x, position.y);
+ initState(state, eventTime, position);
}
}
@@ -821,21 +863,18 @@
return false;
}
-void IntegratingVelocityTrackerStrategy::initState(State& state,
- nsecs_t eventTime, float xpos, float ypos) const {
+void IntegratingVelocityTrackerStrategy::initState(State& state, nsecs_t eventTime,
+ float pos) const {
state.updateTime = eventTime;
state.degree = 0;
- state.xpos = xpos;
- state.xvel = 0;
- state.xaccel = 0;
- state.ypos = ypos;
- state.yvel = 0;
- state.yaccel = 0;
+ state.pos = pos;
+ state.accel = 0;
+ state.vel = 0;
}
-void IntegratingVelocityTrackerStrategy::updateState(State& state,
- nsecs_t eventTime, float xpos, float ypos) const {
+void IntegratingVelocityTrackerStrategy::updateState(State& state, nsecs_t eventTime,
+ float pos) const {
const nsecs_t MIN_TIME_DELTA = 2 * NANOS_PER_MS;
const float FILTER_TIME_CONSTANT = 0.010f; // 10 milliseconds
@@ -846,34 +885,26 @@
float dt = (eventTime - state.updateTime) * 0.000000001f;
state.updateTime = eventTime;
- float xvel = (xpos - state.xpos) / dt;
- float yvel = (ypos - state.ypos) / dt;
+ float vel = (pos - state.pos) / dt;
if (state.degree == 0) {
- state.xvel = xvel;
- state.yvel = yvel;
+ state.vel = vel;
state.degree = 1;
} else {
float alpha = dt / (FILTER_TIME_CONSTANT + dt);
if (mDegree == 1) {
- state.xvel += (xvel - state.xvel) * alpha;
- state.yvel += (yvel - state.yvel) * alpha;
+ state.vel += (vel - state.vel) * alpha;
} else {
- float xaccel = (xvel - state.xvel) / dt;
- float yaccel = (yvel - state.yvel) / dt;
+ float accel = (vel - state.vel) / dt;
if (state.degree == 1) {
- state.xaccel = xaccel;
- state.yaccel = yaccel;
+ state.accel = accel;
state.degree = 2;
} else {
- state.xaccel += (xaccel - state.xaccel) * alpha;
- state.yaccel += (yaccel - state.yaccel) * alpha;
+ state.accel += (accel - state.accel) * alpha;
}
- state.xvel += (state.xaccel * dt) * alpha;
- state.yvel += (state.yaccel * dt) * alpha;
+ state.vel += (state.accel * dt) * alpha;
}
}
- state.xpos = xpos;
- state.ypos = ypos;
+ state.pos = pos;
}
void IntegratingVelocityTrackerStrategy::populateEstimator(const State& state,
@@ -881,12 +912,9 @@
outEstimator->time = state.updateTime;
outEstimator->confidence = 1.0f;
outEstimator->degree = state.degree;
- outEstimator->xCoeff[0] = state.xpos;
- outEstimator->xCoeff[1] = state.xvel;
- outEstimator->xCoeff[2] = state.xaccel / 2;
- outEstimator->yCoeff[0] = state.ypos;
- outEstimator->yCoeff[1] = state.yvel;
- outEstimator->yCoeff[2] = state.yaccel / 2;
+ outEstimator->coeff[0] = state.pos;
+ outEstimator->coeff[1] = state.vel;
+ outEstimator->coeff[2] = state.accel / 2;
}
@@ -909,9 +937,8 @@
mMovements[mIndex].idBits = remainingIdBits;
}
-void LegacyVelocityTrackerStrategy::addMovement(
- nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) {
+void LegacyVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
+ const std::vector<float>& positions) {
if (++mIndex == HISTORY_SIZE) {
mIndex = 0;
}
@@ -959,12 +986,11 @@
// overestimate the velocity at that time point. Most samples might be measured
// 16ms apart but some consecutive samples could be only 0.5sm apart because
// the hardware or driver reports them irregularly or in bursts.
- float accumVx = 0;
- float accumVy = 0;
+ float accumV = 0;
uint32_t index = oldestIndex;
uint32_t samplesUsed = 0;
const Movement& oldestMovement = mMovements[oldestIndex];
- const VelocityTracker::Position& oldestPosition = oldestMovement.getPosition(id);
+ float oldestPosition = oldestMovement.getPosition(id);
nsecs_t lastDuration = 0;
while (numTouches-- > 1) {
@@ -978,26 +1004,22 @@
// the velocity. Consequently, we impose a minimum duration constraint on the
// samples that we include in the calculation.
if (duration >= MIN_DURATION) {
- const VelocityTracker::Position& position = movement.getPosition(id);
+ float position = movement.getPosition(id);
float scale = 1000000000.0f / duration; // one over time delta in seconds
- float vx = (position.x - oldestPosition.x) * scale;
- float vy = (position.y - oldestPosition.y) * scale;
- accumVx = (accumVx * lastDuration + vx * duration) / (duration + lastDuration);
- accumVy = (accumVy * lastDuration + vy * duration) / (duration + lastDuration);
+ float v = (position - oldestPosition) * scale;
+ accumV = (accumV * lastDuration + v * duration) / (duration + lastDuration);
lastDuration = duration;
samplesUsed += 1;
}
}
// Report velocity.
- const VelocityTracker::Position& newestPosition = newestMovement.getPosition(id);
+ float newestPosition = newestMovement.getPosition(id);
outEstimator->time = newestMovement.eventTime;
outEstimator->confidence = 1;
- outEstimator->xCoeff[0] = newestPosition.x;
- outEstimator->yCoeff[0] = newestPosition.y;
+ outEstimator->coeff[0] = newestPosition;
if (samplesUsed) {
- outEstimator->xCoeff[1] = accumVx;
- outEstimator->yCoeff[1] = accumVy;
+ outEstimator->coeff[1] = accumV;
outEstimator->degree = 1;
} else {
outEstimator->degree = 0;
@@ -1024,9 +1046,8 @@
mMovements[mIndex].idBits = remainingIdBits;
}
-void ImpulseVelocityTrackerStrategy::addMovement(
- nsecs_t eventTime, BitSet32 idBits,
- const std::vector<VelocityTracker::Position>& positions) {
+void ImpulseVelocityTrackerStrategy::addMovement(nsecs_t eventTime, BitSet32 idBits,
+ const std::vector<float>& positions) {
if (mMovements[mIndex].eventTime != eventTime) {
// When ACTION_POINTER_DOWN happens, we will first receive ACTION_MOVE with the coordinates
// of the existing pointers, and then ACTION_POINTER_DOWN with the coordinates that include
@@ -1163,8 +1184,7 @@
outEstimator->clear();
// Iterate over movement samples in reverse time order and collect samples.
- float x[HISTORY_SIZE];
- float y[HISTORY_SIZE];
+ float positions[HISTORY_SIZE];
nsecs_t time[HISTORY_SIZE];
size_t m = 0; // number of points that will be used for fitting
size_t index = mIndex;
@@ -1180,9 +1200,7 @@
break;
}
- const VelocityTracker::Position& position = movement.getPosition(id);
- x[m] = position.x;
- y[m] = position.y;
+ positions[m] = movement.getPosition(id);
time[m] = movement.eventTime;
index = (index == 0 ? HISTORY_SIZE : index) - 1;
} while (++m < HISTORY_SIZE);
@@ -1190,33 +1208,30 @@
if (m == 0) {
return false; // no data
}
- outEstimator->xCoeff[0] = 0;
- outEstimator->yCoeff[0] = 0;
- outEstimator->xCoeff[1] = calculateImpulseVelocity(time, x, m);
- outEstimator->yCoeff[1] = calculateImpulseVelocity(time, y, m);
- outEstimator->xCoeff[2] = 0;
- outEstimator->yCoeff[2] = 0;
+ outEstimator->coeff[0] = 0;
+ outEstimator->coeff[1] = calculateImpulseVelocity(time, positions, m);
+ outEstimator->coeff[2] = 0;
+
outEstimator->time = newestMovement.eventTime;
outEstimator->degree = 2; // similar results to 2nd degree fit
outEstimator->confidence = 1;
- ALOGD_IF(DEBUG_STRATEGY, "velocity: (%.1f, %.1f)", outEstimator->xCoeff[1],
- outEstimator->yCoeff[1]);
+ ALOGD_IF(DEBUG_STRATEGY, "velocity: %.1f", outEstimator->coeff[1]);
if (DEBUG_IMPULSE) {
// TODO(b/134179997): delete this block once the switch to 'impulse' is complete.
- // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons
+ // Calculate the lsq2 velocity for the same inputs to allow runtime comparisons.
+ // X axis chosen arbitrarily for velocity comparisons.
VelocityTracker lsq2(VelocityTracker::Strategy::LSQ2);
BitSet32 idBits;
const uint32_t pointerId = 0;
idBits.markBit(pointerId);
for (ssize_t i = m - 1; i >= 0; i--) {
- lsq2.addMovement(time[i], idBits, {{x[i], y[i]}});
+ lsq2.addMovement(time[i], idBits, {{AMOTION_EVENT_AXIS_X, {positions[i]}}});
}
- float outVx = 0, outVy = 0;
- const bool computed = lsq2.getVelocity(pointerId, &outVx, &outVy);
- if (computed) {
- ALOGD("lsq2 velocity: (%.1f, %.1f)", outVx, outVy);
+ std::optional<float> v = lsq2.getVelocity(AMOTION_EVENT_AXIS_X, pointerId);
+ if (v) {
+ ALOGD("lsq2 velocity: %.1f", *v);
} else {
ALOGD("lsq2 velocity: could not compute velocity");
}
diff --git a/libs/input/android/hardware/input/InputDeviceCountryCode.aidl b/libs/input/android/hardware/input/InputDeviceCountryCode.aidl
new file mode 100644
index 0000000..6bb1a60
--- /dev/null
+++ b/libs/input/android/hardware/input/InputDeviceCountryCode.aidl
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware.input;
+
+/**
+ * Constant for HID country code declared by a HID device. These constants are declared as AIDL to
+ * be used by java and native input code.
+ *
+ * @hide
+ */
+@Backing(type="int")
+enum InputDeviceCountryCode {
+ /**
+ * Used as default value where country code is not set in the device HID descriptor
+ */
+ INVALID = -1,
+
+ /**
+ * Used as default value when country code is not supported by the HID device. The HID
+ * descriptor sets "00" as the country code in this case.
+ */
+ NOT_SUPPORTED = 0,
+
+ /**
+ * Arabic
+ */
+ ARABIC = 1,
+
+ /**
+ * Belgian
+ */
+ BELGIAN = 2,
+
+ /**
+ * Canadian (Bilingual)
+ */
+ CANADIAN_BILINGUAL = 3,
+
+ /**
+ * Canadian (French)
+ */
+ CANADIAN_FRENCH = 4,
+
+ /**
+ * Czech Republic
+ */
+ CZECH_REPUBLIC = 5,
+
+ /**
+ * Danish
+ */
+ DANISH = 6,
+
+ /**
+ * Finnish
+ */
+ FINNISH = 7,
+
+ /**
+ * French
+ */
+ FRENCH = 8,
+
+ /**
+ * German
+ */
+ GERMAN = 9,
+
+ /**
+ * Greek
+ */
+ GREEK = 10,
+
+ /**
+ * Hebrew
+ */
+ HEBREW = 11,
+
+ /**
+ * Hungary
+ */
+ HUNGARY = 12,
+
+ /**
+ * International (ISO)
+ */
+ INTERNATIONAL = 13,
+
+ /**
+ * Italian
+ */
+ ITALIAN = 14,
+
+ /**
+ * Japan (Katakana)
+ */
+ JAPAN = 15,
+
+ /**
+ * Korean
+ */
+ KOREAN = 16,
+
+ /**
+ * Latin American
+ */
+ LATIN_AMERICAN = 17,
+
+ /**
+ * Netherlands (Dutch)
+ */
+ DUTCH = 18,
+
+ /**
+ * Norwegian
+ */
+ NORWEGIAN = 19,
+
+ /**
+ * Persian
+ */
+ PERSIAN = 20,
+
+ /**
+ * Poland
+ */
+ POLAND = 21,
+
+ /**
+ * Portuguese
+ */
+ PORTUGUESE = 22,
+
+ /**
+ * Russia
+ */
+ RUSSIA = 23,
+
+ /**
+ * Slovakia
+ */
+ SLOVAKIA = 24,
+
+ /**
+ * Spanish
+ */
+ SPANISH = 25,
+
+ /**
+ * Swedish
+ */
+ SWEDISH = 26,
+
+ /**
+ * Swiss (French)
+ */
+ SWISS_FRENCH = 27,
+
+ /**
+ * Swiss (German)
+ */
+ SWISS_GERMAN = 28,
+
+ /**
+ * Switzerland
+ */
+ SWITZERLAND = 29,
+
+ /**
+ * Taiwan
+ */
+ TAIWAN = 30,
+
+ /**
+ * Turkish_Q
+ */
+ TURKISH_Q = 31,
+
+ /**
+ * UK
+ */
+ UK = 32,
+
+ /**
+ * US
+ */
+ US = 33,
+
+ /**
+ * Yugoslavia
+ */
+ YUGOSLAVIA = 34,
+
+ /**
+ * Turkish_F
+ */
+ TURKISH_F = 35,
+}
\ No newline at end of file
diff --git a/libs/input/tests/VelocityTracker_test.cpp b/libs/input/tests/VelocityTracker_test.cpp
index 4a445de..f8e5052 100644
--- a/libs/input/tests/VelocityTracker_test.cpp
+++ b/libs/input/tests/VelocityTracker_test.cpp
@@ -16,9 +16,10 @@
#define LOG_TAG "VelocityTracker_test"
+#include <math.h>
#include <array>
#include <chrono>
-#include <math.h>
+#include <limits>
#include <android-base/stringprintf.h>
#include <attestation/HmacKeyManager.h>
@@ -198,25 +199,13 @@
const std::vector<MotionEventEntry>& motions, int32_t axis,
float targetVelocity, uint32_t pointerId = DEFAULT_POINTER_ID) {
VelocityTracker vt(strategy);
- float Vx, Vy;
std::vector<MotionEvent> events = createMotionEventStream(motions);
for (MotionEvent event : events) {
vt.addMovement(&event);
}
- vt.getVelocity(pointerId, &Vx, &Vy);
-
- switch (axis) {
- case AMOTION_EVENT_AXIS_X:
- checkVelocity(Vx, targetVelocity);
- break;
- case AMOTION_EVENT_AXIS_Y:
- checkVelocity(Vy, targetVelocity);
- break;
- default:
- FAIL() << "Axis must be either AMOTION_EVENT_AXIS_X or AMOTION_EVENT_AXIS_Y";
- }
+ checkVelocity(vt.getVelocity(axis, pointerId).value_or(0), targetVelocity);
}
static void computeAndCheckQuadraticEstimate(const std::vector<MotionEventEntry>& motions,
@@ -226,17 +215,99 @@
for (MotionEvent event : events) {
vt.addMovement(&event);
}
- VelocityTracker::Estimator estimator;
- EXPECT_TRUE(vt.getEstimator(0, &estimator));
+ VelocityTracker::Estimator estimatorX;
+ VelocityTracker::Estimator estimatorY;
+ EXPECT_TRUE(vt.getEstimator(AMOTION_EVENT_AXIS_X, 0, &estimatorX));
+ EXPECT_TRUE(vt.getEstimator(AMOTION_EVENT_AXIS_Y, 0, &estimatorY));
for (size_t i = 0; i< coefficients.size(); i++) {
- checkCoefficient(estimator.xCoeff[i], coefficients[i]);
- checkCoefficient(estimator.yCoeff[i], coefficients[i]);
+ checkCoefficient(estimatorX.coeff[i], coefficients[i]);
+ checkCoefficient(estimatorY.coeff[i], coefficients[i]);
}
}
/*
* ================== VelocityTracker tests generated manually =====================================
*/
+TEST_F(VelocityTrackerTest, TestComputedVelocity) {
+ VelocityTracker::ComputedVelocity computedVelocity;
+
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_X, 0 /*id*/, 200 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_X, 26U /*id*/, 400 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_X, 27U /*id*/, 650 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_X, MAX_POINTER_ID, 750 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_Y, 0 /*id*/, 1000 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_Y, 26U /*id*/, 2000 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_Y, 27U /*id*/, 3000 /*velocity*/);
+ computedVelocity.addVelocity(AMOTION_EVENT_AXIS_Y, MAX_POINTER_ID, 4000 /*velocity*/);
+
+ // Check the axes/indices with velocity.
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, 0U /*id*/)), 200);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, 26U /*id*/)), 400);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, 27U /*id*/)), 650);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, MAX_POINTER_ID)), 750);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, 0U /*id*/)), 1000);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, 26U /*id*/)), 2000);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, 27U /*id*/)), 3000);
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, MAX_POINTER_ID)), 4000);
+ for (uint32_t id = 0; id <= MAX_POINTER_ID; id++) {
+ // Since no data was added for AXIS_SCROLL, expect empty value for the axis for any id.
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_SCROLL, id))
+ << "Empty scroll data expected at id=" << id;
+ if (id == 0 || id == 26U || id == 27U || id == MAX_POINTER_ID) {
+ // Already checked above; continue.
+ continue;
+ }
+ // No data was added to X/Y for this id, expect empty value.
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, id))
+ << "Empty X data expected at id=" << id;
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, id))
+ << "Empty Y data expected at id=" << id;
+ }
+ // Out-of-bounds ids should given empty values.
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, -1));
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, MAX_POINTER_ID + 1));
+}
+
+TEST_F(VelocityTrackerTest, TestGetComputedVelocity) {
+ std::vector<MotionEventEntry> motions = {
+ {235089067457000ns, {{528.00, 0}}}, {235089084684000ns, {{527.00, 0}}},
+ {235089093349000ns, {{527.00, 0}}}, {235089095677625ns, {{527.00, 0}}},
+ {235089101859000ns, {{527.00, 0}}}, {235089110378000ns, {{528.00, 0}}},
+ {235089112497111ns, {{528.25, 0}}}, {235089118760000ns, {{531.00, 0}}},
+ {235089126686000ns, {{535.00, 0}}}, {235089129316820ns, {{536.33, 0}}},
+ {235089135199000ns, {{540.00, 0}}}, {235089144297000ns, {{546.00, 0}}},
+ {235089146136443ns, {{547.21, 0}}}, {235089152923000ns, {{553.00, 0}}},
+ {235089160784000ns, {{559.00, 0}}}, {235089162955851ns, {{560.66, 0}}},
+ {235089162955851ns, {{560.66, 0}}}, // ACTION_UP
+ };
+ VelocityTracker vt(VelocityTracker::Strategy::IMPULSE);
+ std::vector<MotionEvent> events = createMotionEventStream(motions);
+ for (const MotionEvent& event : events) {
+ vt.addMovement(&event);
+ }
+
+ float maxFloat = std::numeric_limits<float>::max();
+ VelocityTracker::ComputedVelocity computedVelocity;
+ computedVelocity = vt.getComputedVelocity(1000 /* units */, maxFloat);
+ checkVelocity(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, DEFAULT_POINTER_ID)),
+ 764.345703);
+
+ // Expect X velocity to be scaled with respective to provided units.
+ computedVelocity = vt.getComputedVelocity(1000000 /* units */, maxFloat);
+ checkVelocity(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, DEFAULT_POINTER_ID)),
+ 764345.703);
+
+ // Expect X velocity to be clamped by provided max velocity.
+ computedVelocity = vt.getComputedVelocity(1000000 /* units */, 1000);
+ checkVelocity(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_X, DEFAULT_POINTER_ID)), 1000);
+
+ // All 0 data for Y; expect 0 velocity.
+ EXPECT_EQ(*(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_Y, DEFAULT_POINTER_ID)), 0);
+
+ // No data for scroll-axis; expect empty velocity.
+ EXPECT_FALSE(computedVelocity.getVelocity(AMOTION_EVENT_AXIS_SCROLL, DEFAULT_POINTER_ID));
+}
+
TEST_F(VelocityTrackerTest, ThreePointsPositiveVelocityTest) {
// Same coordinate is reported 2 times in a row
// It is difficult to determine the correct answer here, but at least the direction
diff --git a/libs/nativewindow/AHardwareBuffer.cpp b/libs/nativewindow/AHardwareBuffer.cpp
index f3009dd..180dce9 100644
--- a/libs/nativewindow/AHardwareBuffer.cpp
+++ b/libs/nativewindow/AHardwareBuffer.cpp
@@ -16,6 +16,8 @@
#define LOG_TAG "AHardwareBuffer"
+#include <android/hardware_buffer.h>
+#include <android/hardware_buffer_aidl.h>
#include <vndk/hardware_buffer.h>
#include <errno.h>
@@ -32,6 +34,9 @@
#include <android/hardware/graphics/common/1.1/types.h>
#include <aidl/android/hardware/graphics/common/PixelFormat.h>
+// TODO: Better way to handle this
+#include "../binder/ndk/parcel_internal.h"
+
static constexpr int kFdBufferSize = 128 * sizeof(int); // 128 ints
using namespace android;
@@ -412,6 +417,25 @@
return OK;
}
+binder_status_t AHardwareBuffer_readFromParcel(const AParcel* _Nonnull parcel,
+ AHardwareBuffer* _Nullable* _Nonnull outBuffer) {
+ if (!parcel || !outBuffer) return STATUS_BAD_VALUE;
+ auto buffer = sp<GraphicBuffer>::make();
+ status_t status = parcel->get()->read(*buffer);
+ if (status != STATUS_OK) return status;
+ *outBuffer = AHardwareBuffer_from_GraphicBuffer(buffer.get());
+ AHardwareBuffer_acquire(*outBuffer);
+ return STATUS_OK;
+}
+
+binder_status_t AHardwareBuffer_writeToParcel(const AHardwareBuffer* _Nonnull buffer,
+ AParcel* _Nonnull parcel) {
+ const GraphicBuffer* gb = AHardwareBuffer_to_GraphicBuffer(buffer);
+ if (!gb) return STATUS_BAD_VALUE;
+ if (!parcel) return STATUS_BAD_VALUE;
+ return parcel->get()->write(*gb);
+}
+
// ----------------------------------------------------------------------------
// VNDK functions
// ----------------------------------------------------------------------------
diff --git a/libs/nativewindow/ANativeWindow.cpp b/libs/nativewindow/ANativeWindow.cpp
index 731f989..b075080 100644
--- a/libs/nativewindow/ANativeWindow.cpp
+++ b/libs/nativewindow/ANativeWindow.cpp
@@ -220,6 +220,15 @@
return native_window_set_frame_rate(window, frameRate, compatibility, changeFrameRateStrategy);
}
+int32_t ANativeWindow_clearFrameRate(ANativeWindow* window) {
+ if (!window || !query(window, NATIVE_WINDOW_IS_VALID)) {
+ return -EINVAL;
+ }
+ return native_window_set_frame_rate(window, 0,
+ ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT,
+ ANATIVEWINDOW_CHANGE_FRAME_RATE_ONLY_IF_SEAMLESS);
+}
+
/**************************************************************************************************
* vndk-stable
**************************************************************************************************/
diff --git a/libs/nativewindow/Android.bp b/libs/nativewindow/Android.bp
index dd07319..fbfecf6 100644
--- a/libs/nativewindow/Android.bp
+++ b/libs/nativewindow/Android.bp
@@ -96,6 +96,8 @@
"liblog",
"libutils",
"libui",
+ "libbinder",
+ "libbinder_ndk",
"android.hardware.graphics.common@1.1",
],
diff --git a/libs/nativewindow/include/android/hardware_buffer_aidl.h b/libs/nativewindow/include/android/hardware_buffer_aidl.h
new file mode 100644
index 0000000..906d9c6
--- /dev/null
+++ b/libs/nativewindow/include/android/hardware_buffer_aidl.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * @file hardware_buffer_aidl.h
+ * @brief HardwareBuffer NDK AIDL glue code
+ */
+
+/**
+ * @addtogroup AHardwareBuffer
+ *
+ * Parcelable support for AHardwareBuffer. Can be used with libbinder_ndk
+ *
+ * @{
+ */
+
+#ifndef ANDROID_HARDWARE_BUFFER_AIDL_H
+#define ANDROID_HARDWARE_BUFFER_AIDL_H
+
+#include <android/binder_parcel.h>
+#include <android/hardware_buffer.h>
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/**
+ * Read an AHardwareBuffer from a AParcel. The output buffer will have an
+ * initial reference acquired and will need to be released with
+ * AHardwareBuffer_release.
+ *
+ * Available since API level 34.
+ *
+ * \return STATUS_OK on success
+ * STATUS_BAD_VALUE if the parcel or outBuffer is null, or if there's an
+ * issue deserializing (eg, corrupted parcel)
+ * STATUS_BAD_TYPE if the parcel's current data position is not that of
+ * an AHardwareBuffer type
+ * STATUS_NO_MEMORY if an allocation fails
+ */
+binder_status_t AHardwareBuffer_readFromParcel(const AParcel* _Nonnull parcel,
+ AHardwareBuffer* _Nullable* _Nonnull outBuffer) __INTRODUCED_IN(34);
+
+/**
+ * Write an AHardwareBuffer to an AParcel.
+ *
+ * Available since API level 34.
+ *
+ * \return STATUS_OK on success.
+ * STATUS_BAD_VALUE if either buffer or parcel is null, or if the AHardwareBuffer*
+ * fails to serialize (eg, internally corrupted)
+ * STATUS_NO_MEMORY if the parcel runs out of space to store the buffer & is
+ * unable to allocate more
+ * STATUS_FDS_NOT_ALLOWED if the parcel does not allow storing FDs
+ */
+binder_status_t AHardwareBuffer_writeToParcel(const AHardwareBuffer* _Nonnull buffer,
+ AParcel* _Nonnull parcel) __INTRODUCED_IN(34);
+
+__END_DECLS
+
+// Only enable the AIDL glue helper if this is C++
+#ifdef __cplusplus
+
+namespace aidl::android::hardware {
+
+/**
+ * Wrapper class that enables interop with AIDL NDK generation
+ * Takes ownership of the AHardwareBuffer* given to it in reset() and will automatically
+ * destroy it in the destructor, similar to a smart pointer container
+ */
+class HardwareBuffer {
+public:
+ HardwareBuffer() noexcept {}
+ explicit HardwareBuffer(HardwareBuffer&& other) noexcept : mBuffer(other.release()) {}
+
+ ~HardwareBuffer() {
+ reset();
+ }
+
+ binder_status_t readFromParcel(const AParcel* _Nonnull parcel) {
+ reset();
+ return AHardwareBuffer_readFromParcel(parcel, &mBuffer);
+ }
+
+ binder_status_t writeToParcel(AParcel* _Nonnull parcel) const {
+ if (!mBuffer) {
+ return STATUS_BAD_VALUE;
+ }
+ return AHardwareBuffer_writeToParcel(mBuffer, parcel);
+ }
+
+ /**
+ * Destroys any currently owned AHardwareBuffer* and takes ownership of the given
+ * AHardwareBuffer*
+ *
+ * @param buffer The buffer to take ownership of
+ */
+ void reset(AHardwareBuffer* _Nullable buffer = nullptr) noexcept {
+ if (mBuffer) {
+ AHardwareBuffer_release(mBuffer);
+ mBuffer = nullptr;
+ }
+ mBuffer = buffer;
+ }
+
+ inline AHardwareBuffer* _Nullable operator-> () const { return mBuffer; }
+ inline AHardwareBuffer* _Nullable get() const { return mBuffer; }
+ inline explicit operator bool () const { return mBuffer != nullptr; }
+
+ HardwareBuffer& operator=(HardwareBuffer&& other) noexcept {
+ reset(other.release());
+ return *this;
+ }
+
+ /**
+ * Stops managing any contained AHardwareBuffer*, returning it to the caller. Ownership
+ * is released.
+ * @return AHardwareBuffer* or null if this was empty
+ */
+ [[nodiscard]] AHardwareBuffer* _Nullable release() noexcept {
+ AHardwareBuffer* _Nullable ret = mBuffer;
+ mBuffer = nullptr;
+ return ret;
+ }
+
+private:
+ HardwareBuffer(const HardwareBuffer& other) = delete;
+ HardwareBuffer& operator=(const HardwareBuffer& other) = delete;
+
+ AHardwareBuffer* _Nullable mBuffer = nullptr;
+};
+
+} // aidl::android::hardware
+
+#endif // __cplusplus
+
+#endif // ANDROID_HARDWARE_BUFFER_AIDL_H
+
+/** @} */
diff --git a/libs/nativewindow/include/android/native_window.h b/libs/nativewindow/include/android/native_window.h
index 20f4b52..281ec52 100644
--- a/libs/nativewindow/include/android/native_window.h
+++ b/libs/nativewindow/include/android/native_window.h
@@ -313,6 +313,8 @@
* You can register for changes in the refresh rate using
* \a AChoreographer_registerRefreshRateCallback.
*
+ * See ANativeWindow_clearFrameRate().
+ *
* Available since API level 31.
*
* \param window pointer to an ANativeWindow object.
@@ -342,6 +344,37 @@
int8_t compatibility, int8_t changeFrameRateStrategy)
__INTRODUCED_IN(31);
+/**
+ * Clears the frame rate which is set for this window.
+ *
+ * This is equivalent to calling
+ * ANativeWindow_setFrameRateWithChangeStrategy(window, 0, compatibility, changeFrameRateStrategy).
+ *
+ * Usage of this API won't introduce frame rate throttling,
+ * or affect other aspects of the application's frame production
+ * pipeline. However, because the system may change the display refresh rate,
+ * calls to this function may result in changes to Choreographer callback
+ * timings, and changes to the time interval at which the system releases
+ * buffers back to the application.
+ *
+ * Note that this only has an effect for windows presented on the display. If
+ * this ANativeWindow is consumed by something other than the system compositor,
+ * e.g. a media codec, this call has no effect.
+ *
+ * You can register for changes in the refresh rate using
+ * \a AChoreographer_registerRefreshRateCallback.
+ *
+ * See ANativeWindow_setFrameRateWithChangeStrategy().
+ *
+ * Available since API level 34.
+ *
+ * \param window pointer to an ANativeWindow object.
+ *
+ * \return 0 for success, -EINVAL if the window value is invalid.
+ */
+int32_t ANativeWindow_clearFrameRate(ANativeWindow* window)
+ __INTRODUCED_IN(__ANDROID_API_U__);
+
#ifdef __cplusplus
};
#endif
diff --git a/libs/nativewindow/libnativewindow.map.txt b/libs/nativewindow/libnativewindow.map.txt
index 6296f9a..ce108b6 100644
--- a/libs/nativewindow/libnativewindow.map.txt
+++ b/libs/nativewindow/libnativewindow.map.txt
@@ -14,6 +14,8 @@
AHardwareBuffer_release;
AHardwareBuffer_sendHandleToUnixSocket;
AHardwareBuffer_unlock;
+ AHardwareBuffer_readFromParcel; # introduced=34
+ AHardwareBuffer_writeToParcel; # introduced=34
ANativeWindowBuffer_getHardwareBuffer; # llndk
ANativeWindow_OemStorageGet; # llndk
ANativeWindow_OemStorageSet; # llndk
@@ -49,6 +51,7 @@
ANativeWindow_setDequeueTimeout; # systemapi # introduced=30
ANativeWindow_setFrameRate; # introduced=30
ANativeWindow_setFrameRateWithChangeStrategy; # introduced=31
+ ANativeWindow_clearFrameRate; # introduced=UpsideDownCake
ANativeWindow_setSharedBufferMode; # llndk
ANativeWindow_setSwapInterval; # llndk
ANativeWindow_setUsage; # llndk
diff --git a/libs/renderengine/Android.bp b/libs/renderengine/Android.bp
index f6f57dd..0540538 100644
--- a/libs/renderengine/Android.bp
+++ b/libs/renderengine/Android.bp
@@ -21,13 +21,15 @@
cc_defaults {
name: "librenderengine_defaults",
- defaults: ["renderengine_defaults"],
+ defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
+ "renderengine_defaults",
+ ],
cflags: [
"-DGL_GLEXT_PROTOTYPES",
"-DEGL_EGLEXT_PROTOTYPES",
],
shared_libs: [
- "android.hardware.graphics.composer3-V1-ndk",
"libbase",
"libcutils",
"libEGL",
diff --git a/libs/renderengine/benchmark/Android.bp b/libs/renderengine/benchmark/Android.bp
index 249fec5..afbe6cf 100644
--- a/libs/renderengine/benchmark/Android.bp
+++ b/libs/renderengine/benchmark/Android.bp
@@ -24,6 +24,7 @@
cc_benchmark {
name: "librenderengine_bench",
defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
"skia_deps",
"surfaceflinger_defaults",
],
@@ -43,7 +44,6 @@
],
shared_libs: [
- "android.hardware.graphics.composer3-V1-ndk",
"libbase",
"libcutils",
"libjnigraphics",
diff --git a/libs/renderengine/tests/Android.bp b/libs/renderengine/tests/Android.bp
index bbab792..6f328d7 100644
--- a/libs/renderengine/tests/Android.bp
+++ b/libs/renderengine/tests/Android.bp
@@ -24,6 +24,7 @@
cc_test {
name: "librenderengine_test",
defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
"skia_deps",
"surfaceflinger_defaults",
],
@@ -49,7 +50,6 @@
],
shared_libs: [
- "android.hardware.graphics.composer3-V1-ndk",
"libbase",
"libcutils",
"libEGL",
diff --git a/libs/sensor/ISensorServer.cpp b/libs/sensor/ISensorServer.cpp
index a6cacad..78f692b 100644
--- a/libs/sensor/ISensorServer.cpp
+++ b/libs/sensor/ISensorServer.cpp
@@ -22,12 +22,12 @@
#include <cutils/native_handle.h>
#include <utils/Errors.h>
#include <utils/RefBase.h>
-#include <utils/Vector.h>
#include <utils/Timers.h>
+#include <utils/Vector.h>
-#include <binder/Parcel.h>
#include <binder/IInterface.h>
#include <binder/IResultReceiver.h>
+#include <binder/Parcel.h>
#include <sensor/Sensor.h>
#include <sensor/ISensorEventConnection.h>
@@ -205,9 +205,10 @@
if (resource == nullptr) {
return BAD_VALUE;
}
+ native_handle_set_fdsan_tag(resource);
sp<ISensorEventConnection> ch =
createSensorDirectConnection(opPackageName, size, type, format, resource);
- native_handle_close(resource);
+ native_handle_close_with_tag(resource);
native_handle_delete(resource);
reply->writeStrongBinder(IInterface::asBinder(ch));
return NO_ERROR;
diff --git a/libs/shaders/Android.bp b/libs/shaders/Android.bp
index 6b936de..960f845 100644
--- a/libs/shaders/Android.bp
+++ b/libs/shaders/Android.bp
@@ -23,13 +23,14 @@
cc_library_static {
name: "libshaders",
-
+ defaults: [
+ "android.hardware.graphics.common-ndk_shared",
+ "android.hardware.graphics.composer3-ndk_shared",
+ ],
export_include_dirs: ["include"],
local_include_dirs: ["include"],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.graphics.common@1.2",
"libnativewindow",
],
diff --git a/libs/shaders/tests/Android.bp b/libs/shaders/tests/Android.bp
index cf671bc..1e4f45a 100644
--- a/libs/shaders/tests/Android.bp
+++ b/libs/shaders/tests/Android.bp
@@ -23,6 +23,10 @@
cc_test {
name: "libshaders_test",
+ defaults: [
+ "android.hardware.graphics.common-ndk_shared",
+ "android.hardware.graphics.composer3-ndk_shared",
+ ],
test_suites: ["device-tests"],
srcs: [
"shaders_test.cpp",
@@ -31,8 +35,6 @@
"libtonemap_headers",
],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.graphics.common@1.2",
"libnativewindow",
],
diff --git a/libs/tonemap/Android.bp b/libs/tonemap/Android.bp
index 37c9824..8c8815d 100644
--- a/libs/tonemap/Android.bp
+++ b/libs/tonemap/Android.bp
@@ -23,13 +23,15 @@
cc_library_static {
name: "libtonemap",
+ defaults: [
+ "android.hardware.graphics.common-ndk_shared",
+ "android.hardware.graphics.composer3-ndk_shared",
+ ],
vendor_available: true,
local_include_dirs: ["include"],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
- "android.hardware.graphics.composer3-V1-ndk",
"liblog",
"libnativewindow",
],
diff --git a/libs/tonemap/tests/Android.bp b/libs/tonemap/tests/Android.bp
index 58851b4..2abf515 100644
--- a/libs/tonemap/tests/Android.bp
+++ b/libs/tonemap/tests/Android.bp
@@ -23,6 +23,10 @@
cc_test {
name: "libtonemap_test",
+ defaults: [
+ "android.hardware.graphics.common-ndk_shared",
+ "android.hardware.graphics.composer3-ndk_shared",
+ ],
test_suites: ["device-tests"],
srcs: [
"tonemap_test.cpp",
@@ -31,8 +35,6 @@
"libtonemap_headers",
],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
- "android.hardware.graphics.composer3-V1-ndk",
"libnativewindow",
],
static_libs: [
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index ca8adfa..d33dd34 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -152,6 +152,8 @@
],
defaults: [
+ "android.hardware.graphics.allocator-ndk_shared",
+ "android.hardware.graphics.common-ndk_shared",
"libui-defaults",
// Uncomment the following line to enable VALIDATE_REGIONS traces
//defaults: ["libui-validate-regions-defaults"],
@@ -161,8 +163,6 @@
"android.hardware.graphics.allocator@2.0",
"android.hardware.graphics.allocator@3.0",
"android.hardware.graphics.allocator@4.0",
- "android.hardware.graphics.allocator-V1-ndk",
- "android.hardware.graphics.common-V3-ndk",
"android.hardware.graphics.common@1.2",
"android.hardware.graphics.mapper@2.0",
"android.hardware.graphics.mapper@2.1",
@@ -180,7 +180,6 @@
export_shared_lib_headers: [
"android.hardware.graphics.common@1.2",
- "android.hardware.graphics.common-V3-ndk",
"android.hardware.graphics.mapper@4.0",
"libgralloctypes",
],
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index 3732fee..429760f 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -465,7 +465,7 @@
if (flattenWordCount == 13) {
usage = (uint64_t(buf[12]) << 32) | uint32_t(buf[6]);
} else {
- usage = uint64_t(usage_deprecated);
+ usage = uint64_t(ANDROID_NATIVE_UNSIGNED_CAST(usage_deprecated));
}
native_handle* h =
native_handle_create(static_cast<int>(numFds), static_cast<int>(numInts));
diff --git a/libs/ui/include/ui/DisplayId.h b/libs/ui/include/ui/DisplayId.h
index 9120972..d0c03fe 100644
--- a/libs/ui/include/ui/DisplayId.h
+++ b/libs/ui/include/ui/DisplayId.h
@@ -17,9 +17,10 @@
#pragma once
#include <cstdint>
-#include <optional>
#include <string>
+#include <ftl/optional.h>
+
namespace android {
// ID of a physical or a virtual display. This class acts as a type safe wrapper around uint64_t.
@@ -68,7 +69,7 @@
// DisplayId of a physical display, such as the internal display or externally connected display.
struct PhysicalDisplayId : DisplayId {
- static constexpr std::optional<PhysicalDisplayId> tryCast(DisplayId id) {
+ static constexpr ftl::Optional<PhysicalDisplayId> tryCast(DisplayId id) {
if (id.value & FLAG_VIRTUAL) {
return std::nullopt;
}
diff --git a/libs/ui/include/ui/StaticDisplayInfo.h b/libs/ui/include/ui/StaticDisplayInfo.h
index 566e417..83da821 100644
--- a/libs/ui/include/ui/StaticDisplayInfo.h
+++ b/libs/ui/include/ui/StaticDisplayInfo.h
@@ -23,7 +23,7 @@
namespace android::ui {
-enum class DisplayConnectionType { Internal, External };
+enum class DisplayConnectionType { Internal, External, ftl_last = External };
// Immutable information about physical display.
struct StaticDisplayInfo {
diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp
index 29a0e4f..5b286dc 100644
--- a/services/inputflinger/Android.bp
+++ b/services/inputflinger/Android.bp
@@ -148,6 +148,7 @@
srcs: [":libinputflinger_base_sources"],
shared_libs: [
"libbase",
+ "libbinder",
"libcutils",
"libinput",
"liblog",
diff --git a/services/inputflinger/BlockingQueue.h b/services/inputflinger/BlockingQueue.h
index 8300e8a..fe37287 100644
--- a/services/inputflinger/BlockingQueue.h
+++ b/services/inputflinger/BlockingQueue.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_BLOCKING_QUEUE_H
-#define _UI_INPUT_BLOCKING_QUEUE_H
+#pragma once
#include "android-base/thread_annotations.h"
#include <condition_variable>
@@ -106,6 +105,4 @@
std::vector<T> mQueue GUARDED_BY(mLock);
};
-
} // namespace android
-#endif
diff --git a/services/inputflinger/InputManager.h b/services/inputflinger/InputManager.h
index b40ab7f..1137193 100644
--- a/services/inputflinger/InputManager.h
+++ b/services/inputflinger/InputManager.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_MANAGER_H
-#define _UI_INPUT_MANAGER_H
+#pragma once
/**
* Native input manager.
@@ -130,5 +129,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_MANAGER_H
diff --git a/services/inputflinger/InputProcessor.h b/services/inputflinger/InputProcessor.h
index 261e012..bbf391e 100644
--- a/services/inputflinger/InputProcessor.h
+++ b/services/inputflinger/InputProcessor.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_CLASSIFIER_H
-#define _UI_INPUT_CLASSIFIER_H
+#pragma once
#include <android-base/thread_annotations.h>
#include <future>
@@ -288,4 +287,3 @@
};
} // namespace android
-#endif
diff --git a/services/inputflinger/dispatcher/AnrTracker.h b/services/inputflinger/dispatcher/AnrTracker.h
index 097dba5..5e5e0c4 100644
--- a/services/inputflinger/dispatcher/AnrTracker.h
+++ b/services/inputflinger/dispatcher/AnrTracker.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
-#define _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
+#pragma once
#include <binder/IBinder.h>
#include <utils/Timers.h>
@@ -56,5 +55,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_ANRTRACKER_H
diff --git a/services/inputflinger/dispatcher/CancelationOptions.h b/services/inputflinger/dispatcher/CancelationOptions.h
index fec5f83..d210e9e 100644
--- a/services/inputflinger/dispatcher/CancelationOptions.h
+++ b/services/inputflinger/dispatcher/CancelationOptions.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_CANCELLATIONOPTIONS_H
-#define _UI_INPUT_INPUTDISPATCHER_CANCELLATIONOPTIONS_H
+#pragma once
#include <utils/BitSet.h>
#include <optional>
@@ -55,5 +54,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_CANCELLATIONOPTIONS_H
diff --git a/services/inputflinger/dispatcher/Connection.h b/services/inputflinger/dispatcher/Connection.h
index dc6a081..6040e9b 100644
--- a/services/inputflinger/dispatcher/Connection.h
+++ b/services/inputflinger/dispatcher/Connection.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_CONNECTION_H
-#define _UI_INPUT_INPUTDISPATCHER_CONNECTION_H
+#pragma once
#include "InputState.h"
@@ -74,5 +73,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_CONNECTION_H
diff --git a/services/inputflinger/dispatcher/DebugConfig.h b/services/inputflinger/dispatcher/DebugConfig.h
index 4f8995f..d2ad407 100644
--- a/services/inputflinger/dispatcher/DebugConfig.h
+++ b/services/inputflinger/dispatcher/DebugConfig.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_DISPATCHER_DEBUG_CONFIG_H
-#define _UI_INPUT_DISPATCHER_DEBUG_CONFIG_H
+#pragma once
#define LOG_TAG "InputDispatcher"
@@ -75,11 +74,8 @@
/**
* Log debug messages about touch occlusion
- * Enable this via "adb shell setprop log.tag.InputDispatcherTouchOcclusion DEBUG" (requires
- * restart)
*/
-const bool DEBUG_TOUCH_OCCLUSION =
- __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "TouchOcclusion", ANDROID_LOG_INFO);
+constexpr bool DEBUG_TOUCH_OCCLUSION = true;
/**
* Log debug messages about the app switch latency optimization.
@@ -95,5 +91,3 @@
const bool DEBUG_HOVER =
__android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Hover", ANDROID_LOG_INFO);
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_DISPATCHER_DEBUG_CONFIG_H
\ No newline at end of file
diff --git a/services/inputflinger/dispatcher/DragState.h b/services/inputflinger/dispatcher/DragState.h
index d1c8b8a..9809148 100644
--- a/services/inputflinger/dispatcher/DragState.h
+++ b/services/inputflinger/dispatcher/DragState.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_DRAGSTATE_H
-#define _UI_INPUT_INPUTDISPATCHER_DRAGSTATE_H
+#pragma once
#include <gui/WindowInfo.h>
#include <utils/StrongPointer.h>
@@ -44,5 +43,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_DRAGSTATE_H
\ No newline at end of file
diff --git a/services/inputflinger/dispatcher/Entry.h b/services/inputflinger/dispatcher/Entry.h
index 0f79296..1f916f3 100644
--- a/services/inputflinger/dispatcher/Entry.h
+++ b/services/inputflinger/dispatcher/Entry.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_ENTRY_H
-#define _UI_INPUT_INPUTDISPATCHER_ENTRY_H
+#pragma once
#include "InjectionState.h"
#include "InputTarget.h"
@@ -257,5 +256,3 @@
const ui::Transform& rawTransform);
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_ENTRY_H
diff --git a/services/inputflinger/dispatcher/FocusResolver.cpp b/services/inputflinger/dispatcher/FocusResolver.cpp
index 85dcf8f..4da846b 100644
--- a/services/inputflinger/dispatcher/FocusResolver.cpp
+++ b/services/inputflinger/dispatcher/FocusResolver.cpp
@@ -39,7 +39,7 @@
return it != mFocusedWindowTokenByDisplay.end() ? it->second.second : nullptr;
}
-std::optional<FocusRequest> FocusResolver::getFocusRequest(int32_t displayId) const {
+std::optional<FocusRequest> FocusResolver::getFocusRequest(int32_t displayId) {
auto it = mFocusRequestByDisplay.find(displayId);
return it != mFocusRequestByDisplay.end() ? std::make_optional<>(it->second) : std::nullopt;
}
diff --git a/services/inputflinger/dispatcher/FocusResolver.h b/services/inputflinger/dispatcher/FocusResolver.h
index 8a6dfa4..6d11a77 100644
--- a/services/inputflinger/dispatcher/FocusResolver.h
+++ b/services/inputflinger/dispatcher/FocusResolver.h
@@ -62,7 +62,6 @@
std::optional<FocusResolver::FocusChanges> setFocusedWindow(
const android::gui::FocusRequest& request,
const std::vector<sp<android::gui::WindowInfoHandle>>& windows);
- std::optional<android::gui::FocusRequest> getFocusRequest(int32_t displayId) const;
// Display has been removed from the system, clean up old references.
void displayRemoved(int32_t displayId);
@@ -113,6 +112,7 @@
std::optional<FocusResolver::FocusChanges> updateFocusedWindow(
int32_t displayId, const std::string& reason, const sp<IBinder>& token,
const std::string& tokenName = "");
+ std::optional<android::gui::FocusRequest> getFocusRequest(int32_t displayId);
};
} // namespace android::inputdispatcher
diff --git a/services/inputflinger/dispatcher/InjectionState.h b/services/inputflinger/dispatcher/InjectionState.h
index 90cf150..d9e27ba 100644
--- a/services/inputflinger/dispatcher/InjectionState.h
+++ b/services/inputflinger/dispatcher/InjectionState.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INJECTIONSTATE_H
-#define _UI_INPUT_INPUTDISPATCHER_INJECTIONSTATE_H
+#pragma once
#include <stdint.h>
#include "InputDispatcherInterface.h"
@@ -41,5 +40,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INJECTIONSTATE_H
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index b52e312..ff63a6f 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -659,13 +659,6 @@
if (focusedWindowHandle != nullptr) {
return; // We now have a focused window. No need for ANR.
}
- std::optional<FocusRequest> pendingRequest =
- mFocusResolver.getFocusRequest(mAwaitedApplicationDisplayId);
- if (pendingRequest.has_value() && onAnrLocked(*pendingRequest)) {
- // We don't have a focusable window but we know which window should have
- // been focused. Blame that process in case it doesn't belong to the focused app.
- return;
- }
onAnrLocked(mAwaitedFocusedApplication);
}
@@ -2998,7 +2991,7 @@
ATRACE_NAME(message.c_str());
}
- bool wasEmpty = connection->outboundQueue.empty();
+ const bool wasEmpty = connection->outboundQueue.empty();
// Enqueue dispatch entries for the requested modes.
enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,
@@ -3681,6 +3674,8 @@
target.inputChannel = connection->inputChannel;
target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
+ const bool wasEmpty = connection->outboundQueue.empty();
+
for (size_t i = 0; i < cancelationEvents.size(); i++) {
std::unique_ptr<EventEntry> cancelationEventEntry = std::move(cancelationEvents[i]);
switch (cancelationEventEntry->type) {
@@ -3715,7 +3710,10 @@
InputTarget::FLAG_DISPATCH_AS_IS);
}
- startDispatchCycleLocked(currentTime, connection);
+ // If the outbound queue was previously empty, start the dispatch cycle going.
+ if (wasEmpty && !connection->outboundQueue.empty()) {
+ startDispatchCycleLocked(currentTime, connection);
+ }
}
void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
@@ -3747,6 +3745,7 @@
target.inputChannel = connection->inputChannel;
target.flags = InputTarget::FLAG_DISPATCH_AS_IS;
+ const bool wasEmpty = connection->outboundQueue.empty();
for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
switch (downEventEntry->type) {
case EventEntry::Type::MOTION: {
@@ -3773,7 +3772,10 @@
InputTarget::FLAG_DISPATCH_AS_IS);
}
- startDispatchCycleLocked(downTime, connection);
+ // If the outbound queue was previously empty, start the dispatch cycle going.
+ if (wasEmpty && !connection->outboundQueue.empty()) {
+ startDispatchCycleLocked(downTime, connection);
+ }
}
std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
@@ -5855,25 +5857,6 @@
postCommandLocked(std::move(command));
}
-bool InputDispatcher::onAnrLocked(const android::gui::FocusRequest& pendingFocusRequest) {
- if (pendingFocusRequest.token == nullptr) {
- return false;
- }
-
- const std::string reason = android::base::StringPrintf("%s is not focusable.",
- pendingFocusRequest.windowName.c_str());
- updateLastAnrStateLocked(pendingFocusRequest.windowName, reason);
- sp<Connection> connection = getConnectionLocked(pendingFocusRequest.token);
- if (connection != nullptr) {
- processConnectionUnresponsiveLocked(*connection, std::move(reason));
- // Stop waking up for events on this connection, it is already unresponsive
- cancelEventsForAnrLocked(connection);
- } else {
- sendWindowUnresponsiveCommandLocked(pendingFocusRequest.token, std::nullopt, reason);
- }
- return true;
-}
-
void InputDispatcher::onAnrLocked(const sp<Connection>& connection) {
if (connection == nullptr) {
LOG_ALWAYS_FATAL("Caller must check for nullness");
diff --git a/services/inputflinger/dispatcher/InputDispatcher.h b/services/inputflinger/dispatcher/InputDispatcher.h
index dc6dd5c..b5bbce8 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.h
+++ b/services/inputflinger/dispatcher/InputDispatcher.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_DISPATCHER_H
-#define _UI_INPUT_DISPATCHER_H
+#pragma once
#include "AnrTracker.h"
#include "CancelationOptions.h"
@@ -658,7 +657,6 @@
void sendDropWindowCommandLocked(const sp<IBinder>& token, float x, float y) REQUIRES(mLock);
void onAnrLocked(const sp<Connection>& connection) REQUIRES(mLock);
void onAnrLocked(std::shared_ptr<InputApplicationHandle> application) REQUIRES(mLock);
- bool onAnrLocked(const android::gui::FocusRequest& pendingFocusRequest) REQUIRES(mLock);
void updateLastAnrStateLocked(const sp<android::gui::WindowInfoHandle>& window,
const std::string& reason) REQUIRES(mLock);
void updateLastAnrStateLocked(const InputApplicationHandle& application,
@@ -694,5 +692,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_DISPATCHER_H
diff --git a/services/inputflinger/dispatcher/InputEventTimeline.h b/services/inputflinger/dispatcher/InputEventTimeline.h
index 77b8472..daf375d 100644
--- a/services/inputflinger/dispatcher/InputEventTimeline.h
+++ b/services/inputflinger/dispatcher/InputEventTimeline.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTEVENTTIMELINE_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTEVENTTIMELINE_H
+#pragma once
#include <binder/IBinder.h>
#include <input/Input.h>
@@ -104,5 +103,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTEVENTTIMELINE_H
diff --git a/services/inputflinger/dispatcher/InputState.h b/services/inputflinger/dispatcher/InputState.h
index 77a6db1..6ab48c9 100644
--- a/services/inputflinger/dispatcher/InputState.h
+++ b/services/inputflinger/dispatcher/InputState.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTSTATE_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTSTATE_H
+#pragma once
#include "CancelationOptions.h"
#include "Entry.h"
@@ -134,5 +133,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTSTATE_H
diff --git a/services/inputflinger/dispatcher/InputTarget.h b/services/inputflinger/dispatcher/InputTarget.h
index ac20dab..b2966f6 100644
--- a/services/inputflinger/dispatcher/InputTarget.h
+++ b/services/inputflinger/dispatcher/InputTarget.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTTARGET_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTTARGET_H
+#pragma once
#include <gui/constants.h>
#include <input/InputTransport.h>
@@ -136,5 +135,3 @@
std::string dispatchModeToString(int32_t dispatchMode);
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTTARGET_H
diff --git a/services/inputflinger/dispatcher/LatencyAggregator.h b/services/inputflinger/dispatcher/LatencyAggregator.h
index ed5731f..accfc29 100644
--- a/services/inputflinger/dispatcher/LatencyAggregator.h
+++ b/services/inputflinger/dispatcher/LatencyAggregator.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_LATENCYAGGREGATOR_H
-#define _UI_INPUT_INPUTDISPATCHER_LATENCYAGGREGATOR_H
+#pragma once
#include <kll.h>
#include <statslog.h>
@@ -86,5 +85,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_LATENCYAGGREGATOR_H
diff --git a/services/inputflinger/dispatcher/LatencyTracker.h b/services/inputflinger/dispatcher/LatencyTracker.h
index 4b0c618..64dfeef 100644
--- a/services/inputflinger/dispatcher/LatencyTracker.h
+++ b/services/inputflinger/dispatcher/LatencyTracker.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_LATENCYTRACKER_H
-#define _UI_INPUT_INPUTDISPATCHER_LATENCYTRACKER_H
+#pragma once
#include <map>
#include <unordered_map>
@@ -81,5 +80,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_LATENCYTRACKER_H
diff --git a/services/inputflinger/dispatcher/Monitor.h b/services/inputflinger/dispatcher/Monitor.h
index 365d5be..7b51191 100644
--- a/services/inputflinger/dispatcher/Monitor.h
+++ b/services/inputflinger/dispatcher/Monitor.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_MONITOR_H
-#define _UI_INPUT_INPUTDISPATCHER_MONITOR_H
+#pragma once
#include <input/InputTransport.h>
@@ -30,5 +29,3 @@
};
} // namespace android::inputdispatcher
-
-#endif // _UI_INPUT_INPUTDISPATCHER_MONITOR_H
diff --git a/services/inputflinger/dispatcher/TouchState.h b/services/inputflinger/dispatcher/TouchState.h
index 1fb51e1..cf5f1e5 100644
--- a/services/inputflinger/dispatcher/TouchState.h
+++ b/services/inputflinger/dispatcher/TouchState.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_TOUCHSTATE_H
-#define _UI_INPUT_INPUTDISPATCHER_TOUCHSTATE_H
+#pragma once
#include "Monitor.h"
#include "TouchedWindow.h"
@@ -67,5 +66,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_TOUCHSTATE_H
diff --git a/services/inputflinger/dispatcher/TouchedWindow.h b/services/inputflinger/dispatcher/TouchedWindow.h
index a7839db..a6c505b 100644
--- a/services/inputflinger/dispatcher/TouchedWindow.h
+++ b/services/inputflinger/dispatcher/TouchedWindow.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_TOUCHEDWINDOW_H
-#define _UI_INPUT_INPUTDISPATCHER_TOUCHEDWINDOW_H
+#pragma once
namespace android {
@@ -38,5 +37,3 @@
} // namespace inputdispatcher
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_TOUCHEDWINDOW_H
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherConfiguration.h b/services/inputflinger/dispatcher/include/InputDispatcherConfiguration.h
index 00abf47..5eb3a32 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherConfiguration.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherConfiguration.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERCONFIGURATION_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERCONFIGURATION_H
+#pragma once
#include <utils/Timers.h>
@@ -40,5 +39,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERCONFIGURATION_H
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherFactory.h b/services/inputflinger/dispatcher/include/InputDispatcherFactory.h
index 38d0c32..5247d8e 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherFactory.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherFactory.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERFACTORY_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERFACTORY_H
+#pragma once
#include <utils/StrongPointer.h>
@@ -29,5 +28,3 @@
const sp<InputDispatcherPolicyInterface>& policy);
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERFACTORY_H
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherInterface.h b/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
index 32b3ddb..484b0d3 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERINTERFACE_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERINTERFACE_H
+#pragma once
#include <InputListener.h>
#include <android-base/result.h>
@@ -226,5 +225,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERINTERFACE_H
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h b/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
index 7c299b2..44f3baf 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherPolicyInterface.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERPOLICYINTERFACE_H
-#define _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERPOLICYINTERFACE_H
+#pragma once
#include "InputDispatcherConfiguration.h"
@@ -143,5 +142,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_INPUTDISPATCHER_INPUTDISPATCHERPOLICYINTERFACE_H
diff --git a/services/inputflinger/host/InputDriver.h b/services/inputflinger/host/InputDriver.h
index e56673b..b4c9094 100644
--- a/services/inputflinger/host/InputDriver.h
+++ b/services/inputflinger/host/InputDriver.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef ANDROID_INPUT_DRIVER_H
-#define ANDROID_INPUT_DRIVER_H
+#pragma once
#include <stdint.h>
#include <sys/types.h>
@@ -192,4 +191,3 @@
}
} // namespace android
-#endif // ANDROID_INPUT_DRIVER_H
diff --git a/services/inputflinger/host/InputFlinger.h b/services/inputflinger/host/InputFlinger.h
index 3cf1b2b..388988b 100644
--- a/services/inputflinger/host/InputFlinger.h
+++ b/services/inputflinger/host/InputFlinger.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef ANDROID_INPUT_FLINGER_H
-#define ANDROID_INPUT_FLINGER_H
+#pragma once
#include <stdint.h>
#include <sys/types.h>
@@ -58,5 +57,3 @@
};
} // namespace android
-
-#endif // ANDROID_INPUT_FLINGER_H
diff --git a/services/inputflinger/host/InputHost.h b/services/inputflinger/host/InputHost.h
index eda4a89..bdc4225 100644
--- a/services/inputflinger/host/InputHost.h
+++ b/services/inputflinger/host/InputHost.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef ANDROID_INPUT_HOST_H
-#define ANDROID_INPUT_HOST_H
+#pragma once
#include <vector>
@@ -55,4 +54,3 @@
};
} // namespace android
-#endif // ANDRIOD_INPUT_HOST_H
diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h
index d9822ce..c8ab6c5 100644
--- a/services/inputflinger/include/InputListener.h
+++ b/services/inputflinger/include/InputListener.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_LISTENER_H
-#define _UI_INPUT_LISTENER_H
+#pragma once
#include <vector>
@@ -292,5 +291,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_LISTENER_H
diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h
index 77c9142..cacb63c 100644
--- a/services/inputflinger/include/InputReaderBase.h
+++ b/services/inputflinger/include/InputReaderBase.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_READER_BASE_H
-#define _UI_INPUT_READER_BASE_H
+#pragma once
#include <android/os/IInputConstants.h>
#include <input/DisplayViewport.h>
@@ -114,6 +113,8 @@
virtual std::optional<int32_t> getBatteryCapacity(int32_t deviceId) = 0;
/* Get battery status of a particular input device. */
virtual std::optional<int32_t> getBatteryStatus(int32_t deviceId) = 0;
+ /* Get the device path for the battery of an input device. */
+ virtual std::optional<std::string> getBatteryDevicePath(int32_t deviceId) = 0;
virtual std::vector<InputDeviceLightInfo> getLights(int32_t deviceId) = 0;
@@ -395,5 +396,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_READER_COMMON_H
diff --git a/services/inputflinger/include/InputThread.h b/services/inputflinger/include/InputThread.h
index 407365a..5e75027 100644
--- a/services/inputflinger/include/InputThread.h
+++ b/services/inputflinger/include/InputThread.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_THREAD_H
-#define _UI_INPUT_THREAD_H
+#pragma once
#include <utils/Thread.h>
@@ -42,5 +41,3 @@
};
} // namespace android
-
-#endif // _UI_INPUT_THREAD_H
\ No newline at end of file
diff --git a/services/inputflinger/include/PointerControllerInterface.h b/services/inputflinger/include/PointerControllerInterface.h
index db4228d..647e10c 100644
--- a/services/inputflinger/include/PointerControllerInterface.h
+++ b/services/inputflinger/include/PointerControllerInterface.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H
-#define _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H
+#pragma once
#include <input/DisplayViewport.h>
#include <input/Input.h>
@@ -108,5 +107,3 @@
};
} // namespace android
-
-#endif // _INPUTFLINGER_POINTER_CONTROLLER_INTERFACE_H
diff --git a/services/inputflinger/include/VibrationElement.h b/services/inputflinger/include/VibrationElement.h
index 736041e..04c2e39 100644
--- a/services/inputflinger/include/VibrationElement.h
+++ b/services/inputflinger/include/VibrationElement.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _VIBRATION_ELEMENT_H
-#define _VIBRATION_ELEMENT_H
+#pragma once
#include <array>
#include <chrono>
@@ -71,5 +70,3 @@
};
} // namespace android
-
-#endif // _VIBRATION_ELEMENT_H
diff --git a/services/inputflinger/reader/EventHub.cpp b/services/inputflinger/reader/EventHub.cpp
index 06a38c8..c9d21dc 100644
--- a/services/inputflinger/reader/EventHub.cpp
+++ b/services/inputflinger/reader/EventHub.cpp
@@ -61,6 +61,7 @@
#define INDENT3 " "
using android::base::StringPrintf;
+using android::hardware::input::InputDeviceCountryCode;
namespace android {
@@ -302,6 +303,24 @@
}
/**
+ * Read country code information exposed through the sysfs path.
+ */
+static InputDeviceCountryCode readCountryCodeLocked(const std::filesystem::path& sysfsRootPath) {
+ // Check the sysfs root path
+ int hidCountryCode = static_cast<int>(InputDeviceCountryCode::INVALID);
+ std::string str;
+ if (base::ReadFileToString(sysfsRootPath / "country", &str)) {
+ hidCountryCode = std::stoi(str, nullptr, 16);
+ LOG_ALWAYS_FATAL_IF(hidCountryCode > 35 || hidCountryCode < 0,
+ "HID country code should be in range [0, 35]. Found country code "
+ "to be %d",
+ hidCountryCode);
+ }
+
+ return static_cast<InputDeviceCountryCode>(hidCountryCode);
+}
+
+/**
* Read information about batteries exposed through the sysfs path.
*/
static std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> readBatteryConfiguration(
@@ -1238,6 +1257,15 @@
}
}
+InputDeviceCountryCode EventHub::getCountryCode(int32_t deviceId) const {
+ std::scoped_lock _l(mLock);
+ Device* device = getDeviceLocked(deviceId);
+ if (device == nullptr || !device->associatedDevice) {
+ return InputDeviceCountryCode::INVALID;
+ }
+ return device->associatedDevice->countryCode;
+}
+
void EventHub::setExcludedDevices(const std::vector<std::string>& devices) {
std::scoped_lock _l(mLock);
@@ -1384,6 +1412,7 @@
return std::make_shared<AssociatedDevice>(
AssociatedDevice{.sysfsRootPath = path,
+ .countryCode = readCountryCodeLocked(path),
.batteryInfos = readBatteryConfiguration(path),
.lightInfos = readLightsConfiguration(path)});
}
@@ -1516,25 +1545,35 @@
}
std::optional<int32_t> EventHub::getBatteryCapacity(int32_t deviceId, int32_t batteryId) const {
- std::scoped_lock _l(mLock);
+ std::filesystem::path batteryPath;
+ {
+ // Do not read the sysfs node to get the battery state while holding
+ // the EventHub lock. For some peripheral devices, reading battery state
+ // can be broken and take 5+ seconds. Holding the lock in this case would
+ // block all other event processing during this time. For now, we assume this
+ // call never happens on the InputReader thread and read the sysfs node outside
+ // the lock to prevent event processing from being blocked by this call.
+ std::scoped_lock _l(mLock);
- const auto infos = getBatteryInfoLocked(deviceId);
- auto it = infos.find(batteryId);
- if (it == infos.end()) {
- return std::nullopt;
- }
+ const auto& infos = getBatteryInfoLocked(deviceId);
+ auto it = infos.find(batteryId);
+ if (it == infos.end()) {
+ return std::nullopt;
+ }
+ batteryPath = it->second.path;
+ } // release lock
+
std::string buffer;
// Some devices report battery capacity as an integer through the "capacity" file
- if (base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
+ if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY),
&buffer)) {
return std::stoi(base::Trim(buffer));
}
// Other devices report capacity as an enum value POWER_SUPPLY_CAPACITY_LEVEL_XXX
// These values are taken from kernel source code include/linux/power_supply.h
- if (base::ReadFileToString(it->second.path /
- BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
+ if (base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::CAPACITY_LEVEL),
&buffer)) {
// Remove any white space such as trailing new line
const auto levelIt = BATTERY_LEVEL.find(base::Trim(buffer));
@@ -1547,15 +1586,27 @@
}
std::optional<int32_t> EventHub::getBatteryStatus(int32_t deviceId, int32_t batteryId) const {
- std::scoped_lock _l(mLock);
- const auto infos = getBatteryInfoLocked(deviceId);
- auto it = infos.find(batteryId);
- if (it == infos.end()) {
- return std::nullopt;
- }
+ std::filesystem::path batteryPath;
+ {
+ // Do not read the sysfs node to get the battery state while holding
+ // the EventHub lock. For some peripheral devices, reading battery state
+ // can be broken and take 5+ seconds. Holding the lock in this case would
+ // block all other event processing during this time. For now, we assume this
+ // call never happens on the InputReader thread and read the sysfs node outside
+ // the lock to prevent event processing from being blocked by this call.
+ std::scoped_lock _l(mLock);
+
+ const auto& infos = getBatteryInfoLocked(deviceId);
+ auto it = infos.find(batteryId);
+ if (it == infos.end()) {
+ return std::nullopt;
+ }
+ batteryPath = it->second.path;
+ } // release lock
+
std::string buffer;
- if (!base::ReadFileToString(it->second.path / BATTERY_NODES.at(InputBatteryClass::STATUS),
+ if (!base::ReadFileToString(batteryPath / BATTERY_NODES.at(InputBatteryClass::STATUS),
&buffer)) {
ALOGE("Failed to read sysfs battery info: %s", strerror(errno));
return std::nullopt;
@@ -2553,6 +2604,9 @@
device->keyMap.keyLayoutFile.c_str());
dump += StringPrintf(INDENT3 "KeyCharacterMapFile: %s\n",
device->keyMap.keyCharacterMapFile.c_str());
+ dump += StringPrintf(INDENT3 "CountryCode: %d\n",
+ device->associatedDevice ? device->associatedDevice->countryCode
+ : InputDeviceCountryCode::INVALID);
dump += StringPrintf(INDENT3 "ConfigurationFile: %s\n",
device->configurationFile.c_str());
dump += StringPrintf(INDENT3 "VideoDevice: %s\n",
diff --git a/services/inputflinger/reader/InputDevice.cpp b/services/inputflinger/reader/InputDevice.cpp
index 5c9e63e..44a005e 100644
--- a/services/inputflinger/reader/InputDevice.cpp
+++ b/services/inputflinger/reader/InputDevice.cpp
@@ -35,6 +35,8 @@
#include "SwitchInputMapper.h"
#include "VibratorInputMapper.h"
+using android::hardware::input::InputDeviceCountryCode;
+
namespace android {
InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation,
@@ -240,6 +242,7 @@
mSources = 0;
mClasses = ftl::Flags<InputDeviceClass>(0);
mControllerNumber = 0;
+ mCountryCode = InputDeviceCountryCode::INVALID;
for_each_subdevice([this](InputDeviceContext& context) {
mClasses |= context.getDeviceClasses();
@@ -251,6 +254,16 @@
}
mControllerNumber = controllerNumber;
}
+
+ InputDeviceCountryCode countryCode = context.getCountryCode();
+ if (countryCode != InputDeviceCountryCode::INVALID) {
+ if (mCountryCode != InputDeviceCountryCode::INVALID && mCountryCode != countryCode) {
+ ALOGW("InputDevice::configure(): %s device contains multiple unique country "
+ "codes",
+ getName().c_str());
+ }
+ mCountryCode = countryCode;
+ }
});
mIsExternal = mClasses.test(InputDeviceClass::EXTERNAL);
@@ -422,7 +435,7 @@
InputDeviceInfo InputDevice::getDeviceInfo() {
InputDeviceInfo outDeviceInfo;
outDeviceInfo.initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal,
- mHasMic);
+ mHasMic, mCountryCode);
for_each_mapper(
[&outDeviceInfo](InputMapper& mapper) { mapper.populateDeviceInfo(&outDeviceInfo); });
@@ -548,14 +561,6 @@
for_each_mapper([when, readTime](InputMapper& mapper) { mapper.cancelTouch(when, readTime); });
}
-std::optional<int32_t> InputDevice::getBatteryCapacity() {
- return mController ? mController->getBatteryCapacity(DEFAULT_BATTERY_ID) : std::nullopt;
-}
-
-std::optional<int32_t> InputDevice::getBatteryStatus() {
- return mController ? mController->getBatteryStatus(DEFAULT_BATTERY_ID) : std::nullopt;
-}
-
bool InputDevice::setLightColor(int32_t lightId, int32_t color) {
return mController ? mController->setLightColor(lightId, color) : false;
}
@@ -623,6 +628,10 @@
for_each_mapper([reset](InputMapper& mapper) { mapper.updateLedState(reset); });
}
+std::optional<int32_t> InputDevice::getBatteryEventHubId() const {
+ return mController ? std::make_optional(mController->getEventHubId()) : std::nullopt;
+}
+
InputDeviceContext::InputDeviceContext(InputDevice& device, int32_t eventHubId)
: mDevice(device),
mContext(device.getContext()),
diff --git a/services/inputflinger/reader/InputReader.cpp b/services/inputflinger/reader/InputReader.cpp
index dc41051..4c38ce8 100644
--- a/services/inputflinger/reader/InputReader.cpp
+++ b/services/inputflinger/reader/InputReader.cpp
@@ -706,23 +706,71 @@
}
std::optional<int32_t> InputReader::getBatteryCapacity(int32_t deviceId) {
- std::scoped_lock _l(mLock);
+ std::optional<int32_t> eventHubId;
+ {
+ // Do not query the battery state while holding the lock. For some peripheral devices,
+ // reading battery state can be broken and take 5+ seconds. Holding the lock in this case
+ // would block all other event processing during this time. For now, we assume this
+ // call never happens on the InputReader thread and get the battery state outside the
+ // lock to prevent event processing from being blocked by this call.
+ std::scoped_lock _l(mLock);
+ InputDevice* device = findInputDeviceLocked(deviceId);
+ if (!device) return {};
+ eventHubId = device->getBatteryEventHubId();
+ } // release lock
- InputDevice* device = findInputDeviceLocked(deviceId);
- if (device) {
- return device->getBatteryCapacity();
+ if (!eventHubId) return {};
+ const auto batteryIds = mEventHub->getRawBatteryIds(*eventHubId);
+ if (batteryIds.empty()) {
+ ALOGW("%s: There are no battery ids for EventHub device %d", __func__, *eventHubId);
+ return {};
}
- return std::nullopt;
+ return mEventHub->getBatteryCapacity(*eventHubId, batteryIds.front());
}
std::optional<int32_t> InputReader::getBatteryStatus(int32_t deviceId) {
+ std::optional<int32_t> eventHubId;
+ {
+ // Do not query the battery state while holding the lock. For some peripheral devices,
+ // reading battery state can be broken and take 5+ seconds. Holding the lock in this case
+ // would block all other event processing during this time. For now, we assume this
+ // call never happens on the InputReader thread and get the battery state outside the
+ // lock to prevent event processing from being blocked by this call.
+ std::scoped_lock _l(mLock);
+ InputDevice* device = findInputDeviceLocked(deviceId);
+ if (!device) return {};
+ eventHubId = device->getBatteryEventHubId();
+ } // release lock
+
+ if (!eventHubId) return {};
+ const auto batteryIds = mEventHub->getRawBatteryIds(*eventHubId);
+ if (batteryIds.empty()) {
+ ALOGW("%s: There are no battery ids for EventHub device %d", __func__, *eventHubId);
+ return {};
+ }
+ return mEventHub->getBatteryStatus(*eventHubId, batteryIds.front());
+}
+
+std::optional<std::string> InputReader::getBatteryDevicePath(int32_t deviceId) {
std::scoped_lock _l(mLock);
InputDevice* device = findInputDeviceLocked(deviceId);
- if (device) {
- return device->getBatteryStatus();
+ if (!device) return {};
+
+ std::optional<int32_t> eventHubId = device->getBatteryEventHubId();
+ if (!eventHubId) return {};
+ const auto batteryIds = mEventHub->getRawBatteryIds(*eventHubId);
+ if (batteryIds.empty()) {
+ ALOGW("%s: There are no battery ids for EventHub device %d", __func__, *eventHubId);
+ return {};
}
- return std::nullopt;
+ const auto batteryInfo = mEventHub->getRawBatteryInfo(*eventHubId, batteryIds.front());
+ if (!batteryInfo) {
+ ALOGW("%s: Failed to get RawBatteryInfo for battery %d of EventHub device %d", __func__,
+ batteryIds.front(), *eventHubId);
+ return {};
+ }
+ return batteryInfo->path;
}
std::vector<InputDeviceLightInfo> InputReader::getLights(int32_t deviceId) {
diff --git a/services/inputflinger/reader/Macros.h b/services/inputflinger/reader/Macros.h
index 1bbf386..e107d88 100644
--- a/services/inputflinger/reader/Macros.h
+++ b/services/inputflinger/reader/Macros.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_MACROS_H
-#define _UI_INPUTREADER_MACROS_H
+#pragma once
#define LOG_TAG "InputReader"
@@ -115,5 +114,3 @@
}
} // namespace android
-
-#endif // _UI_INPUTREADER_MACROS_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/controller/PeripheralController.cpp b/services/inputflinger/reader/controller/PeripheralController.cpp
index 7673174..eaf5b51 100644
--- a/services/inputflinger/reader/controller/PeripheralController.cpp
+++ b/services/inputflinger/reader/controller/PeripheralController.cpp
@@ -521,4 +521,8 @@
return light->getLightPlayerId();
}
+int32_t PeripheralController::getEventHubId() const {
+ return getDeviceContext().getEventHubId();
+}
+
} // namespace android
diff --git a/services/inputflinger/reader/controller/PeripheralController.h b/services/inputflinger/reader/controller/PeripheralController.h
index b1bc8c7..25cf435 100644
--- a/services/inputflinger/reader/controller/PeripheralController.h
+++ b/services/inputflinger/reader/controller/PeripheralController.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_LIGHT_CONTROLLER_H
-#define _UI_INPUTREADER_LIGHT_CONTROLLER_H
+#pragma once
#include "PeripheralControllerInterface.h"
@@ -31,6 +30,7 @@
explicit PeripheralController(InputDeviceContext& deviceContext);
~PeripheralController() override;
+ int32_t getEventHubId() const override;
void populateDeviceInfo(InputDeviceInfo* deviceInfo) override;
void dump(std::string& dump) override;
bool setLightColor(int32_t lightId, int32_t color) override;
@@ -43,6 +43,7 @@
private:
inline int32_t getDeviceId() { return mDeviceContext.getId(); }
inline InputDeviceContext& getDeviceContext() { return mDeviceContext; }
+ inline InputDeviceContext& getDeviceContext() const { return mDeviceContext; }
InputDeviceContext& mDeviceContext;
void configureLights();
@@ -148,5 +149,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_LIGHT_CONTROLLER_H
diff --git a/services/inputflinger/reader/controller/PeripheralControllerInterface.h b/services/inputflinger/reader/controller/PeripheralControllerInterface.h
index 7688a43..76ed1ca 100644
--- a/services/inputflinger/reader/controller/PeripheralControllerInterface.h
+++ b/services/inputflinger/reader/controller/PeripheralControllerInterface.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_INPUT_CONTROLLER_H
-#define _UI_INPUTREADER_INPUT_CONTROLLER_H
+#pragma once
#include "EventHub.h"
#include "InputDevice.h"
@@ -33,6 +32,8 @@
PeripheralControllerInterface() {}
virtual ~PeripheralControllerInterface() {}
+ virtual int32_t getEventHubId() const = 0;
+
// Interface methods for Battery
virtual std::optional<int32_t> getBatteryCapacity(int32_t batteryId) = 0;
virtual std::optional<int32_t> getBatteryStatus(int32_t batteryId) = 0;
@@ -48,5 +49,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_INPUT_CONTROLLER_H
diff --git a/services/inputflinger/reader/include/EventHub.h b/services/inputflinger/reader/include/EventHub.h
index 8aec367..5cf2214 100644
--- a/services/inputflinger/reader/include/EventHub.h
+++ b/services/inputflinger/reader/include/EventHub.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _RUNTIME_EVENT_HUB_H
-#define _RUNTIME_EVENT_HUB_H
+#pragma once
#include <bitset>
#include <climits>
@@ -43,6 +42,7 @@
#include "TouchVideoDevice.h"
#include "VibrationElement.h"
+#include "android/hardware/input/InputDeviceCountryCode.h"
struct inotify_event;
@@ -301,9 +301,9 @@
int32_t deviceId, int32_t lightId) const = 0;
virtual void setLightIntensities(int32_t deviceId, int32_t lightId,
std::unordered_map<LightColor, int32_t> intensities) = 0;
- /*
- * Query current input state.
- */
+ /* Query Country code associated with the input device. */
+ virtual hardware::input::InputDeviceCountryCode getCountryCode(int32_t deviceId) const = 0;
+ /* Query current input state. */
virtual int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const = 0;
virtual int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const = 0;
virtual int32_t getSwitchState(int32_t deviceId, int32_t sw) const = 0;
@@ -483,6 +483,8 @@
void setLightIntensities(int32_t deviceId, int32_t lightId,
std::unordered_map<LightColor, int32_t> intensities) override final;
+ hardware::input::InputDeviceCountryCode getCountryCode(int32_t deviceId) const override final;
+
void setExcludedDevices(const std::vector<std::string>& devices) override final;
int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const override final;
@@ -544,7 +546,7 @@
struct AssociatedDevice {
// The sysfs root path of the misc device.
std::filesystem::path sysfsRootPath;
-
+ hardware::input::InputDeviceCountryCode countryCode;
std::unordered_map<int32_t /*batteryId*/, RawBatteryInfo> batteryInfos;
std::unordered_map<int32_t /*lightId*/, RawLightInfo> lightInfos;
};
@@ -729,5 +731,3 @@
};
} // namespace android
-
-#endif // _RUNTIME_EVENT_HUB_H
diff --git a/services/inputflinger/reader/include/InputDevice.h b/services/inputflinger/reader/include/InputDevice.h
index 51872ac..4ae9ae9 100644
--- a/services/inputflinger/reader/include/InputDevice.h
+++ b/services/inputflinger/reader/include/InputDevice.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_INPUT_DEVICE_H
-#define _UI_INPUTREADER_INPUT_DEVICE_H
+#pragma once
#include <ftl/flags.h>
#include <input/DisplayViewport.h>
@@ -32,8 +31,6 @@
#include "InputReaderContext.h"
namespace android {
-// TODO b/180733860 support multiple battery in API and remove this.
-constexpr int32_t DEFAULT_BATTERY_ID = 1;
class PeripheralController;
class PeripheralControllerInterface;
@@ -100,8 +97,7 @@
void disableSensor(InputDeviceSensorType sensorType);
void flushSensor(InputDeviceSensorType sensorType);
- std::optional<int32_t> getBatteryCapacity();
- std::optional<int32_t> getBatteryStatus();
+ std::optional<int32_t> getBatteryEventHubId() const;
bool setLightColor(int32_t lightId, int32_t color);
bool setLightPlayerId(int32_t lightId, int32_t playerId);
@@ -158,6 +154,7 @@
int32_t mId;
int32_t mGeneration;
int32_t mControllerNumber;
+ hardware::input::InputDeviceCountryCode mCountryCode;
InputDeviceIdentifier mIdentifier;
std::string mAlias;
ftl::Flags<InputDeviceClass> mClasses;
@@ -311,6 +308,9 @@
}
inline std::vector<TouchVideoFrame> getVideoFrames() { return mEventHub->getVideoFrames(mId); }
+ inline hardware::input::InputDeviceCountryCode getCountryCode() const {
+ return mEventHub->getCountryCode(mId);
+ }
inline int32_t getScanCodeState(int32_t scanCode) const {
return mEventHub->getScanCodeState(mId, scanCode);
}
@@ -408,5 +408,3 @@
};
} // namespace android
-
-#endif //_UI_INPUTREADER_INPUT_DEVICE_H
diff --git a/services/inputflinger/reader/include/InputReader.h b/services/inputflinger/reader/include/InputReader.h
index ae41e01..fbce87f 100644
--- a/services/inputflinger/reader/include/InputReader.h
+++ b/services/inputflinger/reader/include/InputReader.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_INPUT_READER_H
-#define _UI_INPUTREADER_INPUT_READER_H
+#pragma once
#include <PointerControllerInterface.h>
#include <android-base/thread_annotations.h>
@@ -100,6 +99,8 @@
std::optional<int32_t> getBatteryStatus(int32_t deviceId) override;
+ std::optional<std::string> getBatteryDevicePath(int32_t deviceId) override;
+
std::vector<InputDeviceLightInfo> getLights(int32_t deviceId) override;
std::vector<InputDeviceSensorInfo> getSensors(int32_t deviceId) override;
@@ -246,5 +247,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_INPUT_READER_H
diff --git a/services/inputflinger/reader/include/InputReaderContext.h b/services/inputflinger/reader/include/InputReaderContext.h
index 823d160..f2f156c 100644
--- a/services/inputflinger/reader/include/InputReaderContext.h
+++ b/services/inputflinger/reader/include/InputReaderContext.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_INPUT_READER_CONTEXT_H
-#define _UI_INPUTREADER_INPUT_READER_CONTEXT_H
+#pragma once
#include <input/InputDevice.h>
@@ -65,5 +64,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_INPUT_READER_CONTEXT_H
diff --git a/services/inputflinger/reader/include/StylusState.h b/services/inputflinger/reader/include/StylusState.h
index 17f158c..8d14d3c 100644
--- a/services/inputflinger/reader/include/StylusState.h
+++ b/services/inputflinger/reader/include/StylusState.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_STYLUS_STATE_H
-#define _UI_INPUTREADER_STYLUS_STATE_H
+#pragma once
#include <input/Input.h>
@@ -49,5 +48,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_STYLUS_STATE_H
diff --git a/services/inputflinger/reader/include/TouchVideoDevice.h b/services/inputflinger/reader/include/TouchVideoDevice.h
index 7de9b830..08eba31 100644
--- a/services/inputflinger/reader/include/TouchVideoDevice.h
+++ b/services/inputflinger/reader/include/TouchVideoDevice.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTFLINGER_TOUCH_VIDEO_DEVICE_H
-#define _UI_INPUTFLINGER_TOUCH_VIDEO_DEVICE_H
+#pragma once
#include <android-base/unique_fd.h>
#include <input/TouchVideoFrame.h>
@@ -123,5 +122,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTFLINGER_TOUCH_VIDEO_DEVICE_H
diff --git a/services/inputflinger/reader/mapper/CursorInputMapper.cpp b/services/inputflinger/reader/mapper/CursorInputMapper.cpp
index 6058a1e..d6d324b 100644
--- a/services/inputflinger/reader/mapper/CursorInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/CursorInputMapper.cpp
@@ -25,6 +25,8 @@
#include "PointerControllerInterface.h"
#include "TouchCursorInputMapperCommon.h"
+#include "input/PrintTools.h"
+
namespace android {
// The default velocity control parameters that has no effect.
@@ -117,6 +119,7 @@
toString(mCursorScrollAccumulator.haveRelativeHWheel()));
dump += StringPrintf(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale);
dump += StringPrintf(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale);
+ dump += StringPrintf(INDENT3 "DisplayId: %s\n", toString(mDisplayId).c_str());
dump += StringPrintf(INDENT3 "Orientation: %d\n", mOrientation);
dump += StringPrintf(INDENT3 "ButtonState: 0x%08x\n", mButtonState);
dump += StringPrintf(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState)));
@@ -205,21 +208,34 @@
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO) ||
configurePointerCapture) {
+ const bool isPointer = mParameters.mode == Parameters::Mode::POINTER;
+
+ mDisplayId = ADISPLAY_ID_NONE;
+ if (auto viewport = mDeviceContext.getAssociatedViewport(); viewport) {
+ // This InputDevice is associated with a viewport.
+ // Only generate events for the associated display.
+ const bool mismatchedPointerDisplay =
+ isPointer && (viewport->displayId != mPointerController->getDisplayId());
+ mDisplayId = mismatchedPointerDisplay ? std::nullopt
+ : std::make_optional(viewport->displayId);
+ } else if (isPointer) {
+ // The InputDevice is not associated with a viewport, but it controls the mouse pointer.
+ mDisplayId = mPointerController->getDisplayId();
+ }
+
mOrientation = DISPLAY_ORIENTATION_0;
const bool isOrientedDevice =
(mParameters.orientationAware && mParameters.hasAssociatedDisplay);
-
// InputReader works in the un-rotated display coordinate space, so we don't need to do
// anything if the device is already orientation-aware. If the device is not
// orientation-aware, then we need to apply the inverse rotation of the display so that
// when the display rotation is applied later as a part of the per-window transform, we
// get the expected screen coordinates. When pointer capture is enabled, we do not apply any
// rotations and report values directly from the input device.
- if (!isOrientedDevice && mParameters.mode != Parameters::Mode::POINTER_RELATIVE) {
- std::optional<DisplayViewport> internalViewport =
- config->getDisplayViewportByType(ViewportType::INTERNAL);
- if (internalViewport) {
- mOrientation = getInverseRotation(internalViewport->orientation);
+ if (!isOrientedDevice && mDisplayId &&
+ mParameters.mode != Parameters::Mode::POINTER_RELATIVE) {
+ if (auto viewport = config->getDisplayViewportById(*mDisplayId); viewport) {
+ mOrientation = getInverseRotation(viewport->orientation);
}
}
@@ -282,6 +298,11 @@
}
void CursorInputMapper::sync(nsecs_t when, nsecs_t readTime) {
+ if (!mDisplayId) {
+ // Ignore events when there is no target display configured.
+ return;
+ }
+
int32_t lastButtonState = mButtonState;
int32_t currentButtonState = mCursorButtonAccumulator.getButtonState();
mButtonState = currentButtonState;
@@ -327,7 +348,6 @@
mPointerVelocityControl.move(when, &deltaX, &deltaY);
- int32_t displayId = ADISPLAY_ID_NONE;
float xCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
float yCursorPosition = AMOTION_EVENT_INVALID_CURSOR_POSITION;
if (mSource == AINPUT_SOURCE_MOUSE) {
@@ -351,7 +371,6 @@
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY);
- displayId = mPointerController->getDisplayId();
} else {
// Pointer capture and navigation modes
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX);
@@ -373,7 +392,7 @@
// Synthesize key down from buttons if needed.
synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, readTime, getDeviceId(),
- mSource, displayId, policyFlags, lastButtonState, currentButtonState);
+ mSource, *mDisplayId, policyFlags, lastButtonState, currentButtonState);
// Send motion event.
if (downChanged || moved || scrolled || buttonsChanged) {
@@ -394,7 +413,7 @@
int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
buttonState &= ~actionButton;
NotifyMotionArgs releaseArgs(getContext()->getNextId(), when, readTime,
- getDeviceId(), mSource, displayId, policyFlags,
+ getDeviceId(), mSource, *mDisplayId, policyFlags,
AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
metaState, buttonState, MotionClassification::NONE,
AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
@@ -406,7 +425,7 @@
}
NotifyMotionArgs args(getContext()->getNextId(), when, readTime, getDeviceId(), mSource,
- displayId, policyFlags, motionEventAction, 0, 0, metaState,
+ *mDisplayId, policyFlags, motionEventAction, 0, 0, metaState,
currentButtonState, MotionClassification::NONE,
AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties, &pointerCoords,
mXPrecision, mYPrecision, xCursorPosition, yCursorPosition, downTime,
@@ -419,7 +438,7 @@
int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
buttonState |= actionButton;
NotifyMotionArgs pressArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
- mSource, displayId, policyFlags,
+ mSource, *mDisplayId, policyFlags,
AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
metaState, buttonState, MotionClassification::NONE,
AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
@@ -435,7 +454,7 @@
// Send hover move after UP to tell the application that the mouse is hovering now.
if (motionEventAction == AMOTION_EVENT_ACTION_UP && (mSource == AINPUT_SOURCE_MOUSE)) {
NotifyMotionArgs hoverArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
- mSource, displayId, policyFlags,
+ mSource, *mDisplayId, policyFlags,
AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
currentButtonState, MotionClassification::NONE,
AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
@@ -450,7 +469,7 @@
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
NotifyMotionArgs scrollArgs(getContext()->getNextId(), when, readTime, getDeviceId(),
- mSource, displayId, policyFlags,
+ mSource, *mDisplayId, policyFlags,
AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState,
currentButtonState, MotionClassification::NONE,
AMOTION_EVENT_EDGE_FLAG_NONE, 1, &pointerProperties,
@@ -462,7 +481,7 @@
// Synthesize key up from buttons if needed.
synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, readTime, getDeviceId(), mSource,
- displayId, policyFlags, lastButtonState, currentButtonState);
+ *mDisplayId, policyFlags, lastButtonState, currentButtonState);
mCursorMotionAccumulator.finishSync();
mCursorScrollAccumulator.finishSync();
@@ -477,16 +496,7 @@
}
std::optional<int32_t> CursorInputMapper::getAssociatedDisplayId() {
- if (mParameters.hasAssociatedDisplay) {
- if (mParameters.mode == Parameters::Mode::POINTER) {
- return std::make_optional(mPointerController->getDisplayId());
- } else {
- // If the device is orientationAware and not a mouse,
- // it expects to dispatch events to any display
- return std::make_optional(ADISPLAY_ID_NONE);
- }
- }
- return std::nullopt;
+ return mDisplayId;
}
} // namespace android
diff --git a/services/inputflinger/reader/mapper/CursorInputMapper.h b/services/inputflinger/reader/mapper/CursorInputMapper.h
index 75aeffb..a0229a7 100644
--- a/services/inputflinger/reader/mapper/CursorInputMapper.h
+++ b/services/inputflinger/reader/mapper/CursorInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_CURSOR_INPUT_MAPPER_H
-#define _UI_INPUTREADER_CURSOR_INPUT_MAPPER_H
+#pragma once
#include "CursorButtonAccumulator.h"
#include "CursorScrollAccumulator.h"
@@ -111,6 +110,10 @@
VelocityControl mWheelXVelocityControl;
VelocityControl mWheelYVelocityControl;
+ // The display that events generated by this mapper should target. This can be set to
+ // ADISPLAY_ID_NONE to target the focused display. If there is no display target (i.e.
+ // std::nullopt), all events will be ignored.
+ std::optional<int32_t> mDisplayId;
int32_t mOrientation;
std::shared_ptr<PointerControllerInterface> mPointerController;
@@ -125,5 +128,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_CURSOR_INPUT_MAPPER_H
diff --git a/services/inputflinger/reader/mapper/ExternalStylusInputMapper.h b/services/inputflinger/reader/mapper/ExternalStylusInputMapper.h
index 516aa51..03d9909 100644
--- a/services/inputflinger/reader/mapper/ExternalStylusInputMapper.h
+++ b/services/inputflinger/reader/mapper/ExternalStylusInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_EXTERNAL_STYLUS_INPUT_MAPPER_H
-#define _UI_INPUTREADER_EXTERNAL_STYLUS_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -49,5 +48,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_EXTERNAL_STYLUS_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/InputMapper.h b/services/inputflinger/reader/mapper/InputMapper.h
index 7858728..5567cac 100644
--- a/services/inputflinger/reader/mapper/InputMapper.h
+++ b/services/inputflinger/reader/mapper/InputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_INPUT_MAPPER_H
-#define _UI_INPUTREADER_INPUT_MAPPER_H
+#pragma once
#include "EventHub.h"
#include "InputDevice.h"
@@ -109,5 +108,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_INPUT_MAPPER_H
diff --git a/services/inputflinger/reader/mapper/JoystickInputMapper.h b/services/inputflinger/reader/mapper/JoystickInputMapper.h
index 307bf5b..e002397 100644
--- a/services/inputflinger/reader/mapper/JoystickInputMapper.h
+++ b/services/inputflinger/reader/mapper/JoystickInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_JOYSTICK_INPUT_MAPPER_H
-#define _UI_INPUTREADER_JOYSTICK_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -111,5 +110,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_JOYSTICK_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
index 6a406d2..9bb6273 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
@@ -127,7 +127,6 @@
dump += StringPrintf(INDENT3 "Orientation: %d\n", getOrientation());
dump += StringPrintf(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size());
dump += StringPrintf(INDENT3 "MetaState: 0x%0x\n", mMetaState);
- dump += StringPrintf(INDENT3 "DownTime: %" PRId64 "\n", mDownTime);
}
std::optional<DisplayViewport> KeyboardInputMapper::findViewport(
@@ -196,9 +195,7 @@
}
void KeyboardInputMapper::reset(nsecs_t when) {
- mMetaState = AMETA_NONE;
- mDownTime = 0;
- mKeyDowns.clear();
+ cancelAllDownKeys(when);
mCurrentHidUsage = 0;
resetLedState();
@@ -281,6 +278,7 @@
policyFlags = 0;
}
+ nsecs_t downTime = when;
if (down) {
// Rotate key codes according to orientation if needed.
if (mParameters.orientationAware) {
@@ -292,6 +290,7 @@
if (keyDownIndex >= 0) {
// key repeat, be sure to use same keycode as before in case of rotation
keyCode = mKeyDowns[keyDownIndex].keyCode;
+ downTime = mKeyDowns[keyDownIndex].downTime;
} else {
// key down
if ((policyFlags & POLICY_FLAG_VIRTUAL) &&
@@ -305,16 +304,16 @@
KeyDown keyDown;
keyDown.keyCode = keyCode;
keyDown.scanCode = scanCode;
+ keyDown.downTime = when;
mKeyDowns.push_back(keyDown);
}
-
- mDownTime = when;
} else {
// Remove key down.
ssize_t keyDownIndex = findKeyDown(scanCode);
if (keyDownIndex >= 0) {
// key up, be sure to use same keycode as before in case of rotation
keyCode = mKeyDowns[keyDownIndex].keyCode;
+ downTime = mKeyDowns[keyDownIndex].downTime;
mKeyDowns.erase(mKeyDowns.begin() + (size_t)keyDownIndex);
} else {
// key was not actually down
@@ -333,8 +332,6 @@
keyMetaState = mMetaState;
}
- nsecs_t downTime = mDownTime;
-
// Key down on external an keyboard should wake the device.
// We don't do this for internal keyboards to prevent them from waking up in your pocket.
// For internal keyboards and devices for which the default wake behavior is explicitly
@@ -473,4 +470,19 @@
return std::nullopt;
}
+void KeyboardInputMapper::cancelAllDownKeys(nsecs_t when) {
+ size_t n = mKeyDowns.size();
+ for (size_t i = 0; i < n; i++) {
+ NotifyKeyArgs args(getContext()->getNextId(), when, systemTime(SYSTEM_TIME_MONOTONIC),
+ getDeviceId(), mSource, getDisplayId(), 0 /*policyFlags*/,
+ AKEY_EVENT_ACTION_UP,
+ AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_CANCELED,
+ mKeyDowns[i].keyCode, mKeyDowns[i].scanCode, AMETA_NONE,
+ mKeyDowns[i].downTime);
+ getListener().notifyKey(&args);
+ }
+ mKeyDowns.clear();
+ mMetaState = AMETA_NONE;
+}
+
} // namespace android
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.h b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
index 0a55def..2136d25 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.h
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_KEYBOARD_INPUT_MAPPER_H
-#define _UI_INPUTREADER_KEYBOARD_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -50,6 +49,7 @@
std::optional<DisplayViewport> mViewport;
struct KeyDown {
+ nsecs_t downTime;
int32_t keyCode;
int32_t scanCode;
};
@@ -59,7 +59,6 @@
std::vector<KeyDown> mKeyDowns; // keys that are down
int32_t mMetaState;
- nsecs_t mDownTime; // time of most recent key down
int32_t mCurrentHidUsage; // most recent HID usage seen this packet, or 0 if none
@@ -98,8 +97,7 @@
void updateLedStateForModifier(LedState& ledState, int32_t led, int32_t modifier, bool reset);
std::optional<DisplayViewport> findViewport(nsecs_t when,
const InputReaderConfiguration* config);
+ void cancelAllDownKeys(nsecs_t when);
};
} // namespace android
-
-#endif // _UI_INPUTREADER_KEYBOARD_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/MultiTouchInputMapper.h b/services/inputflinger/reader/mapper/MultiTouchInputMapper.h
index fe8af5d..212c9c9 100644
--- a/services/inputflinger/reader/mapper/MultiTouchInputMapper.h
+++ b/services/inputflinger/reader/mapper/MultiTouchInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_MULTI_TOUCH_INPUT_MAPPER_H
-#define _UI_INPUTREADER_MULTI_TOUCH_INPUT_MAPPER_H
+#pragma once
#include "TouchInputMapper.h"
@@ -122,5 +121,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_MULTI_TOUCH_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/RotaryEncoderInputMapper.h b/services/inputflinger/reader/mapper/RotaryEncoderInputMapper.h
index 1859355..42e2421 100644
--- a/services/inputflinger/reader/mapper/RotaryEncoderInputMapper.h
+++ b/services/inputflinger/reader/mapper/RotaryEncoderInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_ROTARY_ENCODER_INPUT_MAPPER_H
-#define _UI_INPUTREADER_ROTARY_ENCODER_INPUT_MAPPER_H
+#pragma once
#include "CursorScrollAccumulator.h"
#include "InputMapper.h"
@@ -46,5 +45,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_ROTARY_ENCODER_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/SensorInputMapper.h b/services/inputflinger/reader/mapper/SensorInputMapper.h
index 27a6177..38d4c3c 100644
--- a/services/inputflinger/reader/mapper/SensorInputMapper.h
+++ b/services/inputflinger/reader/mapper/SensorInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_SENSOR_INPUT_MAPPER_H
-#define _UI_INPUTREADER_SENSOR_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -133,5 +132,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_SENSOR_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/SingleTouchInputMapper.h b/services/inputflinger/reader/mapper/SingleTouchInputMapper.h
index 9cb3f67..f54c195 100644
--- a/services/inputflinger/reader/mapper/SingleTouchInputMapper.h
+++ b/services/inputflinger/reader/mapper/SingleTouchInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_SINGLE_TOUCH_INPUT_MAPPER_H
-#define _UI_INPUTREADER_SINGLE_TOUCH_INPUT_MAPPER_H
+#pragma once
#include "SingleTouchMotionAccumulator.h"
#include "TouchInputMapper.h"
@@ -40,5 +39,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_SINGLE_TOUCH_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/SwitchInputMapper.h b/services/inputflinger/reader/mapper/SwitchInputMapper.h
index 64b9aa2..e0c949f 100644
--- a/services/inputflinger/reader/mapper/SwitchInputMapper.h
+++ b/services/inputflinger/reader/mapper/SwitchInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_SWITCH_INPUT_MAPPER_H
-#define _UI_INPUTREADER_SWITCH_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -41,5 +40,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_SWITCH_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/TouchCursorInputMapperCommon.h b/services/inputflinger/reader/mapper/TouchCursorInputMapperCommon.h
index 31a3d2e..42d819b 100644
--- a/services/inputflinger/reader/mapper/TouchCursorInputMapperCommon.h
+++ b/services/inputflinger/reader/mapper/TouchCursorInputMapperCommon.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_TOUCH_CURSOR_INPUT_MAPPER_COMMON_H
-#define _UI_INPUTREADER_TOUCH_CURSOR_INPUT_MAPPER_COMMON_H
+#pragma once
#include <input/DisplayViewport.h>
#include <stdint.h>
@@ -99,5 +98,3 @@
}
} // namespace android
-
-#endif // _UI_INPUTREADER_TOUCH_CURSOR_INPUT_MAPPER_COMMON_H
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.cpp b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
index eaf03f1..8c241f2 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
@@ -2712,17 +2712,18 @@
// Update the velocity tracker.
{
- std::vector<VelocityTracker::Position> positions;
+ std::vector<float> positionsX;
+ std::vector<float> positionsY;
for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
uint32_t id = idBits.clearFirstMarkedBit();
const RawPointerData::Pointer& pointer =
mCurrentRawState.rawPointerData.pointerForId(id);
- float x = pointer.x * mPointerXMovementScale;
- float y = pointer.y * mPointerYMovementScale;
- positions.push_back({x, y});
+ positionsX.push_back(pointer.x * mPointerXMovementScale);
+ positionsY.push_back(pointer.y * mPointerYMovementScale);
}
mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits,
- positions);
+ {{AMOTION_EVENT_AXIS_X, positionsX},
+ {AMOTION_EVENT_AXIS_Y, positionsY}});
}
// If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning
@@ -2829,9 +2830,12 @@
float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed;
for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty();) {
uint32_t id = idBits.clearFirstMarkedBit();
- float vx, vy;
- if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) {
- float speed = hypotf(vx, vy);
+ std::optional<float> vx =
+ mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_X, id);
+ std::optional<float> vy =
+ mPointerGesture.velocityTracker.getVelocity(AMOTION_EVENT_AXIS_Y, id);
+ if (vx && vy) {
+ float speed = hypotf(*vx, *vy);
if (speed > bestSpeed) {
bestId = id;
bestSpeed = speed;
@@ -2847,22 +2851,10 @@
}
}
- float deltaX = 0, deltaY = 0;
if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
- const RawPointerData::Pointer& currentPointer =
- mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
- const RawPointerData::Pointer& lastPointer =
- mLastRawState.rawPointerData.pointerForId(activeTouchId);
- deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
- deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
-
- rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- // Move the pointer using a relative motion.
// When using spots, the click will occur at the position of the anchor
// spot and all other spots will move there.
- mPointerController->move(deltaX, deltaY);
+ moveMousePointerFromPointerDelta(when, activeTouchId);
} else {
mPointerVelocityControl.reset();
}
@@ -2974,21 +2966,9 @@
mPointerGesture.currentGestureMode = PointerGesture::Mode::TAP_DRAG;
}
- float deltaX = 0, deltaY = 0;
if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) {
- const RawPointerData::Pointer& currentPointer =
- mCurrentRawState.rawPointerData.pointerForId(activeTouchId);
- const RawPointerData::Pointer& lastPointer =
- mLastRawState.rawPointerData.pointerForId(activeTouchId);
- deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
- deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
-
- rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- // Move the pointer using a relative motion.
// When using spots, the hover or drag will occur at the position of the anchor spot.
- mPointerController->move(deltaX, deltaY);
+ moveMousePointerFromPointerDelta(when, activeTouchId);
} else {
mPointerVelocityControl.reset();
}
@@ -3395,6 +3375,20 @@
return true;
}
+void TouchInputMapper::moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId) {
+ const RawPointerData::Pointer& currentPointer =
+ mCurrentRawState.rawPointerData.pointerForId(pointerId);
+ const RawPointerData::Pointer& lastPointer =
+ mLastRawState.rawPointerData.pointerForId(pointerId);
+ float deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale;
+ float deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale;
+
+ rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
+ mPointerVelocityControl.move(when, &deltaX, &deltaY);
+
+ mPointerController->move(deltaX, deltaY);
+}
+
void TouchInputMapper::dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags) {
mPointerSimple.currentCoords.clear();
mPointerSimple.currentProperties.clear();
@@ -3438,21 +3432,8 @@
bool down, hovering;
if (!mCurrentCookedState.mouseIdBits.isEmpty()) {
uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit();
- uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
- float deltaX = 0, deltaY = 0;
if (mLastCookedState.mouseIdBits.hasBit(id)) {
- uint32_t lastIndex = mLastRawState.rawPointerData.idToIndex[id];
- deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x -
- mLastRawState.rawPointerData.pointers[lastIndex].x) *
- mPointerXMovementScale;
- deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y -
- mLastRawState.rawPointerData.pointers[lastIndex].y) *
- mPointerYMovementScale;
-
- rotateDelta(mInputDeviceOrientation, &deltaX, &deltaY);
- mPointerVelocityControl.move(when, &deltaX, &deltaY);
-
- mPointerController->move(deltaX, deltaY);
+ moveMousePointerFromPointerDelta(when, id);
} else {
mPointerVelocityControl.reset();
}
@@ -3462,6 +3443,7 @@
float x, y;
mPointerController->getPosition(&x, &y);
+ uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id];
mPointerSimple.currentCoords.copyFrom(
mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]);
mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.h b/services/inputflinger/reader/mapper/TouchInputMapper.h
index cdf1c7d..bd4cff6 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.h
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_TOUCH_INPUT_MAPPER_H
-#define _UI_INPUTREADER_TOUCH_INPUT_MAPPER_H
+#pragma once
#include <stdint.h>
@@ -754,6 +753,10 @@
bool preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture,
bool* outFinishPreviousGesture, bool isTimeout);
+ // Moves the on-screen mouse pointer based on the movement of the pointer of the given ID
+ // between the last and current events. Uses a relative motion.
+ void moveMousePointerFromPointerDelta(nsecs_t when, uint32_t pointerId);
+
void dispatchPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags);
void abortPointerStylus(nsecs_t when, nsecs_t readTime, uint32_t policyFlags);
@@ -801,5 +804,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_TOUCH_INPUT_MAPPER_H
diff --git a/services/inputflinger/reader/mapper/VibratorInputMapper.h b/services/inputflinger/reader/mapper/VibratorInputMapper.h
index d3c22b6..894c573 100644
--- a/services/inputflinger/reader/mapper/VibratorInputMapper.h
+++ b/services/inputflinger/reader/mapper/VibratorInputMapper.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_VIBRATOR_INPUT_MAPPER_H
-#define _UI_INPUTREADER_VIBRATOR_INPUT_MAPPER_H
+#pragma once
#include "InputMapper.h"
@@ -50,5 +49,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_VIBRATOR_INPUT_MAPPER_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
index 9e15906..ed4c789 100644
--- a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_CURSOR_BUTTON_ACCUMULATOR_H
-#define _UI_INPUTREADER_CURSOR_BUTTON_ACCUMULATOR_H
+#pragma once
#include <stdint.h>
@@ -48,5 +47,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_CURSOR_BUTTON_ACCUMULATOR_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/accumulator/CursorScrollAccumulator.h b/services/inputflinger/reader/mapper/accumulator/CursorScrollAccumulator.h
index 1649559..ae1b7a3 100644
--- a/services/inputflinger/reader/mapper/accumulator/CursorScrollAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/CursorScrollAccumulator.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_CURSOR_SCROLL_ACCUMULATOR_H
-#define _UI_INPUTREADER_CURSOR_SCROLL_ACCUMULATOR_H
+#pragma once
#include <stdint.h>
@@ -56,5 +55,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_CURSOR_SCROLL_ACCUMULATOR_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/accumulator/SingleTouchMotionAccumulator.h b/services/inputflinger/reader/mapper/accumulator/SingleTouchMotionAccumulator.h
index 4c011f1..93056f0 100644
--- a/services/inputflinger/reader/mapper/accumulator/SingleTouchMotionAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/SingleTouchMotionAccumulator.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_SINGLE_TOUCH_MOTION_ACCUMULATOR_H
-#define _UI_INPUTREADER_SINGLE_TOUCH_MOTION_ACCUMULATOR_H
+#pragma once
#include <stdint.h>
@@ -53,5 +52,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_SINGLE_TOUCH_MOTION_ACCUMULATOR_H
\ No newline at end of file
diff --git a/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h b/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
index 22ebb72..7b889be 100644
--- a/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUTREADER_TOUCH_BUTTON_ACCUMULATOR_H
-#define _UI_INPUTREADER_TOUCH_BUTTON_ACCUMULATOR_H
+#pragma once
#include <stdint.h>
@@ -62,5 +61,3 @@
};
} // namespace android
-
-#endif // _UI_INPUTREADER_TOUCH_BUTTON_ACCUMULATOR_H
\ No newline at end of file
diff --git a/services/inputflinger/reporter/InputReporterInterface.h b/services/inputflinger/reporter/InputReporterInterface.h
index e5d3606..72a4aeb 100644
--- a/services/inputflinger/reporter/InputReporterInterface.h
+++ b/services/inputflinger/reporter/InputReporterInterface.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_INPUT_REPORTER_INTERFACE_H
-#define _UI_INPUT_REPORTER_INTERFACE_H
+#pragma once
#include <utils/RefBase.h>
@@ -49,5 +48,3 @@
sp<InputReporterInterface> createInputReporter();
} // namespace android
-
-#endif // _UI_INPUT_REPORTER_INTERFACE_H
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index cd853a6..7ee6950 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -4718,36 +4718,6 @@
// We have a focused application, but no focused window
TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_NoFocusedWindow) {
- FocusRequest request;
- request.token = nullptr;
- request.windowName = "";
- request.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
- request.displayId = mWindow->getInfo()->displayId;
- mDispatcher->setFocusedWindow(request);
- mWindow->consumeFocusEvent(false);
-
- // taps on the window work as normal
- ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
- injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
- WINDOW_LOCATION));
- ASSERT_NO_FATAL_FAILURE(mWindow->consumeMotionDown());
- mDispatcher->waitForIdle();
- mFakePolicy->assertNotifyAnrWasNotCalled();
-
- // Once a focused event arrives, we get an ANR for this application
- // We specify the injection timeout to be smaller than the application timeout, to ensure that
- // injection times out (instead of failing).
- const InputEventInjectionResult result =
- injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
- InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
- ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
- const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
- mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
- ASSERT_TRUE(mDispatcher->waitForIdle());
-}
-
-// We have a focused application, but we are waiting on the requested window to become focusable
-TEST_F(InputDispatcherSingleWindowAnr, FocusedApplication_PendingFocusedRequest) {
mWindow->setFocusable(false);
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
mWindow->consumeFocusEvent(false);
@@ -4768,7 +4738,7 @@
InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
- mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
+ mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
ASSERT_TRUE(mDispatcher->waitForIdle());
}
@@ -4818,10 +4788,11 @@
injectKey(mDispatcher, AKEY_EVENT_ACTION_DOWN, 0 /* repeatCount */, ADISPLAY_ID_DEFAULT,
InputEventInjectionSync::WAIT_FOR_RESULT, 10ms, false /* allowKeyRepeat */);
ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
- const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
- mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
+ const std::chrono::duration appTimeout =
+ mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
+ mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(appTimeout, mApplication);
- std::this_thread::sleep_for(timeout);
+ std::this_thread::sleep_for(appTimeout);
// ANR should not be raised again. It is up to policy to do that if it desires.
mFakePolicy->assertNotifyAnrWasNotCalled();
@@ -4842,8 +4813,8 @@
InputEventInjectionSync::WAIT_FOR_RESULT, 10ms);
ASSERT_EQ(InputEventInjectionResult::TIMED_OUT, result);
- const std::chrono::duration timeout = mWindow->getDispatchingTimeout(DISPATCHING_TIMEOUT);
- mFakePolicy->assertNotifyWindowUnresponsiveWasCalled(timeout, mWindow);
+ const std::chrono::duration timeout = mApplication->getDispatchingTimeout(DISPATCHING_TIMEOUT);
+ mFakePolicy->assertNotifyNoFocusedWindowAnrWasCalled(timeout, mApplication);
// Future focused events get dropped right away
ASSERT_EQ(InputEventInjectionResult::FAILED, injectKeyDown(mDispatcher));
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index 9a0c565..ee6993c 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -31,6 +31,7 @@
#include <SingleTouchInputMapper.h>
#include <SwitchInputMapper.h>
#include <TestInputListener.h>
+#include <TestInputListenerMatchers.h>
#include <TouchInputMapper.h>
#include <UinputDevice.h>
#include <VibratorInputMapper.h>
@@ -38,13 +39,16 @@
#include <gtest/gtest.h>
#include <gui/constants.h>
+#include "android/hardware/input/InputDeviceCountryCode.h"
#include "input/DisplayViewport.h"
#include "input/Input.h"
+using android::hardware::input::InputDeviceCountryCode;
+
namespace android {
using namespace ftl::flag_operators;
-
+using testing::AllOf;
using std::chrono_literals::operator""ms;
// Timeout for waiting for an expected event
@@ -56,7 +60,9 @@
// Arbitrary display properties.
static constexpr int32_t DISPLAY_ID = 0;
+static const std::string DISPLAY_UNIQUE_ID = "local:1";
static constexpr int32_t SECONDARY_DISPLAY_ID = DISPLAY_ID + 1;
+static const std::string SECONDARY_DISPLAY_UNIQUE_ID = "local:2";
static constexpr int32_t DISPLAY_WIDTH = 480;
static constexpr int32_t DISPLAY_HEIGHT = 800;
static constexpr int32_t VIRTUAL_DISPLAY_ID = 1;
@@ -75,6 +81,7 @@
static constexpr int32_t DEFAULT_BATTERY = 1;
static constexpr int32_t BATTERY_STATUS = 4;
static constexpr int32_t BATTERY_CAPACITY = 66;
+static const std::string BATTERY_DEVPATH = "/sys/devices/mydevice/power_supply/mybattery";
static constexpr int32_t LIGHT_BRIGHTNESS = 0x55000000;
static constexpr int32_t LIGHT_COLOR = 0x7F448866;
static constexpr int32_t LIGHT_PLAYER_ID = 2;
@@ -455,6 +462,7 @@
BitArray<MSC_MAX> mscBitmask;
std::vector<VirtualKeyDefinition> virtualKeys;
bool enabled;
+ InputDeviceCountryCode countryCode;
status_t enable() {
enabled = true;
@@ -584,6 +592,11 @@
device->keyCodeStates.replaceValueFor(keyCode, state);
}
+ void setCountryCode(int32_t deviceId, InputDeviceCountryCode countryCode) {
+ Device* device = getDevice(deviceId);
+ device->countryCode = countryCode;
+ }
+
void setScanCodeState(int32_t deviceId, int32_t scanCode, int32_t state) {
Device* device = getDevice(deviceId);
device->scanCodeStates.replaceValueFor(scanCode, state);
@@ -845,6 +858,14 @@
return AKEY_STATE_UNKNOWN;
}
+ InputDeviceCountryCode getCountryCode(int32_t deviceId) const override {
+ Device* device = getDevice(deviceId);
+ if (device) {
+ return device->countryCode;
+ }
+ return InputDeviceCountryCode::INVALID;
+ }
+
int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const override {
Device* device = getDevice(deviceId);
if (device) {
@@ -991,11 +1012,18 @@
return BATTERY_STATUS;
}
- std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const override { return {}; }
+ std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const override {
+ return {DEFAULT_BATTERY};
+ }
std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId,
int32_t batteryId) const override {
- return std::nullopt;
+ if (batteryId != DEFAULT_BATTERY) return {};
+ static const auto BATTERY_INFO = RawBatteryInfo{.id = DEFAULT_BATTERY,
+ .name = "default battery",
+ .flags = InputBatteryClass::CAPACITY,
+ .path = BATTERY_DEVPATH};
+ return BATTERY_INFO;
}
std::vector<int32_t> getRawLightIds(int32_t deviceId) const override {
@@ -2141,6 +2169,8 @@
~FakePeripheralController() override {}
+ int32_t getEventHubId() const { return getDeviceContext().getEventHubId(); }
+
void populateDeviceInfo(InputDeviceInfo* deviceInfo) override {}
void dump(std::string& dump) override {}
@@ -2174,6 +2204,7 @@
InputDeviceContext& mDeviceContext;
inline int32_t getDeviceId() { return mDeviceContext.getId(); }
inline InputDeviceContext& getDeviceContext() { return mDeviceContext; }
+ inline InputDeviceContext& getDeviceContext() const { return mDeviceContext; }
};
TEST_F(InputReaderTest, BatteryGetCapacity) {
@@ -2210,6 +2241,21 @@
ASSERT_EQ(mReader->getBatteryStatus(deviceId), BATTERY_STATUS);
}
+TEST_F(InputReaderTest, BatteryGetDevicePath) {
+ constexpr int32_t deviceId = END_RESERVED_ID + 1000;
+ ftl::Flags<InputDeviceClass> deviceClass =
+ InputDeviceClass::KEYBOARD | InputDeviceClass::BATTERY;
+ constexpr int32_t eventHubId = 1;
+ const char* DEVICE_LOCATION = "BLUETOOTH";
+ std::shared_ptr<InputDevice> device = mReader->newDevice(deviceId, "fake", DEVICE_LOCATION);
+ device->addController<FakePeripheralController>(eventHubId);
+ mReader->pushNextDevice(device);
+
+ ASSERT_NO_FATAL_FAILURE(addDevice(eventHubId, "fake", deviceClass, nullptr));
+
+ ASSERT_EQ(mReader->getBatteryDevicePath(deviceId), BATTERY_DEVPATH);
+}
+
TEST_F(InputReaderTest, LightGetColor) {
constexpr int32_t deviceId = END_RESERVED_ID + 1000;
ftl::Flags<InputDeviceClass> deviceClass = InputDeviceClass::KEYBOARD | InputDeviceClass::LIGHT;
@@ -2685,6 +2731,17 @@
ASSERT_EQ(ftl::Flags<InputDeviceClass>(0), mDevice->getClasses());
}
+TEST_F(InputDeviceTest, CountryCodeCorrectlyMapped) {
+ mFakeEventHub->setCountryCode(EVENTHUB_ID, InputDeviceCountryCode::INTERNATIONAL);
+
+ // Configuration
+ mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, AINPUT_SOURCE_KEYBOARD);
+ InputReaderConfiguration config;
+ mDevice->configure(ARBITRARY_TIME, &config, 0);
+
+ ASSERT_EQ(InputDeviceCountryCode::INTERNATIONAL, mDevice->getDeviceInfo().getCountryCode());
+}
+
TEST_F(InputDeviceTest, WhenDeviceCreated_EnabledIsFalse) {
ASSERT_EQ(mDevice->isEnabled(), false);
}
@@ -2876,7 +2933,6 @@
// Device should be disabled because it is associated with a specific display, but the
// corresponding display is not found.
- const std::string DISPLAY_UNIQUE_ID = "displayUniqueId";
mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
InputReaderConfiguration::CHANGE_DISPLAY_INFO);
@@ -2907,7 +2963,6 @@
mDevice->addMapper<FakeInputMapper>(EVENTHUB_ID, AINPUT_SOURCE_KEYBOARD);
mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(), 0);
- const std::string DISPLAY_UNIQUE_ID = "displayUniqueId";
mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
mFakePolicy->addDisplayViewport(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
DISPLAY_ORIENTATION_0, /* isActive= */ true, DISPLAY_UNIQUE_ID,
@@ -4088,6 +4143,37 @@
ASSERT_EQ(AMETA_NONE, mapper2.getMetaState());
}
+TEST_F(KeyboardInputMapperTest, Process_DisabledDevice) {
+ const int32_t USAGE_A = 0x070004;
+ mFakeEventHub->addKey(EVENTHUB_ID, KEY_HOME, 0, AKEYCODE_HOME, POLICY_FLAG_WAKE);
+ mFakeEventHub->addKey(EVENTHUB_ID, 0, USAGE_A, AKEYCODE_A, POLICY_FLAG_WAKE);
+
+ KeyboardInputMapper& mapper =
+ addMapperAndConfigure<KeyboardInputMapper>(AINPUT_SOURCE_KEYBOARD,
+ AINPUT_KEYBOARD_TYPE_ALPHABETIC);
+ // Key down by scan code.
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, KEY_HOME, 1);
+ NotifyKeyArgs args;
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
+ ASSERT_EQ(DEVICE_ID, args.deviceId);
+ ASSERT_EQ(AINPUT_SOURCE_KEYBOARD, args.source);
+ ASSERT_EQ(ARBITRARY_TIME, args.eventTime);
+ ASSERT_EQ(AKEY_EVENT_ACTION_DOWN, args.action);
+ ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
+ ASSERT_EQ(KEY_HOME, args.scanCode);
+ ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM, args.flags);
+
+ // Disable device, it should synthesize cancellation events for down events.
+ mFakePolicy->addDisabledDevice(DEVICE_ID);
+ configureDevice(InputReaderConfiguration::CHANGE_ENABLED_STATE);
+
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyKeyWasCalled(&args));
+ ASSERT_EQ(AKEY_EVENT_ACTION_UP, args.action);
+ ASSERT_EQ(AKEYCODE_HOME, args.keyCode);
+ ASSERT_EQ(KEY_HOME, args.scanCode);
+ ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_CANCELED, args.flags);
+}
+
// --- KeyboardInputMapperTest_ExternalDevice ---
class KeyboardInputMapperTest_ExternalDevice : public InputMapperTest {
@@ -4191,10 +4277,14 @@
int32_t rotatedX, int32_t rotatedY);
void prepareDisplay(int32_t orientation) {
- const std::string uniqueId = "local:0";
- const ViewportType viewportType = ViewportType::INTERNAL;
- setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
- orientation, uniqueId, NO_PORT, viewportType);
+ setDisplayInfoAndReconfigure(DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT, orientation,
+ DISPLAY_UNIQUE_ID, NO_PORT, ViewportType::INTERNAL);
+ }
+
+ void prepareSecondaryDisplay() {
+ setDisplayInfoAndReconfigure(SECONDARY_DISPLAY_ID, DISPLAY_WIDTH, DISPLAY_HEIGHT,
+ DISPLAY_ORIENTATION_0, SECONDARY_DISPLAY_UNIQUE_ID, NO_PORT,
+ ViewportType::EXTERNAL);
}
static void assertCursorPointerCoords(const PointerCoords& coords, float x, float y,
@@ -4471,6 +4561,7 @@
}
TEST_F(CursorInputMapperTest, Process_WhenOrientationAware_ShouldNotRotateMotions) {
+ mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
addConfigurationProperty("cursor.mode", "navigation");
// InputReader works in the un-rotated coordinate space, so orientation-aware devices do not
// need to be rotated.
@@ -4489,11 +4580,13 @@
}
TEST_F(CursorInputMapperTest, Process_WhenNotOrientationAware_ShouldRotateMotions) {
+ mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, DISPLAY_UNIQUE_ID);
addConfigurationProperty("cursor.mode", "navigation");
// Since InputReader works in the un-rotated coordinate space, only devices that are not
// orientation-aware are affected by display rotation.
CursorInputMapper& mapper = addMapperAndConfigure<CursorInputMapper>();
+ clearViewports();
prepareDisplay(DISPLAY_ORIENTATION_0);
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, 1));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, 1));
@@ -4504,6 +4597,7 @@
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, -1, 0));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, -1, 1));
+ clearViewports();
prepareDisplay(DISPLAY_ORIENTATION_90);
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, -1, 0));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, 1));
@@ -4514,6 +4608,7 @@
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, 0, -1));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, -1, -1));
+ clearViewports();
prepareDisplay(DISPLAY_ORIENTATION_180);
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 0, -1));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, -1, -1));
@@ -4524,6 +4619,7 @@
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 0, 1, 0));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, -1, 1, 1, -1));
+ clearViewports();
prepareDisplay(DISPLAY_ORIENTATION_270);
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 0, 1, 1, 0));
ASSERT_NO_FATAL_FAILURE(testMotionRotation(mapper, 1, 1, 1, -1));
@@ -5020,33 +5116,78 @@
ASSERT_EQ(20, args.pointerCoords[0].getY());
}
-TEST_F(CursorInputMapperTest, Process_ShouldHandleDisplayId) {
+TEST_F(CursorInputMapperTest, ConfigureDisplayId_NoAssociatedViewport) {
CursorInputMapper& mapper = addMapperAndConfigure<CursorInputMapper>();
- // Setup for second display.
- constexpr int32_t SECOND_DISPLAY_ID = 1;
- const std::string SECOND_DISPLAY_UNIQUE_ID = "local:1";
- mFakePolicy->addDisplayViewport(SECOND_DISPLAY_ID, 800, 480, DISPLAY_ORIENTATION_0,
- true /*isActive*/, SECOND_DISPLAY_UNIQUE_ID, NO_PORT,
- ViewportType::EXTERNAL);
- mFakePolicy->setDefaultPointerDisplayId(SECOND_DISPLAY_ID);
+ // Set up the default display.
+ prepareDisplay(DISPLAY_ORIENTATION_90);
+
+ // Set up the secondary display as the display on which the pointer should be shown.
+ // The InputDevice is not associated with any display.
+ prepareSecondaryDisplay();
+ mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO);
- mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1);
+ mFakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
mFakePointerController->setPosition(100, 200);
mFakePointerController->setButtonState(0);
- NotifyMotionArgs args;
+ // Ensure input events are generated for the secondary display.
process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
- ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
- ASSERT_EQ(AINPUT_SOURCE_MOUSE, args.source);
- ASSERT_EQ(AMOTION_EVENT_ACTION_HOVER_MOVE, args.action);
- ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
- 110.0f, 220.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
+ WithSource(AINPUT_SOURCE_MOUSE), WithDisplayId(SECONDARY_DISPLAY_ID),
+ WithCoords(110.0f, 220.0f))));
ASSERT_NO_FATAL_FAILURE(assertPosition(*mFakePointerController, 110.0f, 220.0f));
- ASSERT_EQ(SECOND_DISPLAY_ID, args.displayId);
+}
+
+TEST_F(CursorInputMapperTest, ConfigureDisplayId_WithAssociatedViewport) {
+ CursorInputMapper& mapper = addMapperAndConfigure<CursorInputMapper>();
+
+ // Set up the default display.
+ prepareDisplay(DISPLAY_ORIENTATION_90);
+
+ // Set up the secondary display as the display on which the pointer should be shown,
+ // and associate the InputDevice with the secondary display.
+ prepareSecondaryDisplay();
+ mFakePolicy->setDefaultPointerDisplayId(SECONDARY_DISPLAY_ID);
+ mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, SECONDARY_DISPLAY_UNIQUE_ID);
+ configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO);
+
+ mFakePointerController->setBounds(0, 0, DISPLAY_WIDTH - 1, DISPLAY_HEIGHT - 1);
+ mFakePointerController->setPosition(100, 200);
+ mFakePointerController->setButtonState(0);
+
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
+ WithSource(AINPUT_SOURCE_MOUSE), WithDisplayId(SECONDARY_DISPLAY_ID),
+ WithCoords(110.0f, 220.0f))));
+ ASSERT_NO_FATAL_FAILURE(assertPosition(*mFakePointerController, 110.0f, 220.0f));
+}
+
+TEST_F(CursorInputMapperTest, ConfigureDisplayId_IgnoresEventsForMismatchedPointerDisplay) {
+ CursorInputMapper& mapper = addMapperAndConfigure<CursorInputMapper>();
+
+ // Set up the default display as the display on which the pointer should be shown.
+ prepareDisplay(DISPLAY_ORIENTATION_90);
+ mFakePolicy->setDefaultPointerDisplayId(DISPLAY_ID);
+
+ // Associate the InputDevice with the secondary display.
+ prepareSecondaryDisplay();
+ mFakePolicy->addInputUniqueIdAssociation(DEVICE_LOCATION, SECONDARY_DISPLAY_UNIQUE_ID);
+ configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO);
+
+ // The mapper should not generate any events because it is associated with a display that is
+ // different from the pointer display.
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_X, 10);
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_REL, REL_Y, 20);
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_SYN, SYN_REPORT, 0);
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
}
// --- TouchInputMapperTest ---
diff --git a/services/inputflinger/tests/TestInputListener.h b/services/inputflinger/tests/TestInputListener.h
index 0bdfc6b..cad698f 100644
--- a/services/inputflinger/tests/TestInputListener.h
+++ b/services/inputflinger/tests/TestInputListener.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_TEST_INPUT_LISTENER_H
-#define _UI_TEST_INPUT_LISTENER_H
+#pragma once
#include <android-base/thread_annotations.h>
#include <gmock/gmock.h>
@@ -103,4 +102,3 @@
};
} // namespace android
-#endif
diff --git a/services/inputflinger/tests/TestInputListenerMatchers.h b/services/inputflinger/tests/TestInputListenerMatchers.h
new file mode 100644
index 0000000..03736a3
--- /dev/null
+++ b/services/inputflinger/tests/TestInputListenerMatchers.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <android/input.h>
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+
+namespace android {
+
+MATCHER_P(WithMotionAction, action, "InputEvent with specified action") {
+ if (action == AMOTION_EVENT_ACTION_CANCEL) {
+ *result_listener << "expected FLAG_CANCELED to be set with ACTION_CANCEL, but was not set";
+ return (arg.flags & AMOTION_EVENT_FLAG_CANCELED) != 0;
+ }
+ *result_listener << "expected action " << MotionEvent::actionToString(action) << ", but got "
+ << MotionEvent::actionToString(arg.action);
+ return action == arg.action;
+}
+
+MATCHER_P(WithSource, source, "InputEvent with specified source") {
+ *result_listener << "expected source " << source << ", but got " << arg.source;
+ return arg.source == source;
+}
+
+MATCHER_P(WithDisplayId, displayId, "InputEvent with specified displayId") {
+ *result_listener << "expected displayId " << displayId << ", but got " << arg.displayId;
+ return arg.displayId == displayId;
+}
+
+MATCHER_P2(WithCoords, x, y, "InputEvent with specified coords") {
+ const auto argX = arg.pointerCoords[0].getX();
+ const auto argY = arg.pointerCoords[0].getY();
+ *result_listener << "expected coords (" << x << ", " << y << "), but got (" << argX << ", "
+ << argY << ")";
+ return argX == x && argY == y;
+}
+
+MATCHER_P(WithFlags, flags, "InputEvent with specified flags") {
+ *result_listener << "expected flags " << flags << ", but got " << arg.flags;
+ return arg.flags == flags;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/UinputDevice.h b/services/inputflinger/tests/UinputDevice.h
index a37fc2b..e0ff8c3 100644
--- a/services/inputflinger/tests/UinputDevice.h
+++ b/services/inputflinger/tests/UinputDevice.h
@@ -14,8 +14,7 @@
* limitations under the License.
*/
-#ifndef _UI_TEST_INPUT_UINPUT_INJECTOR_H
-#define _UI_TEST_INPUT_UINPUT_INJECTOR_H
+#pragma once
#include <android-base/unique_fd.h>
#include <gtest/gtest.h>
@@ -155,5 +154,3 @@
};
} // namespace android
-
-#endif // _UI_TEST_INPUT_UINPUT_INJECTOR_H
diff --git a/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp b/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
index 526e4eb..4c84160 100644
--- a/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
+++ b/services/inputflinger/tests/UnwantedInteractionBlocker_test.cpp
@@ -24,6 +24,7 @@
#include "ui/events/ozone/evdev/touch_filter/neural_stylus_palm_detection_filter.h"
#include "TestInputListener.h"
+#include "TestInputListenerMatchers.h"
using ::testing::AllOf;
@@ -55,21 +56,6 @@
constexpr int32_t FLAG_CANCELED = AMOTION_EVENT_FLAG_CANCELED;
-MATCHER_P(WithAction, action, "MotionEvent with specified action") {
- bool result = true;
- if (action == CANCEL) {
- result &= (arg.flags & FLAG_CANCELED) != 0;
- }
- result &= arg.action == action;
- *result_listener << "expected to receive " << MotionEvent::actionToString(action)
- << " but received " << MotionEvent::actionToString(arg.action) << " instead.";
- return result;
-}
-
-MATCHER_P(WithFlags, flags, "MotionEvent with specified flags") {
- return arg.flags == flags;
-}
-
static nsecs_t toNs(std::chrono::nanoseconds duration) {
return duration.count();
}
@@ -605,19 +591,19 @@
// Small touch down
NotifyMotionArgs args1 = generateMotionArgs(0 /*downTime*/, 0 /*eventTime*/, DOWN, {{1, 2, 3}});
mBlocker->notifyMotion(&args1);
- mTestListener.assertNotifyMotionWasCalled(WithAction(DOWN));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(DOWN));
// Large touch oval on the next move
NotifyMotionArgs args2 =
generateMotionArgs(0 /*downTime*/, RESAMPLE_PERIOD, MOVE, {{4, 5, 200}});
mBlocker->notifyMotion(&args2);
- mTestListener.assertNotifyMotionWasCalled(WithAction(MOVE));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(MOVE));
// Lift up the touch to force the model to decide on whether it's a palm
NotifyMotionArgs args3 =
generateMotionArgs(0 /*downTime*/, 2 * RESAMPLE_PERIOD, UP, {{4, 5, 200}});
mBlocker->notifyMotion(&args3);
- mTestListener.assertNotifyMotionWasCalled(WithAction(CANCEL));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(CANCEL));
}
/**
@@ -633,14 +619,14 @@
NotifyMotionArgs args1 = generateMotionArgs(0 /*downTime*/, 0 /*eventTime*/, DOWN, {{1, 2, 3}});
args1.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args1);
- mTestListener.assertNotifyMotionWasCalled(WithAction(DOWN));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(DOWN));
// Move the stylus, setting large TOUCH_MAJOR/TOUCH_MINOR dimensions
NotifyMotionArgs args2 =
generateMotionArgs(0 /*downTime*/, RESAMPLE_PERIOD, MOVE, {{4, 5, 200}});
args2.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args2);
- mTestListener.assertNotifyMotionWasCalled(WithAction(MOVE));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(MOVE));
// Lift up the stylus. If it were a touch event, this would force the model to decide on whether
// it's a palm.
@@ -648,7 +634,7 @@
generateMotionArgs(0 /*downTime*/, 2 * RESAMPLE_PERIOD, UP, {{4, 5, 200}});
args3.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args3);
- mTestListener.assertNotifyMotionWasCalled(WithAction(UP));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(UP));
}
/**
@@ -664,21 +650,21 @@
// Touch down
NotifyMotionArgs args1 = generateMotionArgs(0 /*downTime*/, 0 /*eventTime*/, DOWN, {{1, 2, 3}});
mBlocker->notifyMotion(&args1);
- mTestListener.assertNotifyMotionWasCalled(WithAction(DOWN));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(DOWN));
// Stylus pointer down
NotifyMotionArgs args2 = generateMotionArgs(0 /*downTime*/, RESAMPLE_PERIOD, POINTER_1_DOWN,
{{1, 2, 3}, {10, 20, 30}});
args2.pointerProperties[1].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args2);
- mTestListener.assertNotifyMotionWasCalled(WithAction(POINTER_1_DOWN));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(POINTER_1_DOWN));
// Large touch oval on the next finger move
NotifyMotionArgs args3 = generateMotionArgs(0 /*downTime*/, 2 * RESAMPLE_PERIOD, MOVE,
{{1, 2, 300}, {11, 21, 30}});
args3.pointerProperties[1].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args3);
- mTestListener.assertNotifyMotionWasCalled(WithAction(MOVE));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(MOVE));
// Lift up the finger pointer. It should be canceled due to the heuristic filter.
NotifyMotionArgs args4 = generateMotionArgs(0 /*downTime*/, 3 * RESAMPLE_PERIOD, POINTER_0_UP,
@@ -686,14 +672,14 @@
args4.pointerProperties[1].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args4);
mTestListener.assertNotifyMotionWasCalled(
- AllOf(WithAction(POINTER_0_UP), WithFlags(FLAG_CANCELED)));
+ AllOf(WithMotionAction(POINTER_0_UP), WithFlags(FLAG_CANCELED)));
NotifyMotionArgs args5 =
generateMotionArgs(0 /*downTime*/, 4 * RESAMPLE_PERIOD, MOVE, {{12, 22, 30}});
args5.pointerProperties[0].id = args4.pointerProperties[1].id;
args5.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args5);
- mTestListener.assertNotifyMotionWasCalled(WithAction(MOVE));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(MOVE));
// Lift up the stylus pointer
NotifyMotionArgs args6 =
@@ -701,7 +687,7 @@
args6.pointerProperties[0].id = args4.pointerProperties[1].id;
args6.pointerProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS;
mBlocker->notifyMotion(&args6);
- mTestListener.assertNotifyMotionWasCalled(WithAction(UP));
+ mTestListener.assertNotifyMotionWasCalled(WithMotionAction(UP));
}
using UnwantedInteractionBlockerTestDeathTest = UnwantedInteractionBlockerTest;
diff --git a/services/inputflinger/tests/fuzzers/Android.bp b/services/inputflinger/tests/fuzzers/Android.bp
index 455a1e2..f4ecba2 100644
--- a/services/inputflinger/tests/fuzzers/Android.bp
+++ b/services/inputflinger/tests/fuzzers/Android.bp
@@ -46,3 +46,105 @@
cc: ["android-framework-input@google.com"],
},
}
+
+cc_defaults {
+ name: "inputflinger_fuzz_defaults",
+ defaults: [
+ "inputflinger_defaults",
+ ],
+ include_dirs: [
+ "frameworks/native/services/inputflinger",
+ ],
+ shared_libs: [
+ "android.hardware.input.classifier@1.0",
+ "android.hardware.input.processor-V1-ndk",
+ "libbase",
+ "libbinder",
+ "libcutils",
+ "liblog",
+ "libutils",
+ "libui",
+ "libinput",
+ "libinputflinger",
+ "libinputreader",
+ "libinputflinger_base",
+ "libstatslog",
+ ],
+ header_libs: [
+ "libbatteryservice_headers",
+ "libinputreader_headers",
+ ],
+ fuzz_config: {
+ cc: ["android-framework-input@google.com"],
+ },
+}
+
+cc_fuzz {
+ name: "inputflinger_cursor_input_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "CursorInputFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_keyboard_input_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "KeyboardInputFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_multitouch_input_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "MultiTouchInputFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_switch_input_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "SwitchInputFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_input_reader_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "InputReaderFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_blocking_queue_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "BlockingQueueFuzzer.cpp",
+ ],
+}
+
+cc_fuzz {
+ name: "inputflinger_input_classifier_fuzzer",
+ defaults: [
+ "inputflinger_fuzz_defaults",
+ ],
+ srcs: [
+ "InputClassifierFuzzer.cpp",
+ ],
+}
diff --git a/services/inputflinger/tests/fuzzers/BlockingQueueFuzzer.cpp b/services/inputflinger/tests/fuzzers/BlockingQueueFuzzer.cpp
new file mode 100644
index 0000000..d2595bf
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/BlockingQueueFuzzer.cpp
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <fuzzer/FuzzedDataProvider.h>
+#include <thread>
+#include "BlockingQueue.h"
+
+// Chosen to be a number large enough for variation in fuzzer runs, but not consume too much memory.
+static constexpr size_t MAX_CAPACITY = 1024;
+
+namespace android {
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
+ FuzzedDataProvider fdp(data, size);
+ size_t capacity = fdp.ConsumeIntegralInRange<size_t>(1, MAX_CAPACITY);
+ size_t filled = 0;
+ BlockingQueue<int32_t> queue(capacity);
+
+ while (fdp.remaining_bytes() > 0) {
+ fdp.PickValueInArray<std::function<void()>>({
+ [&]() -> void {
+ size_t numPushes = fdp.ConsumeIntegralInRange<size_t>(0, capacity + 1);
+ for (size_t i = 0; i < numPushes; i++) {
+ queue.push(fdp.ConsumeIntegral<int32_t>());
+ }
+ filled = std::min(capacity, filled + numPushes);
+ },
+ [&]() -> void {
+ // Pops blocks if it is empty, so only pop up to num elements inserted.
+ size_t numPops = fdp.ConsumeIntegralInRange<size_t>(0, filled);
+ for (size_t i = 0; i < numPops; i++) {
+ queue.pop();
+ }
+ filled > numPops ? filled -= numPops : filled = 0;
+ },
+ [&]() -> void {
+ queue.clear();
+ filled = 0;
+ },
+ [&]() -> void {
+ int32_t eraseElement = fdp.ConsumeIntegral<int32_t>();
+ queue.erase([&](int32_t element) {
+ if (element == eraseElement) {
+ filled--;
+ return true;
+ }
+ return false;
+ });
+ },
+ })();
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp
new file mode 100644
index 0000000..4b542aa
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <CursorInputMapper.h>
+#include <FuzzContainer.h>
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<FuzzedDataProvider> fdp) {
+ // Pick a random property to set for the mapper to have set.
+ fdp->PickValueInArray<std::function<void()>>(
+ {[&]() -> void { fuzzer.addProperty("cursor.mode", "pointer"); },
+ [&]() -> void { fuzzer.addProperty("cursor.mode", "navigation"); },
+ [&]() -> void {
+ fuzzer.addProperty("cursor.mode", fdp->ConsumeRandomLengthString(100).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("cursor.orientationAware",
+ fdp->ConsumeRandomLengthString(100).data());
+ }})();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+ std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ FuzzContainer fuzzer(fdp);
+
+ CursorInputMapper& mapper = fuzzer.getMapper<CursorInputMapper>();
+ auto policyConfig = fuzzer.getPolicyConfig();
+
+ // Loop through mapper operations until randomness is exhausted.
+ while (fdp->remaining_bytes() > 0) {
+ fdp->PickValueInArray<std::function<void()>>({
+ [&]() -> void { addProperty(fuzzer, fdp); },
+ [&]() -> void {
+ std::string dump;
+ mapper.dump(dump);
+ },
+ [&]() -> void { mapper.getSources(); },
+ [&]() -> void {
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig,
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ // Need to reconfigure with 0 or you risk a NPE.
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig, 0);
+ InputDeviceInfo info;
+ mapper.populateDeviceInfo(&info);
+ },
+ [&]() -> void {
+ int32_t type, code;
+ type = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidTypes)
+ : fdp->ConsumeIntegral<int32_t>();
+ code = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidCodes)
+ : fdp->ConsumeIntegral<int32_t>();
+
+ // Need to reconfigure with 0 or you risk a NPE.
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig, 0);
+ RawEvent rawEvent{fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ type,
+ code,
+ fdp->ConsumeIntegral<int32_t>()};
+ mapper.process(&rawEvent);
+ },
+ [&]() -> void { mapper.reset(fdp->ConsumeIntegral<nsecs_t>()); },
+ [&]() -> void {
+ mapper.getScanCodeState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ // Need to reconfigure with 0 or you risk a NPE.
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig, 0);
+ mapper.getAssociatedDisplayId();
+ },
+ })();
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/FuzzContainer.h b/services/inputflinger/tests/fuzzers/FuzzContainer.h
new file mode 100644
index 0000000..62615d0
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/FuzzContainer.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <InputDevice.h>
+#include <InputMapper.h>
+#include <InputReader.h>
+#include <MapperHelpers.h>
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+class FuzzContainer {
+ std::shared_ptr<FuzzEventHub> mFuzzEventHub;
+ sp<FuzzInputReaderPolicy> mFuzzPolicy;
+ std::unique_ptr<FuzzInputListener> mFuzzListener;
+ std::unique_ptr<FuzzInputReaderContext> mFuzzContext;
+ std::unique_ptr<InputDevice> mFuzzDevice;
+ InputReaderConfiguration mPolicyConfig;
+ std::shared_ptr<FuzzedDataProvider> mFdp;
+
+public:
+ FuzzContainer(std::shared_ptr<FuzzedDataProvider> fdp) : mFdp(fdp) {
+ // Setup parameters.
+ std::string deviceName = mFdp->ConsumeRandomLengthString(16);
+ std::string deviceLocation = mFdp->ConsumeRandomLengthString(12);
+ int32_t deviceID = mFdp->ConsumeIntegralInRange<int32_t>(0, 5);
+ int32_t deviceGeneration = mFdp->ConsumeIntegralInRange<int32_t>(/*from*/ 0, /*to*/ 5);
+
+ // Create mocked objects.
+ mFuzzEventHub = std::make_shared<FuzzEventHub>(mFdp);
+ mFuzzPolicy = sp<FuzzInputReaderPolicy>::make(mFdp);
+ mFuzzListener = std::make_unique<FuzzInputListener>();
+ mFuzzContext = std::make_unique<FuzzInputReaderContext>(mFuzzEventHub, mFuzzPolicy,
+ *mFuzzListener, mFdp);
+
+ InputDeviceIdentifier identifier;
+ identifier.name = deviceName;
+ identifier.location = deviceLocation;
+ mFuzzDevice = std::make_unique<InputDevice>(mFuzzContext.get(), deviceID, deviceGeneration,
+ identifier);
+ mFuzzPolicy->getReaderConfiguration(&mPolicyConfig);
+ }
+
+ ~FuzzContainer() {}
+
+ void configureDevice() {
+ nsecs_t arbitraryTime = mFdp->ConsumeIntegral<nsecs_t>();
+ mFuzzDevice->configure(arbitraryTime, &mPolicyConfig, 0);
+ mFuzzDevice->reset(arbitraryTime);
+ }
+
+ void addProperty(std::string key, std::string value) {
+ mFuzzEventHub->addProperty(key, value);
+ configureDevice();
+ }
+
+ InputReaderConfiguration& getPolicyConfig() { return mPolicyConfig; }
+
+ template <class T, typename... Args>
+ T& getMapper(Args... args) {
+ T& mapper = mFuzzDevice->addMapper<T>(mFdp->ConsumeIntegral<int32_t>(), args...);
+ configureDevice();
+ return mapper;
+ }
+};
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp b/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp
new file mode 100644
index 0000000..c407cff
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/InputClassifierFuzzer.cpp
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <MapperHelpers.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include "InputCommonConverter.h"
+#include "InputProcessor.h"
+
+namespace android {
+
+static constexpr int32_t MAX_AXES = 64;
+
+// Used by two fuzz operations and a bit lengthy, so pulled out into a function.
+NotifyMotionArgs generateFuzzedMotionArgs(FuzzedDataProvider &fdp) {
+ // Create a basic motion event for testing
+ PointerProperties properties;
+ properties.id = 0;
+ properties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
+ PointerCoords coords;
+ coords.clear();
+ for (int32_t i = 0; i < fdp.ConsumeIntegralInRange<int32_t>(0, MAX_AXES); i++) {
+ coords.setAxisValue(fdp.ConsumeIntegral<int32_t>(), fdp.ConsumeFloatingPoint<float>());
+ }
+
+ const nsecs_t downTime = 2;
+ const nsecs_t readTime = downTime + fdp.ConsumeIntegralInRange<nsecs_t>(0, 1E8);
+ NotifyMotionArgs motionArgs(fdp.ConsumeIntegral<uint32_t>() /*sequenceNum*/,
+ downTime /*eventTime*/, readTime,
+ fdp.ConsumeIntegral<int32_t>() /*deviceId*/, AINPUT_SOURCE_ANY,
+ ADISPLAY_ID_DEFAULT,
+ fdp.ConsumeIntegral<uint32_t>() /*policyFlags*/,
+ AMOTION_EVENT_ACTION_DOWN,
+ fdp.ConsumeIntegral<int32_t>() /*actionButton*/,
+ fdp.ConsumeIntegral<int32_t>() /*flags*/, AMETA_NONE,
+ fdp.ConsumeIntegral<int32_t>() /*buttonState*/,
+ MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE,
+ 1 /*pointerCount*/, &properties, &coords,
+ fdp.ConsumeFloatingPoint<float>() /*xPrecision*/,
+ fdp.ConsumeFloatingPoint<float>() /*yPrecision*/,
+ AMOTION_EVENT_INVALID_CURSOR_POSITION,
+ AMOTION_EVENT_INVALID_CURSOR_POSITION, downTime,
+ {} /*videoFrames*/);
+ return motionArgs;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t *data, size_t size) {
+ FuzzedDataProvider fdp(data, size);
+
+ std::unique_ptr<FuzzInputListener> mFuzzListener = std::make_unique<FuzzInputListener>();
+ std::unique_ptr<InputProcessorInterface> mClassifier =
+ std::make_unique<InputProcessor>(*mFuzzListener);
+
+ while (fdp.remaining_bytes() > 0) {
+ fdp.PickValueInArray<std::function<void()>>({
+ [&]() -> void {
+ // SendToNextStage_NotifyConfigurationChangedArgs
+ NotifyConfigurationChangedArgs
+ args(fdp.ConsumeIntegral<uint32_t>() /*sequenceNum*/,
+ fdp.ConsumeIntegral<nsecs_t>() /*eventTime*/);
+ mClassifier->notifyConfigurationChanged(&args);
+ },
+ [&]() -> void {
+ // SendToNextStage_NotifyKeyArgs
+ const nsecs_t eventTime = fdp.ConsumeIntegral<nsecs_t>();
+ const nsecs_t readTime =
+ eventTime + fdp.ConsumeIntegralInRange<nsecs_t>(0, 1E8);
+ NotifyKeyArgs keyArgs(fdp.ConsumeIntegral<uint32_t>() /*sequenceNum*/,
+ eventTime, readTime,
+ fdp.ConsumeIntegral<int32_t>() /*deviceId*/,
+ AINPUT_SOURCE_KEYBOARD, ADISPLAY_ID_DEFAULT,
+ fdp.ConsumeIntegral<uint32_t>() /*policyFlags*/,
+ AKEY_EVENT_ACTION_DOWN,
+ fdp.ConsumeIntegral<int32_t>() /*flags*/, AKEYCODE_HOME,
+ fdp.ConsumeIntegral<int32_t>() /*scanCode*/, AMETA_NONE,
+ fdp.ConsumeIntegral<nsecs_t>() /*downTime*/);
+
+ mClassifier->notifyKey(&keyArgs);
+ },
+ [&]() -> void {
+ // SendToNextStage_NotifyMotionArgs
+ NotifyMotionArgs motionArgs = generateFuzzedMotionArgs(fdp);
+ mClassifier->notifyMotion(&motionArgs);
+ },
+ [&]() -> void {
+ // SendToNextStage_NotifySwitchArgs
+ NotifySwitchArgs switchArgs(fdp.ConsumeIntegral<uint32_t>() /*sequenceNum*/,
+ fdp.ConsumeIntegral<nsecs_t>() /*eventTime*/,
+ fdp.ConsumeIntegral<uint32_t>() /*policyFlags*/,
+ fdp.ConsumeIntegral<uint32_t>() /*switchValues*/,
+ fdp.ConsumeIntegral<uint32_t>() /*switchMask*/);
+
+ mClassifier->notifySwitch(&switchArgs);
+ },
+ [&]() -> void {
+ // SendToNextStage_NotifyDeviceResetArgs
+ NotifyDeviceResetArgs resetArgs(fdp.ConsumeIntegral<uint32_t>() /*sequenceNum*/,
+ fdp.ConsumeIntegral<nsecs_t>() /*eventTime*/,
+ fdp.ConsumeIntegral<int32_t>() /*deviceId*/);
+
+ mClassifier->notifyDeviceReset(&resetArgs);
+ },
+ [&]() -> void {
+ // InputClassifierConverterTest
+ const NotifyMotionArgs motionArgs = generateFuzzedMotionArgs(fdp);
+ aidl::android::hardware::input::common::MotionEvent motionEvent =
+ notifyMotionArgsToHalMotionEvent(motionArgs);
+ },
+ })();
+ }
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp b/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp
new file mode 100644
index 0000000..f5bd297
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp
@@ -0,0 +1,284 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <InputReader.h>
+#include <MapperHelpers.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include <input/InputDevice.h>
+#include <chrono>
+#include <thread>
+
+namespace android {
+
+constexpr InputDeviceSensorType kInputDeviceSensorType[] = {
+ InputDeviceSensorType::ACCELEROMETER,
+ InputDeviceSensorType::MAGNETIC_FIELD,
+ InputDeviceSensorType::ORIENTATION,
+ InputDeviceSensorType::GYROSCOPE,
+ InputDeviceSensorType::LIGHT,
+ InputDeviceSensorType::PRESSURE,
+ InputDeviceSensorType::TEMPERATURE,
+ InputDeviceSensorType::PROXIMITY,
+ InputDeviceSensorType::GRAVITY,
+ InputDeviceSensorType::LINEAR_ACCELERATION,
+ InputDeviceSensorType::ROTATION_VECTOR,
+ InputDeviceSensorType::RELATIVE_HUMIDITY,
+ InputDeviceSensorType::AMBIENT_TEMPERATURE,
+ InputDeviceSensorType::MAGNETIC_FIELD_UNCALIBRATED,
+ InputDeviceSensorType::GAME_ROTATION_VECTOR,
+ InputDeviceSensorType::GYROSCOPE_UNCALIBRATED,
+ InputDeviceSensorType::SIGNIFICANT_MOTION,
+};
+
+class FuzzInputReader : public InputReaderInterface {
+public:
+ FuzzInputReader(std::shared_ptr<EventHubInterface> fuzzEventHub,
+ const sp<InputReaderPolicyInterface>& fuzzPolicy,
+ InputListenerInterface& fuzzListener) {
+ reader = std::make_unique<InputReader>(fuzzEventHub, fuzzPolicy, fuzzListener);
+ }
+
+ void dump(std::string& dump) { reader->dump(dump); }
+
+ void monitor() { reader->monitor(); }
+
+ bool isInputDeviceEnabled(int32_t deviceId) { return reader->isInputDeviceEnabled(deviceId); }
+
+ status_t start() { return reader->start(); }
+
+ status_t stop() { return reader->stop(); }
+
+ std::vector<InputDeviceInfo> getInputDevices() const { return reader->getInputDevices(); }
+
+ int32_t getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) {
+ return reader->getScanCodeState(deviceId, sourceMask, scanCode);
+ }
+
+ int32_t getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) {
+ return reader->getKeyCodeState(deviceId, sourceMask, keyCode);
+ }
+
+ int32_t getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t sw) {
+ return reader->getSwitchState(deviceId, sourceMask, sw);
+ }
+
+ void toggleCapsLockState(int32_t deviceId) { reader->toggleCapsLockState(deviceId); }
+
+ bool hasKeys(int32_t deviceId, uint32_t sourceMask, const std::vector<int32_t>& keyCodes,
+ uint8_t* outFlags) {
+ return reader->hasKeys(deviceId, sourceMask, keyCodes, outFlags);
+ }
+
+ void requestRefreshConfiguration(uint32_t changes) {
+ reader->requestRefreshConfiguration(changes);
+ }
+
+ void vibrate(int32_t deviceId, const VibrationSequence& sequence, ssize_t repeat,
+ int32_t token) {
+ reader->vibrate(deviceId, sequence, repeat, token);
+ }
+
+ void cancelVibrate(int32_t deviceId, int32_t token) { reader->cancelVibrate(deviceId, token); }
+
+ bool isVibrating(int32_t deviceId) { return reader->isVibrating(deviceId); }
+
+ std::vector<int32_t> getVibratorIds(int32_t deviceId) {
+ return reader->getVibratorIds(deviceId);
+ }
+
+ std::optional<int32_t> getBatteryCapacity(int32_t deviceId) {
+ return reader->getBatteryCapacity(deviceId);
+ }
+
+ std::optional<int32_t> getBatteryStatus(int32_t deviceId) {
+ return reader->getBatteryStatus(deviceId);
+ }
+
+ std::optional<std::string> getBatteryDevicePath(int32_t deviceId) {
+ return reader->getBatteryDevicePath(deviceId);
+ }
+
+ std::vector<InputDeviceLightInfo> getLights(int32_t deviceId) {
+ return reader->getLights(deviceId);
+ }
+
+ std::vector<InputDeviceSensorInfo> getSensors(int32_t deviceId) {
+ return reader->getSensors(deviceId);
+ }
+
+ bool canDispatchToDisplay(int32_t deviceId, int32_t displayId) {
+ return reader->canDispatchToDisplay(deviceId, displayId);
+ }
+
+ bool enableSensor(int32_t deviceId, InputDeviceSensorType sensorType,
+ std::chrono::microseconds samplingPeriod,
+ std::chrono::microseconds maxBatchReportLatency) {
+ return reader->enableSensor(deviceId, sensorType, samplingPeriod, maxBatchReportLatency);
+ }
+
+ void disableSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
+ return reader->disableSensor(deviceId, sensorType);
+ }
+
+ void flushSensor(int32_t deviceId, InputDeviceSensorType sensorType) {
+ return reader->flushSensor(deviceId, sensorType);
+ }
+
+ bool setLightColor(int32_t deviceId, int32_t lightId, int32_t color) {
+ return reader->setLightColor(deviceId, lightId, color);
+ }
+
+ bool setLightPlayerId(int32_t deviceId, int32_t lightId, int32_t playerId) {
+ return reader->setLightPlayerId(deviceId, lightId, playerId);
+ }
+
+ std::optional<int32_t> getLightColor(int32_t deviceId, int32_t lightId) {
+ return reader->getLightColor(deviceId, lightId);
+ }
+
+ std::optional<int32_t> getLightPlayerId(int32_t deviceId, int32_t lightId) {
+ return reader->getLightPlayerId(deviceId, lightId);
+ }
+
+ int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const {
+ return reader->getKeyCodeForKeyLocation(deviceId, locationKeyCode);
+ }
+
+private:
+ std::unique_ptr<InputReaderInterface> reader;
+};
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+ std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+
+ FuzzInputListener fuzzListener;
+ sp<FuzzInputReaderPolicy> fuzzPolicy = sp<FuzzInputReaderPolicy>::make(fdp);
+ std::shared_ptr<FuzzEventHub> fuzzEventHub = std::make_shared<FuzzEventHub>(fdp);
+ std::unique_ptr<FuzzInputReader> reader =
+ std::make_unique<FuzzInputReader>(fuzzEventHub, fuzzPolicy, fuzzListener);
+ fuzzEventHub->addEvents(fdp);
+ size_t patternCount = fdp->ConsumeIntegralInRange<size_t>(1, 260);
+ VibrationSequence pattern(patternCount);
+ for (size_t i = 0; i < patternCount; ++i) {
+ VibrationElement element(i);
+ element.addChannel(fdp->ConsumeIntegral<int32_t>() /* vibratorId */,
+ fdp->ConsumeIntegral<uint8_t>() /* amplitude */);
+ pattern.addElement(element);
+ }
+ reader->vibrate(fdp->ConsumeIntegral<int32_t>(), pattern,
+ fdp->ConsumeIntegral<ssize_t>() /*repeat*/,
+ fdp->ConsumeIntegral<int32_t>() /*token*/);
+ reader->start();
+
+ // Loop through mapper operations until randomness is exhausted.
+ while (fdp->remaining_bytes() > 0) {
+ fdp->PickValueInArray<std::function<void()>>({
+ [&]() -> void {
+ std::string dump;
+ reader->dump(dump);
+ },
+ [&]() -> void { reader->monitor(); },
+ [&]() -> void { reader->getInputDevices(); },
+ [&]() -> void { reader->isInputDeviceEnabled(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void {
+ reader->getScanCodeState(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->getKeyCodeState(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->getSwitchState(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void { reader->toggleCapsLockState(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void {
+ size_t count = fdp->ConsumeIntegralInRange<size_t>(1, 1024);
+ std::vector<uint8_t> outFlags(count);
+ std::vector<int32_t> keyCodes;
+ for (size_t i = 0; i < count; ++i) {
+ keyCodes.push_back(fdp->ConsumeIntegral<int32_t>());
+ }
+ reader->hasKeys(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<uint32_t>(), keyCodes, outFlags.data());
+ },
+ [&]() -> void {
+ reader->requestRefreshConfiguration(fdp->ConsumeIntegral<uint32_t>());
+ },
+ [&]() -> void {
+ reader->cancelVibrate(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->canDispatchToDisplay(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->getKeyCodeForKeyLocation(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void { reader->getBatteryCapacity(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void { reader->getBatteryStatus(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void { reader->getBatteryDevicePath(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void { reader->getLights(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void { reader->getSensors(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void {
+ reader->getLightPlayerId(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->getLightColor(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->setLightPlayerId(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->setLightColor(fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ reader->flushSensor(fdp->ConsumeIntegral<int32_t>(),
+ fdp->PickValueInArray<InputDeviceSensorType>(
+ kInputDeviceSensorType));
+ },
+ [&]() -> void {
+ reader->disableSensor(fdp->ConsumeIntegral<int32_t>(),
+ fdp->PickValueInArray<InputDeviceSensorType>(
+ kInputDeviceSensorType));
+ },
+ [&]() -> void {
+ reader->enableSensor(fdp->ConsumeIntegral<int32_t>(),
+ fdp->PickValueInArray<InputDeviceSensorType>(
+ kInputDeviceSensorType),
+ std::chrono::microseconds(fdp->ConsumeIntegral<size_t>()),
+ std::chrono::microseconds(fdp->ConsumeIntegral<size_t>()));
+ },
+ })();
+ }
+
+ reader->stop();
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp
new file mode 100644
index 0000000..c48a099
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <FuzzContainer.h>
+#include <KeyboardInputMapper.h>
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+const int32_t kMaxKeycodes = 100;
+
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<FuzzedDataProvider> fdp) {
+ // Pick a random property to set for the mapper to have set.
+ fdp->PickValueInArray<std::function<void()>>(
+ {[&]() -> void { fuzzer.addProperty("keyboard.orientationAware", "1"); },
+ [&]() -> void {
+ fuzzer.addProperty("keyboard.orientationAware",
+ fdp->ConsumeRandomLengthString(100).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("keyboard.doNotWakeByDefault",
+ fdp->ConsumeRandomLengthString(100).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("keyboard.handlesKeyRepeat",
+ fdp->ConsumeRandomLengthString(100).data());
+ }})();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+ std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ FuzzContainer fuzzer(fdp);
+
+ KeyboardInputMapper& mapper =
+ fuzzer.getMapper<KeyboardInputMapper>(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ auto policyConfig = fuzzer.getPolicyConfig();
+
+ // Loop through mapper operations until randomness is exhausted.
+ while (fdp->remaining_bytes() > 0) {
+ fdp->PickValueInArray<std::function<void()>>({
+ [&]() -> void { addProperty(fuzzer, fdp); },
+ [&]() -> void {
+ std::string dump;
+ mapper.dump(dump);
+ },
+ [&]() -> void {
+ InputDeviceInfo info;
+ mapper.populateDeviceInfo(&info);
+ },
+ [&]() -> void { mapper.getSources(); },
+ [&]() -> void {
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig,
+ fdp->ConsumeIntegral<uint32_t>());
+ },
+ [&]() -> void { mapper.reset(fdp->ConsumeIntegral<nsecs_t>()); },
+ [&]() -> void {
+ int32_t type, code;
+ type = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidTypes)
+ : fdp->ConsumeIntegral<int32_t>();
+ code = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidCodes)
+ : fdp->ConsumeIntegral<int32_t>();
+ RawEvent rawEvent{fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ type,
+ code,
+ fdp->ConsumeIntegral<int32_t>()};
+ mapper.process(&rawEvent);
+ },
+ [&]() -> void {
+ mapper.getKeyCodeState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ mapper.getScanCodeState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ std::vector<int32_t> keyCodes;
+ int32_t numBytes = fdp->ConsumeIntegralInRange<int32_t>(0, kMaxKeycodes);
+ for (int32_t i = 0; i < numBytes; ++i) {
+ keyCodes.push_back(fdp->ConsumeIntegral<int32_t>());
+ }
+ mapper.markSupportedKeyCodes(fdp->ConsumeIntegral<uint32_t>(), keyCodes,
+ nullptr);
+ },
+ [&]() -> void { mapper.getMetaState(); },
+ [&]() -> void { mapper.updateMetaState(fdp->ConsumeIntegral<int32_t>()); },
+ [&]() -> void { mapper.getAssociatedDisplayId(); },
+ })();
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/MapperHelpers.h b/services/inputflinger/tests/fuzzers/MapperHelpers.h
new file mode 100644
index 0000000..53a7b16
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/MapperHelpers.h
@@ -0,0 +1,372 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <InputDevice.h>
+#include <InputMapper.h>
+#include <InputReader.h>
+#include <fuzzer/FuzzedDataProvider.h>
+#include "android/hardware/input/InputDeviceCountryCode.h"
+
+using android::hardware::input::InputDeviceCountryCode;
+
+constexpr size_t kValidTypes[] = {EV_SW,
+ EV_SYN,
+ SYN_REPORT,
+ EV_ABS,
+ EV_KEY,
+ EV_MSC,
+ EV_REL,
+ android::EventHubInterface::DEVICE_ADDED,
+ android::EventHubInterface::DEVICE_REMOVED,
+ android::EventHubInterface::FINISHED_DEVICE_SCAN};
+
+constexpr size_t kValidCodes[] = {
+ SYN_REPORT,
+ ABS_MT_SLOT,
+ SYN_MT_REPORT,
+ ABS_MT_POSITION_X,
+ ABS_MT_POSITION_Y,
+ ABS_MT_TOUCH_MAJOR,
+ ABS_MT_TOUCH_MINOR,
+ ABS_MT_WIDTH_MAJOR,
+ ABS_MT_WIDTH_MINOR,
+ ABS_MT_ORIENTATION,
+ ABS_MT_TRACKING_ID,
+ ABS_MT_PRESSURE,
+ ABS_MT_DISTANCE,
+ ABS_MT_TOOL_TYPE,
+ SYN_MT_REPORT,
+ MSC_SCAN,
+ REL_X,
+ REL_Y,
+ REL_WHEEL,
+ REL_HWHEEL,
+ BTN_LEFT,
+ BTN_RIGHT,
+ BTN_MIDDLE,
+ BTN_BACK,
+ BTN_SIDE,
+ BTN_FORWARD,
+ BTN_EXTRA,
+ BTN_TASK,
+};
+
+constexpr InputDeviceCountryCode kCountryCodes[] = {
+ InputDeviceCountryCode::INVALID,
+ InputDeviceCountryCode::NOT_SUPPORTED,
+ InputDeviceCountryCode::ARABIC,
+ InputDeviceCountryCode::BELGIAN,
+ InputDeviceCountryCode::CANADIAN_BILINGUAL,
+ InputDeviceCountryCode::CANADIAN_FRENCH,
+ InputDeviceCountryCode::CZECH_REPUBLIC,
+ InputDeviceCountryCode::DANISH,
+ InputDeviceCountryCode::FINNISH,
+ InputDeviceCountryCode::FRENCH,
+ InputDeviceCountryCode::GERMAN,
+ InputDeviceCountryCode::GREEK,
+ InputDeviceCountryCode::HEBREW,
+ InputDeviceCountryCode::HUNGARY,
+ InputDeviceCountryCode::INTERNATIONAL,
+ InputDeviceCountryCode::ITALIAN,
+ InputDeviceCountryCode::JAPAN,
+ InputDeviceCountryCode::KOREAN,
+ InputDeviceCountryCode::LATIN_AMERICAN,
+ InputDeviceCountryCode::DUTCH,
+ InputDeviceCountryCode::NORWEGIAN,
+ InputDeviceCountryCode::PERSIAN,
+ InputDeviceCountryCode::POLAND,
+ InputDeviceCountryCode::PORTUGUESE,
+ InputDeviceCountryCode::RUSSIA,
+ InputDeviceCountryCode::SLOVAKIA,
+ InputDeviceCountryCode::SPANISH,
+ InputDeviceCountryCode::SWEDISH,
+ InputDeviceCountryCode::SWISS_FRENCH,
+ InputDeviceCountryCode::SWISS_GERMAN,
+ InputDeviceCountryCode::SWITZERLAND,
+ InputDeviceCountryCode::TAIWAN,
+ InputDeviceCountryCode::TURKISH_Q,
+ InputDeviceCountryCode::UK,
+ InputDeviceCountryCode::US,
+ InputDeviceCountryCode::YUGOSLAVIA,
+ InputDeviceCountryCode::TURKISH_F,
+};
+
+constexpr size_t kMaxSize = 256;
+
+namespace android {
+
+class FuzzEventHub : public EventHubInterface {
+ InputDeviceIdentifier mIdentifier;
+ std::vector<TouchVideoFrame> mVideoFrames;
+ PropertyMap mFuzzConfig;
+ size_t mCount = 0;
+ std::array<RawEvent, kMaxSize> mBuf;
+ std::shared_ptr<FuzzedDataProvider> mFdp;
+
+public:
+ FuzzEventHub(std::shared_ptr<FuzzedDataProvider> fdp) : mFdp(std::move(fdp)) {}
+ ~FuzzEventHub() {}
+ void addProperty(std::string key, std::string value) { mFuzzConfig.addProperty(key, value); }
+ void addEvents(std::shared_ptr<FuzzedDataProvider> fdp) {
+ mCount = fdp->ConsumeIntegralInRange<size_t>(0, kMaxSize);
+
+ for (size_t i = 0; i < mCount; ++i) {
+ int32_t type = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidTypes)
+ : fdp->ConsumeIntegral<int32_t>();
+ int32_t code = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidCodes)
+ : fdp->ConsumeIntegral<int32_t>();
+ mBuf[i] = {fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ type,
+ code,
+ fdp->ConsumeIntegral<int32_t>()};
+ }
+ }
+
+ ftl::Flags<InputDeviceClass> getDeviceClasses(int32_t deviceId) const override {
+ return ftl::Flags<InputDeviceClass>(mFdp->ConsumeIntegral<uint32_t>());
+ }
+ InputDeviceIdentifier getDeviceIdentifier(int32_t deviceId) const override {
+ return mIdentifier;
+ }
+ int32_t getDeviceControllerNumber(int32_t deviceId) const override {
+ return mFdp->ConsumeIntegral<int32_t>();
+ }
+ void getConfiguration(int32_t deviceId, PropertyMap* outConfiguration) const override {
+ *outConfiguration = mFuzzConfig;
+ }
+ status_t getAbsoluteAxisInfo(int32_t deviceId, int axis,
+ RawAbsoluteAxisInfo* outAxisInfo) const override {
+ return mFdp->ConsumeIntegral<status_t>();
+ }
+ bool hasRelativeAxis(int32_t deviceId, int axis) const override { return mFdp->ConsumeBool(); }
+ bool hasInputProperty(int32_t deviceId, int property) const override {
+ return mFdp->ConsumeBool();
+ }
+ bool hasMscEvent(int32_t deviceId, int mscEvent) const override { return mFdp->ConsumeBool(); }
+ status_t mapKey(int32_t deviceId, int32_t scanCode, int32_t usageCode, int32_t metaState,
+ int32_t* outKeycode, int32_t* outMetaState, uint32_t* outFlags) const override {
+ return mFdp->ConsumeIntegral<status_t>();
+ }
+ status_t mapAxis(int32_t deviceId, int32_t scanCode, AxisInfo* outAxisInfo) const override {
+ return mFdp->ConsumeIntegral<status_t>();
+ }
+ void setExcludedDevices(const std::vector<std::string>& devices) override {}
+ size_t getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) override {
+ for (size_t i = 0; i < mCount; ++i) buffer[i] = mBuf[i];
+
+ return mCount;
+ }
+ std::vector<TouchVideoFrame> getVideoFrames(int32_t deviceId) override { return mVideoFrames; }
+
+ base::Result<std::pair<InputDeviceSensorType, int32_t>> mapSensor(
+ int32_t deviceId, int32_t absCode) const override {
+ return base::ResultError("Fuzzer", UNKNOWN_ERROR);
+ };
+ // Raw batteries are sysfs power_supply nodes we found from the EventHub device sysfs node,
+ // containing the raw info of the sysfs node structure.
+ std::vector<int32_t> getRawBatteryIds(int32_t deviceId) const override { return {}; }
+ std::optional<RawBatteryInfo> getRawBatteryInfo(int32_t deviceId,
+ int32_t BatteryId) const override {
+ return std::nullopt;
+ };
+
+ std::vector<int32_t> getRawLightIds(int32_t deviceId) const override { return {}; };
+ std::optional<RawLightInfo> getRawLightInfo(int32_t deviceId, int32_t lightId) const override {
+ return std::nullopt;
+ };
+ std::optional<int32_t> getLightBrightness(int32_t deviceId, int32_t lightId) const override {
+ return std::nullopt;
+ };
+ void setLightBrightness(int32_t deviceId, int32_t lightId, int32_t brightness) override{};
+ std::optional<std::unordered_map<LightColor, int32_t>> getLightIntensities(
+ int32_t deviceId, int32_t lightId) const override {
+ return std::nullopt;
+ };
+ void setLightIntensities(int32_t deviceId, int32_t lightId,
+ std::unordered_map<LightColor, int32_t> intensities) override{};
+
+ InputDeviceCountryCode getCountryCode(int32_t deviceId) const override {
+ return mFdp->PickValueInArray<InputDeviceCountryCode>(kCountryCodes);
+ };
+
+ int32_t getScanCodeState(int32_t deviceId, int32_t scanCode) const override {
+ return mFdp->ConsumeIntegral<int32_t>();
+ }
+ int32_t getKeyCodeState(int32_t deviceId, int32_t keyCode) const override {
+ return mFdp->ConsumeIntegral<int32_t>();
+ }
+ int32_t getSwitchState(int32_t deviceId, int32_t sw) const override {
+ return mFdp->ConsumeIntegral<int32_t>();
+ }
+ int32_t getKeyCodeForKeyLocation(int32_t deviceId, int32_t locationKeyCode) const override {
+ return mFdp->ConsumeIntegral<int32_t>();
+ }
+ status_t getAbsoluteAxisValue(int32_t deviceId, int32_t axis,
+ int32_t* outValue) const override {
+ return mFdp->ConsumeIntegral<status_t>();
+ }
+ bool markSupportedKeyCodes(int32_t deviceId, const std::vector<int32_t>& keyCodes,
+ uint8_t* outFlags) const override {
+ return mFdp->ConsumeBool();
+ }
+ bool hasScanCode(int32_t deviceId, int32_t scanCode) const override {
+ return mFdp->ConsumeBool();
+ }
+ bool hasKeyCode(int32_t deviceId, int32_t keyCode) const override {
+ return mFdp->ConsumeBool();
+ }
+ bool hasLed(int32_t deviceId, int32_t led) const override { return mFdp->ConsumeBool(); }
+ void setLedState(int32_t deviceId, int32_t led, bool on) override {}
+ void getVirtualKeyDefinitions(
+ int32_t deviceId, std::vector<VirtualKeyDefinition>& outVirtualKeys) const override {}
+ const std::shared_ptr<KeyCharacterMap> getKeyCharacterMap(int32_t deviceId) const override {
+ return nullptr;
+ }
+ bool setKeyboardLayoutOverlay(int32_t deviceId, std::shared_ptr<KeyCharacterMap> map) override {
+ return mFdp->ConsumeBool();
+ }
+ void vibrate(int32_t deviceId, const VibrationElement& effect) override {}
+ void cancelVibrate(int32_t deviceId) override {}
+
+ std::vector<int32_t> getVibratorIds(int32_t deviceId) const override { return {}; };
+
+ /* Query battery level. */
+ std::optional<int32_t> getBatteryCapacity(int32_t deviceId, int32_t batteryId) const override {
+ return std::nullopt;
+ };
+
+ /* Query battery status. */
+ std::optional<int32_t> getBatteryStatus(int32_t deviceId, int32_t batteryId) const override {
+ return std::nullopt;
+ };
+
+ void requestReopenDevices() override {}
+ void wake() override {}
+ void dump(std::string& dump) const override {}
+ void monitor() const override {}
+ bool isDeviceEnabled(int32_t deviceId) const override { return mFdp->ConsumeBool(); }
+ status_t enableDevice(int32_t deviceId) override { return mFdp->ConsumeIntegral<status_t>(); }
+ status_t disableDevice(int32_t deviceId) override { return mFdp->ConsumeIntegral<status_t>(); }
+};
+
+class FuzzPointerController : public PointerControllerInterface {
+ std::shared_ptr<FuzzedDataProvider> mFdp;
+
+public:
+ FuzzPointerController(std::shared_ptr<FuzzedDataProvider> mFdp) : mFdp(mFdp) {}
+ ~FuzzPointerController() {}
+ bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const override {
+ return mFdp->ConsumeBool();
+ }
+ void move(float deltaX, float deltaY) override {}
+ void setButtonState(int32_t buttonState) override {}
+ int32_t getButtonState() const override { return mFdp->ConsumeIntegral<int32_t>(); }
+ void setPosition(float x, float y) override {}
+ void getPosition(float* outX, float* outY) const override {}
+ void fade(Transition transition) override {}
+ void unfade(Transition transition) override {}
+ void setPresentation(Presentation presentation) override {}
+ void setSpots(const PointerCoords* spotCoords, const uint32_t* spotIdToIndex,
+ BitSet32 spotIdBits, int32_t displayId) override {}
+ void clearSpots() override {}
+ int32_t getDisplayId() const override { return mFdp->ConsumeIntegral<int32_t>(); }
+ void setDisplayViewport(const DisplayViewport& displayViewport) override {}
+};
+
+class FuzzInputReaderPolicy : public InputReaderPolicyInterface {
+ TouchAffineTransformation mTransform;
+ std::shared_ptr<FuzzPointerController> mPointerController;
+ std::shared_ptr<FuzzedDataProvider> mFdp;
+
+protected:
+ ~FuzzInputReaderPolicy() {}
+
+public:
+ FuzzInputReaderPolicy(std::shared_ptr<FuzzedDataProvider> mFdp) : mFdp(mFdp) {
+ mPointerController = std::make_shared<FuzzPointerController>(mFdp);
+ }
+ void getReaderConfiguration(InputReaderConfiguration* outConfig) override {}
+ std::shared_ptr<PointerControllerInterface> obtainPointerController(int32_t deviceId) override {
+ return mPointerController;
+ }
+ void notifyInputDevicesChanged(const std::vector<InputDeviceInfo>& inputDevices) override {}
+ std::shared_ptr<KeyCharacterMap> getKeyboardLayoutOverlay(
+ const InputDeviceIdentifier& identifier) override {
+ return nullptr;
+ }
+ std::string getDeviceAlias(const InputDeviceIdentifier& identifier) {
+ return mFdp->ConsumeRandomLengthString(32);
+ }
+ TouchAffineTransformation getTouchAffineTransformation(const std::string& inputDeviceDescriptor,
+ int32_t surfaceRotation) override {
+ return mTransform;
+ }
+ void setTouchAffineTransformation(const TouchAffineTransformation t) { mTransform = t; }
+};
+
+class FuzzInputListener : public virtual InputListenerInterface {
+public:
+ void notifyConfigurationChanged(const NotifyConfigurationChangedArgs* args) override {}
+ void notifyKey(const NotifyKeyArgs* args) override {}
+ void notifyMotion(const NotifyMotionArgs* args) override {}
+ void notifySwitch(const NotifySwitchArgs* args) override {}
+ void notifySensor(const NotifySensorArgs* args) override{};
+ void notifyVibratorState(const NotifyVibratorStateArgs* args) override{};
+ void notifyDeviceReset(const NotifyDeviceResetArgs* args) override {}
+ void notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs* args) override{};
+};
+
+class FuzzInputReaderContext : public InputReaderContext {
+ std::shared_ptr<EventHubInterface> mEventHub;
+ sp<InputReaderPolicyInterface> mPolicy;
+ InputListenerInterface& mListener;
+ std::shared_ptr<FuzzedDataProvider> mFdp;
+
+public:
+ FuzzInputReaderContext(std::shared_ptr<EventHubInterface> eventHub,
+ const sp<InputReaderPolicyInterface>& policy,
+ InputListenerInterface& listener,
+ std::shared_ptr<FuzzedDataProvider> mFdp)
+ : mEventHub(eventHub), mPolicy(policy), mListener(listener), mFdp(mFdp) {}
+ ~FuzzInputReaderContext() {}
+ void updateGlobalMetaState() override {}
+ int32_t getGlobalMetaState() { return mFdp->ConsumeIntegral<int32_t>(); }
+ void disableVirtualKeysUntil(nsecs_t time) override {}
+ bool shouldDropVirtualKey(nsecs_t now, int32_t keyCode, int32_t scanCode) override {
+ return mFdp->ConsumeBool();
+ }
+ void fadePointer() override {}
+ std::shared_ptr<PointerControllerInterface> getPointerController(int32_t deviceId) override {
+ return mPolicy->obtainPointerController(0);
+ }
+ void requestTimeoutAtTime(nsecs_t when) override {}
+ int32_t bumpGeneration() override { return mFdp->ConsumeIntegral<int32_t>(); }
+ void getExternalStylusDevices(std::vector<InputDeviceInfo>& outDevices) override {}
+ void dispatchExternalStylusState(const StylusState& outState) override {}
+ InputReaderPolicyInterface* getPolicy() override { return mPolicy.get(); }
+ InputListenerInterface& getListener() override { return mListener; }
+ EventHubInterface* getEventHub() override { return mEventHub.get(); }
+ int32_t getNextId() override { return mFdp->ConsumeIntegral<int32_t>(); }
+
+ void updateLedMetaState(int32_t metaState) override{};
+ int32_t getLedMetaState() override { return mFdp->ConsumeIntegral<int32_t>(); };
+};
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp
new file mode 100644
index 0000000..59b0642
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp
@@ -0,0 +1,134 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <FuzzContainer.h>
+#include <MultiTouchInputMapper.h>
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+const int32_t kMaxKeycodes = 100;
+
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<FuzzedDataProvider> fdp) {
+ // Pick a random property to set for the mapper to have set.
+ fdp->PickValueInArray<std::function<void()>>(
+ {[&]() -> void { fuzzer.addProperty("touch.deviceType", "touchScreen"); },
+ [&]() -> void {
+ fuzzer.addProperty("touch.deviceType", fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.size.scale", fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.size.bias", fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.size.isSummed",
+ fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.size.calibration",
+ fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.pressure.scale",
+ fdp->ConsumeRandomLengthString(8).data());
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.size.calibration",
+ fdp->ConsumeBool() ? "diameter" : "area");
+ },
+ [&]() -> void {
+ fuzzer.addProperty("touch.pressure.calibration",
+ fdp->ConsumeRandomLengthString(8).data());
+ }})();
+}
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+ std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ FuzzContainer fuzzer(fdp);
+
+ MultiTouchInputMapper& mapper = fuzzer.getMapper<MultiTouchInputMapper>();
+ auto policyConfig = fuzzer.getPolicyConfig();
+
+ // Loop through mapper operations until randomness is exhausted.
+ while (fdp->remaining_bytes() > 0) {
+ fdp->PickValueInArray<std::function<void()>>({
+ [&]() -> void { addProperty(fuzzer, fdp); },
+ [&]() -> void {
+ std::string dump;
+ mapper.dump(dump);
+ },
+ [&]() -> void {
+ InputDeviceInfo info;
+ mapper.populateDeviceInfo(&info);
+ },
+ [&]() -> void { mapper.getSources(); },
+ [&]() -> void {
+ mapper.configure(fdp->ConsumeIntegral<nsecs_t>(), &policyConfig,
+ fdp->ConsumeIntegral<uint32_t>());
+ },
+ [&]() -> void { mapper.reset(fdp->ConsumeIntegral<nsecs_t>()); },
+ [&]() -> void {
+ int32_t type = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidTypes)
+ : fdp->ConsumeIntegral<int32_t>();
+ int32_t code = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidCodes)
+ : fdp->ConsumeIntegral<int32_t>();
+ RawEvent rawEvent{fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ type,
+ code,
+ fdp->ConsumeIntegral<int32_t>()};
+ mapper.process(&rawEvent);
+ },
+ [&]() -> void {
+ mapper.getKeyCodeState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ mapper.getScanCodeState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ [&]() -> void {
+ std::vector<int32_t> keyCodes;
+ int32_t numBytes = fdp->ConsumeIntegralInRange<int32_t>(0, kMaxKeycodes);
+ for (int32_t i = 0; i < numBytes; ++i) {
+ keyCodes.push_back(fdp->ConsumeIntegral<int32_t>());
+ }
+ mapper.markSupportedKeyCodes(fdp->ConsumeIntegral<uint32_t>(), keyCodes,
+ nullptr);
+ },
+ [&]() -> void {
+ mapper.cancelTouch(fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>());
+ },
+ [&]() -> void { mapper.timeoutExpired(fdp->ConsumeIntegral<nsecs_t>()); },
+ [&]() -> void {
+ StylusState state{fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeFloatingPoint<float>(),
+ fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>()};
+ mapper.updateExternalStylusState(state);
+ },
+ [&]() -> void { mapper.getAssociatedDisplayId(); },
+ })();
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp
new file mode 100644
index 0000000..e76bd72
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <FuzzContainer.h>
+#include <SwitchInputMapper.h>
+#include <fuzzer/FuzzedDataProvider.h>
+
+namespace android {
+
+extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
+ std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ FuzzContainer fuzzer(fdp);
+
+ SwitchInputMapper& mapper = fuzzer.getMapper<SwitchInputMapper>();
+ auto policyConfig = fuzzer.getPolicyConfig();
+
+ // Loop through mapper operations until randomness is exhausted.
+ while (fdp->remaining_bytes() > 0) {
+ fdp->PickValueInArray<std::function<void()>>({
+ [&]() -> void {
+ std::string dump;
+ mapper.dump(dump);
+ },
+ [&]() -> void { mapper.getSources(); },
+ [&]() -> void {
+ int32_t type = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidTypes)
+ : fdp->ConsumeIntegral<int32_t>();
+ int32_t code = fdp->ConsumeBool() ? fdp->PickValueInArray(kValidCodes)
+ : fdp->ConsumeIntegral<int32_t>();
+ RawEvent rawEvent{fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<nsecs_t>(),
+ fdp->ConsumeIntegral<int32_t>(),
+ type,
+ code,
+ fdp->ConsumeIntegral<int32_t>()};
+ mapper.process(&rawEvent);
+ },
+ [&]() -> void {
+ mapper.getSwitchState(fdp->ConsumeIntegral<uint32_t>(),
+ fdp->ConsumeIntegral<int32_t>());
+ },
+ })();
+ }
+
+ return 0;
+}
+
+} // namespace android
diff --git a/services/sensorservice/AidlSensorHalWrapper.cpp b/services/sensorservice/AidlSensorHalWrapper.cpp
index 4d1de96..f67c610 100644
--- a/services/sensorservice/AidlSensorHalWrapper.cpp
+++ b/services/sensorservice/AidlSensorHalWrapper.cpp
@@ -726,7 +726,7 @@
.type = type,
.format = format,
.size = static_cast<int32_t>(memory->size),
- .memoryHandle = makeToAidl(memory->handle),
+ .memoryHandle = dupToAidl(memory->handle),
};
return convertToStatus(mSensors->registerDirectChannel(mem, channelHandle));
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index de050e0..10ca990 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -39,7 +39,6 @@
#include <thread>
using namespace android::hardware::sensors;
-using android::hardware::Return;
using android::util::ProtoOutputStream;
namespace android {
diff --git a/services/sensorservice/SensorDirectConnection.cpp b/services/sensorservice/SensorDirectConnection.cpp
index 2dd12e9..291c770 100644
--- a/services/sensorservice/SensorDirectConnection.cpp
+++ b/services/sensorservice/SensorDirectConnection.cpp
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-#include "SensorDevice.h"
#include "SensorDirectConnection.h"
#include <android/util/ProtoOutputStream.h>
#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
#include <hardware/sensors.h>
+#include "SensorDevice.h"
#define UNUSED(x) (void)(x)
@@ -51,7 +51,7 @@
stopAll();
mService->cleanupConnection(this);
if (mMem.handle != nullptr) {
- native_handle_close(mMem.handle);
+ native_handle_close_with_tag(mMem.handle);
native_handle_delete(const_cast<struct native_handle*>(mMem.handle));
}
mDestroyed = true;
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index e0a4f03..21d6b6b 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -16,7 +16,6 @@
#include <android-base/strings.h>
#include <android/content/pm/IPackageManagerNative.h>
#include <android/util/ProtoOutputStream.h>
-#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
#include <binder/ActivityManager.h>
#include <binder/BinderService.h>
#include <binder/IServiceManager.h>
@@ -25,6 +24,7 @@
#include <cutils/ashmem.h>
#include <cutils/misc.h>
#include <cutils/properties.h>
+#include <frameworks/base/core/proto/android/service/sensor_service.proto.h>
#include <hardware/sensors.h>
#include <hardware_legacy/power.h>
#include <log/log.h>
@@ -1475,6 +1475,7 @@
if (!clone) {
return nullptr;
}
+ native_handle_set_fdsan_tag(clone);
sp<SensorDirectConnection> conn;
SensorDevice& dev(SensorDevice::getInstance());
@@ -1488,7 +1489,7 @@
}
if (conn == nullptr) {
- native_handle_close(clone);
+ native_handle_close_with_tag(clone);
native_handle_delete(clone);
} else {
// add to list of direct connections
diff --git a/services/sensorservice/tests/sensorservicetest.cpp b/services/sensorservice/tests/sensorservicetest.cpp
index caf7f03..b00d1a7 100644
--- a/services/sensorservice/tests/sensorservicetest.cpp
+++ b/services/sensorservice/tests/sensorservicetest.cpp
@@ -89,6 +89,17 @@
// Should print -22 (BAD_VALUE) and the device runtime shouldn't restart
printf("createInvalidDirectChannel=%d\n", ret);
+
+ // Secondary test: correct channel creation & destruction (should print 0)
+ ret = mgr.createDirectChannel(kMemSize, ASENSOR_DIRECT_CHANNEL_TYPE_HARDWARE_BUFFER,
+ resourceHandle);
+ printf("createValidDirectChannel=%d\n", ret);
+
+ // Third test: double-destroy (should not crash)
+ mgr.destroyDirectChannel(ret);
+ AHardwareBuffer_release(hardwareBuffer);
+ printf("duplicate destroyDirectChannel...\n");
+ mgr.destroyDirectChannel(ret);
}
int main() {
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index 76429ff..b911ae7 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -25,6 +25,7 @@
cc_defaults {
name: "libsurfaceflinger_defaults",
defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
"surfaceflinger_defaults",
"skia_renderengine_deps",
],
@@ -46,7 +47,6 @@
"android.hardware.graphics.composer@2.2",
"android.hardware.graphics.composer@2.3",
"android.hardware.graphics.composer@2.4",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.power@1.0",
"android.hardware.power@1.3",
"android.hardware.power-V2-cpp",
@@ -106,7 +106,6 @@
"android.hardware.graphics.composer@2.2",
"android.hardware.graphics.composer@2.3",
"android.hardware.graphics.composer@2.4",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.power@1.3",
"libhidlbase",
"libtimestats",
@@ -142,17 +141,16 @@
name: "libsurfaceflinger_sources",
srcs: [
"BackgroundExecutor.cpp",
- "BufferStateLayer.cpp",
- "ClientCache.cpp",
"Client.cpp",
- "EffectLayer.cpp",
+ "ClientCache.cpp",
+ "Display/DisplaySnapshot.cpp",
"DisplayDevice.cpp",
"DisplayHardware/AidlComposerHal.cpp",
- "DisplayHardware/HidlComposerHal.cpp",
"DisplayHardware/ComposerHal.cpp",
"DisplayHardware/FramebufferSurface.cpp",
"DisplayHardware/HWC2.cpp",
"DisplayHardware/HWComposer.cpp",
+ "DisplayHardware/HidlComposerHal.cpp",
"DisplayHardware/PowerAdvisor.cpp",
"DisplayHardware/VirtualDisplaySurface.cpp",
"DisplayRenderArea.cpp",
diff --git a/services/surfaceflinger/BufferStateLayer.cpp b/services/surfaceflinger/BufferStateLayer.cpp
deleted file mode 100644
index 0cedfc8..0000000
--- a/services/surfaceflinger/BufferStateLayer.cpp
+++ /dev/null
@@ -1,1639 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-//#define LOG_NDEBUG 0
-#undef LOG_TAG
-#define LOG_TAG "BufferStateLayer"
-#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-
-#include "BufferStateLayer.h"
-
-#include <limits>
-
-#include <FrameTimeline/FrameTimeline.h>
-#include <compositionengine/CompositionEngine.h>
-#include <gui/BufferQueue.h>
-#include <private/gui/SyncFeatures.h>
-#include <renderengine/Image.h>
-#include "TunnelModeEnabledReporter.h"
-
-#include <gui/TraceUtils.h>
-#include "EffectLayer.h"
-#include "FrameTracer/FrameTracer.h"
-#include "TimeStats/TimeStats.h"
-
-#define EARLY_RELEASE_ENABLED false
-
-#include <compositionengine/LayerFECompositionState.h>
-#include <compositionengine/OutputLayer.h>
-#include <compositionengine/impl/OutputLayerCompositionState.h>
-#include <cutils/compiler.h>
-#include <cutils/native_handle.h>
-#include <cutils/properties.h>
-#include <gui/BufferItem.h>
-#include <gui/BufferQueue.h>
-#include <gui/GLConsumer.h>
-#include <gui/LayerDebugInfo.h>
-#include <gui/Surface.h>
-#include <renderengine/RenderEngine.h>
-#include <ui/DebugUtils.h>
-#include <utils/Errors.h>
-#include <utils/Log.h>
-#include <utils/NativeHandle.h>
-#include <utils/StopWatch.h>
-#include <utils/Trace.h>
-
-#include <cmath>
-#include <cstdlib>
-#include <mutex>
-#include <sstream>
-
-#include "Colorizer.h"
-#include "DisplayDevice.h"
-#include "FrameTracer/FrameTracer.h"
-#include "TimeStats/TimeStats.h"
-
-namespace android {
-
-using PresentState = frametimeline::SurfaceFrame::PresentState;
-using gui::WindowInfo;
-namespace {
-static constexpr float defaultMaxLuminance = 1000.0;
-
-constexpr mat4 inverseOrientation(uint32_t transform) {
- const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
- const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
- const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
- mat4 tr;
-
- if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
- tr = tr * rot90;
- }
- if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
- tr = tr * flipH;
- }
- if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
- tr = tr * flipV;
- }
- return inverse(tr);
-}
-
-bool assignTransform(ui::Transform* dst, ui::Transform& from) {
- if (*dst == from) {
- return false;
- }
- *dst = from;
- return true;
-}
-
-TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
- using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
- using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
- const auto frameRateCompatibility = [frameRate] {
- switch (frameRate.type) {
- case Layer::FrameRateCompatibility::Default:
- return FrameRateCompatibility::Default;
- case Layer::FrameRateCompatibility::ExactOrMultiple:
- return FrameRateCompatibility::ExactOrMultiple;
- default:
- return FrameRateCompatibility::Undefined;
- }
- }();
-
- const auto seamlessness = [frameRate] {
- switch (frameRate.seamlessness) {
- case scheduler::Seamlessness::OnlySeamless:
- return Seamlessness::ShouldBeSeamless;
- case scheduler::Seamlessness::SeamedAndSeamless:
- return Seamlessness::NotRequired;
- default:
- return Seamlessness::Undefined;
- }
- }();
-
- return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
- .frameRateCompatibility = frameRateCompatibility,
- .seamlessness = seamlessness};
-}
-} // namespace
-
-BufferStateLayer::BufferStateLayer(const LayerCreationArgs& args)
- : Layer(args),
- mTextureName(args.textureName),
- mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()},
- mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
- ALOGV("Creating Layer %s", getDebugName());
-
- mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
- mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
- mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
- mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
-}
-
-BufferStateLayer::~BufferStateLayer() {
- // The original layer and the clone layer share the same texture and buffer. Therefore, only
- // one of the layers, in this case the original layer, needs to handle the deletion. The
- // original layer and the clone should be removed at the same time so there shouldn't be any
- // issue with the clone layer trying to use the texture.
- if (mBufferInfo.mBuffer != nullptr) {
- callReleaseBufferCallback(mDrawingState.releaseBufferListener,
- mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
- mBufferInfo.mFence,
- mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
- mOwnerUid));
- }
- if (!isClone()) {
- // The original layer and the clone layer share the same texture. Therefore, only one of
- // the layers, in this case the original layer, needs to handle the deletion. The original
- // layer and the clone should be removed at the same time so there shouldn't be any issue
- // with the clone layer trying to use the deleted texture.
- mFlinger->deleteTextureAsync(mTextureName);
- }
- const int32_t layerId = getSequence();
- mFlinger->mTimeStats->onDestroy(layerId);
- mFlinger->mFrameTracer->onDestroy(layerId);
-}
-
-void BufferStateLayer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
- const sp<GraphicBuffer>& buffer,
- uint64_t framenumber,
- const sp<Fence>& releaseFence,
- uint32_t currentMaxAcquiredBufferCount) {
- if (!listener) {
- return;
- }
- ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
- listener->onReleaseBuffer({buffer->getId(), framenumber},
- releaseFence ? releaseFence : Fence::NO_FENCE,
- currentMaxAcquiredBufferCount);
-}
-
-// -----------------------------------------------------------------------
-// Interface implementation for Layer
-// -----------------------------------------------------------------------
-void BufferStateLayer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
- // If we are displayed on multiple displays in a single composition cycle then we would
- // need to do careful tracking to enable the use of the mLastClientCompositionFence.
- // For example we can only use it if all the displays are client comp, and we need
- // to merge all the client comp fences. We could do this, but for now we just
- // disable the optimization when a layer is composed on multiple displays.
- if (mClearClientCompositionFenceOnLayerDisplayed) {
- mLastClientCompositionFence = nullptr;
- } else {
- mClearClientCompositionFenceOnLayerDisplayed = true;
- }
-
- // The previous release fence notifies the client that SurfaceFlinger is done with the previous
- // buffer that was presented on this layer. The first transaction that came in this frame that
- // replaced the previous buffer on this layer needs this release fence, because the fence will
- // let the client know when that previous buffer is removed from the screen.
- //
- // Every other transaction on this layer does not need a release fence because no other
- // Transactions that were set on this layer this frame are going to have their preceeding buffer
- // removed from the display this frame.
- //
- // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
- // buffer so it doesn't need a previous release fence because the layer still needs the previous
- // buffer. The second transaction contains a buffer so it needs a previous release fence because
- // the previous buffer will be released this frame. The third transaction also contains a
- // buffer. It replaces the buffer in the second transaction. The buffer in the second
- // transaction will now no longer be presented so it is released immediately and the third
- // transaction doesn't need a previous release fence.
- sp<CallbackHandle> ch;
- for (auto& handle : mDrawingState.callbackHandles) {
- if (handle->releasePreviousBuffer &&
- mDrawingState.releaseBufferEndpoint == handle->listener) {
- ch = handle;
- break;
- }
- }
-
- // Prevent tracing the same release multiple times.
- if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
- mPreviousReleasedFrameNumber = mPreviousFrameNumber;
- }
-
- if (ch != nullptr) {
- ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
- ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
- ch->name = mName;
- }
-}
-
-void BufferStateLayer::onSurfaceFrameCreated(
- const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
- while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
- // Too many SurfaceFrames pending classification. The front of the deque is probably not
- // tracked by FrameTimeline and will never be presented. This will only result in a memory
- // leak.
- ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
- mName.c_str());
- std::string miniDump = mPendingJankClassifications.front()->miniDump();
- ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
- mPendingJankClassifications.pop_front();
- }
- mPendingJankClassifications.emplace_back(surfaceFrame);
-}
-
-void BufferStateLayer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
- for (const auto& handle : mDrawingState.callbackHandles) {
- handle->transformHint = mTransformHint;
- handle->dequeueReadyTime = dequeueReadyTime;
- handle->currentMaxAcquiredBufferCount =
- mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
- ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
- handle->previousReleaseCallbackId.framenumber);
- }
-
- for (auto& handle : mDrawingState.callbackHandles) {
- if (handle->releasePreviousBuffer &&
- mDrawingState.releaseBufferEndpoint == handle->listener) {
- handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
- break;
- }
- }
-
- std::vector<JankData> jankData;
- jankData.reserve(mPendingJankClassifications.size());
- while (!mPendingJankClassifications.empty()
- && mPendingJankClassifications.front()->getJankType()) {
- std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
- mPendingJankClassifications.front();
- mPendingJankClassifications.pop_front();
- jankData.emplace_back(
- JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
- }
-
- mFlinger->getTransactionCallbackInvoker().addCallbackHandles(
- mDrawingState.callbackHandles, jankData);
-
- sp<Fence> releaseFence = Fence::NO_FENCE;
- for (auto& handle : mDrawingState.callbackHandles) {
- if (handle->releasePreviousBuffer &&
- mDrawingState.releaseBufferEndpoint == handle->listener) {
- releaseFence =
- handle->previousReleaseFence ? handle->previousReleaseFence : Fence::NO_FENCE;
- break;
- }
- }
-
- mDrawingState.callbackHandles = {};
-}
-
-bool BufferStateLayer::willPresentCurrentTransaction() const {
- // Returns true if the most recent Transaction applied to CurrentState will be presented.
- return (getSidebandStreamChanged() || getAutoRefresh() ||
- (mDrawingState.modified &&
- (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
-}
-
-Rect BufferStateLayer::getCrop(const Layer::State& s) const {
- return s.crop;
-}
-
-bool BufferStateLayer::setTransform(uint32_t transform) {
- if (mDrawingState.bufferTransform == transform) return false;
- mDrawingState.bufferTransform = transform;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
- if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
- mDrawingState.sequence++;
- mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setCrop(const Rect& crop) {
- if (mDrawingState.crop == crop) return false;
- mDrawingState.sequence++;
- mDrawingState.crop = crop;
-
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setBufferCrop(const Rect& bufferCrop) {
- if (mDrawingState.bufferCrop == bufferCrop) return false;
-
- mDrawingState.sequence++;
- mDrawingState.bufferCrop = bufferCrop;
-
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setDestinationFrame(const Rect& destinationFrame) {
- if (mDrawingState.destinationFrame == destinationFrame) return false;
-
- mDrawingState.sequence++;
- mDrawingState.destinationFrame = destinationFrame;
-
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-// Translate destination frame into scale and position. If a destination frame is not set, use the
-// provided scale and position
-bool BufferStateLayer::updateGeometry() {
- if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
- mDrawingState.destinationFrame.isEmpty()) {
- // If destination frame is not set, use the requested transform set via
- // BufferStateLayer::setPosition and BufferStateLayer::setMatrix.
- return assignTransform(&mDrawingState.transform, mRequestedTransform);
- }
-
- Rect destRect = mDrawingState.destinationFrame;
- int32_t destW = destRect.width();
- int32_t destH = destRect.height();
- if (destRect.left < 0) {
- destRect.left = 0;
- destRect.right = destW;
- }
- if (destRect.top < 0) {
- destRect.top = 0;
- destRect.bottom = destH;
- }
-
- if (!mDrawingState.buffer) {
- ui::Transform t;
- t.set(destRect.left, destRect.top);
- return assignTransform(&mDrawingState.transform, t);
- }
-
- uint32_t bufferWidth = mDrawingState.buffer->getWidth();
- uint32_t bufferHeight = mDrawingState.buffer->getHeight();
- // Undo any transformations on the buffer.
- if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
- std::swap(bufferWidth, bufferHeight);
- }
- uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
- if (mDrawingState.transformToDisplayInverse) {
- if (invTransform & ui::Transform::ROT_90) {
- std::swap(bufferWidth, bufferHeight);
- }
- }
-
- float sx = destW / static_cast<float>(bufferWidth);
- float sy = destH / static_cast<float>(bufferHeight);
- ui::Transform t;
- t.set(sx, 0, 0, sy);
- t.set(destRect.left, destRect.top);
- return assignTransform(&mDrawingState.transform, t);
-}
-
-bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix) {
- if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
- mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
- return false;
- }
-
- ui::Transform t;
- t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
-
- mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
-
- mDrawingState.sequence++;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
-
- return true;
-}
-
-bool BufferStateLayer::setPosition(float x, float y) {
- if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
- return false;
- }
-
- mRequestedTransform.set(x, y);
-
- mDrawingState.sequence++;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
-
- return true;
-}
-
-bool BufferStateLayer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
- const BufferData& bufferData, nsecs_t postTime,
- nsecs_t desiredPresentTime, bool isAutoTimestamp,
- std::optional<nsecs_t> dequeueTime,
- const FrameTimelineInfo& info) {
- ATRACE_CALL();
-
- if (!buffer) {
- return false;
- }
-
- const bool frameNumberChanged =
- bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
- const uint64_t frameNumber =
- frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
-
- if (mDrawingState.buffer) {
- mReleasePreviousBuffer = true;
- if (!mBufferInfo.mBuffer ||
- (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
- mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
- // If mDrawingState has a buffer, and we are about to update again
- // before swapping to drawing state, then the first buffer will be
- // dropped and we should decrement the pending buffer count and
- // call any release buffer callbacks if set.
- callReleaseBufferCallback(mDrawingState.releaseBufferListener,
- mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
- mDrawingState.acquireFence,
- mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
- mOwnerUid));
- decrementPendingBufferCount();
- if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
- mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
- addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
- mDrawingState.bufferSurfaceFrameTX.reset();
- }
- } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
- callReleaseBufferCallback(mDrawingState.releaseBufferListener,
- mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
- mLastClientCompositionFence,
- mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
- mOwnerUid));
- mLastClientCompositionFence = nullptr;
- }
- }
-
- mDrawingState.frameNumber = frameNumber;
- mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
- mDrawingState.buffer = std::move(buffer);
- mDrawingState.clientCacheId = bufferData.cachedBuffer;
-
- mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
- ? bufferData.acquireFence
- : Fence::NO_FENCE;
- mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
- if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
- // We latched this buffer unsiganled, so we need to pass the acquire fence
- // on the callback instead of just the acquire time, since it's unknown at
- // this point.
- mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
- } else {
- mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
- }
-
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
-
- const int32_t layerId = getSequence();
- mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
- mOwnerUid, postTime, getGameMode());
- mDrawingState.desiredPresentTime = desiredPresentTime;
- mDrawingState.isAutoTimestamp = isAutoTimestamp;
-
- const nsecs_t presentTime = [&] {
- if (!isAutoTimestamp) return desiredPresentTime;
-
- const auto prediction =
- mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
- if (prediction.has_value()) return prediction->presentTime;
-
- return static_cast<nsecs_t>(0);
- }();
-
- using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
- mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
-
- setFrameTimelineVsyncForBufferTransaction(info, postTime);
-
- if (dequeueTime && *dequeueTime != 0) {
- const uint64_t bufferId = mDrawingState.buffer->getId();
- mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
- mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
- FrameTracer::FrameEvent::DEQUEUE);
- mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
- FrameTracer::FrameEvent::QUEUE);
- }
-
- mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
- return true;
-}
-
-bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
- if (mDrawingState.dataspace == dataspace) return false;
- mDrawingState.dataspace = dataspace;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
- if (mDrawingState.hdrMetadata == hdrMetadata) return false;
- mDrawingState.hdrMetadata = hdrMetadata;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
- mDrawingState.surfaceDamageRegion = surfaceDamage;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setApi(int32_t api) {
- if (mDrawingState.api == api) return false;
- mDrawingState.api = api;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
- if (mDrawingState.sidebandStream == sidebandStream) return false;
-
- if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
- mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
- } else if (sidebandStream != nullptr) {
- mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
- }
-
- mDrawingState.sidebandStream = sidebandStream;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- if (!mSidebandStreamChanged.exchange(true)) {
- // mSidebandStreamChanged was false
- mFlinger->onLayerUpdate();
- }
- return true;
-}
-
-bool BufferStateLayer::setTransactionCompletedListeners(
- const std::vector<sp<CallbackHandle>>& handles) {
- // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
- if (handles.empty()) {
- mReleasePreviousBuffer = false;
- return false;
- }
-
- const bool willPresent = willPresentCurrentTransaction();
-
- for (const auto& handle : handles) {
- // If this transaction set a buffer on this layer, release its previous buffer
- handle->releasePreviousBuffer = mReleasePreviousBuffer;
-
- // If this layer will be presented in this frame
- if (willPresent) {
- // If this transaction set an acquire fence on this layer, set its acquire time
- handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
- handle->frameNumber = mDrawingState.frameNumber;
-
- // Store so latched time and release fence can be set
- mDrawingState.callbackHandles.push_back(handle);
-
- } else { // If this layer will NOT need to be relatched and presented this frame
- // Notify the transaction completed thread this handle is done
- mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
- }
- }
-
- mReleasePreviousBuffer = false;
- mCallbackHandleAcquireTimeOrFence = -1;
-
- return willPresent;
-}
-
-Rect BufferStateLayer::getBufferSize(const State& /*s*/) const {
- // for buffer state layers we use the display frame size as the buffer size.
-
- if (mBufferInfo.mBuffer == nullptr) {
- return Rect::INVALID_RECT;
- }
-
- uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
- uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
-
- // Undo any transformations on the buffer and return the result.
- if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
- std::swap(bufWidth, bufHeight);
- }
-
- if (getTransformToDisplayInverse()) {
- uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
- if (invTransform & ui::Transform::ROT_90) {
- std::swap(bufWidth, bufHeight);
- }
- }
-
- return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
-}
-
-FloatRect BufferStateLayer::computeSourceBounds(const FloatRect& parentBounds) const {
- if (mBufferInfo.mBuffer == nullptr) {
- return parentBounds;
- }
-
- return getBufferSize(getDrawingState()).toFloatRect();
-}
-
-// -----------------------------------------------------------------------
-bool BufferStateLayer::fenceHasSignaled() const {
- if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
- return true;
- }
-
- const bool fenceSignaled =
- getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
- if (!fenceSignaled) {
- mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
- TimeStats::LatchSkipReason::LateAcquire);
- }
-
- return fenceSignaled;
-}
-
-bool BufferStateLayer::onPreComposition(nsecs_t refreshStartTime) {
- for (const auto& handle : mDrawingState.callbackHandles) {
- handle->refreshStartTime = refreshStartTime;
- }
- return hasReadyFrame();
-}
-
-void BufferStateLayer::setAutoRefresh(bool autoRefresh) {
- mDrawingState.autoRefresh = autoRefresh;
-}
-
-bool BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
- // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
- editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
-
- if (mSidebandStreamChanged.exchange(false)) {
- const State& s(getDrawingState());
- // mSidebandStreamChanged was true
- mSidebandStream = s.sidebandStream;
- editCompositionState()->sidebandStream = mSidebandStream;
- if (mSidebandStream != nullptr) {
- setTransactionFlags(eTransactionNeeded);
- mFlinger->setTransactionFlags(eTraversalNeeded);
- }
- recomputeVisibleRegions = true;
-
- return true;
- }
- return false;
-}
-
-bool BufferStateLayer::hasFrameUpdate() const {
- const State& c(getDrawingState());
- return (mDrawingStateModified || mDrawingState.modified) && (c.buffer != nullptr || c.bgColorLayer != nullptr);
-}
-
-void BufferStateLayer::updateTexImage(nsecs_t latchTime) {
- const State& s(getDrawingState());
-
- if (!s.buffer) {
- if (s.bgColorLayer) {
- for (auto& handle : mDrawingState.callbackHandles) {
- handle->latchTime = latchTime;
- }
- }
- return;
- }
-
- for (auto& handle : mDrawingState.callbackHandles) {
- if (handle->frameNumber == mDrawingState.frameNumber) {
- handle->latchTime = latchTime;
- }
- }
-
- const int32_t layerId = getSequence();
- const uint64_t bufferId = mDrawingState.buffer->getId();
- const uint64_t frameNumber = mDrawingState.frameNumber;
- const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
- mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
- mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
-
- mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
- FrameTracer::FrameEvent::ACQUIRE_FENCE);
- mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
- FrameTracer::FrameEvent::LATCH);
-
- auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
- if (bufferSurfaceFrame != nullptr &&
- bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
- // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
- // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
- // are processing the next state.
- addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
- mDrawingState.acquireFenceTime->getSignalTime(),
- latchTime);
- mDrawingState.bufferSurfaceFrameTX.reset();
- }
-
- std::deque<sp<CallbackHandle>> remainingHandles;
- mFlinger->getTransactionCallbackInvoker()
- .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
- mDrawingState.callbackHandles = remainingHandles;
-
- mDrawingStateModified = false;
-}
-
-void BufferStateLayer::gatherBufferInfo() {
- if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
- decrementPendingBufferCount();
- }
-
- mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
- mBufferInfo.mBuffer = mDrawingState.buffer;
- mBufferInfo.mFence = mDrawingState.acquireFence;
- mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
- mBufferInfo.mPixelFormat =
- !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
- mBufferInfo.mFrameLatencyNeeded = true;
- mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
- mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
- mBufferInfo.mFence = mDrawingState.acquireFence;
- mBufferInfo.mTransform = mDrawingState.bufferTransform;
- auto lastDataspace = mBufferInfo.mDataspace;
- mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
- if (lastDataspace != mBufferInfo.mDataspace) {
- mFlinger->mSomeDataspaceChanged = true;
- }
- mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
- mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
- mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
- mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
- mBufferInfo.mApi = mDrawingState.api;
- mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
- mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
-}
-
-Rect BufferStateLayer::computeBufferCrop(const State& s) {
- if (s.buffer && !s.bufferCrop.isEmpty()) {
- Rect bufferCrop;
- s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
- return bufferCrop;
- } else if (s.buffer) {
- return s.buffer->getBounds();
- } else {
- return s.bufferCrop;
- }
-}
-
-sp<Layer> BufferStateLayer::createClone() {
- LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
- args.textureName = mTextureName;
- sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
- layer->mHwcSlotGenerator = mHwcSlotGenerator;
- layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
- return layer;
-}
-
-bool BufferStateLayer::bufferNeedsFiltering() const {
- const State& s(getDrawingState());
- if (!s.buffer) {
- return false;
- }
-
- int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
- int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
-
- // Undo any transformations on the buffer and return the result.
- if (s.bufferTransform & ui::Transform::ROT_90) {
- std::swap(bufferWidth, bufferHeight);
- }
-
- if (s.transformToDisplayInverse) {
- uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
- if (invTransform & ui::Transform::ROT_90) {
- std::swap(bufferWidth, bufferHeight);
- }
- }
-
- const Rect layerSize{getBounds()};
- int32_t layerWidth = layerSize.getWidth();
- int32_t layerHeight = layerSize.getHeight();
-
- // Align the layer orientation with the buffer before comparism
- if (mTransformHint & ui::Transform::ROT_90) {
- std::swap(layerWidth, layerHeight);
- }
-
- return layerWidth != bufferWidth || layerHeight != bufferHeight;
-}
-
-void BufferStateLayer::decrementPendingBufferCount() {
- int32_t pendingBuffers = --mPendingBufferTransactions;
- tracePendingBufferCount(pendingBuffers);
-}
-
-void BufferStateLayer::tracePendingBufferCount(int32_t pendingBuffers) {
- ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
-}
-
-
-/*
- * We don't want to send the layer's transform to input, but rather the
- * parent's transform. This is because BufferStateLayer's transform is
- * information about how the buffer is placed on screen. The parent's
- * transform makes more sense to send since it's information about how the
- * layer is placed on screen. This transform is used by input to determine
- * how to go from screen space back to window space.
- */
-ui::Transform BufferStateLayer::getInputTransform() const {
- sp<Layer> parent = mDrawingParent.promote();
- if (parent == nullptr) {
- return ui::Transform();
- }
-
- return parent->getTransform();
-}
-
-/**
- * Similar to getInputTransform, we need to update the bounds to include the transform.
- * This is because bounds for BSL doesn't include buffer transform, where the input assumes
- * that's already included.
- */
-Rect BufferStateLayer::getInputBounds() const {
- Rect bufferBounds = getCroppedBufferSize(getDrawingState());
- if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
- return bufferBounds;
- }
- return mDrawingState.transform.transform(bufferBounds);
-}
-
-bool BufferStateLayer::simpleBufferUpdate(const layer_state_t& s) const {
- const uint64_t requiredFlags = layer_state_t::eBufferChanged;
-
- const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
- layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
- layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
- layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
- layer_state_t::eReparent;
-
- const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
- layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
- layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
- layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
- layer_state_t::eInputInfoChanged;
-
- if ((s.what & requiredFlags) != requiredFlags) {
- ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
- (s.what | requiredFlags) & ~s.what);
- return false;
- }
-
- if (s.what & deniedFlags) {
- ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
- return false;
- }
-
- if (s.what & allowedFlags) {
- ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
- }
-
- if (s.what & layer_state_t::ePositionChanged) {
- if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
- ALOGV("%s: false [ePositionChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eAlphaChanged) {
- if (mDrawingState.color.a != s.alpha) {
- ALOGV("%s: false [eAlphaChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eColorTransformChanged) {
- if (mDrawingState.colorTransform != s.colorTransform) {
- ALOGV("%s: false [eColorTransformChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eBackgroundColorChanged) {
- if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
- ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eMatrixChanged) {
- if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
- mRequestedTransform.dtdy() != s.matrix.dtdy ||
- mRequestedTransform.dtdx() != s.matrix.dtdx ||
- mRequestedTransform.dsdy() != s.matrix.dsdy) {
- ALOGV("%s: false [eMatrixChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eCornerRadiusChanged) {
- if (mDrawingState.cornerRadius != s.cornerRadius) {
- ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
- if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
- ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eTransformChanged) {
- if (mDrawingState.bufferTransform != s.transform) {
- ALOGV("%s: false [eTransformChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
- if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
- ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eCropChanged) {
- if (mDrawingState.crop != s.crop) {
- ALOGV("%s: false [eCropChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eDataspaceChanged) {
- if (mDrawingState.dataspace != s.dataspace) {
- ALOGV("%s: false [eDataspaceChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eHdrMetadataChanged) {
- if (mDrawingState.hdrMetadata != s.hdrMetadata) {
- ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eSidebandStreamChanged) {
- if (mDrawingState.sidebandStream != s.sidebandStream) {
- ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
- if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
- ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eShadowRadiusChanged) {
- if (mDrawingState.shadowRadius != s.shadowRadius) {
- ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eFixedTransformHintChanged) {
- if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
- ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eTrustedOverlayChanged) {
- if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
- ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eStretchChanged) {
- StretchEffect temp = s.stretchEffect;
- temp.sanitize();
- if (mDrawingState.stretchEffect != temp) {
- ALOGV("%s: false [eStretchChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eBufferCropChanged) {
- if (mDrawingState.bufferCrop != s.bufferCrop) {
- ALOGV("%s: false [eBufferCropChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eDestinationFrameChanged) {
- if (mDrawingState.destinationFrame != s.destinationFrame) {
- ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
- return false;
- }
- }
-
- if (s.what & layer_state_t::eDimmingEnabledChanged) {
- if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
- ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
- return false;
- }
- }
-
- ALOGV("%s: true", __func__);
- return true;
-}
-
-void BufferStateLayer::useSurfaceDamage() {
- if (mFlinger->mForceFullDamage) {
- surfaceDamageRegion = Region::INVALID_REGION;
- } else {
- surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
- }
-}
-
-void BufferStateLayer::useEmptyDamage() {
- surfaceDamageRegion.clear();
-}
-
-bool BufferStateLayer::isOpaque(const Layer::State& s) const {
- // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
- // layer's opaque flag.
- if ((mSidebandStream == nullptr) && (mBufferInfo.mBuffer == nullptr)) {
- return false;
- }
-
- // if the layer has the opaque flag, then we're always opaque,
- // otherwise we use the current buffer's format.
- return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
-}
-
-bool BufferStateLayer::canReceiveInput() const {
- return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
-}
-
-bool BufferStateLayer::isVisible() const {
- return !isHiddenByPolicy() && getAlpha() > 0.0f &&
- (mBufferInfo.mBuffer != nullptr || mSidebandStream != nullptr);
-}
-
-std::optional<compositionengine::LayerFE::LayerSettings> BufferStateLayer::prepareClientComposition(
- compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
- std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
- prepareClientCompositionInternal(targetSettings);
- // Nothing to render.
- if (!layerSettings) {
- return {};
- }
-
- // HWC requests to clear this layer.
- if (targetSettings.clearContent) {
- prepareClearClientComposition(*layerSettings, false /* blackout */);
- return *layerSettings;
- }
-
- // set the shadow for the layer if needed
- prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
-
- return *layerSettings;
-}
-
-std::optional<compositionengine::LayerFE::LayerSettings>
-BufferStateLayer::prepareClientCompositionInternal(
- compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
- ATRACE_CALL();
-
- std::optional<compositionengine::LayerFE::LayerSettings> result =
- Layer::prepareClientComposition(targetSettings);
- if (!result) {
- return result;
- }
-
- if (CC_UNLIKELY(mBufferInfo.mBuffer == 0) && mSidebandStream != nullptr) {
- // For surfaceview of tv sideband, there is no activeBuffer
- // in bufferqueue, we need return LayerSettings.
- return result;
- }
- const bool blackOutLayer = (isProtected() && !targetSettings.supportsProtectedContent) ||
- ((isSecure() || isProtected()) && !targetSettings.isSecure);
- const bool bufferCanBeUsedAsHwTexture =
- mBufferInfo.mBuffer->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
- compositionengine::LayerFE::LayerSettings& layer = *result;
- if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
- ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
- mName.c_str());
- prepareClearClientComposition(layer, true /* blackout */);
- return layer;
- }
-
- const State& s(getDrawingState());
- layer.source.buffer.buffer = mBufferInfo.mBuffer;
- layer.source.buffer.isOpaque = isOpaque(s);
- layer.source.buffer.fence = mBufferInfo.mFence;
- layer.source.buffer.textureName = mTextureName;
- layer.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
- layer.source.buffer.isY410BT2020 = isHdrY410();
- bool hasSmpte2086 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::SMPTE2086;
- bool hasCta861_3 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::CTA861_3;
- float maxLuminance = 0.f;
- if (hasSmpte2086 && hasCta861_3) {
- maxLuminance = std::min(mBufferInfo.mHdrMetadata.smpte2086.maxLuminance,
- mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel);
- } else if (hasSmpte2086) {
- maxLuminance = mBufferInfo.mHdrMetadata.smpte2086.maxLuminance;
- } else if (hasCta861_3) {
- maxLuminance = mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel;
- } else {
- switch (layer.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
- case HAL_DATASPACE_TRANSFER_ST2084:
- case HAL_DATASPACE_TRANSFER_HLG:
- // Behavior-match previous releases for HDR content
- maxLuminance = defaultMaxLuminance;
- break;
- }
- }
- layer.source.buffer.maxLuminanceNits = maxLuminance;
- layer.frameNumber = mCurrentFrameNumber;
- layer.bufferId = mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getId() : 0;
-
- const bool useFiltering =
- targetSettings.needsFiltering || mNeedsFiltering || bufferNeedsFiltering();
-
- // Query the texture matrix given our current filtering mode.
- float textureMatrix[16];
- getDrawingTransformMatrix(useFiltering, textureMatrix);
-
- if (getTransformToDisplayInverse()) {
- /*
- * the code below applies the primary display's inverse transform to
- * the texture transform
- */
- uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
- mat4 tr = inverseOrientation(transform);
-
- /**
- * TODO(b/36727915): This is basically a hack.
- *
- * Ensure that regardless of the parent transformation,
- * this buffer is always transformed from native display
- * orientation to display orientation. For example, in the case
- * of a camera where the buffer remains in native orientation,
- * we want the pixels to always be upright.
- */
- sp<Layer> p = mDrawingParent.promote();
- if (p != nullptr) {
- const auto parentTransform = p->getTransform();
- tr = tr * inverseOrientation(parentTransform.getOrientation());
- }
-
- // and finally apply it to the original texture matrix
- const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
- memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
- }
-
- const Rect win{getBounds()};
- float bufferWidth = getBufferSize(s).getWidth();
- float bufferHeight = getBufferSize(s).getHeight();
-
- // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
- // been set and there is no parent layer bounds. In that case, the scale is meaningless so
- // ignore them.
- if (!getBufferSize(s).isValid()) {
- bufferWidth = float(win.right) - float(win.left);
- bufferHeight = float(win.bottom) - float(win.top);
- }
-
- const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
- const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
- const float translateY = float(win.top) / bufferHeight;
- const float translateX = float(win.left) / bufferWidth;
-
- // Flip y-coordinates because GLConsumer expects OpenGL convention.
- mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
- mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
- mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
- mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
-
- layer.source.buffer.useTextureFiltering = useFiltering;
- layer.source.buffer.textureTransform = mat4(static_cast<const float*>(textureMatrix)) * tr;
-
- return layer;
-}
-
-bool BufferStateLayer::isHdrY410() const {
- // pixel format is HDR Y410 masquerading as RGBA_1010102
- return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
- mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
- mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
-}
-
-sp<compositionengine::LayerFE> BufferStateLayer::getCompositionEngineLayerFE() const {
- return asLayerFE();
-}
-
-compositionengine::LayerFECompositionState* BufferStateLayer::editCompositionState() {
- return mCompositionState.get();
-}
-
-const compositionengine::LayerFECompositionState* BufferStateLayer::getCompositionState() const {
- return mCompositionState.get();
-}
-
-void BufferStateLayer::preparePerFrameCompositionState() {
- Layer::preparePerFrameCompositionState();
-
- // Sideband layers
- auto* compositionState = editCompositionState();
- if (compositionState->sidebandStream.get() && !compositionState->sidebandStreamHasFrame) {
- compositionState->compositionType =
- aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
- return;
- } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
- compositionState->compositionType =
- aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
- } else {
- // Normal buffer layers
- compositionState->hdrMetadata = mBufferInfo.mHdrMetadata;
- compositionState->compositionType = mPotentialCursor
- ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
- : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
- }
-
- compositionState->buffer = getBuffer();
- compositionState->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
- ? 0
- : mBufferInfo.mBufferSlot;
- compositionState->acquireFence = mBufferInfo.mFence;
- compositionState->frameNumber = mBufferInfo.mFrameNumber;
- compositionState->sidebandStreamHasFrame = false;
-}
-
-void BufferStateLayer::onPostComposition(const DisplayDevice* display,
- const std::shared_ptr<FenceTime>& glDoneFence,
- const std::shared_ptr<FenceTime>& presentFence,
- const CompositorTiming& compositorTiming) {
- // mFrameLatencyNeeded is true when a new frame was latched for the
- // composition.
- if (!mBufferInfo.mFrameLatencyNeeded) return;
-
- for (const auto& handle : mDrawingState.callbackHandles) {
- handle->gpuCompositionDoneFence = glDoneFence;
- handle->compositorTiming = compositorTiming;
- }
-
- // Update mFrameTracker.
- nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
- mFrameTracker.setDesiredPresentTime(desiredPresentTime);
-
- const int32_t layerId = getSequence();
- mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
-
- const auto outputLayer = findOutputLayerForDisplay(display);
- if (outputLayer && outputLayer->requiresClientComposition()) {
- nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
- mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
- clientCompositionTimestamp,
- FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
- // Update the SurfaceFrames in the drawing state
- if (mDrawingState.bufferSurfaceFrameTX) {
- mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
- }
- for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
- surfaceFrame->setGpuComposition();
- }
- }
-
- std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
- if (frameReadyFence->isValid()) {
- mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
- } else {
- // There was no fence for this frame, so assume that it was ready
- // to be presented at the desired present time.
- mFrameTracker.setFrameReadyTime(desiredPresentTime);
- }
-
- if (display) {
- const Fps refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
- const std::optional<Fps> renderRate =
- mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
-
- const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
- const auto gameMode = getGameMode();
-
- if (presentFence->isValid()) {
- mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
- refreshRate, renderRate, vote, gameMode);
- mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
- presentFence,
- FrameTracer::FrameEvent::PRESENT_FENCE);
- mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
- } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
- displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
- // The HWC doesn't support present fences, so use the refresh
- // timestamp instead.
- const nsecs_t actualPresentTime = display->getRefreshTimestamp();
- mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
- refreshRate, renderRate, vote, gameMode);
- mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
- mCurrentFrameNumber, actualPresentTime,
- FrameTracer::FrameEvent::PRESENT_FENCE);
- mFrameTracker.setActualPresentTime(actualPresentTime);
- }
- }
-
- mFrameTracker.advanceFrame();
- mBufferInfo.mFrameLatencyNeeded = false;
-}
-
-bool BufferStateLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
- ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
- getDrawingState().frameNumber);
-
- bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
-
- if (refreshRequired) {
- return refreshRequired;
- }
-
- // If the head buffer's acquire fence hasn't signaled yet, return and
- // try again later
- if (!fenceHasSignaled()) {
- ATRACE_NAME("!fenceHasSignaled()");
- mFlinger->onLayerUpdate();
- return false;
- }
-
- updateTexImage(latchTime);
- if (mDrawingState.buffer == nullptr) {
- return false;
- }
-
- // Capture the old state of the layer for comparisons later
- BufferInfo oldBufferInfo = mBufferInfo;
- const bool oldOpacity = isOpaque(mDrawingState);
- mPreviousFrameNumber = mCurrentFrameNumber;
- mCurrentFrameNumber = mDrawingState.frameNumber;
- gatherBufferInfo();
-
- if (oldBufferInfo.mBuffer == nullptr) {
- // the first time we receive a buffer, we need to trigger a
- // geometry invalidation.
- recomputeVisibleRegions = true;
- }
-
- if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
- (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
- (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
- (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
- recomputeVisibleRegions = true;
- }
-
- if (oldBufferInfo.mBuffer != nullptr) {
- uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
- uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
- if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
- bufHeight != oldBufferInfo.mBuffer->getHeight()) {
- recomputeVisibleRegions = true;
- }
- }
-
- if (oldOpacity != isOpaque(mDrawingState)) {
- recomputeVisibleRegions = true;
- }
-
- return true;
-}
-
-bool BufferStateLayer::hasReadyFrame() const {
- return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
-}
-
-bool BufferStateLayer::isProtected() const {
- return (mBufferInfo.mBuffer != nullptr) &&
- (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
-}
-
-// As documented in libhardware header, formats in the range
-// 0x100 - 0x1FF are specific to the HAL implementation, and
-// are known to have no alpha channel
-// TODO: move definition for device-specific range into
-// hardware.h, instead of using hard-coded values here.
-#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
-
-bool BufferStateLayer::getOpacityForFormat(PixelFormat format) {
- if (HARDWARE_IS_DEVICE_FORMAT(format)) {
- return true;
- }
- switch (format) {
- case PIXEL_FORMAT_RGBA_8888:
- case PIXEL_FORMAT_BGRA_8888:
- case PIXEL_FORMAT_RGBA_FP16:
- case PIXEL_FORMAT_RGBA_1010102:
- case PIXEL_FORMAT_R_8:
- return false;
- }
- // in all other case, we have no blending (also for unknown formats)
- return true;
-}
-
-bool BufferStateLayer::needsFiltering(const DisplayDevice* display) const {
- const auto outputLayer = findOutputLayerForDisplay(display);
- if (outputLayer == nullptr) {
- return false;
- }
-
- // We need filtering if the sourceCrop rectangle size does not match the
- // displayframe rectangle size (not a 1:1 render)
- const auto& compositionState = outputLayer->getState();
- const auto displayFrame = compositionState.displayFrame;
- const auto sourceCrop = compositionState.sourceCrop;
- return sourceCrop.getHeight() != displayFrame.getHeight() ||
- sourceCrop.getWidth() != displayFrame.getWidth();
-}
-
-bool BufferStateLayer::needsFilteringForScreenshots(
- const DisplayDevice* display, const ui::Transform& inverseParentTransform) const {
- const auto outputLayer = findOutputLayerForDisplay(display);
- if (outputLayer == nullptr) {
- return false;
- }
-
- // We need filtering if the sourceCrop rectangle size does not match the
- // viewport rectangle size (not a 1:1 render)
- const auto& compositionState = outputLayer->getState();
- const ui::Transform& displayTransform = display->getTransform();
- const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
- // Undo the transformation of the displayFrame so that we're back into
- // layer-stack space.
- const Rect frame = inverseTransform.transform(compositionState.displayFrame);
- const FloatRect sourceCrop = compositionState.sourceCrop;
-
- int32_t frameHeight = frame.getHeight();
- int32_t frameWidth = frame.getWidth();
- // If the display transform had a rotational component then undo the
- // rotation so that the orientation matches the source crop.
- if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
- std::swap(frameHeight, frameWidth);
- }
- return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
-}
-
-void BufferStateLayer::latchAndReleaseBuffer() {
- if (hasReadyFrame()) {
- bool ignored = false;
- latchBuffer(ignored, systemTime());
- }
- releasePendingBuffer(systemTime());
-}
-
-PixelFormat BufferStateLayer::getPixelFormat() const {
- return mBufferInfo.mPixelFormat;
-}
-
-bool BufferStateLayer::getTransformToDisplayInverse() const {
- return mBufferInfo.mTransformToDisplayInverse;
-}
-
-Rect BufferStateLayer::getBufferCrop() const {
- // this is the crop rectangle that applies to the buffer
- // itself (as opposed to the window)
- if (!mBufferInfo.mCrop.isEmpty()) {
- // if the buffer crop is defined, we use that
- return mBufferInfo.mCrop;
- } else if (mBufferInfo.mBuffer != nullptr) {
- // otherwise we use the whole buffer
- return mBufferInfo.mBuffer->getBounds();
- } else {
- // if we don't have a buffer yet, we use an empty/invalid crop
- return Rect();
- }
-}
-
-uint32_t BufferStateLayer::getBufferTransform() const {
- return mBufferInfo.mTransform;
-}
-
-ui::Dataspace BufferStateLayer::getDataSpace() const {
- return mBufferInfo.mDataspace;
-}
-
-ui::Dataspace BufferStateLayer::translateDataspace(ui::Dataspace dataspace) {
- ui::Dataspace updatedDataspace = dataspace;
- // translate legacy dataspaces to modern dataspaces
- switch (dataspace) {
- case ui::Dataspace::SRGB:
- updatedDataspace = ui::Dataspace::V0_SRGB;
- break;
- case ui::Dataspace::SRGB_LINEAR:
- updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
- break;
- case ui::Dataspace::JFIF:
- updatedDataspace = ui::Dataspace::V0_JFIF;
- break;
- case ui::Dataspace::BT601_625:
- updatedDataspace = ui::Dataspace::V0_BT601_625;
- break;
- case ui::Dataspace::BT601_525:
- updatedDataspace = ui::Dataspace::V0_BT601_525;
- break;
- case ui::Dataspace::BT709:
- updatedDataspace = ui::Dataspace::V0_BT709;
- break;
- default:
- break;
- }
-
- return updatedDataspace;
-}
-
-sp<GraphicBuffer> BufferStateLayer::getBuffer() const {
- return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
-}
-
-void BufferStateLayer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
- sp<GraphicBuffer> buffer = getBuffer();
- if (!buffer) {
- ALOGE("Buffer should not be null!");
- return;
- }
- GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
- buffer->getPixelFormat(), mBufferInfo.mCrop,
- mBufferInfo.mTransform, filteringEnabled);
-}
-
-void BufferStateLayer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
- Layer::setInitialValuesForClone(clonedFrom);
-
- sp<BufferStateLayer> bufferClonedFrom =
- sp<BufferStateLayer>::fromExisting(static_cast<BufferStateLayer*>(clonedFrom.get()));
- mPremultipliedAlpha = bufferClonedFrom->mPremultipliedAlpha;
- mPotentialCursor = bufferClonedFrom->mPotentialCursor;
- mProtectedByApp = bufferClonedFrom->mProtectedByApp;
-
- updateCloneBufferInfo();
-}
-
-void BufferStateLayer::updateCloneBufferInfo() {
- if (!isClone() || !isClonedFromAlive()) {
- return;
- }
-
- sp<BufferStateLayer> clonedFrom = sp<BufferStateLayer>::fromExisting(
- static_cast<BufferStateLayer*>(getClonedFrom().get()));
- mBufferInfo = clonedFrom->mBufferInfo;
- mSidebandStream = clonedFrom->mSidebandStream;
- surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
- mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
- mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
-
- // After buffer info is updated, the drawingState from the real layer needs to be copied into
- // the cloned. This is because some properties of drawingState can change when latchBuffer is
- // called. However, copying the drawingState would also overwrite the cloned layer's relatives
- // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
- // the cloned drawingState again.
- wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
- SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
- wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
- WindowInfo tmpInputInfo = mDrawingState.inputInfo;
-
- cloneDrawingState(clonedFrom.get());
-
- mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
- mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
- mDrawingState.zOrderRelatives = tmpZOrderRelatives;
- mDrawingState.inputInfo = tmpInputInfo;
-}
-
-void BufferStateLayer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
- mTransformHint = getFixedTransformHint();
- if (mTransformHint == ui::Transform::ROT_INVALID) {
- mTransformHint = displayTransformHint;
- }
-}
-
-const std::shared_ptr<renderengine::ExternalTexture>& BufferStateLayer::getExternalTexture() const {
- return mBufferInfo.mBuffer;
-}
-
-} // namespace android
diff --git a/services/surfaceflinger/BufferStateLayer.h b/services/surfaceflinger/BufferStateLayer.h
index a0a52bf..e53e1c1 100644
--- a/services/surfaceflinger/BufferStateLayer.h
+++ b/services/surfaceflinger/BufferStateLayer.h
@@ -16,288 +16,13 @@
#pragma once
-#include <sys/types.h>
-#include <cstdint>
-#include <list>
-#include <stack>
-
-#include <android/gui/ISurfaceComposerClient.h>
-#include <gui/LayerState.h>
-#include <renderengine/Image.h>
-#include <renderengine/Mesh.h>
-#include <renderengine/RenderEngine.h>
-#include <renderengine/Texture.h>
-#include <system/window.h> // For NATIVE_WINDOW_SCALING_MODE_FREEZE
-#include <ui/FrameStats.h>
-#include <ui/GraphicBuffer.h>
-#include <ui/PixelFormat.h>
-#include <ui/Region.h>
-#include <utils/RefBase.h>
-#include <utils/String8.h>
-#include <utils/Timers.h>
-
-#include "Client.h"
-#include "DisplayHardware/HWComposer.h"
-#include "FrameTimeline.h"
-#include "FrameTracker.h"
-#include "HwcSlotGenerator.h"
#include "Layer.h"
-#include "LayerVector.h"
-#include "SurfaceFlinger.h"
namespace android {
-class SlotGenerationTest;
-
class BufferStateLayer : public Layer {
public:
- explicit BufferStateLayer(const LayerCreationArgs&);
-
- ~BufferStateLayer() override;
-
- // Implements Layer.
- sp<compositionengine::LayerFE> getCompositionEngineLayerFE() const override;
- compositionengine::LayerFECompositionState* editCompositionState() override;
-
- // If we have received a new buffer this frame, we will pass its surface
- // damage down to hardware composer. Otherwise, we must send a region with
- // one empty rect.
- void useSurfaceDamage() override;
- void useEmptyDamage() override;
-
- bool isOpaque(const Layer::State& s) const override;
- bool canReceiveInput() const override;
-
- // isVisible - true if this layer is visible, false otherwise
- bool isVisible() const override;
-
- // isProtected - true if the layer may contain protected content in the
- // GRALLOC_USAGE_PROTECTED sense.
- bool isProtected() const override;
-
- bool usesSourceCrop() const override { return true; }
-
- bool isHdrY410() const override;
-
- void onPostComposition(const DisplayDevice*, const std::shared_ptr<FenceTime>& glDoneFence,
- const std::shared_ptr<FenceTime>& presentFence,
- const CompositorTiming&) override;
-
- // latchBuffer - called each time the screen is redrawn and returns whether
- // the visible regions need to be recomputed (this is a fairly heavy
- // operation, so this should be set only if needed). Typically this is used
- // to figure out if the content or size of a surface has changed.
- bool latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) override;
- bool hasReadyFrame() const override;
-
- // Calls latchBuffer if the buffer has a frame queued and then releases the buffer.
- // This is used if the buffer is just latched and releases to free up the buffer
- // and will not be shown on screen.
- // Should only be called on the main thread.
- void latchAndReleaseBuffer() override;
-
- bool getTransformToDisplayInverse() const override;
-
- Rect getBufferCrop() const override;
-
- uint32_t getBufferTransform() const override;
-
- ui::Dataspace getDataSpace() const override;
-
- sp<GraphicBuffer> getBuffer() const override;
- const std::shared_ptr<renderengine::ExternalTexture>& getExternalTexture() const override;
-
- ui::Transform::RotationFlags getTransformHint() const override { return mTransformHint; }
-
- // Implements Layer.
- const char* getType() const override { return "BufferStateLayer"; }
-
- void onLayerDisplayed(ftl::SharedFuture<FenceResult>) override;
-
- void releasePendingBuffer(nsecs_t dequeueReadyTime) override;
-
- Rect getCrop(const Layer::State& s) const;
-
- bool setTransform(uint32_t transform) override;
- bool setTransformToDisplayInverse(bool transformToDisplayInverse) override;
- bool setCrop(const Rect& crop) override;
- bool setBuffer(std::shared_ptr<renderengine::ExternalTexture>& /* buffer */,
- const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
- bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
- const FrameTimelineInfo& info) override;
- bool setDataspace(ui::Dataspace dataspace) override;
- bool setHdrMetadata(const HdrMetadata& hdrMetadata) override;
- bool setSurfaceDamageRegion(const Region& surfaceDamage) override;
- bool setApi(int32_t api) override;
- bool setSidebandStream(const sp<NativeHandle>& sidebandStream) override;
- bool setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) override;
- bool setPosition(float /*x*/, float /*y*/) override;
- bool setMatrix(const layer_state_t::matrix22_t& /*matrix*/);
-
- // BufferStateLayers can return Rect::INVALID_RECT if the layer does not have a display frame
- // and its parent layer is not bounded
- Rect getBufferSize(const State& s) const override;
- FloatRect computeSourceBounds(const FloatRect& parentBounds) const override;
- void setAutoRefresh(bool autoRefresh) override;
-
- bool setBufferCrop(const Rect& bufferCrop) override;
- bool setDestinationFrame(const Rect& destinationFrame) override;
- bool updateGeometry() override;
-
- bool fenceHasSignaled() const;
- bool onPreComposition(nsecs_t) override;
-
- // See mPendingBufferTransactions
- void decrementPendingBufferCount();
- std::atomic<int32_t>* getPendingBufferCounter() override { return &mPendingBufferTransactions; }
- std::string getPendingBufferCounterName() override { return mBlastTransactionName; }
-
- std::optional<compositionengine::LayerFE::LayerSettings> prepareClientComposition(
- compositionengine::LayerFE::ClientCompositionTargetSettings&) const override;
-
-protected:
- void gatherBufferInfo();
- void onSurfaceFrameCreated(const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame);
- ui::Transform getInputTransform() const override;
- Rect getInputBounds() const override;
-
- struct BufferInfo {
- nsecs_t mDesiredPresentTime;
- std::shared_ptr<FenceTime> mFenceTime;
- sp<Fence> mFence;
- uint32_t mTransform{0};
- ui::Dataspace mDataspace{ui::Dataspace::UNKNOWN};
- Rect mCrop;
- uint32_t mScaleMode{NATIVE_WINDOW_SCALING_MODE_FREEZE};
- Region mSurfaceDamage;
- HdrMetadata mHdrMetadata;
- int mApi;
- PixelFormat mPixelFormat{PIXEL_FORMAT_NONE};
- bool mTransformToDisplayInverse{false};
-
- std::shared_ptr<renderengine::ExternalTexture> mBuffer;
- uint64_t mFrameNumber;
- int mBufferSlot{BufferQueue::INVALID_BUFFER_SLOT};
-
- bool mFrameLatencyNeeded{false};
- };
-
- BufferInfo mBufferInfo;
-
- /*
- * compositionengine::LayerFE overrides
- */
- const compositionengine::LayerFECompositionState* getCompositionState() const override;
- void preparePerFrameCompositionState() override;
-
- static bool getOpacityForFormat(PixelFormat format);
-
- // from graphics API
- const uint32_t mTextureName;
- ui::Dataspace translateDataspace(ui::Dataspace dataspace);
- void setInitialValuesForClone(const sp<Layer>& clonedFrom);
- void updateCloneBufferInfo() override;
- uint64_t mPreviousFrameNumber = 0;
-
- void setTransformHint(ui::Transform::RotationFlags displayTransformHint) override;
-
- // Transform hint provided to the producer. This must be accessed holding
- // the mStateLock.
- ui::Transform::RotationFlags mTransformHint = ui::Transform::ROT_0;
-
- bool getAutoRefresh() const { return mDrawingState.autoRefresh; }
- bool getSidebandStreamChanged() const { return mSidebandStreamChanged; }
-
- std::atomic<bool> mSidebandStreamChanged{false};
-
-private:
- friend class SlotGenerationTest;
- friend class TransactionFrameTracerTest;
- friend class TransactionSurfaceFrameTest;
-
- // We generate InputWindowHandles for all non-cursor buffered layers regardless of whether they
- // have an InputChannel. This is to enable the InputDispatcher to do PID based occlusion
- // detection.
- bool needsInputInfo() const override { return !mPotentialCursor; }
-
- // Returns true if this layer requires filtering
- bool needsFiltering(const DisplayDevice*) const override;
- bool needsFilteringForScreenshots(const DisplayDevice*,
- const ui::Transform& inverseParentTransform) const override;
-
- PixelFormat getPixelFormat() const;
-
- // Computes the transform matrix using the setFilteringEnabled to determine whether the
- // transform matrix should be computed for use with bilinear filtering.
- void getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const;
-
- std::unique_ptr<compositionengine::LayerFECompositionState> mCompositionState;
-
- inline void tracePendingBufferCount(int32_t pendingBuffers);
-
- bool updateFrameEventHistory(const sp<Fence>& acquireFence, nsecs_t postedTime,
- nsecs_t requestedPresentTime);
-
- // Latch sideband stream and returns true if the dirty region should be updated.
- bool latchSidebandStream(bool& recomputeVisibleRegions);
-
- bool hasFrameUpdate() const;
-
- void updateTexImage(nsecs_t latchTime);
-
- sp<Layer> createClone() override;
-
- // Crop that applies to the buffer
- Rect computeBufferCrop(const State& s);
-
- bool willPresentCurrentTransaction() const;
-
- // Returns true if the transformed buffer size does not match the layer size and we need
- // to apply filtering.
- bool bufferNeedsFiltering() const;
-
- bool simpleBufferUpdate(const layer_state_t& s) const override;
-
- void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
- const sp<GraphicBuffer>& buffer, uint64_t framenumber,
- const sp<Fence>& releaseFence,
- uint32_t currentMaxAcquiredBufferCount);
-
- std::optional<compositionengine::LayerFE::LayerSettings> prepareClientCompositionInternal(
- compositionengine::LayerFE::ClientCompositionTargetSettings&) const;
-
- ReleaseCallbackId mPreviousReleaseCallbackId = ReleaseCallbackId::INVALID_ID;
- uint64_t mPreviousReleasedFrameNumber = 0;
-
- uint64_t mPreviousBarrierFrameNumber = 0;
-
- bool mReleasePreviousBuffer = false;
-
- // Stores the last set acquire fence signal time used to populate the callback handle's acquire
- // time.
- std::variant<nsecs_t, sp<Fence>> mCallbackHandleAcquireTimeOrFence = -1;
-
- std::deque<std::shared_ptr<android::frametimeline::SurfaceFrame>> mPendingJankClassifications;
- // An upper bound on the number of SurfaceFrames in the pending classifications deque.
- static constexpr int kPendingClassificationMaxSurfaceFrames = 25;
-
- const std::string mBlastTransactionName{"BufferTX - " + mName};
- // This integer is incremented everytime a buffer arrives at the server for this layer,
- // and decremented when a buffer is dropped or latched. When changed the integer is exported
- // to systrace with ATRACE_INT and mBlastTransactionName. This way when debugging perf it is
- // possible to see when a buffer arrived at the server, and in which frame it latched.
- //
- // You can understand the trace this way:
- // - If the integer increases, a buffer arrived at the server.
- // - If the integer decreases in latchBuffer, that buffer was latched
- // - If the integer decreases in setBuffer or doTransaction, a buffer was dropped
- std::atomic<int32_t> mPendingBufferTransactions{0};
-
- // Contains requested position and matrix updates. This will be applied if the client does
- // not specify a destination frame.
- ui::Transform mRequestedTransform;
-
- sp<HwcSlotGenerator> mHwcSlotGenerator;
+ explicit BufferStateLayer(const LayerCreationArgs& args) : Layer(args){};
};
} // namespace android
diff --git a/services/surfaceflinger/CompositionEngine/Android.bp b/services/surfaceflinger/CompositionEngine/Android.bp
index 11a9e19..b5d2ad0 100644
--- a/services/surfaceflinger/CompositionEngine/Android.bp
+++ b/services/surfaceflinger/CompositionEngine/Android.bp
@@ -9,7 +9,10 @@
cc_defaults {
name: "libcompositionengine_defaults",
- defaults: ["surfaceflinger_defaults"],
+ defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
+ "surfaceflinger_defaults",
+ ],
cflags: [
"-DLOG_TAG=\"CompositionEngine\"",
"-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
@@ -20,7 +23,6 @@
"android.hardware.graphics.composer@2.2",
"android.hardware.graphics.composer@2.3",
"android.hardware.graphics.composer@2.4",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.power@1.0",
"android.hardware.power@1.3",
"android.hardware.power-V2-cpp",
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
index 16cb41b..5e84be1 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
@@ -56,6 +56,9 @@
// similar requests if needed.
virtual void createClientCompositionCache(uint32_t cacheSize) = 0;
+ // Sends the brightness setting to HWC
+ virtual void applyDisplayBrightness(const bool applyImmediately) = 0;
+
protected:
~Display() = default;
};
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h
index 9753a6c..a738da0 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h
@@ -53,31 +53,8 @@
// Called before composition starts. Should return true if this layer has
// pending updates which would require an extra display refresh cycle to
// process.
- virtual bool onPreComposition(nsecs_t refreshStartTime) = 0;
-
- // Used with latchCompositionState()
- enum class StateSubset {
- // Gets the basic geometry (bounds, transparent region, visibility,
- // transforms, alpha) for the layer, for computing visibility and
- // coverage.
- BasicGeometry,
-
- // Gets the full geometry (crops, buffer transforms, metadata) and
- // content (buffer or color) state for the layer.
- GeometryAndContent,
-
- // Gets the per frame content (buffer or color) state for the layer.
- Content,
-
- // Gets the cursor state for the layer.
- Cursor,
- };
-
- // Prepares the output-independent composition state for the layer. The
- // StateSubset argument selects what portion of the state is actually needed
- // by the CompositionEngine code, since computing everything may be
- // expensive.
- virtual void prepareCompositionState(StateSubset) = 0;
+ virtual bool onPreComposition(nsecs_t refreshStartTime,
+ bool updatingOutputGeometryThisFrame) = 0;
struct ClientCompositionTargetSettings {
enum class BlurSetting {
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
index 2203639..874b330 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
@@ -262,9 +262,6 @@
// Presents the output, finalizing all composition details
virtual void present(const CompositionRefreshArgs&) = 0;
- // Latches the front-end layer state for each output layer
- virtual void updateLayerStateFromFE(const CompositionRefreshArgs&) const = 0;
-
// Enables predicting composition strategy to run client composition earlier
virtual void setPredictCompositionStrategy(bool) = 0;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/CompositionEngine.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/CompositionEngine.h
index 386808d..0907926 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/CompositionEngine.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/CompositionEngine.h
@@ -51,8 +51,6 @@
// Debugging
void dump(std::string&) const override;
- void updateLayerStateFromFE(CompositionRefreshArgs& args);
-
// Testing
void setNeedsAnotherUpdateForTest(bool);
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
index fa7bc5d..33a10a3 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
@@ -72,6 +72,7 @@
const compositionengine::DisplayColorProfileCreationArgs&) override;
void createRenderSurface(const compositionengine::RenderSurfaceCreationArgs&) override;
void createClientCompositionCache(uint32_t cacheSize) override;
+ void applyDisplayBrightness(const bool applyImmediately) override;
// Internal helpers used by chooseCompositionStrategy()
using ChangedTypes = android::HWComposer::DeviceRequestedChanges::ChangedTypes;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
index fc8dd8b..23d5570 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
@@ -89,7 +89,6 @@
compositionengine::Output::CoverageState&) override;
void setReleasedLayers(const compositionengine::CompositionRefreshArgs&) override;
- void updateLayerStateFromFE(const CompositionRefreshArgs&) const override;
void updateCompositionState(const compositionengine::CompositionRefreshArgs&) override;
void planComposition() override;
void writeCompositionState(const compositionengine::CompositionRefreshArgs&) override;
@@ -152,6 +151,8 @@
virtual const compositionengine::CompositionEngine& getCompositionEngine() const = 0;
virtual void dumpState(std::string& out) const = 0;
+ bool mustRecompose() const;
+
private:
void dirtyEntireOutput();
void updateCompositionStateForBorder(const compositionengine::CompositionRefreshArgs&);
@@ -171,6 +172,9 @@
std::unique_ptr<ClientCompositionRequestCache> mClientCompositionRequestCache;
std::unique_ptr<planner::Planner> mPlanner;
std::unique_ptr<HwcAsyncWorker> mHwComposerAsyncWorker;
+
+ // Whether the content must be recomposed this frame.
+ bool mMustRecompose = false;
};
// This template factory function standardizes the implementation details of the
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
index 72e6f3b..7e99ec2 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
@@ -41,6 +41,7 @@
MOCK_METHOD1(createDisplayColorProfile, void(const DisplayColorProfileCreationArgs&));
MOCK_METHOD1(createRenderSurface, void(const RenderSurfaceCreationArgs&));
MOCK_METHOD1(createClientCompositionCache, void(uint32_t));
+ MOCK_METHOD1(applyDisplayBrightness, void(const bool));
MOCK_METHOD1(setPredictCompositionStrategy, void(bool));
};
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
index 2b704e6..be0dbce 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
@@ -42,9 +42,8 @@
MOCK_CONST_METHOD0(getCompositionState, const LayerFECompositionState*());
- MOCK_METHOD1(onPreComposition, bool(nsecs_t));
+ MOCK_METHOD2(onPreComposition, bool(nsecs_t, bool));
- MOCK_METHOD1(prepareCompositionState, void(compositionengine::LayerFE::StateSubset));
MOCK_CONST_METHOD1(prepareClientComposition,
std::optional<compositionengine::LayerFE::LayerSettings>(
compositionengine::LayerFE::ClientCompositionTargetSettings&));
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
index 2a04949..7592cac 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
@@ -91,7 +91,6 @@
void(sp<compositionengine::LayerFE>&, compositionengine::Output::CoverageState&));
MOCK_METHOD1(setReleasedLayers, void(const compositionengine::CompositionRefreshArgs&));
- MOCK_CONST_METHOD1(updateLayerStateFromFE, void(const CompositionRefreshArgs&));
MOCK_METHOD1(updateCompositionState, void(const CompositionRefreshArgs&));
MOCK_METHOD0(planComposition, void());
MOCK_METHOD1(writeCompositionState, void(const CompositionRefreshArgs&));
diff --git a/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp b/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp
index 6203dc6..855507e 100644
--- a/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/CompositionEngine.cpp
@@ -105,8 +105,6 @@
}
}
- updateLayerStateFromFE(args);
-
for (const auto& output : args.outputs) {
output->present(args);
}
@@ -119,8 +117,6 @@
for (const auto& output : args.outputs) {
for (auto* layer : output->getOutputLayersOrderedByZ()) {
if (layer->isHardwareCursor()) {
- // Latch the cursor composition state from each front-end layer.
- layer->getLayerFE().prepareCompositionState(LayerFE::StateSubset::Cursor);
layer->writeCursorPositionToHWC();
}
}
@@ -136,7 +132,7 @@
mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
for (auto& layer : args.layers) {
- if (layer->onPreComposition(mRefreshStartTime)) {
+ if (layer->onPreComposition(mRefreshStartTime, args.updatingOutputGeometryThisFrame)) {
needsAnotherUpdate = true;
}
}
@@ -152,12 +148,5 @@
mNeedsAnotherUpdate = value;
}
-void CompositionEngine::updateLayerStateFromFE(CompositionRefreshArgs& args) {
- // Update the composition state from each front-end layer
- for (const auto& output : args.outputs) {
- output->updateLayerStateFromFE(args);
- }
-}
-
} // namespace impl
} // namespace android::compositionengine
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index 09adaed..0b69d44 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -203,6 +203,24 @@
setReleasedLayers(std::move(releasedLayers));
}
+void Display::applyDisplayBrightness(const bool applyImmediately) {
+ auto& hwc = getCompositionEngine().getHwComposer();
+ const auto halDisplayId = HalDisplayId::tryCast(*getDisplayId());
+ if (const auto physicalDisplayId = PhysicalDisplayId::tryCast(*halDisplayId);
+ physicalDisplayId && getState().displayBrightness) {
+ const status_t result =
+ hwc.setDisplayBrightness(*physicalDisplayId, *getState().displayBrightness,
+ getState().displayBrightnessNits,
+ Hwc2::Composer::DisplayBrightnessOptions{
+ .applyImmediately = applyImmediately})
+ .get();
+ ALOGE_IF(result != NO_ERROR, "setDisplayBrightness failed for %s: %d, (%s)",
+ getName().c_str(), result, strerror(-result));
+ }
+ // Clear out the display brightness now that it's been communicated to composer.
+ editState().displayBrightness.reset();
+}
+
void Display::beginFrame() {
Output::beginFrame();
@@ -212,20 +230,7 @@
return;
}
- auto& hwc = getCompositionEngine().getHwComposer();
- if (const auto physicalDisplayId = PhysicalDisplayId::tryCast(*halDisplayId);
- physicalDisplayId && getState().displayBrightness) {
- const status_t result =
- hwc.setDisplayBrightness(*physicalDisplayId, *getState().displayBrightness,
- getState().displayBrightnessNits,
- Hwc2::Composer::DisplayBrightnessOptions{
- .applyImmediately = false})
- .get();
- ALOGE_IF(result != NO_ERROR, "setDisplayBrightness failed for %s: %d, (%s)",
- getName().c_str(), result, strerror(-result));
- }
- // Clear out the display brightness now that it's been communicated to composer.
- editState().displayBrightness.reset();
+ applyDisplayBrightness(false);
}
bool Display::chooseCompositionStrategy(
@@ -243,7 +248,7 @@
return false;
}
- const nsecs_t startTime = systemTime();
+ const TimePoint startTime = TimePoint::now();
// Get any composition changes requested by the HWC device, and apply them.
std::optional<android::HWComposer::DeviceRequestedChanges> changes;
@@ -261,7 +266,7 @@
}
if (isPowerHintSessionEnabled()) {
- mPowerAdvisor->setHwcValidateTiming(mId, startTime, systemTime());
+ mPowerAdvisor->setHwcValidateTiming(mId, startTime, TimePoint::now());
mPowerAdvisor->setRequiresClientComposition(mId, requiresClientComposition);
}
@@ -365,7 +370,7 @@
auto& hwc = getCompositionEngine().getHwComposer();
- const nsecs_t startTime = systemTime();
+ const TimePoint startTime = TimePoint::now();
if (isPowerHintSessionEnabled()) {
if (!getCompositionEngine().getHwComposer().getComposer()->isSupported(
@@ -379,7 +384,7 @@
getState().previousPresentFence);
if (isPowerHintSessionEnabled()) {
- mPowerAdvisor->setHwcPresentTiming(mId, startTime, systemTime());
+ mPowerAdvisor->setHwcPresentTiming(mId, startTime, TimePoint::now());
}
fences.presentFence = hwc.getPresentFence(*halDisplayIdOpt);
@@ -421,7 +426,7 @@
// 1) It is being handled by hardware composer, which may need this to
// keep its virtual display state machine in sync, or
// 2) There is work to be done (the dirty region isn't empty)
- if (GpuVirtualDisplayId::tryCast(mId) && getDirtyRegion().isEmpty()) {
+ if (GpuVirtualDisplayId::tryCast(mId) && !mustRecompose()) {
ALOGV("Skipping display composition");
return;
}
diff --git a/services/surfaceflinger/CompositionEngine/src/Output.cpp b/services/surfaceflinger/CompositionEngine/src/Output.cpp
index ea78517..e3f3680 100644
--- a/services/surfaceflinger/CompositionEngine/src/Output.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Output.cpp
@@ -501,7 +501,6 @@
// appear on multiple outputs.
if (!coverage.latchedLayers.count(layerFE)) {
coverage.latchedLayers.insert(layerFE);
- layerFE->prepareCompositionState(compositionengine::LayerFE::StateSubset::BasicGeometry);
}
// Only consider the layers on this output
@@ -725,14 +724,6 @@
// The base class does nothing with this call.
}
-void Output::updateLayerStateFromFE(const CompositionRefreshArgs& args) const {
- for (auto* layer : getOutputLayersOrderedByZ()) {
- layer->getLayerFE().prepareCompositionState(
- args.updatingGeometryThisFrame ? LayerFE::StateSubset::GeometryAndContent
- : LayerFE::StateSubset::Content);
- }
-}
-
void Output::updateCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
ATRACE_CALL();
ALOGV(__FUNCTION__);
@@ -1015,17 +1006,17 @@
// frame, then nothing more until we get new layers.
// - When a display is created with a private layer stack, we won't
// emit any black frames until a layer is added to the layer stack.
- const bool mustRecompose = dirty && !(empty && wasEmpty);
+ mMustRecompose = dirty && !(empty && wasEmpty);
const char flagPrefix[] = {'-', '+'};
static_cast<void>(flagPrefix);
- ALOGV_IF("%s: %s composition for %s (%cdirty %cempty %cwasEmpty)", __FUNCTION__,
- mustRecompose ? "doing" : "skipping", getName().c_str(), flagPrefix[dirty],
- flagPrefix[empty], flagPrefix[wasEmpty]);
+ ALOGV("%s: %s composition for %s (%cdirty %cempty %cwasEmpty)", __func__,
+ mMustRecompose ? "doing" : "skipping", getName().c_str(), flagPrefix[dirty],
+ flagPrefix[empty], flagPrefix[wasEmpty]);
- mRenderSurface->beginFrame(mustRecompose);
+ mRenderSurface->beginFrame(mMustRecompose);
- if (mustRecompose) {
+ if (mMustRecompose) {
outputState.lastCompositionHadVisibleLayers = !empty;
}
}
@@ -1631,5 +1622,9 @@
mRenderSurface->prepareFrame(state.usesClientComposition, state.usesDeviceComposition);
}
+bool Output::mustRecompose() const {
+ return mMustRecompose;
+}
+
} // namespace impl
} // namespace android::compositionengine
diff --git a/services/surfaceflinger/CompositionEngine/tests/CompositionEngineTest.cpp b/services/surfaceflinger/CompositionEngine/tests/CompositionEngineTest.cpp
index de9de01..b570979 100644
--- a/services/surfaceflinger/CompositionEngine/tests/CompositionEngineTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/CompositionEngineTest.cpp
@@ -108,12 +108,6 @@
EXPECT_CALL(*mOutput2, prepare(Ref(mRefreshArgs), _));
EXPECT_CALL(*mOutput3, prepare(Ref(mRefreshArgs), _));
- // The next step in presenting is to make sure all outputs have the latest
- // state from the front-end (SurfaceFlinger).
- EXPECT_CALL(*mOutput1, updateLayerStateFromFE(Ref(mRefreshArgs)));
- EXPECT_CALL(*mOutput2, updateLayerStateFromFE(Ref(mRefreshArgs)));
- EXPECT_CALL(*mOutput3, updateLayerStateFromFE(Ref(mRefreshArgs)));
-
// The last step is to actually present each output.
EXPECT_CALL(*mOutput1, present(Ref(mRefreshArgs)));
EXPECT_CALL(*mOutput2, present(Ref(mRefreshArgs)));
@@ -175,21 +169,18 @@
{
InSequence seq;
EXPECT_CALL(mOutput2Layer1.outputLayer, isHardwareCursor()).WillRepeatedly(Return(true));
- EXPECT_CALL(*mOutput2Layer1.layerFE, prepareCompositionState(LayerFE::StateSubset::Cursor));
EXPECT_CALL(mOutput2Layer1.outputLayer, writeCursorPositionToHWC());
}
{
InSequence seq;
EXPECT_CALL(mOutput3Layer1.outputLayer, isHardwareCursor()).WillRepeatedly(Return(true));
- EXPECT_CALL(*mOutput3Layer1.layerFE, prepareCompositionState(LayerFE::StateSubset::Cursor));
EXPECT_CALL(mOutput3Layer1.outputLayer, writeCursorPositionToHWC());
}
{
InSequence seq;
EXPECT_CALL(mOutput3Layer2.outputLayer, isHardwareCursor()).WillRepeatedly(Return(true));
- EXPECT_CALL(*mOutput3Layer2.layerFE, prepareCompositionState(LayerFE::StateSubset::Cursor));
EXPECT_CALL(mOutput3Layer2.outputLayer, writeCursorPositionToHWC());
}
@@ -222,9 +213,12 @@
nsecs_t ts1 = 0;
nsecs_t ts2 = 0;
nsecs_t ts3 = 0;
- EXPECT_CALL(*mLayer1FE, onPreComposition(_)).WillOnce(DoAll(SaveArg<0>(&ts1), Return(false)));
- EXPECT_CALL(*mLayer2FE, onPreComposition(_)).WillOnce(DoAll(SaveArg<0>(&ts2), Return(false)));
- EXPECT_CALL(*mLayer3FE, onPreComposition(_)).WillOnce(DoAll(SaveArg<0>(&ts3), Return(false)));
+ EXPECT_CALL(*mLayer1FE, onPreComposition(_, _))
+ .WillOnce(DoAll(SaveArg<0>(&ts1), Return(false)));
+ EXPECT_CALL(*mLayer2FE, onPreComposition(_, _))
+ .WillOnce(DoAll(SaveArg<0>(&ts2), Return(false)));
+ EXPECT_CALL(*mLayer3FE, onPreComposition(_, _))
+ .WillOnce(DoAll(SaveArg<0>(&ts3), Return(false)));
mRefreshArgs.outputs = {mOutput1};
mRefreshArgs.layers = {mLayer1FE, mLayer2FE, mLayer3FE};
@@ -238,9 +232,9 @@
}
TEST_F(CompositionTestPreComposition, preCompositionDefaultsToNoUpdateNeeded) {
- EXPECT_CALL(*mLayer1FE, onPreComposition(_)).WillOnce(Return(false));
- EXPECT_CALL(*mLayer2FE, onPreComposition(_)).WillOnce(Return(false));
- EXPECT_CALL(*mLayer3FE, onPreComposition(_)).WillOnce(Return(false));
+ EXPECT_CALL(*mLayer1FE, onPreComposition(_, _)).WillOnce(Return(false));
+ EXPECT_CALL(*mLayer2FE, onPreComposition(_, _)).WillOnce(Return(false));
+ EXPECT_CALL(*mLayer3FE, onPreComposition(_, _)).WillOnce(Return(false));
mEngine.setNeedsAnotherUpdateForTest(true);
@@ -255,9 +249,9 @@
TEST_F(CompositionTestPreComposition,
preCompositionSetsNeedsAnotherUpdateIfAtLeastOneLayerRequestsIt) {
- EXPECT_CALL(*mLayer1FE, onPreComposition(_)).WillOnce(Return(true));
- EXPECT_CALL(*mLayer2FE, onPreComposition(_)).WillOnce(Return(false));
- EXPECT_CALL(*mLayer3FE, onPreComposition(_)).WillOnce(Return(false));
+ EXPECT_CALL(*mLayer1FE, onPreComposition(_, _)).WillOnce(Return(true));
+ EXPECT_CALL(*mLayer2FE, onPreComposition(_, _)).WillOnce(Return(false));
+ EXPECT_CALL(*mLayer3FE, onPreComposition(_, _)).WillOnce(Return(false));
mRefreshArgs.outputs = {mOutput1};
mRefreshArgs.layers = {mLayer1FE, mLayer2FE, mLayer3FE};
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index 51ca213..95459c0 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -971,16 +971,40 @@
// We expect no calls to queueBuffer if composition was skipped.
EXPECT_CALL(*renderSurface, queueBuffer(_)).Times(0);
+ EXPECT_CALL(*renderSurface, beginFrame(false));
gpuDisplay->editState().isEnabled = true;
gpuDisplay->editState().usesClientComposition = false;
gpuDisplay->editState().layerStackSpace.setContent(Rect(0, 0, 1, 1));
gpuDisplay->editState().dirtyRegion = Region::INVALID_REGION;
+ gpuDisplay->editState().lastCompositionHadVisibleLayers = true;
+ gpuDisplay->beginFrame();
gpuDisplay->finishFrame({}, std::move(mResultWithoutBuffer));
}
-TEST_F(DisplayFinishFrameTest, performsCompositionIfDirty) {
+TEST_F(DisplayFinishFrameTest, skipsCompositionIfEmpty) {
+ auto args = getDisplayCreationArgsForGpuVirtualDisplay();
+ std::shared_ptr<impl::Display> gpuDisplay = impl::createDisplay(mCompositionEngine, args);
+
+ mock::RenderSurface* renderSurface = new StrictMock<mock::RenderSurface>();
+ gpuDisplay->setRenderSurfaceForTest(std::unique_ptr<RenderSurface>(renderSurface));
+
+ // We expect no calls to queueBuffer if composition was skipped.
+ EXPECT_CALL(*renderSurface, queueBuffer(_)).Times(0);
+ EXPECT_CALL(*renderSurface, beginFrame(false));
+
+ gpuDisplay->editState().isEnabled = true;
+ gpuDisplay->editState().usesClientComposition = false;
+ gpuDisplay->editState().layerStackSpace.setContent(Rect(0, 0, 1, 1));
+ gpuDisplay->editState().dirtyRegion = Region(Rect(0, 0, 1, 1));
+ gpuDisplay->editState().lastCompositionHadVisibleLayers = false;
+
+ gpuDisplay->beginFrame();
+ gpuDisplay->finishFrame({}, std::move(mResultWithoutBuffer));
+}
+
+TEST_F(DisplayFinishFrameTest, performsCompositionIfDirtyAndNotEmpty) {
auto args = getDisplayCreationArgsForGpuVirtualDisplay();
std::shared_ptr<impl::Display> gpuDisplay = impl::createDisplay(mCompositionEngine, args);
@@ -989,11 +1013,15 @@
// We expect a single call to queueBuffer when composition is not skipped.
EXPECT_CALL(*renderSurface, queueBuffer(_)).Times(1);
+ EXPECT_CALL(*renderSurface, beginFrame(true));
gpuDisplay->editState().isEnabled = true;
gpuDisplay->editState().usesClientComposition = false;
gpuDisplay->editState().layerStackSpace.setContent(Rect(0, 0, 1, 1));
gpuDisplay->editState().dirtyRegion = Region(Rect(0, 0, 1, 1));
+ gpuDisplay->editState().lastCompositionHadVisibleLayers = true;
+
+ gpuDisplay->beginFrame();
gpuDisplay->finishFrame({}, std::move(mResultWithBuffer));
}
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h b/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
index c8bd5e4..e220541 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockPowerAdvisor.h
@@ -38,7 +38,7 @@
MOCK_METHOD(bool, usePowerHintSession, (), (override));
MOCK_METHOD(bool, supportsPowerHintSession, (), (override));
MOCK_METHOD(bool, isPowerHintSessionRunning, (), (override));
- MOCK_METHOD(void, setTargetWorkDuration, (int64_t targetDuration), (override));
+ MOCK_METHOD(void, setTargetWorkDuration, (Duration targetDuration), (override));
MOCK_METHOD(void, sendActualWorkDuration, (), (override));
MOCK_METHOD(void, sendPredictedWorkDuration, (), (override));
MOCK_METHOD(void, enablePowerHint, (bool enabled), (override));
@@ -46,25 +46,24 @@
MOCK_METHOD(void, setGpuFenceTime,
(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime), (override));
MOCK_METHOD(void, setHwcValidateTiming,
- (DisplayId displayId, nsecs_t valiateStartTime, nsecs_t validateEndTime),
+ (DisplayId displayId, TimePoint validateStartTime, TimePoint validateEndTime),
(override));
MOCK_METHOD(void, setHwcPresentTiming,
- (DisplayId displayId, nsecs_t presentStartTime, nsecs_t presentEndTime),
+ (DisplayId displayId, TimePoint presentStartTime, TimePoint presentEndTime),
(override));
MOCK_METHOD(void, setSkippedValidate, (DisplayId displayId, bool skipped), (override));
MOCK_METHOD(void, setRequiresClientComposition,
(DisplayId displayId, bool requiresClientComposition), (override));
- MOCK_METHOD(void, setExpectedPresentTime, (nsecs_t expectedPresentTime), (override));
- MOCK_METHOD(void, setSfPresentTiming, (nsecs_t presentFenceTime, nsecs_t presentEndTime),
+ MOCK_METHOD(void, setExpectedPresentTime, (TimePoint expectedPresentTime), (override));
+ MOCK_METHOD(void, setSfPresentTiming, (TimePoint presentFenceTime, TimePoint presentEndTime),
(override));
MOCK_METHOD(void, setHwcPresentDelayedTime,
- (DisplayId displayId,
- std::chrono::steady_clock::time_point earliestFrameStartTime));
- MOCK_METHOD(void, setFrameDelay, (nsecs_t frameDelayDuration), (override));
- MOCK_METHOD(void, setCommitStart, (nsecs_t commitStartTime), (override));
- MOCK_METHOD(void, setCompositeEnd, (nsecs_t compositeEndtime), (override));
+ (DisplayId displayId, TimePoint earliestFrameStartTime));
+ MOCK_METHOD(void, setFrameDelay, (Duration frameDelayDuration), (override));
+ MOCK_METHOD(void, setCommitStart, (TimePoint commitStartTime), (override));
+ MOCK_METHOD(void, setCompositeEnd, (TimePoint compositeEndTime), (override));
MOCK_METHOD(void, setDisplays, (std::vector<DisplayId> & displayIds), (override));
- MOCK_METHOD(void, setTotalFrameTargetWorkDuration, (int64_t targetDuration), (override));
+ MOCK_METHOD(void, setTotalFrameTargetWorkDuration, (Duration targetDuration), (override));
};
} // namespace mock
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
index ace2864..eb209e9 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
@@ -758,56 +758,6 @@
}
/*
- * Output::updateLayerStateFromFE()
- */
-
-using OutputUpdateLayerStateFromFETest = OutputTest;
-
-TEST_F(OutputUpdateLayerStateFromFETest, handlesNoOutputLayerCase) {
- CompositionRefreshArgs refreshArgs;
-
- mOutput->updateLayerStateFromFE(refreshArgs);
-}
-
-TEST_F(OutputUpdateLayerStateFromFETest, preparesContentStateForAllContainedLayers) {
- InjectedLayer layer1;
- InjectedLayer layer2;
- InjectedLayer layer3;
-
- EXPECT_CALL(*layer1.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
- EXPECT_CALL(*layer2.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
- EXPECT_CALL(*layer3.layerFE.get(), prepareCompositionState(LayerFE::StateSubset::Content));
-
- injectOutputLayer(layer1);
- injectOutputLayer(layer2);
- injectOutputLayer(layer3);
-
- CompositionRefreshArgs refreshArgs;
- refreshArgs.updatingGeometryThisFrame = false;
-
- mOutput->updateLayerStateFromFE(refreshArgs);
-}
-
-TEST_F(OutputUpdateLayerStateFromFETest, preparesGeometryAndContentStateForAllContainedLayers) {
- InjectedLayer layer1;
- InjectedLayer layer2;
- InjectedLayer layer3;
-
- EXPECT_CALL(*layer1.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
- EXPECT_CALL(*layer2.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
- EXPECT_CALL(*layer3.layerFE, prepareCompositionState(LayerFE::StateSubset::GeometryAndContent));
-
- injectOutputLayer(layer1);
- injectOutputLayer(layer2);
- injectOutputLayer(layer3);
-
- CompositionRefreshArgs refreshArgs;
- refreshArgs.updatingGeometryThisFrame = true;
-
- mOutput->updateLayerStateFromFE(refreshArgs);
-}
-
-/*
* Output::updateAndWriteCompositionState()
*/
@@ -1536,9 +1486,6 @@
TEST_F(OutputEnsureOutputLayerIfVisibleTest, performsGeomLatchBeforeCheckingIfLayerIncluded) {
EXPECT_CALL(mOutput, includesLayer(sp<LayerFE>(mLayer.layerFE))).WillOnce(Return(false));
- EXPECT_CALL(*mLayer.layerFE,
- prepareCompositionState(compositionengine::LayerFE::StateSubset::BasicGeometry));
-
mGeomSnapshots.clear();
ensureOutputLayerIfVisible();
diff --git a/services/surfaceflinger/Display/DisplayMap.h b/services/surfaceflinger/Display/DisplayMap.h
new file mode 100644
index 0000000..baf0da9
--- /dev/null
+++ b/services/surfaceflinger/Display/DisplayMap.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <ftl/small_map.h>
+
+namespace android::display {
+
+// The static capacities were chosen to exceed a typical number of physical and/or virtual displays.
+
+template <typename Key, typename Value>
+using DisplayMap = ftl::SmallMap<Key, Value, 5>;
+
+template <typename Key, typename Value>
+using PhysicalDisplayMap = ftl::SmallMap<Key, Value, 3>;
+
+} // namespace android::display
diff --git a/services/surfaceflinger/Display/DisplaySnapshot.cpp b/services/surfaceflinger/Display/DisplaySnapshot.cpp
new file mode 100644
index 0000000..b4f104a
--- /dev/null
+++ b/services/surfaceflinger/Display/DisplaySnapshot.cpp
@@ -0,0 +1,58 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include <functional>
+#include <utility>
+
+#include <ftl/algorithm.h>
+#include <ftl/enum.h>
+
+#include "DisplaySnapshot.h"
+
+namespace android::display {
+
+DisplaySnapshot::DisplaySnapshot(PhysicalDisplayId displayId,
+ ui::DisplayConnectionType connectionType,
+ DisplayModes&& displayModes,
+ std::optional<DeviceProductInfo>&& deviceProductInfo)
+ : mDisplayId(displayId),
+ mConnectionType(connectionType),
+ mDisplayModes(std::move(displayModes)),
+ mDeviceProductInfo(std::move(deviceProductInfo)) {}
+
+std::optional<DisplayModeId> DisplaySnapshot::translateModeId(hal::HWConfigId hwcId) const {
+ return ftl::find_if(mDisplayModes,
+ [hwcId](const DisplayModes::value_type& pair) {
+ return pair.second->getHwcId() == hwcId;
+ })
+ .transform(&ftl::to_key<DisplayModes>);
+}
+
+void DisplaySnapshot::dump(std::string& out) const {
+ using namespace std::string_literals;
+
+ out += " connectionType="s;
+ out += ftl::enum_string(mConnectionType);
+
+ out += "\n deviceProductInfo="s;
+ if (mDeviceProductInfo) {
+ mDeviceProductInfo->dump(out);
+ } else {
+ out += "{}"s;
+ }
+}
+
+} // namespace android::display
diff --git a/services/surfaceflinger/Display/DisplaySnapshot.h b/services/surfaceflinger/Display/DisplaySnapshot.h
new file mode 100644
index 0000000..0279220
--- /dev/null
+++ b/services/surfaceflinger/Display/DisplaySnapshot.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <optional>
+#include <string>
+
+#include <ui/DisplayId.h>
+#include <ui/StaticDisplayInfo.h>
+
+#include "../DisplayHardware/DisplayMode.h"
+
+namespace android::display {
+
+// Immutable state of a physical display, captured on hotplug.
+class DisplaySnapshot {
+public:
+ DisplaySnapshot(PhysicalDisplayId, ui::DisplayConnectionType, DisplayModes&&,
+ std::optional<DeviceProductInfo>&&);
+
+ DisplaySnapshot(const DisplaySnapshot&) = delete;
+ DisplaySnapshot(DisplaySnapshot&&) = default;
+
+ PhysicalDisplayId displayId() const { return mDisplayId; }
+ ui::DisplayConnectionType connectionType() const { return mConnectionType; }
+
+ std::optional<DisplayModeId> translateModeId(hal::HWConfigId) const;
+
+ const auto& displayModes() const { return mDisplayModes; }
+ const auto& deviceProductInfo() const { return mDeviceProductInfo; }
+
+ void dump(std::string&) const;
+
+private:
+ const PhysicalDisplayId mDisplayId;
+ const ui::DisplayConnectionType mConnectionType;
+
+ // Effectively const except in move constructor.
+ DisplayModes mDisplayModes;
+ std::optional<DeviceProductInfo> mDeviceProductInfo;
+};
+
+} // namespace android::display
diff --git a/services/surfaceflinger/Display/PhysicalDisplay.h b/services/surfaceflinger/Display/PhysicalDisplay.h
new file mode 100644
index 0000000..cba1014
--- /dev/null
+++ b/services/surfaceflinger/Display/PhysicalDisplay.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2022 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <functional>
+#include <utility>
+
+#include <binder/IBinder.h>
+#include <ui/DisplayId.h>
+#include <utils/StrongPointer.h>
+
+#include "DisplayMap.h"
+#include "DisplaySnapshot.h"
+
+namespace android::display {
+
+// TODO(b/229877597): Replace with AIDL type.
+using DisplayToken = IBinder;
+
+class PhysicalDisplay {
+public:
+ template <typename... Args>
+ PhysicalDisplay(sp<DisplayToken> token, Args&&... args)
+ : mToken(std::move(token)), mSnapshot(std::forward<Args>(args)...) {}
+
+ PhysicalDisplay(const PhysicalDisplay&) = delete;
+ PhysicalDisplay(PhysicalDisplay&&) = default;
+
+ const sp<DisplayToken>& token() const { return mToken; }
+ const DisplaySnapshot& snapshot() const { return mSnapshot; }
+
+ // Transformers for PhysicalDisplays::get.
+
+ using SnapshotRef = std::reference_wrapper<const DisplaySnapshot>;
+ SnapshotRef snapshotRef() const { return std::cref(mSnapshot); }
+
+ bool isInternal() const {
+ return mSnapshot.connectionType() == ui::DisplayConnectionType::Internal;
+ }
+
+ // Predicate for ftl::find_if on PhysicalDisplays.
+ static constexpr auto hasToken(const sp<DisplayToken>& token) {
+ return [&token](const std::pair<const PhysicalDisplayId, PhysicalDisplay>& pair) {
+ return pair.second.token() == token;
+ };
+ }
+
+private:
+ const sp<DisplayToken> mToken;
+
+ // Effectively const except in move constructor.
+ DisplaySnapshot mSnapshot;
+};
+
+using PhysicalDisplays = PhysicalDisplayMap<PhysicalDisplayId, PhysicalDisplay>;
+
+// Combinator for ftl::Optional<PhysicalDisplayId>::and_then.
+constexpr auto getPhysicalDisplay(const PhysicalDisplays& displays) {
+ return [&](PhysicalDisplayId id) { return displays.get(id); };
+}
+
+} // namespace android::display
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index bff301e..029e449 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -39,6 +39,7 @@
#include <system/window.h>
#include <ui/GraphicTypes.h>
+#include "Display/DisplaySnapshot.h"
#include "DisplayDevice.h"
#include "Layer.h"
#include "RefreshRateOverlay.h"
@@ -63,12 +64,10 @@
mHwComposer(args.hwComposer),
mDisplayToken(args.displayToken),
mSequenceId(args.sequenceId),
- mConnectionType(args.connectionType),
mCompositionDisplay{args.compositionDisplay},
mActiveModeFPSTrace("ActiveModeFPS -" + to_string(getId())),
mActiveModeFPSHwcTrace("ActiveModeFPS_HWC -" + to_string(getId())),
mPhysicalOrientation(args.physicalOrientation),
- mSupportedModes(std::move(args.supportedModes)),
mIsPrimary(args.isPrimary),
mRefreshRateConfigs(std::move(args.refreshRateConfigs)) {
mCompositionDisplay->editState().isSecure = args.isSecure;
@@ -104,7 +103,7 @@
mCompositionDisplay->getRenderSurface()->initialize();
- setPowerMode(args.initialPowerMode);
+ if (args.initialPowerMode.has_value()) setPowerMode(args.initialPowerMode.value());
// initialize the display orientation transform.
setProjection(ui::ROTATION_0, Rect::INVALID_RECT, Rect::INVALID_RECT);
@@ -132,10 +131,6 @@
}
}
-void DisplayDevice::setDeviceProductInfo(std::optional<DeviceProductInfo> info) {
- mDeviceProductInfo = std::move(info);
-}
-
auto DisplayDevice::getInputInfo() const -> InputInfo {
gui::DisplayInfo info;
info.displayId = getLayerStack().id;
@@ -169,32 +164,47 @@
}
void DisplayDevice::setPowerMode(hal::PowerMode mode) {
+ if (mode == hal::PowerMode::OFF || mode == hal::PowerMode::ON) {
+ if (mStagedBrightness && mBrightness != *mStagedBrightness) {
+ getCompositionDisplay()->setNextBrightness(*mStagedBrightness);
+ mBrightness = *mStagedBrightness;
+ }
+ mStagedBrightness = std::nullopt;
+ getCompositionDisplay()->applyDisplayBrightness(true);
+ }
+
mPowerMode = mode;
- getCompositionDisplay()->setCompositionEnabled(mPowerMode != hal::PowerMode::OFF);
+
+ getCompositionDisplay()->setCompositionEnabled(mPowerMode.has_value() &&
+ *mPowerMode != hal::PowerMode::OFF);
}
void DisplayDevice::enableLayerCaching(bool enable) {
getCompositionDisplay()->setLayerCachingEnabled(enable);
}
-hal::PowerMode DisplayDevice::getPowerMode() const {
+std::optional<hal::PowerMode> DisplayDevice::getPowerMode() const {
return mPowerMode;
}
bool DisplayDevice::isPoweredOn() const {
- return mPowerMode != hal::PowerMode::OFF;
+ return mPowerMode && *mPowerMode != hal::PowerMode::OFF;
}
-void DisplayDevice::setActiveMode(DisplayModeId id) {
- const auto mode = getMode(id);
- LOG_FATAL_IF(!mode, "Cannot set active mode which is not supported.");
- ATRACE_INT(mActiveModeFPSTrace.c_str(), mode->getFps().getIntValue());
- mActiveMode = mode;
+void DisplayDevice::setActiveMode(DisplayModeId modeId, const display::DisplaySnapshot& snapshot) {
+ const auto modeOpt = snapshot.displayModes().get(modeId);
+ LOG_ALWAYS_FATAL_IF(!modeOpt, "Unknown mode");
+
+ mActiveMode = modeOpt->get();
+ const Fps fps = mActiveMode->getFps();
+
+ ATRACE_INT(mActiveModeFPSTrace.c_str(), fps.getIntValue());
+
if (mRefreshRateConfigs) {
- mRefreshRateConfigs->setActiveModeId(mActiveMode->getId());
+ mRefreshRateConfigs->setActiveModeId(modeId);
}
if (mRefreshRateOverlay) {
- mRefreshRateOverlay->changeRefreshRate(mActiveMode->getFps());
+ mRefreshRateOverlay->changeRefreshRate(fps);
}
}
@@ -218,25 +228,6 @@
return mActiveMode;
}
-const DisplayModes& DisplayDevice::getSupportedModes() const {
- return mSupportedModes;
-}
-
-DisplayModePtr DisplayDevice::getMode(DisplayModeId modeId) const {
- const DisplayModePtr nullMode;
- return mSupportedModes.get(modeId).value_or(std::cref(nullMode));
-}
-
-std::optional<DisplayModeId> DisplayDevice::translateModeId(hal::HWConfigId hwcId) const {
- const auto it =
- std::find_if(mSupportedModes.begin(), mSupportedModes.end(),
- [hwcId](const auto& pair) { return pair.second->getHwcId() == hwcId; });
- if (it != mSupportedModes.end()) {
- return it->second->getId();
- }
- return {};
-}
-
nsecs_t DisplayDevice::getVsyncPeriodFromHWC() const {
const auto physicalId = getPhysicalId();
if (!mHwComposer.isConnected(physicalId)) {
@@ -266,10 +257,10 @@
return mCompositionDisplay->getState().dataspace;
}
-void DisplayDevice::setLayerStack(ui::LayerStack stack) {
- mCompositionDisplay->setLayerFilter({stack, isInternal()});
+void DisplayDevice::setLayerFilter(ui::LayerFilter filter) {
+ mCompositionDisplay->setLayerFilter(filter);
if (mRefreshRateOverlay) {
- mRefreshRateOverlay->setLayerStack(stack);
+ mRefreshRateOverlay->setLayerStack(filter.layerStack);
}
}
@@ -341,11 +332,7 @@
std::string name = "Display "s + to_string(getId()) + " ("s;
- if (mConnectionType) {
- name += isInternal() ? "internal"s : "external"s;
- } else {
- name += "virtual"s;
- }
+ name += isVirtual() ? "virtual"s : "physical"s;
if (isPrimary()) {
name += ", primary"s;
@@ -359,17 +346,8 @@
result += getDebugName();
- if (!isVirtual()) {
- result += "\n deviceProductInfo="s;
- if (mDeviceProductInfo) {
- mDeviceProductInfo->dump(result);
- } else {
- result += "{}"s;
- }
- }
-
result += "\n powerMode="s;
- result += to_string(mPowerMode);
+ result += mPowerMode.has_value() ? to_string(mPowerMode.value()) : "OFF(reset)";
result += '\n';
if (mRefreshRateConfigs) {
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index 10fc095..d79a6b5 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -65,6 +65,10 @@
class DisplaySurface;
} // namespace compositionengine
+namespace display {
+class DisplaySnapshot;
+} // namespace display
+
class DisplayDevice : public RefBase {
public:
constexpr static float sDefaultMinLumiance = 0.0;
@@ -80,11 +84,8 @@
return mCompositionDisplay;
}
- std::optional<ui::DisplayConnectionType> getConnectionType() const { return mConnectionType; }
-
- bool isVirtual() const { return !mConnectionType; }
+ bool isVirtual() const { return VirtualDisplayId::tryCast(getId()).has_value(); }
bool isPrimary() const { return mIsPrimary; }
- bool isInternal() const { return mConnectionType == ui::DisplayConnectionType::Internal; }
// isSecure indicates whether this display can be trusted to display
// secure surfaces.
@@ -94,7 +95,7 @@
int getHeight() const;
ui::Size getSize() const { return {getWidth(), getHeight()}; }
- void setLayerStack(ui::LayerStack);
+ void setLayerFilter(ui::LayerFilter);
void setDisplaySize(int width, int height);
void setProjection(ui::Rotation orientation, Rect viewport, Rect frame);
void stageBrightness(float brightness) REQUIRES(kMainThreadContext);
@@ -164,11 +165,6 @@
void setDisplayName(const std::string& displayName);
const std::string& getDisplayName() const { return mDisplayName; }
- void setDeviceProductInfo(std::optional<DeviceProductInfo> info);
- const std::optional<DeviceProductInfo>& getDeviceProductInfo() const {
- return mDeviceProductInfo;
- }
-
struct InputInfo {
gui::DisplayInfo info;
ui::Transform transform;
@@ -181,7 +177,7 @@
/* ------------------------------------------------------------------------
* Display power mode management.
*/
- hardware::graphics::composer::hal::PowerMode getPowerMode() const;
+ std::optional<hardware::graphics::composer::hal::PowerMode> getPowerMode() const;
void setPowerMode(hardware::graphics::composer::hal::PowerMode mode);
bool isPoweredOn() const;
@@ -211,24 +207,14 @@
return mUpcomingActiveMode;
}
- void setActiveMode(DisplayModeId) REQUIRES(kMainThreadContext);
+ // Precondition: DisplaySnapshot must contain a mode with DisplayModeId.
+ void setActiveMode(DisplayModeId, const display::DisplaySnapshot&) REQUIRES(kMainThreadContext);
+
status_t initiateModeChange(const ActiveModeInfo&,
const hal::VsyncPeriodChangeConstraints& constraints,
hal::VsyncPeriodChangeTimeline* outTimeline)
REQUIRES(kMainThreadContext);
- // Return the immutable list of supported display modes. The HWC may report different modes
- // after a hotplug reconnect event, in which case the DisplayDevice object will be recreated.
- // Hotplug reconnects are common for external displays.
- const DisplayModes& getSupportedModes() const;
-
- // Returns nullptr if the given mode ID is not supported. A previously
- // supported mode may be no longer supported for some devices like TVs and
- // set-top boxes after a hotplug reconnect.
- DisplayModePtr getMode(DisplayModeId) const;
-
- std::optional<DisplayModeId> translateModeId(hal::HWConfigId) const;
-
// Returns the refresh rate configs for this display.
scheduler::RefreshRateConfigs& refreshRateConfigs() const { return *mRefreshRateConfigs; }
@@ -267,7 +253,6 @@
HWComposer& mHwComposer;
const wp<IBinder> mDisplayToken;
const int32_t mSequenceId;
- const std::optional<ui::DisplayConnectionType> mConnectionType;
const std::shared_ptr<compositionengine::Display> mCompositionDisplay;
@@ -280,12 +265,11 @@
static ui::Transform::RotationFlags sPrimaryDisplayRotationFlags;
- hardware::graphics::composer::hal::PowerMode mPowerMode =
- hardware::graphics::composer::hal::PowerMode::OFF;
+ // allow initial power mode as null.
+ std::optional<hardware::graphics::composer::hal::PowerMode> mPowerMode;
DisplayModePtr mActiveMode;
std::optional<float> mStagedBrightness = std::nullopt;
float mBrightness = -1.f;
- const DisplayModes mSupportedModes;
std::atomic<nsecs_t> mLastHwVsync = 0;
@@ -294,8 +278,6 @@
uint32_t mFlags = 0;
- std::optional<DeviceProductInfo> mDeviceProductInfo;
-
std::vector<ui::Hdr> mOverrideHdrTypes;
std::shared_ptr<scheduler::RefreshRateConfigs> mRefreshRateConfigs;
@@ -313,14 +295,11 @@
struct DisplayDeviceState {
struct Physical {
PhysicalDisplayId id;
- ui::DisplayConnectionType type;
hardware::graphics::composer::hal::HWDisplayId hwcDisplayId;
- std::optional<DeviceProductInfo> deviceProductInfo;
- DisplayModes supportedModes;
DisplayModePtr activeMode;
bool operator==(const Physical& other) const {
- return id == other.id && type == other.type && hwcDisplayId == other.hwcDisplayId;
+ return id == other.id && hwcDisplayId == other.hwcDisplayId;
}
};
@@ -356,7 +335,6 @@
std::shared_ptr<scheduler::RefreshRateConfigs> refreshRateConfigs;
int32_t sequenceId{0};
- std::optional<ui::DisplayConnectionType> connectionType;
bool isSecure{false};
sp<ANativeWindow> nativeWindow;
sp<compositionengine::DisplaySurface> displaySurface;
@@ -365,10 +343,8 @@
HdrCapabilities hdrCapabilities;
int32_t supportedPerFrameMetadata{0};
std::unordered_map<ui::ColorMode, std::vector<ui::RenderIntent>> hwcColorModes;
- hardware::graphics::composer::hal::PowerMode initialPowerMode{
- hardware::graphics::composer::hal::PowerMode::ON};
+ std::optional<hardware::graphics::composer::hal::PowerMode> initialPowerMode;
bool isPrimary{false};
- DisplayModes supportedModes;
DisplayModeId activeModeId;
};
diff --git a/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp b/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
index 566537b..cb2c8c5 100644
--- a/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
+++ b/services/surfaceflinger/DisplayHardware/PowerAdvisor.cpp
@@ -59,8 +59,6 @@
using android::hardware::power::Mode;
using android::hardware::power::WorkDuration;
-using scheduler::OneShotTimer;
-
PowerAdvisor::~PowerAdvisor() = default;
namespace {
@@ -196,7 +194,7 @@
return mPowerHintSessionRunning;
}
-void PowerAdvisor::setTargetWorkDuration(int64_t targetDuration) {
+void PowerAdvisor::setTargetWorkDuration(Duration targetDuration) {
if (!usePowerHintSession()) {
ALOGV("Power hint session target duration cannot be set, skipping");
return;
@@ -215,13 +213,13 @@
ALOGV("Actual work duration power hint cannot be sent, skipping");
return;
}
- const std::optional<nsecs_t> actualDuration = estimateWorkDuration(false);
+ const std::optional<Duration> actualDuration = estimateWorkDuration(false);
if (actualDuration.has_value()) {
std::lock_guard lock(mPowerHalMutex);
HalWrapper* const halWrapper = getPowerHal();
if (halWrapper != nullptr) {
- halWrapper->sendActualWorkDuration(*actualDuration + kTargetSafetyMargin.count(),
- systemTime());
+ halWrapper->sendActualWorkDuration(*actualDuration + kTargetSafetyMargin,
+ TimePoint::now());
}
}
}
@@ -232,14 +230,14 @@
return;
}
- const std::optional<nsecs_t> predictedDuration = estimateWorkDuration(true);
+ const std::optional<Duration> predictedDuration = estimateWorkDuration(true);
if (predictedDuration.has_value()) {
std::lock_guard lock(mPowerHalMutex);
HalWrapper* const halWrapper = getPowerHal();
if (halWrapper != nullptr) {
- halWrapper->sendActualWorkDuration(*predictedDuration + kTargetSafetyMargin.count(),
- systemTime());
+ halWrapper->sendActualWorkDuration(*predictedDuration + kTargetSafetyMargin,
+ TimePoint::now());
}
}
}
@@ -281,22 +279,22 @@
}
}
displayData.lastValidGpuStartTime = displayData.gpuStartTime;
- displayData.lastValidGpuEndTime = signalTime;
+ displayData.lastValidGpuEndTime = TimePoint::fromNs(signalTime);
}
}
displayData.gpuEndFenceTime = std::move(fenceTime);
- displayData.gpuStartTime = systemTime();
+ displayData.gpuStartTime = TimePoint::now();
}
-void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
- nsecs_t validateEndTime) {
+void PowerAdvisor::setHwcValidateTiming(DisplayId displayId, TimePoint validateStartTime,
+ TimePoint validateEndTime) {
DisplayTimingData& displayData = mDisplayTimingData[displayId];
displayData.hwcValidateStartTime = validateStartTime;
displayData.hwcValidateEndTime = validateEndTime;
}
-void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
- nsecs_t presentEndTime) {
+void PowerAdvisor::setHwcPresentTiming(DisplayId displayId, TimePoint presentStartTime,
+ TimePoint presentEndTime) {
DisplayTimingData& displayData = mDisplayTimingData[displayId];
displayData.hwcPresentStartTime = presentStartTime;
displayData.hwcPresentEndTime = presentEndTime;
@@ -311,43 +309,41 @@
mDisplayTimingData[displayId].usedClientComposition = requiresClientComposition;
}
-void PowerAdvisor::setExpectedPresentTime(nsecs_t expectedPresentTime) {
+void PowerAdvisor::setExpectedPresentTime(TimePoint expectedPresentTime) {
mExpectedPresentTimes.append(expectedPresentTime);
}
-void PowerAdvisor::setSfPresentTiming(nsecs_t presentFenceTime, nsecs_t presentEndTime) {
+void PowerAdvisor::setSfPresentTiming(TimePoint presentFenceTime, TimePoint presentEndTime) {
mLastSfPresentEndTime = presentEndTime;
mLastPresentFenceTime = presentFenceTime;
}
-void PowerAdvisor::setFrameDelay(nsecs_t frameDelayDuration) {
+void PowerAdvisor::setFrameDelay(Duration frameDelayDuration) {
mFrameDelayDuration = frameDelayDuration;
}
-void PowerAdvisor::setHwcPresentDelayedTime(
- DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) {
- mDisplayTimingData[displayId].hwcPresentDelayedTime =
- (earliestFrameStartTime - std::chrono::steady_clock::now()).count() + systemTime();
+void PowerAdvisor::setHwcPresentDelayedTime(DisplayId displayId, TimePoint earliestFrameStartTime) {
+ mDisplayTimingData[displayId].hwcPresentDelayedTime = earliestFrameStartTime;
}
-void PowerAdvisor::setCommitStart(nsecs_t commitStartTime) {
+void PowerAdvisor::setCommitStart(TimePoint commitStartTime) {
mCommitStartTimes.append(commitStartTime);
}
-void PowerAdvisor::setCompositeEnd(nsecs_t compositeEnd) {
- mLastPostcompDuration = compositeEnd - mLastSfPresentEndTime;
+void PowerAdvisor::setCompositeEnd(TimePoint compositeEndTime) {
+ mLastPostcompDuration = compositeEndTime - mLastSfPresentEndTime;
}
void PowerAdvisor::setDisplays(std::vector<DisplayId>& displayIds) {
mDisplayIds = displayIds;
}
-void PowerAdvisor::setTotalFrameTargetWorkDuration(nsecs_t targetDuration) {
+void PowerAdvisor::setTotalFrameTargetWorkDuration(Duration targetDuration) {
mTotalFrameTargetDuration = targetDuration;
}
std::vector<DisplayId> PowerAdvisor::getOrderedDisplayIds(
- std::optional<nsecs_t> DisplayTimingData::*sortBy) {
+ std::optional<TimePoint> DisplayTimingData::*sortBy) {
std::vector<DisplayId> sortedDisplays;
std::copy_if(mDisplayIds.begin(), mDisplayIds.end(), std::back_inserter(sortedDisplays),
[&](DisplayId id) {
@@ -360,33 +356,34 @@
return sortedDisplays;
}
-std::optional<nsecs_t> PowerAdvisor::estimateWorkDuration(bool earlyHint) {
+std::optional<Duration> PowerAdvisor::estimateWorkDuration(bool earlyHint) {
if (earlyHint && (!mExpectedPresentTimes.isFull() || !mCommitStartTimes.isFull())) {
return std::nullopt;
}
// Tracks when we finish presenting to hwc
- nsecs_t estimatedEndTime = mCommitStartTimes[0];
+ TimePoint estimatedEndTime = mCommitStartTimes[0];
// How long we spent this frame not doing anything, waiting for fences or vsync
- nsecs_t idleDuration = 0;
+ Duration idleDuration = 0ns;
// Most recent previous gpu end time in the current frame, probably from a prior display, used
// as the start time for the next gpu operation if it ran over time since it probably blocked
- std::optional<nsecs_t> previousValidGpuEndTime;
+ std::optional<TimePoint> previousValidGpuEndTime;
// The currently estimated gpu end time for the frame,
// used to accumulate gpu time as we iterate over the active displays
- std::optional<nsecs_t> estimatedGpuEndTime;
+ std::optional<TimePoint> estimatedGpuEndTime;
// If we're predicting at the start of the frame, we use last frame as our reference point
// If we're predicting at the end of the frame, we use the current frame as a reference point
- nsecs_t referenceFrameStartTime = (earlyHint ? mCommitStartTimes[-1] : mCommitStartTimes[0]);
+ TimePoint referenceFrameStartTime = (earlyHint ? mCommitStartTimes[-1] : mCommitStartTimes[0]);
// When the prior frame should be presenting to the display
// If we're predicting at the start of the frame, we use last frame's expected present time
// If we're predicting at the end of the frame, the present fence time is already known
- nsecs_t lastFramePresentTime = (earlyHint ? mExpectedPresentTimes[-1] : mLastPresentFenceTime);
+ TimePoint lastFramePresentTime =
+ (earlyHint ? mExpectedPresentTimes[-1] : mLastPresentFenceTime);
// The timing info for the previously calculated display, if there was one
std::optional<DisplayTimeline> previousDisplayReferenceTiming;
@@ -427,10 +424,10 @@
// Track how long we spent waiting for the fence, can be excluded from the timing estimate
idleDuration += estimatedTiming.probablyWaitsForPresentFence
? lastFramePresentTime - estimatedTiming.presentFenceWaitStartTime
- : 0;
+ : 0ns;
// Track how long we spent waiting to present, can be excluded from the timing estimate
- idleDuration += earlyHint ? 0 : referenceTiming.hwcPresentDelayDuration;
+ idleDuration += earlyHint ? 0ns : referenceTiming.hwcPresentDelayDuration;
// Estimate the reference frame's gpu timing
auto gpuTiming = displayData.estimateGpuTiming(previousValidGpuEndTime);
@@ -438,15 +435,15 @@
previousValidGpuEndTime = gpuTiming->startTime + gpuTiming->duration;
// Estimate the prediction frame's gpu end time from the reference frame
- estimatedGpuEndTime =
- std::max(estimatedTiming.hwcPresentStartTime, estimatedGpuEndTime.value_or(0)) +
+ estimatedGpuEndTime = std::max(estimatedTiming.hwcPresentStartTime,
+ estimatedGpuEndTime.value_or(TimePoint{0ns})) +
gpuTiming->duration;
}
previousDisplayReferenceTiming = referenceTiming;
}
- ATRACE_INT64("Idle duration", idleDuration);
+ ATRACE_INT64("Idle duration", idleDuration.ns());
- nsecs_t estimatedFlingerEndTime = earlyHint ? estimatedEndTime : mLastSfPresentEndTime;
+ TimePoint estimatedFlingerEndTime = earlyHint ? estimatedEndTime : mLastSfPresentEndTime;
// Don't count time spent idly waiting in the estimate as we could do more work in that time
estimatedEndTime -= idleDuration;
@@ -454,21 +451,22 @@
// We finish the frame when both present and the gpu are done, so wait for the later of the two
// Also add the frame delay duration since the target did not move while we were delayed
- nsecs_t totalDuration = mFrameDelayDuration +
- std::max(estimatedEndTime, estimatedGpuEndTime.value_or(0)) - mCommitStartTimes[0];
+ Duration totalDuration = mFrameDelayDuration +
+ std::max(estimatedEndTime, estimatedGpuEndTime.value_or(TimePoint{0ns})) -
+ mCommitStartTimes[0];
// We finish SurfaceFlinger when post-composition finishes, so add that in here
- nsecs_t flingerDuration =
+ Duration flingerDuration =
estimatedFlingerEndTime + mLastPostcompDuration - mCommitStartTimes[0];
// Combine the two timings into a single normalized one
- nsecs_t combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
+ Duration combinedDuration = combineTimingEstimates(totalDuration, flingerDuration);
return std::make_optional(combinedDuration);
}
-nsecs_t PowerAdvisor::combineTimingEstimates(nsecs_t totalDuration, nsecs_t flingerDuration) {
- nsecs_t targetDuration;
+Duration PowerAdvisor::combineTimingEstimates(Duration totalDuration, Duration flingerDuration) {
+ Duration targetDuration{0ns};
{
std::lock_guard lock(mPowerHalMutex);
targetDuration = *getPowerHal()->getTargetWorkDuration();
@@ -477,17 +475,18 @@
// Normalize total to the flinger target (vsync period) since that's how often we actually send
// hints
- nsecs_t normalizedTotalDuration = (targetDuration * totalDuration) / *mTotalFrameTargetDuration;
+ Duration normalizedTotalDuration = Duration::fromNs((targetDuration.ns() * totalDuration.ns()) /
+ mTotalFrameTargetDuration->ns());
return std::max(flingerDuration, normalizedTotalDuration);
}
PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimeline::estimateTimelineFromReference(
- nsecs_t fenceTime, nsecs_t displayStartTime) {
+ TimePoint fenceTime, TimePoint displayStartTime) {
DisplayTimeline estimated;
estimated.hwcPresentStartTime = displayStartTime;
// We don't predict waiting for vsync alignment yet
- estimated.hwcPresentDelayDuration = 0;
+ estimated.hwcPresentDelayDuration = 0ns;
// How long we expect to run before we start waiting for the fence
// For now just re-use last frame's post-present duration and assume it will not change much
@@ -502,12 +501,11 @@
}
PowerAdvisor::DisplayTimeline PowerAdvisor::DisplayTimingData::calculateDisplayTimeline(
- nsecs_t fenceTime) {
+ TimePoint fenceTime) {
DisplayTimeline timeline;
// How long between calling hwc present and trying to wait on the fence
- const nsecs_t fenceWaitStartDelay =
- (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated)
- .count();
+ const Duration fenceWaitStartDelay =
+ (skippedValidate ? kFenceWaitStartDelaySkippedValidate : kFenceWaitStartDelayValidated);
// Did our reference frame wait for an appropriate vsync before calling into hwc
const bool waitedOnHwcPresentTime = hwcPresentDelayedTime.has_value() &&
@@ -522,7 +520,7 @@
// How long hwc present was delayed waiting for the next appropriate vsync
timeline.hwcPresentDelayDuration =
- (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0);
+ (waitedOnHwcPresentTime ? *hwcPresentDelayedTime - *hwcPresentStartTime : 0ns);
// When we started waiting for the present fence after calling into hwc present
timeline.presentFenceWaitStartTime =
timeline.hwcPresentStartTime + timeline.hwcPresentDelayDuration + fenceWaitStartDelay;
@@ -537,23 +535,26 @@
}
std::optional<PowerAdvisor::GpuTimeline> PowerAdvisor::DisplayTimingData::estimateGpuTiming(
- std::optional<nsecs_t> previousEnd) {
+ std::optional<TimePoint> previousEndTime) {
if (!(usedClientComposition && lastValidGpuStartTime.has_value() && gpuEndFenceTime)) {
return std::nullopt;
}
- const nsecs_t latestGpuStartTime = std::max(previousEnd.value_or(0), *gpuStartTime);
- const nsecs_t latestGpuEndTime = gpuEndFenceTime->getSignalTime();
- nsecs_t gpuDuration = 0;
- if (latestGpuEndTime != Fence::SIGNAL_TIME_INVALID &&
- latestGpuEndTime != Fence::SIGNAL_TIME_PENDING) {
+ const TimePoint latestGpuStartTime =
+ std::max(previousEndTime.value_or(TimePoint{0ns}), *gpuStartTime);
+ const nsecs_t gpuEndFenceSignal = gpuEndFenceTime->getSignalTime();
+ Duration gpuDuration{0ns};
+ if (gpuEndFenceSignal != Fence::SIGNAL_TIME_INVALID &&
+ gpuEndFenceSignal != Fence::SIGNAL_TIME_PENDING) {
+ const TimePoint latestGpuEndTime = TimePoint::fromNs(gpuEndFenceSignal);
+
// If we know how long the most recent gpu duration was, use that
gpuDuration = latestGpuEndTime - latestGpuStartTime;
} else if (lastValidGpuEndTime.has_value()) {
// If we don't have the fence data, use the most recent information we do have
gpuDuration = *lastValidGpuEndTime - *lastValidGpuStartTime;
- if (latestGpuEndTime == Fence::SIGNAL_TIME_PENDING) {
+ if (gpuEndFenceSignal == Fence::SIGNAL_TIME_PENDING) {
// If pending but went over the previous duration, use current time as the end
- gpuDuration = std::max(gpuDuration, systemTime() - latestGpuStartTime);
+ gpuDuration = std::max(gpuDuration, Duration{TimePoint::now() - latestGpuStartTime});
}
}
return GpuTimeline{.duration = gpuDuration, .startTime = latestGpuStartTime};
@@ -614,15 +615,15 @@
bool startPowerHintSession() override { return false; }
- void setTargetWorkDuration(int64_t) override {}
+ void setTargetWorkDuration(Duration) override {}
- void sendActualWorkDuration(int64_t, nsecs_t) override {}
+ void sendActualWorkDuration(Duration, TimePoint) override {}
bool shouldReconnectHAL() override { return false; }
std::vector<int32_t> getPowerHintSessionThreadIds() override { return std::vector<int32_t>{}; }
- std::optional<int64_t> getTargetWorkDuration() override { return std::nullopt; }
+ std::optional<Duration> getTargetWorkDuration() override { return std::nullopt; }
private:
const sp<V1_3::IPower> mPowerHal = nullptr;
@@ -640,9 +641,6 @@
}
mSupportsPowerHint = checkPowerHintSessionSupported();
-
- // Currently set to 0 to disable rate limiter by default
- mAllowedActualDeviation = base::GetIntProperty<nsecs_t>("debug.sf.allowed_actual_deviation", 0);
}
AidlPowerHalWrapper::~AidlPowerHalWrapper() {
@@ -730,9 +728,9 @@
ALOGV("Cannot start power hint session, skipping");
return false;
}
- auto ret =
- mPowerHal->createHintSession(getpid(), static_cast<int32_t>(getuid()),
- mPowerHintThreadIds, mTargetDuration, &mPowerHintSession);
+ auto ret = mPowerHal->createHintSession(getpid(), static_cast<int32_t>(getuid()),
+ mPowerHintThreadIds, mTargetDuration.ns(),
+ &mPowerHintSession);
if (!ret.isOk()) {
ALOGW("Failed to start power hint session with error: %s",
ret.exceptionToString(ret.exceptionCode()).c_str());
@@ -742,14 +740,14 @@
return isPowerHintSessionRunning();
}
-void AidlPowerHalWrapper::setTargetWorkDuration(int64_t targetDuration) {
+void AidlPowerHalWrapper::setTargetWorkDuration(Duration targetDuration) {
ATRACE_CALL();
mTargetDuration = targetDuration;
- if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration);
+ if (sTraceHintSessionData) ATRACE_INT64("Time target", targetDuration.ns());
if (isPowerHintSessionRunning() && (targetDuration != mLastTargetDurationSent)) {
- ALOGV("Sending target time: %" PRId64 "ns", targetDuration);
+ ALOGV("Sending target time: %" PRId64 "ns", targetDuration.ns());
mLastTargetDurationSent = targetDuration;
- auto ret = mPowerHintSession->updateTargetWorkDuration(targetDuration);
+ auto ret = mPowerHintSession->updateTargetWorkDuration(targetDuration.ns());
if (!ret.isOk()) {
ALOGW("Failed to set power hint target work duration with error: %s",
ret.exceptionMessage().c_str());
@@ -758,65 +756,40 @@
}
}
-bool AidlPowerHalWrapper::shouldReportActualDurations() {
- // Report if we have never reported before or will go stale next frame
- if (!mLastActualDurationSent.has_value() ||
- (mLastTargetDurationSent + systemTime() - mLastActualReportTimestamp) >
- kStaleTimeout.count()) {
- return true;
- }
-
- if (!mActualDuration.has_value()) {
- return false;
- }
- // Report if the change in actual duration exceeds the threshold
- return abs(*mActualDuration - *mLastActualDurationSent) > mAllowedActualDeviation;
-}
-
-void AidlPowerHalWrapper::sendActualWorkDuration(int64_t actualDuration, nsecs_t timestamp) {
+void AidlPowerHalWrapper::sendActualWorkDuration(Duration actualDuration, TimePoint timestamp) {
ATRACE_CALL();
-
- if (actualDuration < 0 || !isPowerHintSessionRunning()) {
+ if (actualDuration < 0ns || !isPowerHintSessionRunning()) {
ALOGV("Failed to send actual work duration, skipping");
return;
}
- const nsecs_t reportedDuration = actualDuration;
-
- mActualDuration = reportedDuration;
+ mActualDuration = actualDuration;
WorkDuration duration;
- duration.durationNanos = reportedDuration;
- duration.timeStampNanos = timestamp;
+ duration.durationNanos = actualDuration.ns();
+ duration.timeStampNanos = timestamp.ns();
mPowerHintQueue.push_back(duration);
if (sTraceHintSessionData) {
- ATRACE_INT64("Measured duration", actualDuration);
- ATRACE_INT64("Target error term", actualDuration - mTargetDuration);
+ ATRACE_INT64("Measured duration", actualDuration.ns());
+ ATRACE_INT64("Target error term", Duration{actualDuration - mTargetDuration}.ns());
- ATRACE_INT64("Reported duration", reportedDuration);
- ATRACE_INT64("Reported target", mLastTargetDurationSent);
- ATRACE_INT64("Reported target error term", reportedDuration - mLastTargetDurationSent);
+ ATRACE_INT64("Reported duration", actualDuration.ns());
+ ATRACE_INT64("Reported target", mLastTargetDurationSent.ns());
+ ATRACE_INT64("Reported target error term",
+ Duration{actualDuration - mLastTargetDurationSent}.ns());
}
ALOGV("Sending actual work duration of: %" PRId64 " on reported target: %" PRId64
" with error: %" PRId64,
- reportedDuration, mLastTargetDurationSent, reportedDuration - mLastTargetDurationSent);
+ actualDuration.ns(), mLastTargetDurationSent.ns(),
+ Duration{actualDuration - mLastTargetDurationSent}.ns());
- // This rate limiter queues similar duration reports to the powerhal into
- // batches to avoid excessive binder calls. The criteria to send a given batch
- // are outlined in shouldReportActualDurationsNow()
- if (shouldReportActualDurations()) {
- ALOGV("Sending hint update batch");
- mLastActualReportTimestamp = systemTime();
- auto ret = mPowerHintSession->reportActualWorkDuration(mPowerHintQueue);
- if (!ret.isOk()) {
- ALOGW("Failed to report actual work durations with error: %s",
- ret.exceptionMessage().c_str());
- mShouldReconnectHal = true;
- }
- mPowerHintQueue.clear();
- // We save the actual duration here for rate limiting
- mLastActualDurationSent = actualDuration;
+ auto ret = mPowerHintSession->reportActualWorkDuration(mPowerHintQueue);
+ if (!ret.isOk()) {
+ ALOGW("Failed to report actual work durations with error: %s",
+ ret.exceptionMessage().c_str());
+ mShouldReconnectHal = true;
}
+ mPowerHintQueue.clear();
}
bool AidlPowerHalWrapper::shouldReconnectHAL() {
@@ -827,14 +800,10 @@
return mPowerHintThreadIds;
}
-std::optional<int64_t> AidlPowerHalWrapper::getTargetWorkDuration() {
+std::optional<Duration> AidlPowerHalWrapper::getTargetWorkDuration() {
return mTargetDuration;
}
-void AidlPowerHalWrapper::setAllowedActualDeviation(nsecs_t allowedDeviation) {
- mAllowedActualDeviation = allowedDeviation;
-}
-
const bool AidlPowerHalWrapper::sTraceHintSessionData =
base::GetBoolProperty(std::string("debug.sf.trace_hint_sessions"), false);
@@ -845,7 +814,7 @@
// Grab old hint session values before we destroy any existing wrapper
std::vector<int32_t> oldPowerHintSessionThreadIds;
- std::optional<int64_t> oldTargetWorkDuration;
+ std::optional<Duration> oldTargetWorkDuration;
if (mHalWrapper != nullptr) {
oldPowerHintSessionThreadIds = mHalWrapper->getPowerHintSessionThreadIds();
diff --git a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
index 53db612..1c9d123 100644
--- a/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
+++ b/services/surfaceflinger/DisplayHardware/PowerAdvisor.h
@@ -27,6 +27,7 @@
#include <android/hardware/power/IPower.h>
#include <compositionengine/impl/OutputCompositionState.h>
+#include <scheduler/Time.h>
#include <ui/DisplayIdentification.h>
#include "../Scheduler/OneShotTimer.h"
@@ -53,7 +54,7 @@
virtual bool supportsPowerHintSession() = 0;
virtual bool isPowerHintSessionRunning() = 0;
// Sends a power hint that updates to the target work duration for the frame
- virtual void setTargetWorkDuration(nsecs_t targetDuration) = 0;
+ virtual void setTargetWorkDuration(Duration targetDuration) = 0;
// Sends a power hint for the actual known work duration at the end of the frame
virtual void sendActualWorkDuration() = 0;
// Sends a power hint for the upcoming frame predicted from previous frame timing
@@ -65,33 +66,33 @@
// Provides PowerAdvisor with a copy of the gpu fence so it can determine the gpu end time
virtual void setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime) = 0;
// Reports the start and end times of a hwc validate call this frame for a given display
- virtual void setHwcValidateTiming(DisplayId displayId, nsecs_t validateStartTime,
- nsecs_t validateEndTime) = 0;
+ virtual void setHwcValidateTiming(DisplayId displayId, TimePoint validateStartTime,
+ TimePoint validateEndTime) = 0;
// Reports the start and end times of a hwc present call this frame for a given display
- virtual void setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
- nsecs_t presentEndTime) = 0;
+ virtual void setHwcPresentTiming(DisplayId displayId, TimePoint presentStartTime,
+ TimePoint presentEndTime) = 0;
// Reports the expected time that the current frame will present to the display
- virtual void setExpectedPresentTime(nsecs_t expectedPresentTime) = 0;
+ virtual void setExpectedPresentTime(TimePoint expectedPresentTime) = 0;
// Reports the most recent present fence time and end time once known
- virtual void setSfPresentTiming(nsecs_t presentFenceTime, nsecs_t presentEndTime) = 0;
+ virtual void setSfPresentTiming(TimePoint presentFenceTime, TimePoint presentEndTime) = 0;
// Reports whether a display used client composition this frame
virtual void setRequiresClientComposition(DisplayId displayId,
bool requiresClientComposition) = 0;
// Reports whether a given display skipped validation this frame
virtual void setSkippedValidate(DisplayId displayId, bool skipped) = 0;
// Reports when a hwc present is delayed, and the time that it will resume
- virtual void setHwcPresentDelayedTime(
- DisplayId displayId, std::chrono::steady_clock::time_point earliestFrameStartTime) = 0;
+ virtual void setHwcPresentDelayedTime(DisplayId displayId,
+ TimePoint earliestFrameStartTime) = 0;
// Reports the start delay for SurfaceFlinger this frame
- virtual void setFrameDelay(nsecs_t frameDelayDuration) = 0;
+ virtual void setFrameDelay(Duration frameDelayDuration) = 0;
// Reports the SurfaceFlinger commit start time this frame
- virtual void setCommitStart(nsecs_t commitStartTime) = 0;
+ virtual void setCommitStart(TimePoint commitStartTime) = 0;
// Reports the SurfaceFlinger composite end time this frame
- virtual void setCompositeEnd(nsecs_t compositeEndTime) = 0;
+ virtual void setCompositeEnd(TimePoint compositeEndTime) = 0;
// Reports the list of the currently active displays
virtual void setDisplays(std::vector<DisplayId>& displayIds) = 0;
// Sets the target duration for the entire pipeline including the gpu
- virtual void setTotalFrameTargetWorkDuration(nsecs_t targetDuration) = 0;
+ virtual void setTotalFrameTargetWorkDuration(Duration targetDuration) = 0;
};
namespace impl {
@@ -111,11 +112,11 @@
virtual void restartPowerHintSession() = 0;
virtual void setPowerHintSessionThreadIds(const std::vector<int32_t>& threadIds) = 0;
virtual bool startPowerHintSession() = 0;
- virtual void setTargetWorkDuration(nsecs_t targetDuration) = 0;
- virtual void sendActualWorkDuration(nsecs_t actualDuration, nsecs_t timestamp) = 0;
+ virtual void setTargetWorkDuration(Duration targetDuration) = 0;
+ virtual void sendActualWorkDuration(Duration actualDuration, TimePoint timestamp) = 0;
virtual bool shouldReconnectHAL() = 0;
virtual std::vector<int32_t> getPowerHintSessionThreadIds() = 0;
- virtual std::optional<nsecs_t> getTargetWorkDuration() = 0;
+ virtual std::optional<Duration> getTargetWorkDuration() = 0;
};
PowerAdvisor(SurfaceFlinger& flinger);
@@ -129,29 +130,27 @@
bool usePowerHintSession() override;
bool supportsPowerHintSession() override;
bool isPowerHintSessionRunning() override;
- void setTargetWorkDuration(nsecs_t targetDuration) override;
+ void setTargetWorkDuration(Duration targetDuration) override;
void sendActualWorkDuration() override;
void sendPredictedWorkDuration() override;
void enablePowerHint(bool enabled) override;
bool startPowerHintSession(const std::vector<int32_t>& threadIds) override;
void setGpuFenceTime(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime);
- void setHwcValidateTiming(DisplayId displayId, nsecs_t valiateStartTime,
- nsecs_t validateEndTime) override;
- void setHwcPresentTiming(DisplayId displayId, nsecs_t presentStartTime,
- nsecs_t presentEndTime) override;
+ void setHwcValidateTiming(DisplayId displayId, TimePoint validateStartTime,
+ TimePoint validateEndTime) override;
+ void setHwcPresentTiming(DisplayId displayId, TimePoint presentStartTime,
+ TimePoint presentEndTime) override;
void setSkippedValidate(DisplayId displayId, bool skipped) override;
void setRequiresClientComposition(DisplayId displayId, bool requiresClientComposition) override;
- void setExpectedPresentTime(nsecs_t expectedPresentTime) override;
- void setSfPresentTiming(nsecs_t presentFenceTime, nsecs_t presentEndTime) override;
- void setHwcPresentDelayedTime(
- DisplayId displayId,
- std::chrono::steady_clock::time_point earliestFrameStartTime) override;
+ void setExpectedPresentTime(TimePoint expectedPresentTime) override;
+ void setSfPresentTiming(TimePoint presentFenceTime, TimePoint presentEndTime) override;
+ void setHwcPresentDelayedTime(DisplayId displayId, TimePoint earliestFrameStartTime) override;
- void setFrameDelay(nsecs_t frameDelayDuration) override;
- void setCommitStart(nsecs_t commitStartTime) override;
- void setCompositeEnd(nsecs_t compositeEndTime) override;
+ void setFrameDelay(Duration frameDelayDuration) override;
+ void setCommitStart(TimePoint commitStartTime) override;
+ void setCompositeEnd(TimePoint compositeEndTime) override;
void setDisplays(std::vector<DisplayId>& displayIds) override;
- void setTotalFrameTargetWorkDuration(nsecs_t targetDuration) override;
+ void setTotalFrameTargetWorkDuration(Duration targetDuration) override;
private:
friend class PowerAdvisorTest;
@@ -178,44 +177,45 @@
// Higher-level timing data used for estimation
struct DisplayTimeline {
// The start of hwc present, or the start of validate if it happened there instead
- nsecs_t hwcPresentStartTime = -1;
+ TimePoint hwcPresentStartTime;
// The end of hwc present or validate, whichever one actually presented
- nsecs_t hwcPresentEndTime = -1;
+ TimePoint hwcPresentEndTime;
// How long the actual hwc present was delayed after hwcPresentStartTime
- nsecs_t hwcPresentDelayDuration = 0;
+ Duration hwcPresentDelayDuration{0ns};
// When we think we started waiting for the present fence after calling into hwc present and
// after potentially waiting for the earliest present time
- nsecs_t presentFenceWaitStartTime = -1;
+ TimePoint presentFenceWaitStartTime;
// How long we ran after we finished waiting for the fence but before hwc present finished
- nsecs_t postPresentFenceHwcPresentDuration = 0;
+ Duration postPresentFenceHwcPresentDuration{0ns};
// Are we likely to have waited for the present fence during composition
bool probablyWaitsForPresentFence = false;
// Estimate one frame's timeline from that of a previous frame
- DisplayTimeline estimateTimelineFromReference(nsecs_t fenceTime, nsecs_t displayStartTime);
+ DisplayTimeline estimateTimelineFromReference(TimePoint fenceTime,
+ TimePoint displayStartTime);
};
struct GpuTimeline {
- nsecs_t duration = 0;
- nsecs_t startTime = -1;
+ Duration duration{0ns};
+ TimePoint startTime;
};
// Power hint session data recorded from the pipeline
struct DisplayTimingData {
std::unique_ptr<FenceTime> gpuEndFenceTime;
- std::optional<nsecs_t> gpuStartTime;
- std::optional<nsecs_t> lastValidGpuEndTime;
- std::optional<nsecs_t> lastValidGpuStartTime;
- std::optional<nsecs_t> hwcPresentStartTime;
- std::optional<nsecs_t> hwcPresentEndTime;
- std::optional<nsecs_t> hwcValidateStartTime;
- std::optional<nsecs_t> hwcValidateEndTime;
- std::optional<nsecs_t> hwcPresentDelayedTime;
+ std::optional<TimePoint> gpuStartTime;
+ std::optional<TimePoint> lastValidGpuEndTime;
+ std::optional<TimePoint> lastValidGpuStartTime;
+ std::optional<TimePoint> hwcPresentStartTime;
+ std::optional<TimePoint> hwcPresentEndTime;
+ std::optional<TimePoint> hwcValidateStartTime;
+ std::optional<TimePoint> hwcValidateEndTime;
+ std::optional<TimePoint> hwcPresentDelayedTime;
bool usedClientComposition = false;
bool skippedValidate = false;
// Calculate high-level timing milestones from more granular display timing data
- DisplayTimeline calculateDisplayTimeline(nsecs_t fenceTime);
+ DisplayTimeline calculateDisplayTimeline(TimePoint fenceTime);
// Estimate the gpu duration for a given display from previous gpu timing data
- std::optional<GpuTimeline> estimateGpuTiming(std::optional<nsecs_t> previousEnd);
+ std::optional<GpuTimeline> estimateGpuTiming(std::optional<TimePoint> previousEndTime);
};
template <class T, size_t N>
@@ -240,30 +240,31 @@
};
// Filter and sort the display ids by a given property
- std::vector<DisplayId> getOrderedDisplayIds(std::optional<nsecs_t> DisplayTimingData::*sortBy);
+ std::vector<DisplayId> getOrderedDisplayIds(
+ std::optional<TimePoint> DisplayTimingData::*sortBy);
// Estimates a frame's total work duration including gpu time.
// Runs either at the beginning or end of a frame, using the most recent data available
- std::optional<nsecs_t> estimateWorkDuration(bool earlyHint);
+ std::optional<Duration> estimateWorkDuration(bool earlyHint);
// There are two different targets and actual work durations we care about,
// this normalizes them together and takes the max of the two
- nsecs_t combineTimingEstimates(nsecs_t totalDuration, nsecs_t flingerDuration);
+ Duration combineTimingEstimates(Duration totalDuration, Duration flingerDuration);
std::unordered_map<DisplayId, DisplayTimingData> mDisplayTimingData;
// Current frame's delay
- nsecs_t mFrameDelayDuration = 0;
+ Duration mFrameDelayDuration{0ns};
// Last frame's post-composition duration
- nsecs_t mLastPostcompDuration = 0;
+ Duration mLastPostcompDuration{0ns};
// Buffer of recent commit start times
- RingBuffer<nsecs_t, 2> mCommitStartTimes;
+ RingBuffer<TimePoint, 2> mCommitStartTimes;
// Buffer of recent expected present times
- RingBuffer<nsecs_t, 2> mExpectedPresentTimes;
+ RingBuffer<TimePoint, 2> mExpectedPresentTimes;
// Most recent present fence time, provided by SF after composition engine finishes presenting
- nsecs_t mLastPresentFenceTime = -1;
+ TimePoint mLastPresentFenceTime;
// Most recent composition engine present end time, returned with the present fence from SF
- nsecs_t mLastSfPresentEndTime = -1;
+ TimePoint mLastSfPresentEndTime;
// Target duration for the entire pipeline including gpu
- std::optional<nsecs_t> mTotalFrameTargetDuration;
+ std::optional<Duration> mTotalFrameTargetDuration;
// Updated list of display IDs
std::vector<DisplayId> mDisplayIds;
@@ -273,11 +274,11 @@
// An adjustable safety margin which pads the "actual" value sent to PowerHAL,
// encouraging more aggressive boosting to give SurfaceFlinger a larger margin for error
- static constexpr const std::chrono::nanoseconds kTargetSafetyMargin = 1ms;
+ static constexpr const Duration kTargetSafetyMargin{1ms};
// How long we expect hwc to run after the present call until it waits for the fence
- static constexpr const std::chrono::nanoseconds kFenceWaitStartDelayValidated = 150us;
- static constexpr const std::chrono::nanoseconds kFenceWaitStartDelaySkippedValidate = 250us;
+ static constexpr const Duration kFenceWaitStartDelayValidated{150us};
+ static constexpr const Duration kFenceWaitStartDelaySkippedValidate{250us};
};
class AidlPowerHalWrapper : public PowerAdvisor::HalWrapper {
@@ -294,21 +295,17 @@
void restartPowerHintSession() override;
void setPowerHintSessionThreadIds(const std::vector<int32_t>& threadIds) override;
bool startPowerHintSession() override;
- void setTargetWorkDuration(nsecs_t targetDuration) override;
- void sendActualWorkDuration(nsecs_t actualDuration, nsecs_t timestamp) override;
+ void setTargetWorkDuration(Duration targetDuration) override;
+ void sendActualWorkDuration(Duration actualDuration, TimePoint timestamp) override;
bool shouldReconnectHAL() override;
std::vector<int32_t> getPowerHintSessionThreadIds() override;
- std::optional<nsecs_t> getTargetWorkDuration() override;
+ std::optional<Duration> getTargetWorkDuration() override;
private:
friend class AidlPowerHalWrapperTest;
bool checkPowerHintSessionSupported();
void closePowerHintSession();
- bool shouldReportActualDurations();
-
- // Used for testing
- void setAllowedActualDeviation(nsecs_t);
const sp<hardware::power::IPower> mPowerHal = nullptr;
bool mHasExpensiveRendering = false;
@@ -323,24 +320,15 @@
// Queue of actual durations saved to report
std::vector<hardware::power::WorkDuration> mPowerHintQueue;
// The latest values we have received for target and actual
- nsecs_t mTargetDuration = kDefaultTarget.count();
- std::optional<nsecs_t> mActualDuration;
+ Duration mTargetDuration = kDefaultTargetDuration;
+ std::optional<Duration> mActualDuration;
// The list of thread ids, stored so we can restart the session from this class if needed
std::vector<int32_t> mPowerHintThreadIds;
bool mSupportsPowerHint = false;
- // Keep track of the last messages sent for rate limiter change detection
- std::optional<nsecs_t> mLastActualDurationSent;
- // Timestamp of the last report we sent, used to avoid stale sessions
- nsecs_t mLastActualReportTimestamp = 0;
- nsecs_t mLastTargetDurationSent = kDefaultTarget.count();
- // Max amount the error term can vary without causing an actual value report
- nsecs_t mAllowedActualDeviation = -1;
+ Duration mLastTargetDurationSent = kDefaultTargetDuration;
// Whether we should emit ATRACE_INT data for hint sessions
static const bool sTraceHintSessionData;
- static constexpr const std::chrono::nanoseconds kDefaultTarget = 16ms;
- // Amount of time after the last message was sent before the session goes stale
- // actually 100ms but we use 80 here to give some slack
- static constexpr const std::chrono::nanoseconds kStaleTimeout = 80ms;
+ static constexpr Duration kDefaultTargetDuration{16ms};
};
} // namespace impl
diff --git a/services/surfaceflinger/EffectLayer.cpp b/services/surfaceflinger/EffectLayer.cpp
deleted file mode 100644
index d161c51..0000000
--- a/services/surfaceflinger/EffectLayer.cpp
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// TODO(b/129481165): remove the #pragma below and fix conversion issues
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wconversion"
-
-// #define LOG_NDEBUG 0
-#undef LOG_TAG
-#define LOG_TAG "EffectLayer"
-
-#include "EffectLayer.h"
-
-#include <stdint.h>
-#include <stdlib.h>
-#include <sys/types.h>
-
-#include <compositionengine/CompositionEngine.h>
-#include <compositionengine/LayerFECompositionState.h>
-#include <renderengine/RenderEngine.h>
-#include <ui/GraphicBuffer.h>
-#include <utils/Errors.h>
-#include <utils/Log.h>
-
-#include "DisplayDevice.h"
-#include "SurfaceFlinger.h"
-
-namespace android {
-// ---------------------------------------------------------------------------
-
-EffectLayer::EffectLayer(const LayerCreationArgs& args)
- : Layer(args),
- mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()} {}
-
-EffectLayer::~EffectLayer() = default;
-
-std::optional<compositionengine::LayerFE::LayerSettings> EffectLayer::prepareClientComposition(
- compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
- std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
- Layer::prepareClientComposition(targetSettings);
- // Nothing to render.
- if (!layerSettings) {
- return {};
- }
-
- // set the shadow for the layer if needed
- prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
-
- // If fill bounds are occluded or the fill color is invalid skip the fill settings.
- if (targetSettings.realContentIsVisible && fillsColor()) {
- // Set color for color fill settings.
- layerSettings->source.solidColor = getColor().rgb;
- return layerSettings;
- } else if (hasBlur() || drawShadows()) {
- layerSettings->skipContentDraw = true;
- return layerSettings;
- }
-
- return {};
-}
-
-bool EffectLayer::isVisible() const {
- return hasSomethingToDraw() && !isHiddenByPolicy() && (getAlpha() > 0.0_hf || hasBlur());
-}
-
-bool EffectLayer::setColor(const half3& color) {
- if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
- mDrawingState.color.b == color.b) {
- return false;
- }
-
- mDrawingState.sequence++;
- mDrawingState.color.r = color.r;
- mDrawingState.color.g = color.g;
- mDrawingState.color.b = color.b;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool EffectLayer::setDataspace(ui::Dataspace dataspace) {
- if (mDrawingState.dataspace == dataspace) {
- return false;
- }
-
- mDrawingState.sequence++;
- mDrawingState.dataspace = dataspace;
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-void EffectLayer::preparePerFrameCompositionState() {
- Layer::preparePerFrameCompositionState();
-
- auto* compositionState = editCompositionState();
- compositionState->color = getColor();
- compositionState->compositionType =
- aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
-}
-
-sp<compositionengine::LayerFE> EffectLayer::getCompositionEngineLayerFE() const {
- // There's no need to get a CE Layer if the EffectLayer isn't going to draw anything. In that
- // case, it acts more like a ContainerLayer so returning a null CE Layer makes more sense
- if (hasSomethingToDraw()) {
- return asLayerFE();
- } else {
- return nullptr;
- }
-}
-
-compositionengine::LayerFECompositionState* EffectLayer::editCompositionState() {
- return mCompositionState.get();
-}
-
-const compositionengine::LayerFECompositionState* EffectLayer::getCompositionState() const {
- return mCompositionState.get();
-}
-
-bool EffectLayer::isOpaque(const Layer::State& s) const {
- // Consider the layer to be opaque if its opaque flag is set or its effective
- // alpha (considering the alpha of its parents as well) is 1.0;
- return (s.flags & layer_state_t::eLayerOpaque) != 0 || (fillsColor() && getAlpha() == 1.0_hf);
-}
-
-ui::Dataspace EffectLayer::getDataSpace() const {
- return mDrawingState.dataspace;
-}
-
-sp<Layer> EffectLayer::createClone() {
- sp<EffectLayer> layer = mFlinger->getFactory().createEffectLayer(
- LayerCreationArgs(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata()));
- layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
- return layer;
-}
-
-bool EffectLayer::fillsColor() const {
- return mDrawingState.color.r >= 0.0_hf && mDrawingState.color.g >= 0.0_hf &&
- mDrawingState.color.b >= 0.0_hf;
-}
-
-bool EffectLayer::hasBlur() const {
- return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
-}
-
-} // namespace android
-
-// TODO(b/129481165): remove the #pragma below and fix conversion issues
-#pragma clang diagnostic pop // ignored "-Wconversion"
diff --git a/services/surfaceflinger/EffectLayer.h b/services/surfaceflinger/EffectLayer.h
deleted file mode 100644
index 747b0bf..0000000
--- a/services/surfaceflinger/EffectLayer.h
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2007 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-#pragma once
-
-#include <sys/types.h>
-
-#include <cstdint>
-
-#include "Layer.h"
-
-namespace android {
-
-// A layer that can render a combination of the following effects.
-// * fill the bounds of the layer with a color
-// * render a shadow cast by the bounds of the layer
-// If no effects are enabled, the layer is considered to be invisible.
-class EffectLayer : public Layer {
-public:
- explicit EffectLayer(const LayerCreationArgs&);
- ~EffectLayer() override;
-
- sp<compositionengine::LayerFE> getCompositionEngineLayerFE() const override;
- compositionengine::LayerFECompositionState* editCompositionState() override;
-
- const char* getType() const override { return "EffectLayer"; }
- bool isVisible() const override;
-
- bool setColor(const half3& color) override;
-
- bool setDataspace(ui::Dataspace dataspace) override;
-
- ui::Dataspace getDataSpace() const override;
-
- bool isOpaque(const Layer::State& s) const override;
-
-protected:
- /*
- * compositionengine::LayerFE overrides
- */
- const compositionengine::LayerFECompositionState* getCompositionState() const override;
- void preparePerFrameCompositionState() override;
- std::optional<compositionengine::LayerFE::LayerSettings> prepareClientComposition(
- compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings)
- const override;
-
- std::unique_ptr<compositionengine::LayerFECompositionState> mCompositionState;
-
- sp<Layer> createClone() override;
-
-private:
- // Returns true if there is a valid color to fill.
- bool fillsColor() const;
- // Returns true if this layer has a blur value.
- bool hasBlur() const;
- bool hasSomethingToDraw() const { return fillsColor() || drawShadows() || hasBlur(); }
-};
-
-} // namespace android
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 8a401eb..08b71c2 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -29,6 +29,7 @@
#include <android-base/stringprintf.h>
#include <android/native_window.h>
#include <binder/IPCThreadState.h>
+#include <compositionengine/CompositionEngine.h>
#include <compositionengine/Display.h>
#include <compositionengine/LayerFECompositionState.h>
#include <compositionengine/OutputLayer.h>
@@ -39,8 +40,10 @@
#include <ftl/enum.h>
#include <ftl/fake_guard.h>
#include <gui/BufferItem.h>
+#include <gui/GLConsumer.h>
#include <gui/LayerDebugInfo.h>
#include <gui/Surface.h>
+#include <gui/TraceUtils.h>
#include <math.h>
#include <private/android_filesystem_config.h>
#include <renderengine/RenderEngine.h>
@@ -62,10 +65,9 @@
#include <mutex>
#include <sstream>
-#include "Colorizer.h"
+#include "BufferStateLayer.h"
#include "DisplayDevice.h"
#include "DisplayHardware/HWComposer.h"
-#include "EffectLayer.h"
#include "FrameTimeline.h"
#include "FrameTracer/FrameTracer.h"
#include "LayerProtoHelper.h"
@@ -74,11 +76,72 @@
#include "TunnelModeEnabledReporter.h"
#define DEBUG_RESIZE 0
+#define EARLY_RELEASE_ENABLED false
namespace android {
namespace {
constexpr int kDumpTableRowLength = 159;
+
+static constexpr float defaultMaxLuminance = 1000.0;
+
const ui::Transform kIdentityTransform;
+
+constexpr mat4 inverseOrientation(uint32_t transform) {
+ const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
+ const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
+ const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
+ mat4 tr;
+
+ if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
+ tr = tr * rot90;
+ }
+ if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
+ tr = tr * flipH;
+ }
+ if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
+ tr = tr * flipV;
+ }
+ return inverse(tr);
+}
+
+bool assignTransform(ui::Transform* dst, ui::Transform& from) {
+ if (*dst == from) {
+ return false;
+ }
+ *dst = from;
+ return true;
+}
+
+TimeStats::SetFrameRateVote frameRateToSetFrameRateVotePayload(Layer::FrameRate frameRate) {
+ using FrameRateCompatibility = TimeStats::SetFrameRateVote::FrameRateCompatibility;
+ using Seamlessness = TimeStats::SetFrameRateVote::Seamlessness;
+ const auto frameRateCompatibility = [frameRate] {
+ switch (frameRate.type) {
+ case Layer::FrameRateCompatibility::Default:
+ return FrameRateCompatibility::Default;
+ case Layer::FrameRateCompatibility::ExactOrMultiple:
+ return FrameRateCompatibility::ExactOrMultiple;
+ default:
+ return FrameRateCompatibility::Undefined;
+ }
+ }();
+
+ const auto seamlessness = [frameRate] {
+ switch (frameRate.seamlessness) {
+ case scheduler::Seamlessness::OnlySeamless:
+ return Seamlessness::ShouldBeSeamless;
+ case scheduler::Seamlessness::SeamedAndSeamless:
+ return Seamlessness::NotRequired;
+ default:
+ return Seamlessness::Undefined;
+ }
+ }();
+
+ return TimeStats::SetFrameRateVote{.frameRate = frameRate.rate.getValue(),
+ .frameRateCompatibility = frameRateCompatibility,
+ .seamlessness = seamlessness};
+}
+
} // namespace
using namespace ftl::flag_operators;
@@ -100,7 +163,12 @@
mWindowType(static_cast<WindowInfo::Type>(
args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))),
mLayerCreationFlags(args.flags),
- mBorderEnabled(false) {
+ mBorderEnabled(false),
+ mTextureName(args.textureName),
+ mCompositionState{mFlinger->getCompositionEngine().createLayerFECompositionState()},
+ mHwcSlotGenerator(sp<HwcSlotGenerator>::make()) {
+ ALOGV("Creating Layer %s", getDebugName());
+
uint32_t layerFlags = 0;
if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden;
if (args.flags & ISurfaceComposerClient::eOpaque) layerFlags |= layer_state_t::eLayerOpaque;
@@ -124,6 +192,7 @@
mDrawingState.acquireFence = sp<Fence>::make(-1);
mDrawingState.acquireFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
mDrawingState.dataspace = ui::Dataspace::UNKNOWN;
+ mDrawingState.dataspaceRequested = false;
mDrawingState.hdrMetadata.validTypes = 0;
mDrawingState.surfaceDamageRegion = Region::INVALID_REGION;
mDrawingState.cornerRadius = 0.0f;
@@ -165,6 +234,11 @@
mOwnerUid = mCallingUid;
mOwnerPid = mCallingPid;
}
+
+ mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
+ mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
+ mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
+ mDrawingState.dataspace = ui::Dataspace::V0_SRGB;
}
void Layer::onFirstRef() {
@@ -172,6 +246,28 @@
}
Layer::~Layer() {
+ // The original layer and the clone layer share the same texture and buffer. Therefore, only
+ // one of the layers, in this case the original layer, needs to handle the deletion. The
+ // original layer and the clone should be removed at the same time so there shouldn't be any
+ // issue with the clone layer trying to use the texture.
+ if (mBufferInfo.mBuffer != nullptr) {
+ callReleaseBufferCallback(mDrawingState.releaseBufferListener,
+ mBufferInfo.mBuffer->getBuffer(), mBufferInfo.mFrameNumber,
+ mBufferInfo.mFence,
+ mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
+ mOwnerUid));
+ }
+ if (!isClone()) {
+ // The original layer and the clone layer share the same texture. Therefore, only one of
+ // the layers, in this case the original layer, needs to handle the deletion. The original
+ // layer and the clone should be removed at the same time so there shouldn't be any issue
+ // with the clone layer trying to use the deleted texture.
+ mFlinger->deleteTextureAsync(mTextureName);
+ }
+ const int32_t layerId = getSequence();
+ mFlinger->mTimeStats->onDestroy(layerId);
+ mFlinger->mFrameTracer->onDestroy(layerId);
+
sp<Client> c(mClientRef.promote());
if (c != 0) {
c->detachLayer(this);
@@ -204,13 +300,6 @@
// callbacks
// ---------------------------------------------------------------------------
-/*
- * onLayerDisplayed is only meaningful for BufferLayer, but, is called through
- * Layer. So, the implementation is done in BufferLayer. When called on a
- * EffectLayer object, it's essentially a NOP.
- */
-void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult>) {}
-
void Layer::removeRelativeZ(const std::vector<Layer*>& layersInTree) {
if (mDrawingState.zOrderRelativeOf == nullptr) {
return;
@@ -376,6 +465,10 @@
for (const sp<Layer>& child : mDrawingChildren) {
child->computeBounds(mBounds, mEffectiveTransform, childShadowRadius);
}
+
+ if (mPotentialCursor) {
+ prepareCursorCompositionState();
+ }
}
Rect Layer::getCroppedBufferSize(const State& s) const {
@@ -499,6 +592,46 @@
// Retrieve it from the scheduler which maintains an instance of LayerHistory, and store it in
// LayerFECompositionState where it would be visible to Flattener.
compositionState->fps = mFlinger->getLayerFramerate(systemTime(), getSequence());
+
+ if (hasBufferOrSidebandStream()) {
+ preparePerFrameBufferCompositionState();
+ } else {
+ preparePerFrameEffectsCompositionState();
+ }
+}
+
+void Layer::preparePerFrameBufferCompositionState() {
+ // Sideband layers
+ auto* compositionState = editCompositionState();
+ if (compositionState->sidebandStream.get() && !compositionState->sidebandStreamHasFrame) {
+ compositionState->compositionType =
+ aidl::android::hardware::graphics::composer3::Composition::SIDEBAND;
+ return;
+ } else if ((mDrawingState.flags & layer_state_t::eLayerIsDisplayDecoration) != 0) {
+ compositionState->compositionType =
+ aidl::android::hardware::graphics::composer3::Composition::DISPLAY_DECORATION;
+ } else {
+ // Normal buffer layers
+ compositionState->hdrMetadata = mBufferInfo.mHdrMetadata;
+ compositionState->compositionType = mPotentialCursor
+ ? aidl::android::hardware::graphics::composer3::Composition::CURSOR
+ : aidl::android::hardware::graphics::composer3::Composition::DEVICE;
+ }
+
+ compositionState->buffer = getBuffer();
+ compositionState->bufferSlot = (mBufferInfo.mBufferSlot == BufferQueue::INVALID_BUFFER_SLOT)
+ ? 0
+ : mBufferInfo.mBufferSlot;
+ compositionState->acquireFence = mBufferInfo.mFence;
+ compositionState->frameNumber = mBufferInfo.mFrameNumber;
+ compositionState->sidebandStreamHasFrame = false;
+}
+
+void Layer::preparePerFrameEffectsCompositionState() {
+ auto* compositionState = editCompositionState();
+ compositionState->color = getColor();
+ compositionState->compositionType =
+ aidl::android::hardware::graphics::composer3::Composition::SOLID_COLOR;
}
void Layer::prepareCursorCompositionState() {
@@ -521,46 +654,6 @@
return sp<compositionengine::LayerFE>::fromExisting(layerFE);
}
-sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
- return nullptr;
-}
-
-compositionengine::LayerFECompositionState* Layer::editCompositionState() {
- return nullptr;
-}
-
-const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
- return nullptr;
-}
-
-bool Layer::onPreComposition(nsecs_t) {
- return false;
-}
-
-void Layer::prepareCompositionState(compositionengine::LayerFE::StateSubset subset) {
- using StateSubset = compositionengine::LayerFE::StateSubset;
-
- switch (subset) {
- case StateSubset::BasicGeometry:
- prepareBasicGeometryCompositionState();
- break;
-
- case StateSubset::GeometryAndContent:
- prepareBasicGeometryCompositionState();
- prepareGeometryCompositionState();
- preparePerFrameCompositionState();
- break;
-
- case StateSubset::Content:
- preparePerFrameCompositionState();
- break;
-
- case StateSubset::Cursor:
- prepareCursorCompositionState();
- break;
- }
-}
-
const char* Layer::getDebugName() const {
return mName.c_str();
}
@@ -571,6 +664,29 @@
std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientComposition(
compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
+ std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
+ prepareClientCompositionInternal(targetSettings);
+ // Nothing to render.
+ if (!layerSettings) {
+ return {};
+ }
+
+ // HWC requests to clear this layer.
+ if (targetSettings.clearContent) {
+ prepareClearClientComposition(*layerSettings, false /* blackout */);
+ return layerSettings;
+ }
+
+ // set the shadow for the layer if needed
+ prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
+
+ return layerSettings;
+}
+
+std::optional<compositionengine::LayerFE::LayerSettings> Layer::prepareClientCompositionInternal(
+ compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
+ ATRACE_CALL();
+
if (!getCompositionState()) {
return {};
}
@@ -632,6 +748,13 @@
layerSettings.stretchEffect = getStretchEffect();
// Record the name of the layer for debugging further down the stack.
layerSettings.name = getName();
+
+ if (hasEffect() && !hasBufferOrSidebandStream()) {
+ prepareEffectsClientComposition(layerSettings, targetSettings);
+ return layerSettings;
+ }
+
+ prepareBufferStateClientComposition(layerSettings, targetSettings);
return layerSettings;
}
@@ -648,6 +771,132 @@
layerSettings.name = getName();
}
+void Layer::prepareEffectsClientComposition(
+ compositionengine::LayerFE::LayerSettings& layerSettings,
+ compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
+ // If fill bounds are occluded or the fill color is invalid skip the fill settings.
+ if (targetSettings.realContentIsVisible && fillsColor()) {
+ // Set color for color fill settings.
+ layerSettings.source.solidColor = getColor().rgb;
+ } else if (hasBlur() || drawShadows()) {
+ layerSettings.skipContentDraw = true;
+ }
+}
+
+void Layer::prepareBufferStateClientComposition(
+ compositionengine::LayerFE::LayerSettings& layerSettings,
+ compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
+ if (CC_UNLIKELY(!mBufferInfo.mBuffer)) {
+ // For surfaceview of tv sideband, there is no activeBuffer
+ // in bufferqueue, we need return LayerSettings.
+ return;
+ }
+ const bool blackOutLayer = (isProtected() && !targetSettings.supportsProtectedContent) ||
+ ((isSecure() || isProtected()) && !targetSettings.isSecure);
+ const bool bufferCanBeUsedAsHwTexture =
+ mBufferInfo.mBuffer->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
+ if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
+ ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
+ mName.c_str());
+ prepareClearClientComposition(layerSettings, true /* blackout */);
+ return;
+ }
+
+ const State& s(getDrawingState());
+ layerSettings.source.buffer.buffer = mBufferInfo.mBuffer;
+ layerSettings.source.buffer.isOpaque = isOpaque(s);
+ layerSettings.source.buffer.fence = mBufferInfo.mFence;
+ layerSettings.source.buffer.textureName = mTextureName;
+ layerSettings.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
+ layerSettings.source.buffer.isY410BT2020 = isHdrY410();
+ bool hasSmpte2086 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::SMPTE2086;
+ bool hasCta861_3 = mBufferInfo.mHdrMetadata.validTypes & HdrMetadata::CTA861_3;
+ float maxLuminance = 0.f;
+ if (hasSmpte2086 && hasCta861_3) {
+ maxLuminance = std::min(mBufferInfo.mHdrMetadata.smpte2086.maxLuminance,
+ mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel);
+ } else if (hasSmpte2086) {
+ maxLuminance = mBufferInfo.mHdrMetadata.smpte2086.maxLuminance;
+ } else if (hasCta861_3) {
+ maxLuminance = mBufferInfo.mHdrMetadata.cta8613.maxContentLightLevel;
+ } else {
+ switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
+ case HAL_DATASPACE_TRANSFER_ST2084:
+ case HAL_DATASPACE_TRANSFER_HLG:
+ // Behavior-match previous releases for HDR content
+ maxLuminance = defaultMaxLuminance;
+ break;
+ }
+ }
+ layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
+ layerSettings.frameNumber = mCurrentFrameNumber;
+ layerSettings.bufferId = mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getId() : 0;
+
+ const bool useFiltering =
+ targetSettings.needsFiltering || mNeedsFiltering || bufferNeedsFiltering();
+
+ // Query the texture matrix given our current filtering mode.
+ float textureMatrix[16];
+ getDrawingTransformMatrix(useFiltering, textureMatrix);
+
+ if (getTransformToDisplayInverse()) {
+ /*
+ * the code below applies the primary display's inverse transform to
+ * the texture transform
+ */
+ uint32_t transform = DisplayDevice::getPrimaryDisplayRotationFlags();
+ mat4 tr = inverseOrientation(transform);
+
+ /**
+ * TODO(b/36727915): This is basically a hack.
+ *
+ * Ensure that regardless of the parent transformation,
+ * this buffer is always transformed from native display
+ * orientation to display orientation. For example, in the case
+ * of a camera where the buffer remains in native orientation,
+ * we want the pixels to always be upright.
+ */
+ sp<Layer> p = mDrawingParent.promote();
+ if (p != nullptr) {
+ const auto parentTransform = p->getTransform();
+ tr = tr * inverseOrientation(parentTransform.getOrientation());
+ }
+
+ // and finally apply it to the original texture matrix
+ const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
+ memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
+ }
+
+ const Rect win{getBounds()};
+ float bufferWidth = getBufferSize(s).getWidth();
+ float bufferHeight = getBufferSize(s).getHeight();
+
+ // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
+ // been set and there is no parent layer bounds. In that case, the scale is meaningless so
+ // ignore them.
+ if (!getBufferSize(s).isValid()) {
+ bufferWidth = float(win.right) - float(win.left);
+ bufferHeight = float(win.bottom) - float(win.top);
+ }
+
+ const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
+ const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
+ const float translateY = float(win.top) / bufferHeight;
+ const float translateX = float(win.left) / bufferWidth;
+
+ // Flip y-coordinates because GLConsumer expects OpenGL convention.
+ mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
+ mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
+ mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
+ mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
+
+ layerSettings.source.buffer.useTextureFiltering = useFiltering;
+ layerSettings.source.buffer.textureTransform =
+ mat4(static_cast<const float*>(textureMatrix)) * tr;
+
+ return;
+}
+
aidl::android::hardware::graphics::composer3::Composition Layer::getCompositionType(
const DisplayDevice& display) const {
const auto outputLayer = findOutputLayerForDisplay(&display);
@@ -736,16 +985,6 @@
mTransactionFlags |= mask;
}
-bool Layer::setPosition(float x, float y) {
- if (mDrawingState.transform.tx() == x && mDrawingState.transform.ty() == y) return false;
- mDrawingState.sequence++;
- mDrawingState.transform.set(x, y);
-
- mDrawingState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
ssize_t idx = mCurrentChildren.indexOf(childLayer);
if (idx < 0) {
@@ -939,24 +1178,6 @@
setTransactionFlags(eTransactionNeeded);
return true;
}
-bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
- if (matrix.dsdx == mDrawingState.transform.dsdx() &&
- matrix.dtdy == mDrawingState.transform.dtdy() &&
- matrix.dtdx == mDrawingState.transform.dtdx() &&
- matrix.dsdy == mDrawingState.transform.dsdy()) {
- return false;
- }
-
- ui::Transform t;
- t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
-
- mDrawingState.sequence++;
- mDrawingState.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
- mDrawingState.modified = true;
-
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
bool Layer::setTransparentRegionHint(const Region& transparent) {
mDrawingState.sequence++;
@@ -1964,8 +2185,8 @@
renderengine::ShadowSettings state = mFlinger->mDrawingState.globalShadowSettings;
// Note: this preserves existing behavior of shadowing the entire layer and not cropping it if
- // transparent regions are present. This may not be necessary since shadows are only cast by
- // SurfaceFlinger's EffectLayers, which do not typically use transparent regions.
+ // transparent regions are present. This may not be necessary since shadows are typically cast
+ // by layers without transparent regions.
state.boundaries = mBounds;
// Shift the spot light x-position to the middle of the display and then
@@ -2188,14 +2409,6 @@
return mRemovedFromDrawingState;
}
-ui::Transform Layer::getInputTransform() const {
- return getTransform();
-}
-
-Rect Layer::getInputBounds() const {
- return getCroppedBufferSize(getDrawingState());
-}
-
// Applies the given transform to the region, while protecting against overflows caused by any
// offsets. If applying the offset in the transform to any of the Rects in the region would result
// in an overflow, they are not added to the output Region.
@@ -2459,10 +2672,6 @@
mDrawingState.inputInfo.inputConfig.test(WindowInfo::InputConfig::NO_INPUT_CHANNEL);
}
-bool Layer::canReceiveInput() const {
- return !isHiddenByPolicy();
-}
-
compositionengine::OutputLayer* Layer::findOutputLayerForDisplay(
const DisplayDevice* display) const {
if (!display) return nullptr;
@@ -2477,6 +2686,40 @@
void Layer::setInitialValuesForClone(const sp<Layer>& clonedFrom) {
cloneDrawingState(clonedFrom.get());
mClonedFrom = clonedFrom;
+ mPremultipliedAlpha = clonedFrom->mPremultipliedAlpha;
+ mPotentialCursor = clonedFrom->mPotentialCursor;
+ mProtectedByApp = clonedFrom->mProtectedByApp;
+ updateCloneBufferInfo();
+}
+
+void Layer::updateCloneBufferInfo() {
+ if (!isClone() || !isClonedFromAlive()) {
+ return;
+ }
+
+ sp<Layer> clonedFrom = getClonedFrom();
+ mBufferInfo = clonedFrom->mBufferInfo;
+ mSidebandStream = clonedFrom->mSidebandStream;
+ surfaceDamageRegion = clonedFrom->surfaceDamageRegion;
+ mCurrentFrameNumber = clonedFrom->mCurrentFrameNumber.load();
+ mPreviousFrameNumber = clonedFrom->mPreviousFrameNumber;
+
+ // After buffer info is updated, the drawingState from the real layer needs to be copied into
+ // the cloned. This is because some properties of drawingState can change when latchBuffer is
+ // called. However, copying the drawingState would also overwrite the cloned layer's relatives
+ // and touchableRegionCrop. Therefore, temporarily store the relatives so they can be set in
+ // the cloned drawingState again.
+ wp<Layer> tmpZOrderRelativeOf = mDrawingState.zOrderRelativeOf;
+ SortedVector<wp<Layer>> tmpZOrderRelatives = mDrawingState.zOrderRelatives;
+ wp<Layer> tmpTouchableRegionCrop = mDrawingState.touchableRegionCrop;
+ WindowInfo tmpInputInfo = mDrawingState.inputInfo;
+
+ cloneDrawingState(clonedFrom.get());
+
+ mDrawingState.touchableRegionCrop = tmpTouchableRegionCrop;
+ mDrawingState.zOrderRelativeOf = tmpZOrderRelativeOf;
+ mDrawingState.zOrderRelatives = tmpZOrderRelatives;
+ mDrawingState.inputInfo = tmpInputInfo;
}
void Layer::updateMirrorInfo() {
@@ -2684,18 +2927,1311 @@
mDrawingState.callbackHandles = {};
}
-bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
- if (handles.empty()) {
+void Layer::callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
+ const sp<GraphicBuffer>& buffer, uint64_t framenumber,
+ const sp<Fence>& releaseFence,
+ uint32_t currentMaxAcquiredBufferCount) {
+ if (!listener) {
+ return;
+ }
+ ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber);
+ listener->onReleaseBuffer({buffer->getId(), framenumber},
+ releaseFence ? releaseFence : Fence::NO_FENCE,
+ currentMaxAcquiredBufferCount);
+}
+
+void Layer::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult) {
+ // If we are displayed on multiple displays in a single composition cycle then we would
+ // need to do careful tracking to enable the use of the mLastClientCompositionFence.
+ // For example we can only use it if all the displays are client comp, and we need
+ // to merge all the client comp fences. We could do this, but for now we just
+ // disable the optimization when a layer is composed on multiple displays.
+ if (mClearClientCompositionFenceOnLayerDisplayed) {
+ mLastClientCompositionFence = nullptr;
+ } else {
+ mClearClientCompositionFenceOnLayerDisplayed = true;
+ }
+
+ // The previous release fence notifies the client that SurfaceFlinger is done with the previous
+ // buffer that was presented on this layer. The first transaction that came in this frame that
+ // replaced the previous buffer on this layer needs this release fence, because the fence will
+ // let the client know when that previous buffer is removed from the screen.
+ //
+ // Every other transaction on this layer does not need a release fence because no other
+ // Transactions that were set on this layer this frame are going to have their preceding buffer
+ // removed from the display this frame.
+ //
+ // For example, if we have 3 transactions this frame. The first transaction doesn't contain a
+ // buffer so it doesn't need a previous release fence because the layer still needs the previous
+ // buffer. The second transaction contains a buffer so it needs a previous release fence because
+ // the previous buffer will be released this frame. The third transaction also contains a
+ // buffer. It replaces the buffer in the second transaction. The buffer in the second
+ // transaction will now no longer be presented so it is released immediately and the third
+ // transaction doesn't need a previous release fence.
+ sp<CallbackHandle> ch;
+ for (auto& handle : mDrawingState.callbackHandles) {
+ if (handle->releasePreviousBuffer &&
+ mDrawingState.releaseBufferEndpoint == handle->listener) {
+ ch = handle;
+ break;
+ }
+ }
+
+ // Prevent tracing the same release multiple times.
+ if (mPreviousFrameNumber != mPreviousReleasedFrameNumber) {
+ mPreviousReleasedFrameNumber = mPreviousFrameNumber;
+ }
+
+ if (ch != nullptr) {
+ ch->previousReleaseCallbackId = mPreviousReleaseCallbackId;
+ ch->previousReleaseFences.emplace_back(std::move(futureFenceResult));
+ ch->name = mName;
+ }
+}
+
+void Layer::onSurfaceFrameCreated(
+ const std::shared_ptr<frametimeline::SurfaceFrame>& surfaceFrame) {
+ while (mPendingJankClassifications.size() >= kPendingClassificationMaxSurfaceFrames) {
+ // Too many SurfaceFrames pending classification. The front of the deque is probably not
+ // tracked by FrameTimeline and will never be presented. This will only result in a memory
+ // leak.
+ ALOGW("Removing the front of pending jank deque from layer - %s to prevent memory leak",
+ mName.c_str());
+ std::string miniDump = mPendingJankClassifications.front()->miniDump();
+ ALOGD("Head SurfaceFrame mini dump\n%s", miniDump.c_str());
+ mPendingJankClassifications.pop_front();
+ }
+ mPendingJankClassifications.emplace_back(surfaceFrame);
+}
+
+void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
+ for (const auto& handle : mDrawingState.callbackHandles) {
+ handle->transformHint = mTransformHint;
+ handle->dequeueReadyTime = dequeueReadyTime;
+ handle->currentMaxAcquiredBufferCount =
+ mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mOwnerUid);
+ ATRACE_FORMAT_INSTANT("releasePendingBuffer %s - %" PRIu64, getDebugName(),
+ handle->previousReleaseCallbackId.framenumber);
+ }
+
+ for (auto& handle : mDrawingState.callbackHandles) {
+ if (handle->releasePreviousBuffer &&
+ mDrawingState.releaseBufferEndpoint == handle->listener) {
+ handle->previousReleaseCallbackId = mPreviousReleaseCallbackId;
+ break;
+ }
+ }
+
+ std::vector<JankData> jankData;
+ jankData.reserve(mPendingJankClassifications.size());
+ while (!mPendingJankClassifications.empty() &&
+ mPendingJankClassifications.front()->getJankType()) {
+ std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame =
+ mPendingJankClassifications.front();
+ mPendingJankClassifications.pop_front();
+ jankData.emplace_back(
+ JankData(surfaceFrame->getToken(), surfaceFrame->getJankType().value()));
+ }
+
+ mFlinger->getTransactionCallbackInvoker().addCallbackHandles(mDrawingState.callbackHandles,
+ jankData);
+
+ sp<Fence> releaseFence = Fence::NO_FENCE;
+ for (auto& handle : mDrawingState.callbackHandles) {
+ if (handle->releasePreviousBuffer &&
+ mDrawingState.releaseBufferEndpoint == handle->listener) {
+ releaseFence =
+ handle->previousReleaseFence ? handle->previousReleaseFence : Fence::NO_FENCE;
+ break;
+ }
+ }
+
+ mDrawingState.callbackHandles = {};
+}
+
+bool Layer::willPresentCurrentTransaction() const {
+ // Returns true if the most recent Transaction applied to CurrentState will be presented.
+ return (getSidebandStreamChanged() || getAutoRefresh() ||
+ (mDrawingState.modified &&
+ (mDrawingState.buffer != nullptr || mDrawingState.bgColorLayer != nullptr)));
+}
+
+bool Layer::setTransform(uint32_t transform) {
+ if (mDrawingState.bufferTransform == transform) return false;
+ mDrawingState.bufferTransform = transform;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
+ if (mDrawingState.transformToDisplayInverse == transformToDisplayInverse) return false;
+ mDrawingState.sequence++;
+ mDrawingState.transformToDisplayInverse = transformToDisplayInverse;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setBufferCrop(const Rect& bufferCrop) {
+ if (mDrawingState.bufferCrop == bufferCrop) return false;
+
+ mDrawingState.sequence++;
+ mDrawingState.bufferCrop = bufferCrop;
+
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setDestinationFrame(const Rect& destinationFrame) {
+ if (mDrawingState.destinationFrame == destinationFrame) return false;
+
+ mDrawingState.sequence++;
+ mDrawingState.destinationFrame = destinationFrame;
+
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+// Translate destination frame into scale and position. If a destination frame is not set, use the
+// provided scale and position
+bool Layer::updateGeometry() {
+ if ((mDrawingState.flags & layer_state_t::eIgnoreDestinationFrame) ||
+ mDrawingState.destinationFrame.isEmpty()) {
+ // If destination frame is not set, use the requested transform set via
+ // Layer::setPosition and Layer::setMatrix.
+ return assignTransform(&mDrawingState.transform, mRequestedTransform);
+ }
+
+ Rect destRect = mDrawingState.destinationFrame;
+ int32_t destW = destRect.width();
+ int32_t destH = destRect.height();
+ if (destRect.left < 0) {
+ destRect.left = 0;
+ destRect.right = destW;
+ }
+ if (destRect.top < 0) {
+ destRect.top = 0;
+ destRect.bottom = destH;
+ }
+
+ if (!mDrawingState.buffer) {
+ ui::Transform t;
+ t.set(destRect.left, destRect.top);
+ return assignTransform(&mDrawingState.transform, t);
+ }
+
+ uint32_t bufferWidth = mDrawingState.buffer->getWidth();
+ uint32_t bufferHeight = mDrawingState.buffer->getHeight();
+ // Undo any transformations on the buffer.
+ if (mDrawingState.bufferTransform & ui::Transform::ROT_90) {
+ std::swap(bufferWidth, bufferHeight);
+ }
+ uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
+ if (mDrawingState.transformToDisplayInverse) {
+ if (invTransform & ui::Transform::ROT_90) {
+ std::swap(bufferWidth, bufferHeight);
+ }
+ }
+
+ float sx = destW / static_cast<float>(bufferWidth);
+ float sy = destH / static_cast<float>(bufferHeight);
+ ui::Transform t;
+ t.set(sx, 0, 0, sy);
+ t.set(destRect.left, destRect.top);
+ return assignTransform(&mDrawingState.transform, t);
+}
+
+bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
+ if (mRequestedTransform.dsdx() == matrix.dsdx && mRequestedTransform.dtdy() == matrix.dtdy &&
+ mRequestedTransform.dtdx() == matrix.dtdx && mRequestedTransform.dsdy() == matrix.dsdy) {
return false;
}
+ mRequestedTransform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
+
+ mDrawingState.sequence++;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+
+ return true;
+}
+
+bool Layer::setPosition(float x, float y) {
+ if (mRequestedTransform.tx() == x && mRequestedTransform.ty() == y) {
+ return false;
+ }
+
+ mRequestedTransform.set(x, y);
+
+ mDrawingState.sequence++;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+
+ return true;
+}
+
+bool Layer::setBuffer(std::shared_ptr<renderengine::ExternalTexture>& buffer,
+ const BufferData& bufferData, nsecs_t postTime, nsecs_t desiredPresentTime,
+ bool isAutoTimestamp, std::optional<nsecs_t> dequeueTime,
+ const FrameTimelineInfo& info) {
+ ATRACE_CALL();
+
+ if (!buffer) {
+ return false;
+ }
+
+ const bool frameNumberChanged =
+ bufferData.flags.test(BufferData::BufferDataChange::frameNumberChanged);
+ const uint64_t frameNumber =
+ frameNumberChanged ? bufferData.frameNumber : mDrawingState.frameNumber + 1;
+
+ if (mDrawingState.buffer) {
+ mReleasePreviousBuffer = true;
+ if (!mBufferInfo.mBuffer ||
+ (!mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer) ||
+ mDrawingState.frameNumber != mBufferInfo.mFrameNumber)) {
+ // If mDrawingState has a buffer, and we are about to update again
+ // before swapping to drawing state, then the first buffer will be
+ // dropped and we should decrement the pending buffer count and
+ // call any release buffer callbacks if set.
+ callReleaseBufferCallback(mDrawingState.releaseBufferListener,
+ mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
+ mDrawingState.acquireFence,
+ mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
+ mOwnerUid));
+ decrementPendingBufferCount();
+ if (mDrawingState.bufferSurfaceFrameTX != nullptr &&
+ mDrawingState.bufferSurfaceFrameTX->getPresentState() != PresentState::Presented) {
+ addSurfaceFrameDroppedForBuffer(mDrawingState.bufferSurfaceFrameTX);
+ mDrawingState.bufferSurfaceFrameTX.reset();
+ }
+ } else if (EARLY_RELEASE_ENABLED && mLastClientCompositionFence != nullptr) {
+ callReleaseBufferCallback(mDrawingState.releaseBufferListener,
+ mDrawingState.buffer->getBuffer(), mDrawingState.frameNumber,
+ mLastClientCompositionFence,
+ mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(
+ mOwnerUid));
+ mLastClientCompositionFence = nullptr;
+ }
+ }
+
+ mDrawingState.frameNumber = frameNumber;
+ mDrawingState.releaseBufferListener = bufferData.releaseBufferListener;
+ mDrawingState.buffer = std::move(buffer);
+ mDrawingState.clientCacheId = bufferData.cachedBuffer;
+
+ mDrawingState.acquireFence = bufferData.flags.test(BufferData::BufferDataChange::fenceChanged)
+ ? bufferData.acquireFence
+ : Fence::NO_FENCE;
+ mDrawingState.acquireFenceTime = std::make_unique<FenceTime>(mDrawingState.acquireFence);
+ if (mDrawingState.acquireFenceTime->getSignalTime() == Fence::SIGNAL_TIME_PENDING) {
+ // We latched this buffer unsiganled, so we need to pass the acquire fence
+ // on the callback instead of just the acquire time, since it's unknown at
+ // this point.
+ mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFence;
+ } else {
+ mCallbackHandleAcquireTimeOrFence = mDrawingState.acquireFenceTime->getSignalTime();
+ }
+
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+
+ const int32_t layerId = getSequence();
+ mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(),
+ mOwnerUid, postTime, getGameMode());
+ mDrawingState.desiredPresentTime = desiredPresentTime;
+ mDrawingState.isAutoTimestamp = isAutoTimestamp;
+
+ const nsecs_t presentTime = [&] {
+ if (!isAutoTimestamp) return desiredPresentTime;
+
+ const auto prediction =
+ mFlinger->mFrameTimeline->getTokenManager()->getPredictionsForToken(info.vsyncId);
+ if (prediction.has_value()) return prediction->presentTime;
+
+ return static_cast<nsecs_t>(0);
+ }();
+
+ using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType;
+ mFlinger->mScheduler->recordLayerHistory(this, presentTime, LayerUpdateType::Buffer);
+
+ setFrameTimelineVsyncForBufferTransaction(info, postTime);
+
+ if (dequeueTime && *dequeueTime != 0) {
+ const uint64_t bufferId = mDrawingState.buffer->getId();
+ mFlinger->mFrameTracer->traceNewLayer(layerId, getName().c_str());
+ mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, *dequeueTime,
+ FrameTracer::FrameEvent::DEQUEUE);
+ mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, postTime,
+ FrameTracer::FrameEvent::QUEUE);
+ }
+
+ mDrawingState.releaseBufferEndpoint = bufferData.releaseBufferEndpoint;
+ return true;
+}
+
+bool Layer::setDataspace(ui::Dataspace dataspace) {
+ mDrawingState.dataspaceRequested = true;
+ if (mDrawingState.dataspace == dataspace) return false;
+ mDrawingState.dataspace = dataspace;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
+ if (mDrawingState.hdrMetadata == hdrMetadata) return false;
+ mDrawingState.hdrMetadata = hdrMetadata;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setSurfaceDamageRegion(const Region& surfaceDamage) {
+ mDrawingState.surfaceDamageRegion = surfaceDamage;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setApi(int32_t api) {
+ if (mDrawingState.api == api) return false;
+ mDrawingState.api = api;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
+ if (mDrawingState.sidebandStream == sidebandStream) return false;
+
+ if (mDrawingState.sidebandStream != nullptr && sidebandStream == nullptr) {
+ mFlinger->mTunnelModeEnabledReporter->decrementTunnelModeCount();
+ } else if (sidebandStream != nullptr) {
+ mFlinger->mTunnelModeEnabledReporter->incrementTunnelModeCount();
+ }
+
+ mDrawingState.sidebandStream = sidebandStream;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ if (!mSidebandStreamChanged.exchange(true)) {
+ // mSidebandStreamChanged was false
+ mFlinger->onLayerUpdate();
+ }
+ return true;
+}
+
+bool Layer::setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) {
+ // If there is no handle, we will not send a callback so reset mReleasePreviousBuffer and return
+ if (handles.empty()) {
+ mReleasePreviousBuffer = false;
+ return false;
+ }
+
+ const bool willPresent = willPresentCurrentTransaction();
+
for (const auto& handle : handles) {
- mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
+ // If this transaction set a buffer on this layer, release its previous buffer
+ handle->releasePreviousBuffer = mReleasePreviousBuffer;
+
+ // If this layer will be presented in this frame
+ if (willPresent) {
+ // If this transaction set an acquire fence on this layer, set its acquire time
+ handle->acquireTimeOrFence = mCallbackHandleAcquireTimeOrFence;
+ handle->frameNumber = mDrawingState.frameNumber;
+
+ // Store so latched time and release fence can be set
+ mDrawingState.callbackHandles.push_back(handle);
+
+ } else { // If this layer will NOT need to be relatched and presented this frame
+ // Notify the transaction completed thread this handle is done
+ mFlinger->getTransactionCallbackInvoker().registerUnpresentedCallbackHandle(handle);
+ }
+ }
+
+ mReleasePreviousBuffer = false;
+ mCallbackHandleAcquireTimeOrFence = -1;
+
+ return willPresent;
+}
+
+Rect Layer::getBufferSize(const State& /*s*/) const {
+ // for buffer state layers we use the display frame size as the buffer size.
+
+ if (mBufferInfo.mBuffer == nullptr) {
+ return Rect::INVALID_RECT;
+ }
+
+ uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
+ uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
+
+ // Undo any transformations on the buffer and return the result.
+ if (mBufferInfo.mTransform & ui::Transform::ROT_90) {
+ std::swap(bufWidth, bufHeight);
+ }
+
+ if (getTransformToDisplayInverse()) {
+ uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
+ if (invTransform & ui::Transform::ROT_90) {
+ std::swap(bufWidth, bufHeight);
+ }
+ }
+
+ return Rect(0, 0, static_cast<int32_t>(bufWidth), static_cast<int32_t>(bufHeight));
+}
+
+FloatRect Layer::computeSourceBounds(const FloatRect& parentBounds) const {
+ if (mBufferInfo.mBuffer == nullptr) {
+ return parentBounds;
+ }
+
+ return getBufferSize(getDrawingState()).toFloatRect();
+}
+
+bool Layer::fenceHasSignaled() const {
+ if (SurfaceFlinger::enableLatchUnsignaledConfig != LatchUnsignaledConfig::Disabled) {
+ return true;
+ }
+
+ const bool fenceSignaled =
+ getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
+ if (!fenceSignaled) {
+ mFlinger->mTimeStats->incrementLatchSkipped(getSequence(),
+ TimeStats::LatchSkipReason::LateAcquire);
+ }
+
+ return fenceSignaled;
+}
+
+bool Layer::onPreComposition(nsecs_t refreshStartTime, bool /* updatingOutputGeometryThisFrame */) {
+ for (const auto& handle : mDrawingState.callbackHandles) {
+ handle->refreshStartTime = refreshStartTime;
+ }
+ return hasReadyFrame();
+}
+
+void Layer::setAutoRefresh(bool autoRefresh) {
+ mDrawingState.autoRefresh = autoRefresh;
+}
+
+bool Layer::latchSidebandStream(bool& recomputeVisibleRegions) {
+ // We need to update the sideband stream if the layer has both a buffer and a sideband stream.
+ editCompositionState()->sidebandStreamHasFrame = hasFrameUpdate() && mSidebandStream.get();
+
+ if (mSidebandStreamChanged.exchange(false)) {
+ const State& s(getDrawingState());
+ // mSidebandStreamChanged was true
+ mSidebandStream = s.sidebandStream;
+ editCompositionState()->sidebandStream = mSidebandStream;
+ if (mSidebandStream != nullptr) {
+ setTransactionFlags(eTransactionNeeded);
+ mFlinger->setTransactionFlags(eTraversalNeeded);
+ }
+ recomputeVisibleRegions = true;
+
+ return true;
+ }
+ return false;
+}
+
+bool Layer::hasFrameUpdate() const {
+ const State& c(getDrawingState());
+ return (mDrawingStateModified || mDrawingState.modified) &&
+ (c.buffer != nullptr || c.bgColorLayer != nullptr);
+}
+
+void Layer::updateTexImage(nsecs_t latchTime) {
+ const State& s(getDrawingState());
+
+ if (!s.buffer) {
+ if (s.bgColorLayer) {
+ for (auto& handle : mDrawingState.callbackHandles) {
+ handle->latchTime = latchTime;
+ }
+ }
+ return;
+ }
+
+ for (auto& handle : mDrawingState.callbackHandles) {
+ if (handle->frameNumber == mDrawingState.frameNumber) {
+ handle->latchTime = latchTime;
+ }
+ }
+
+ const int32_t layerId = getSequence();
+ const uint64_t bufferId = mDrawingState.buffer->getId();
+ const uint64_t frameNumber = mDrawingState.frameNumber;
+ const auto acquireFence = std::make_shared<FenceTime>(mDrawingState.acquireFence);
+ mFlinger->mTimeStats->setAcquireFence(layerId, frameNumber, acquireFence);
+ mFlinger->mTimeStats->setLatchTime(layerId, frameNumber, latchTime);
+
+ mFlinger->mFrameTracer->traceFence(layerId, bufferId, frameNumber, acquireFence,
+ FrameTracer::FrameEvent::ACQUIRE_FENCE);
+ mFlinger->mFrameTracer->traceTimestamp(layerId, bufferId, frameNumber, latchTime,
+ FrameTracer::FrameEvent::LATCH);
+
+ auto& bufferSurfaceFrame = mDrawingState.bufferSurfaceFrameTX;
+ if (bufferSurfaceFrame != nullptr &&
+ bufferSurfaceFrame->getPresentState() != PresentState::Presented) {
+ // Update only if the bufferSurfaceFrame wasn't already presented. A Presented
+ // bufferSurfaceFrame could be seen here if a pending state was applied successfully and we
+ // are processing the next state.
+ addSurfaceFramePresentedForBuffer(bufferSurfaceFrame,
+ mDrawingState.acquireFenceTime->getSignalTime(),
+ latchTime);
+ mDrawingState.bufferSurfaceFrameTX.reset();
+ }
+
+ std::deque<sp<CallbackHandle>> remainingHandles;
+ mFlinger->getTransactionCallbackInvoker()
+ .addOnCommitCallbackHandles(mDrawingState.callbackHandles, remainingHandles);
+ mDrawingState.callbackHandles = remainingHandles;
+
+ mDrawingStateModified = false;
+}
+
+void Layer::gatherBufferInfo() {
+ if (!mBufferInfo.mBuffer || !mDrawingState.buffer->hasSameBuffer(*mBufferInfo.mBuffer)) {
+ decrementPendingBufferCount();
+ }
+
+ mPreviousReleaseCallbackId = {getCurrentBufferId(), mBufferInfo.mFrameNumber};
+ mBufferInfo.mBuffer = mDrawingState.buffer;
+ mBufferInfo.mFence = mDrawingState.acquireFence;
+ mBufferInfo.mFrameNumber = mDrawingState.frameNumber;
+ mBufferInfo.mPixelFormat =
+ !mBufferInfo.mBuffer ? PIXEL_FORMAT_NONE : mBufferInfo.mBuffer->getPixelFormat();
+ mBufferInfo.mFrameLatencyNeeded = true;
+ mBufferInfo.mDesiredPresentTime = mDrawingState.desiredPresentTime;
+ mBufferInfo.mFenceTime = std::make_shared<FenceTime>(mDrawingState.acquireFence);
+ mBufferInfo.mFence = mDrawingState.acquireFence;
+ mBufferInfo.mTransform = mDrawingState.bufferTransform;
+ auto lastDataspace = mBufferInfo.mDataspace;
+ mBufferInfo.mDataspace = translateDataspace(mDrawingState.dataspace);
+ if (lastDataspace != mBufferInfo.mDataspace) {
+ mFlinger->mSomeDataspaceChanged = true;
+ }
+ mBufferInfo.mCrop = computeBufferCrop(mDrawingState);
+ mBufferInfo.mScaleMode = NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW;
+ mBufferInfo.mSurfaceDamage = mDrawingState.surfaceDamageRegion;
+ mBufferInfo.mHdrMetadata = mDrawingState.hdrMetadata;
+ mBufferInfo.mApi = mDrawingState.api;
+ mBufferInfo.mTransformToDisplayInverse = mDrawingState.transformToDisplayInverse;
+ mBufferInfo.mBufferSlot = mHwcSlotGenerator->getHwcCacheSlot(mDrawingState.clientCacheId);
+}
+
+Rect Layer::computeBufferCrop(const State& s) {
+ if (s.buffer && !s.bufferCrop.isEmpty()) {
+ Rect bufferCrop;
+ s.buffer->getBounds().intersect(s.bufferCrop, &bufferCrop);
+ return bufferCrop;
+ } else if (s.buffer) {
+ return s.buffer->getBounds();
+ } else {
+ return s.bufferCrop;
+ }
+}
+
+sp<Layer> Layer::createClone() {
+ LayerCreationArgs args(mFlinger.get(), nullptr, mName + " (Mirror)", 0, LayerMetadata());
+ args.textureName = mTextureName;
+ sp<BufferStateLayer> layer = mFlinger->getFactory().createBufferStateLayer(args);
+ layer->mHwcSlotGenerator = mHwcSlotGenerator;
+ layer->setInitialValuesForClone(sp<Layer>::fromExisting(this));
+ return layer;
+}
+
+bool Layer::bufferNeedsFiltering() const {
+ const State& s(getDrawingState());
+ if (!s.buffer) {
+ return false;
+ }
+
+ int32_t bufferWidth = static_cast<int32_t>(s.buffer->getWidth());
+ int32_t bufferHeight = static_cast<int32_t>(s.buffer->getHeight());
+
+ // Undo any transformations on the buffer and return the result.
+ if (s.bufferTransform & ui::Transform::ROT_90) {
+ std::swap(bufferWidth, bufferHeight);
+ }
+
+ if (s.transformToDisplayInverse) {
+ uint32_t invTransform = DisplayDevice::getPrimaryDisplayRotationFlags();
+ if (invTransform & ui::Transform::ROT_90) {
+ std::swap(bufferWidth, bufferHeight);
+ }
+ }
+
+ const Rect layerSize{getBounds()};
+ int32_t layerWidth = layerSize.getWidth();
+ int32_t layerHeight = layerSize.getHeight();
+
+ // Align the layer orientation with the buffer before comparism
+ if (mTransformHint & ui::Transform::ROT_90) {
+ std::swap(layerWidth, layerHeight);
+ }
+
+ return layerWidth != bufferWidth || layerHeight != bufferHeight;
+}
+
+void Layer::decrementPendingBufferCount() {
+ int32_t pendingBuffers = --mPendingBufferTransactions;
+ tracePendingBufferCount(pendingBuffers);
+}
+
+void Layer::tracePendingBufferCount(int32_t pendingBuffers) {
+ ATRACE_INT(mBlastTransactionName.c_str(), pendingBuffers);
+}
+
+/*
+ * We don't want to send the layer's transform to input, but rather the
+ * parent's transform. This is because Layer's transform is
+ * information about how the buffer is placed on screen. The parent's
+ * transform makes more sense to send since it's information about how the
+ * layer is placed on screen. This transform is used by input to determine
+ * how to go from screen space back to window space.
+ */
+ui::Transform Layer::getInputTransform() const {
+ if (!hasBufferOrSidebandStream()) {
+ return getTransform();
+ }
+ sp<Layer> parent = mDrawingParent.promote();
+ if (parent == nullptr) {
+ return ui::Transform();
+ }
+
+ return parent->getTransform();
+}
+
+/**
+ * Similar to getInputTransform, we need to update the bounds to include the transform.
+ * This is because bounds don't include the buffer transform, where the input assumes
+ * that's already included.
+ */
+Rect Layer::getInputBounds() const {
+ if (!hasBufferOrSidebandStream()) {
+ return getCroppedBufferSize(getDrawingState());
+ }
+
+ Rect bufferBounds = getCroppedBufferSize(getDrawingState());
+ if (mDrawingState.transform.getType() == ui::Transform::IDENTITY || !bufferBounds.isValid()) {
+ return bufferBounds;
+ }
+ return mDrawingState.transform.transform(bufferBounds);
+}
+
+bool Layer::simpleBufferUpdate(const layer_state_t& s) const {
+ const uint64_t requiredFlags = layer_state_t::eBufferChanged;
+
+ const uint64_t deniedFlags = layer_state_t::eProducerDisconnect | layer_state_t::eLayerChanged |
+ layer_state_t::eRelativeLayerChanged | layer_state_t::eTransparentRegionChanged |
+ layer_state_t::eFlagsChanged | layer_state_t::eBlurRegionsChanged |
+ layer_state_t::eLayerStackChanged | layer_state_t::eAutoRefreshChanged |
+ layer_state_t::eReparent;
+
+ const uint64_t allowedFlags = layer_state_t::eHasListenerCallbacksChanged |
+ layer_state_t::eFrameRateSelectionPriority | layer_state_t::eFrameRateChanged |
+ layer_state_t::eSurfaceDamageRegionChanged | layer_state_t::eApiChanged |
+ layer_state_t::eMetadataChanged | layer_state_t::eDropInputModeChanged |
+ layer_state_t::eInputInfoChanged;
+
+ if ((s.what & requiredFlags) != requiredFlags) {
+ ALOGV("%s: false [missing required flags 0x%" PRIx64 "]", __func__,
+ (s.what | requiredFlags) & ~s.what);
+ return false;
+ }
+
+ if (s.what & deniedFlags) {
+ ALOGV("%s: false [has denied flags 0x%" PRIx64 "]", __func__, s.what & deniedFlags);
+ return false;
+ }
+
+ if (s.what & allowedFlags) {
+ ALOGV("%s: [has allowed flags 0x%" PRIx64 "]", __func__, s.what & allowedFlags);
+ }
+
+ if (s.what & layer_state_t::ePositionChanged) {
+ if (mRequestedTransform.tx() != s.x || mRequestedTransform.ty() != s.y) {
+ ALOGV("%s: false [ePositionChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eAlphaChanged) {
+ if (mDrawingState.color.a != s.alpha) {
+ ALOGV("%s: false [eAlphaChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eColorTransformChanged) {
+ if (mDrawingState.colorTransform != s.colorTransform) {
+ ALOGV("%s: false [eColorTransformChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eBackgroundColorChanged) {
+ if (mDrawingState.bgColorLayer || s.bgColorAlpha != 0) {
+ ALOGV("%s: false [eBackgroundColorChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eMatrixChanged) {
+ if (mRequestedTransform.dsdx() != s.matrix.dsdx ||
+ mRequestedTransform.dtdy() != s.matrix.dtdy ||
+ mRequestedTransform.dtdx() != s.matrix.dtdx ||
+ mRequestedTransform.dsdy() != s.matrix.dsdy) {
+ ALOGV("%s: false [eMatrixChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eCornerRadiusChanged) {
+ if (mDrawingState.cornerRadius != s.cornerRadius) {
+ ALOGV("%s: false [eCornerRadiusChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eBackgroundBlurRadiusChanged) {
+ if (mDrawingState.backgroundBlurRadius != static_cast<int>(s.backgroundBlurRadius)) {
+ ALOGV("%s: false [eBackgroundBlurRadiusChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eTransformChanged) {
+ if (mDrawingState.bufferTransform != s.transform) {
+ ALOGV("%s: false [eTransformChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eTransformToDisplayInverseChanged) {
+ if (mDrawingState.transformToDisplayInverse != s.transformToDisplayInverse) {
+ ALOGV("%s: false [eTransformToDisplayInverseChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eCropChanged) {
+ if (mDrawingState.crop != s.crop) {
+ ALOGV("%s: false [eCropChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eDataspaceChanged) {
+ if (mDrawingState.dataspace != s.dataspace) {
+ ALOGV("%s: false [eDataspaceChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eHdrMetadataChanged) {
+ if (mDrawingState.hdrMetadata != s.hdrMetadata) {
+ ALOGV("%s: false [eHdrMetadataChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eSidebandStreamChanged) {
+ if (mDrawingState.sidebandStream != s.sidebandStream) {
+ ALOGV("%s: false [eSidebandStreamChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eColorSpaceAgnosticChanged) {
+ if (mDrawingState.colorSpaceAgnostic != s.colorSpaceAgnostic) {
+ ALOGV("%s: false [eColorSpaceAgnosticChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eShadowRadiusChanged) {
+ if (mDrawingState.shadowRadius != s.shadowRadius) {
+ ALOGV("%s: false [eShadowRadiusChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eFixedTransformHintChanged) {
+ if (mDrawingState.fixedTransformHint != s.fixedTransformHint) {
+ ALOGV("%s: false [eFixedTransformHintChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eTrustedOverlayChanged) {
+ if (mDrawingState.isTrustedOverlay != s.isTrustedOverlay) {
+ ALOGV("%s: false [eTrustedOverlayChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eStretchChanged) {
+ StretchEffect temp = s.stretchEffect;
+ temp.sanitize();
+ if (mDrawingState.stretchEffect != temp) {
+ ALOGV("%s: false [eStretchChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eBufferCropChanged) {
+ if (mDrawingState.bufferCrop != s.bufferCrop) {
+ ALOGV("%s: false [eBufferCropChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eDestinationFrameChanged) {
+ if (mDrawingState.destinationFrame != s.destinationFrame) {
+ ALOGV("%s: false [eDestinationFrameChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ if (s.what & layer_state_t::eDimmingEnabledChanged) {
+ if (mDrawingState.dimmingEnabled != s.dimmingEnabled) {
+ ALOGV("%s: false [eDimmingEnabledChanged changed]", __func__);
+ return false;
+ }
+ }
+
+ ALOGV("%s: true", __func__);
+ return true;
+}
+
+bool Layer::isHdrY410() const {
+ // pixel format is HDR Y410 masquerading as RGBA_1010102
+ return (mBufferInfo.mDataspace == ui::Dataspace::BT2020_ITU_PQ &&
+ mBufferInfo.mApi == NATIVE_WINDOW_API_MEDIA &&
+ mBufferInfo.mPixelFormat == HAL_PIXEL_FORMAT_RGBA_1010102);
+}
+
+sp<compositionengine::LayerFE> Layer::getCompositionEngineLayerFE() const {
+ // There's no need to get a CE Layer if the layer isn't going to draw anything.
+ if (hasSomethingToDraw()) {
+ return asLayerFE();
+ } else {
+ return nullptr;
+ }
+}
+
+compositionengine::LayerFECompositionState* Layer::editCompositionState() {
+ return mCompositionState.get();
+}
+
+const compositionengine::LayerFECompositionState* Layer::getCompositionState() const {
+ return mCompositionState.get();
+}
+
+void Layer::useSurfaceDamage() {
+ if (mFlinger->mForceFullDamage) {
+ surfaceDamageRegion = Region::INVALID_REGION;
+ } else {
+ surfaceDamageRegion = mBufferInfo.mSurfaceDamage;
+ }
+}
+
+void Layer::useEmptyDamage() {
+ surfaceDamageRegion.clear();
+}
+
+bool Layer::isOpaque(const Layer::State& s) const {
+ // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
+ // layer's opaque flag.
+ if (!hasSomethingToDraw()) {
+ return false;
+ }
+
+ // if the layer has the opaque flag, then we're always opaque
+ if ((s.flags & layer_state_t::eLayerOpaque) == layer_state_t::eLayerOpaque) {
+ return true;
+ }
+
+ // If the buffer has no alpha channel, then we are opaque
+ if (hasBufferOrSidebandStream() && isOpaqueFormat(getPixelFormat())) {
+ return true;
+ }
+
+ // Lastly consider the layer opaque if drawing a color with alpha == 1.0
+ return fillsColor() && getAlpha() == 1.0_hf;
+}
+
+bool Layer::canReceiveInput() const {
+ return !isHiddenByPolicy() && (mBufferInfo.mBuffer == nullptr || getAlpha() > 0.0f);
+}
+
+bool Layer::isVisible() const {
+ if (!hasSomethingToDraw()) {
+ return false;
+ }
+
+ if (isHiddenByPolicy()) {
+ return false;
+ }
+
+ return getAlpha() > 0.0f || hasBlur();
+}
+
+void Layer::onPostComposition(const DisplayDevice* display,
+ const std::shared_ptr<FenceTime>& glDoneFence,
+ const std::shared_ptr<FenceTime>& presentFence,
+ const CompositorTiming& compositorTiming) {
+ // mFrameLatencyNeeded is true when a new frame was latched for the
+ // composition.
+ if (!mBufferInfo.mFrameLatencyNeeded) return;
+
+ for (const auto& handle : mDrawingState.callbackHandles) {
+ handle->gpuCompositionDoneFence = glDoneFence;
+ handle->compositorTiming = compositorTiming;
+ }
+
+ // Update mFrameTracker.
+ nsecs_t desiredPresentTime = mBufferInfo.mDesiredPresentTime;
+ mFrameTracker.setDesiredPresentTime(desiredPresentTime);
+
+ const int32_t layerId = getSequence();
+ mFlinger->mTimeStats->setDesiredTime(layerId, mCurrentFrameNumber, desiredPresentTime);
+
+ const auto outputLayer = findOutputLayerForDisplay(display);
+ if (outputLayer && outputLayer->requiresClientComposition()) {
+ nsecs_t clientCompositionTimestamp = outputLayer->getState().clientCompositionTimestamp;
+ mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(), mCurrentFrameNumber,
+ clientCompositionTimestamp,
+ FrameTracer::FrameEvent::FALLBACK_COMPOSITION);
+ // Update the SurfaceFrames in the drawing state
+ if (mDrawingState.bufferSurfaceFrameTX) {
+ mDrawingState.bufferSurfaceFrameTX->setGpuComposition();
+ }
+ for (auto& [token, surfaceFrame] : mDrawingState.bufferlessSurfaceFramesTX) {
+ surfaceFrame->setGpuComposition();
+ }
+ }
+
+ std::shared_ptr<FenceTime> frameReadyFence = mBufferInfo.mFenceTime;
+ if (frameReadyFence->isValid()) {
+ mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
+ } else {
+ // There was no fence for this frame, so assume that it was ready
+ // to be presented at the desired present time.
+ mFrameTracker.setFrameReadyTime(desiredPresentTime);
+ }
+
+ if (display) {
+ const Fps refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
+ const std::optional<Fps> renderRate =
+ mFlinger->mScheduler->getFrameRateOverride(getOwnerUid());
+
+ const auto vote = frameRateToSetFrameRateVotePayload(mDrawingState.frameRate);
+ const auto gameMode = getGameMode();
+
+ if (presentFence->isValid()) {
+ mFlinger->mTimeStats->setPresentFence(layerId, mCurrentFrameNumber, presentFence,
+ refreshRate, renderRate, vote, gameMode);
+ mFlinger->mFrameTracer->traceFence(layerId, getCurrentBufferId(), mCurrentFrameNumber,
+ presentFence,
+ FrameTracer::FrameEvent::PRESENT_FENCE);
+ mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
+ } else if (const auto displayId = PhysicalDisplayId::tryCast(display->getId());
+ displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
+ // The HWC doesn't support present fences, so use the refresh
+ // timestamp instead.
+ const nsecs_t actualPresentTime = display->getRefreshTimestamp();
+ mFlinger->mTimeStats->setPresentTime(layerId, mCurrentFrameNumber, actualPresentTime,
+ refreshRate, renderRate, vote, gameMode);
+ mFlinger->mFrameTracer->traceTimestamp(layerId, getCurrentBufferId(),
+ mCurrentFrameNumber, actualPresentTime,
+ FrameTracer::FrameEvent::PRESENT_FENCE);
+ mFrameTracker.setActualPresentTime(actualPresentTime);
+ }
+ }
+
+ mFrameTracker.advanceFrame();
+ mBufferInfo.mFrameLatencyNeeded = false;
+}
+
+bool Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
+ ATRACE_FORMAT_INSTANT("latchBuffer %s - %" PRIu64, getDebugName(),
+ getDrawingState().frameNumber);
+
+ bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
+
+ if (refreshRequired) {
+ return refreshRequired;
+ }
+
+ // If the head buffer's acquire fence hasn't signaled yet, return and
+ // try again later
+ if (!fenceHasSignaled()) {
+ ATRACE_NAME("!fenceHasSignaled()");
+ mFlinger->onLayerUpdate();
+ return false;
+ }
+
+ updateTexImage(latchTime);
+ if (mDrawingState.buffer == nullptr) {
+ return false;
+ }
+
+ // Capture the old state of the layer for comparisons later
+ BufferInfo oldBufferInfo = mBufferInfo;
+ const bool oldOpacity = isOpaque(mDrawingState);
+ mPreviousFrameNumber = mCurrentFrameNumber;
+ mCurrentFrameNumber = mDrawingState.frameNumber;
+ gatherBufferInfo();
+
+ if (oldBufferInfo.mBuffer == nullptr) {
+ // the first time we receive a buffer, we need to trigger a
+ // geometry invalidation.
+ recomputeVisibleRegions = true;
+ }
+
+ if ((mBufferInfo.mCrop != oldBufferInfo.mCrop) ||
+ (mBufferInfo.mTransform != oldBufferInfo.mTransform) ||
+ (mBufferInfo.mScaleMode != oldBufferInfo.mScaleMode) ||
+ (mBufferInfo.mTransformToDisplayInverse != oldBufferInfo.mTransformToDisplayInverse)) {
+ recomputeVisibleRegions = true;
+ }
+
+ if (oldBufferInfo.mBuffer != nullptr) {
+ uint32_t bufWidth = mBufferInfo.mBuffer->getWidth();
+ uint32_t bufHeight = mBufferInfo.mBuffer->getHeight();
+ if (bufWidth != oldBufferInfo.mBuffer->getWidth() ||
+ bufHeight != oldBufferInfo.mBuffer->getHeight()) {
+ recomputeVisibleRegions = true;
+ }
+ }
+
+ if (oldOpacity != isOpaque(mDrawingState)) {
+ recomputeVisibleRegions = true;
}
return true;
}
+bool Layer::hasReadyFrame() const {
+ return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
+}
+
+bool Layer::isProtected() const {
+ return (mBufferInfo.mBuffer != nullptr) &&
+ (mBufferInfo.mBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
+}
+
+// As documented in libhardware header, formats in the range
+// 0x100 - 0x1FF are specific to the HAL implementation, and
+// are known to have no alpha channel
+// TODO: move definition for device-specific range into
+// hardware.h, instead of using hard-coded values here.
+#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
+
+bool Layer::isOpaqueFormat(PixelFormat format) {
+ if (HARDWARE_IS_DEVICE_FORMAT(format)) {
+ return true;
+ }
+ switch (format) {
+ case PIXEL_FORMAT_RGBA_8888:
+ case PIXEL_FORMAT_BGRA_8888:
+ case PIXEL_FORMAT_RGBA_FP16:
+ case PIXEL_FORMAT_RGBA_1010102:
+ case PIXEL_FORMAT_R_8:
+ return false;
+ }
+ // in all other case, we have no blending (also for unknown formats)
+ return true;
+}
+
+bool Layer::needsFiltering(const DisplayDevice* display) const {
+ if (!hasBufferOrSidebandStream()) {
+ return false;
+ }
+ const auto outputLayer = findOutputLayerForDisplay(display);
+ if (outputLayer == nullptr) {
+ return false;
+ }
+
+ // We need filtering if the sourceCrop rectangle size does not match the
+ // displayframe rectangle size (not a 1:1 render)
+ const auto& compositionState = outputLayer->getState();
+ const auto displayFrame = compositionState.displayFrame;
+ const auto sourceCrop = compositionState.sourceCrop;
+ return sourceCrop.getHeight() != displayFrame.getHeight() ||
+ sourceCrop.getWidth() != displayFrame.getWidth();
+}
+
+bool Layer::needsFilteringForScreenshots(const DisplayDevice* display,
+ const ui::Transform& inverseParentTransform) const {
+ if (!hasBufferOrSidebandStream()) {
+ return false;
+ }
+ const auto outputLayer = findOutputLayerForDisplay(display);
+ if (outputLayer == nullptr) {
+ return false;
+ }
+
+ // We need filtering if the sourceCrop rectangle size does not match the
+ // viewport rectangle size (not a 1:1 render)
+ const auto& compositionState = outputLayer->getState();
+ const ui::Transform& displayTransform = display->getTransform();
+ const ui::Transform inverseTransform = inverseParentTransform * displayTransform.inverse();
+ // Undo the transformation of the displayFrame so that we're back into
+ // layer-stack space.
+ const Rect frame = inverseTransform.transform(compositionState.displayFrame);
+ const FloatRect sourceCrop = compositionState.sourceCrop;
+
+ int32_t frameHeight = frame.getHeight();
+ int32_t frameWidth = frame.getWidth();
+ // If the display transform had a rotational component then undo the
+ // rotation so that the orientation matches the source crop.
+ if (displayTransform.getOrientation() & ui::Transform::ROT_90) {
+ std::swap(frameHeight, frameWidth);
+ }
+ return sourceCrop.getHeight() != frameHeight || sourceCrop.getWidth() != frameWidth;
+}
+
+void Layer::latchAndReleaseBuffer() {
+ if (hasReadyFrame()) {
+ bool ignored = false;
+ latchBuffer(ignored, systemTime());
+ }
+ releasePendingBuffer(systemTime());
+}
+
+PixelFormat Layer::getPixelFormat() const {
+ return mBufferInfo.mPixelFormat;
+}
+
+bool Layer::getTransformToDisplayInverse() const {
+ return mBufferInfo.mTransformToDisplayInverse;
+}
+
+Rect Layer::getBufferCrop() const {
+ // this is the crop rectangle that applies to the buffer
+ // itself (as opposed to the window)
+ if (!mBufferInfo.mCrop.isEmpty()) {
+ // if the buffer crop is defined, we use that
+ return mBufferInfo.mCrop;
+ } else if (mBufferInfo.mBuffer != nullptr) {
+ // otherwise we use the whole buffer
+ return mBufferInfo.mBuffer->getBounds();
+ } else {
+ // if we don't have a buffer yet, we use an empty/invalid crop
+ return Rect();
+ }
+}
+
+uint32_t Layer::getBufferTransform() const {
+ return mBufferInfo.mTransform;
+}
+
+ui::Dataspace Layer::getDataSpace() const {
+ return mDrawingState.dataspaceRequested ? getRequestedDataSpace() : ui::Dataspace::UNKNOWN;
+}
+
+ui::Dataspace Layer::getRequestedDataSpace() const {
+ return hasBufferOrSidebandStream() ? mBufferInfo.mDataspace : mDrawingState.dataspace;
+}
+
+ui::Dataspace Layer::translateDataspace(ui::Dataspace dataspace) {
+ ui::Dataspace updatedDataspace = dataspace;
+ // translate legacy dataspaces to modern dataspaces
+ switch (dataspace) {
+ case ui::Dataspace::SRGB:
+ updatedDataspace = ui::Dataspace::V0_SRGB;
+ break;
+ case ui::Dataspace::SRGB_LINEAR:
+ updatedDataspace = ui::Dataspace::V0_SRGB_LINEAR;
+ break;
+ case ui::Dataspace::JFIF:
+ updatedDataspace = ui::Dataspace::V0_JFIF;
+ break;
+ case ui::Dataspace::BT601_625:
+ updatedDataspace = ui::Dataspace::V0_BT601_625;
+ break;
+ case ui::Dataspace::BT601_525:
+ updatedDataspace = ui::Dataspace::V0_BT601_525;
+ break;
+ case ui::Dataspace::BT709:
+ updatedDataspace = ui::Dataspace::V0_BT709;
+ break;
+ default:
+ break;
+ }
+
+ return updatedDataspace;
+}
+
+sp<GraphicBuffer> Layer::getBuffer() const {
+ return mBufferInfo.mBuffer ? mBufferInfo.mBuffer->getBuffer() : nullptr;
+}
+
+void Layer::getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const {
+ sp<GraphicBuffer> buffer = getBuffer();
+ if (!buffer) {
+ ALOGE("Buffer should not be null!");
+ return;
+ }
+ GLConsumer::computeTransformMatrix(outMatrix, buffer->getWidth(), buffer->getHeight(),
+ buffer->getPixelFormat(), mBufferInfo.mCrop,
+ mBufferInfo.mTransform, filteringEnabled);
+}
+
+void Layer::setTransformHint(ui::Transform::RotationFlags displayTransformHint) {
+ mTransformHint = getFixedTransformHint();
+ if (mTransformHint == ui::Transform::ROT_INVALID) {
+ mTransformHint = displayTransformHint;
+ }
+}
+
+const std::shared_ptr<renderengine::ExternalTexture>& Layer::getExternalTexture() const {
+ return mBufferInfo.mBuffer;
+}
+
+bool Layer::setColor(const half3& color) {
+ if (mDrawingState.color.r == color.r && mDrawingState.color.g == color.g &&
+ mDrawingState.color.b == color.b) {
+ return false;
+ }
+
+ mDrawingState.sequence++;
+ mDrawingState.color.r = color.r;
+ mDrawingState.color.g = color.g;
+ mDrawingState.color.b = color.b;
+ mDrawingState.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool Layer::fillsColor() const {
+ return !hasBufferOrSidebandStream() && mDrawingState.color.r >= 0.0_hf &&
+ mDrawingState.color.g >= 0.0_hf && mDrawingState.color.b >= 0.0_hf;
+}
+
+bool Layer::hasBlur() const {
+ return getBackgroundBlurRadius() > 0 || getDrawingState().blurRegions.size() > 0;
+}
+
+void Layer::updateSnapshot(bool updateGeometry) {
+ if (!getCompositionEngineLayerFE()) {
+ return;
+ }
+
+ if (updateGeometry) {
+ prepareBasicGeometryCompositionState();
+ prepareGeometryCompositionState();
+ }
+ preparePerFrameCompositionState();
+}
+
// ---------------------------------------------------------------------------
std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate) {
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index b05a4a0..5030fd8 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -48,12 +48,10 @@
#include <vector>
#include "Client.h"
-#include "ClientCache.h"
-#include "DisplayHardware/ComposerHal.h"
#include "DisplayHardware/HWComposer.h"
#include "FrameTracker.h"
+#include "HwcSlotGenerator.h"
#include "LayerVector.h"
-#include "RenderArea.h"
#include "Scheduler/LayerInfo.h"
#include "SurfaceFlinger.h"
#include "Tracing/LayerTracing.h"
@@ -170,10 +168,9 @@
gui::WindowInfo inputInfo;
wp<Layer> touchableRegionCrop;
- // dataspace is only used by BufferStateLayer and EffectLayer
ui::Dataspace dataspace;
+ bool dataspaceRequested;
- // The fields below this point are only used by BufferStateLayer
uint64_t frameNumber;
ui::Transform transform;
uint32_t bufferTransform;
@@ -307,17 +304,17 @@
static void miniDumpHeader(std::string& result);
// Provide unique string for each class type in the Layer hierarchy
- virtual const char* getType() const = 0;
+ virtual const char* getType() const { return "Layer"; }
// true if this layer is visible, false otherwise
- virtual bool isVisible() const = 0;
+ virtual bool isVisible() const;
- virtual sp<Layer> createClone() = 0;
+ virtual sp<Layer> createClone();
// Set a 2x2 transformation matrix on the layer. This transform
// will be applied after parent transforms, but before any final
// producer specified transform.
- virtual bool setMatrix(const layer_state_t::matrix22_t& matrix);
+ bool setMatrix(const layer_state_t::matrix22_t& matrix);
// This second set of geometry attributes are controlled by
// setGeometryAppliesWithResize, and their default mode is to be
@@ -327,9 +324,9 @@
// setPosition operates in parent buffer space (pre parent-transform) or display
// space for top-level layers.
- virtual bool setPosition(float x, float y);
+ bool setPosition(float x, float y);
// Buffer space
- virtual bool setCrop(const Rect& crop);
+ bool setCrop(const Rect& crop);
// TODO(b/38182121): Could we eliminate the various latching modes by
// using the layer hierarchy?
@@ -338,7 +335,7 @@
virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
virtual bool setAlpha(float alpha);
- virtual bool setColor(const half3& /*color*/) { return false; };
+ bool setColor(const half3& /*color*/);
// Set rounded corner radius for this layer and its children.
//
@@ -364,30 +361,25 @@
virtual bool isColorSpaceAgnostic() const { return mDrawingState.colorSpaceAgnostic; }
virtual bool isDimmingEnabled() const { return getDrawingState().dimmingEnabled; };
- // Used only to set BufferStateLayer state
- virtual bool setTransform(uint32_t /*transform*/) { return false; };
- virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/) { return false; };
- virtual bool setBuffer(std::shared_ptr<renderengine::ExternalTexture>& /* buffer */,
- const BufferData& /* bufferData */, nsecs_t /* postTime */,
- nsecs_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/,
- std::optional<nsecs_t> /* dequeueTime */,
- const FrameTimelineInfo& /*info*/) {
- return false;
- };
- virtual bool setDataspace(ui::Dataspace /*dataspace*/) { return false; };
- virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) { return false; };
- virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) { return false; };
- virtual bool setApi(int32_t /*api*/) { return false; };
- virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/) { return false; };
- virtual bool setTransactionCompletedListeners(
- const std::vector<sp<CallbackHandle>>& /*handles*/);
+ bool setTransform(uint32_t /*transform*/);
+ bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/);
+ bool setBuffer(std::shared_ptr<renderengine::ExternalTexture>& /* buffer */,
+ const BufferData& /* bufferData */, nsecs_t /* postTime */,
+ nsecs_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/,
+ std::optional<nsecs_t> /* dequeueTime */, const FrameTimelineInfo& /*info*/);
+ bool setDataspace(ui::Dataspace /*dataspace*/);
+ bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/);
+ bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/);
+ bool setApi(int32_t /*api*/);
+ bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/);
+ bool setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& /*handles*/);
virtual bool setBackgroundColor(const half3& color, float alpha, ui::Dataspace dataspace);
virtual bool setColorSpaceAgnostic(const bool agnostic);
virtual bool setDimmingEnabled(const bool dimmingEnabled);
virtual bool setDefaultFrameRateCompatibility(FrameRateCompatibility compatibility);
virtual bool setFrameRateSelectionPriority(int32_t priority);
virtual bool setFixedTransformHint(ui::Transform::RotationFlags fixedTransformHint);
- virtual void setAutoRefresh(bool /* autoRefresh */) {}
+ void setAutoRefresh(bool /* autoRefresh */);
bool setDropInputMode(gui::DropInputMode);
// If the variable is not set on the layer, it traverses up the tree to inherit the frame
@@ -396,16 +388,17 @@
//
virtual FrameRateCompatibility getDefaultFrameRateCompatibility() const;
//
- virtual ui::Dataspace getDataSpace() const { return ui::Dataspace::UNKNOWN; }
+ ui::Dataspace getDataSpace() const;
+ ui::Dataspace getRequestedDataSpace() const;
virtual sp<compositionengine::LayerFE> getCompositionEngineLayerFE() const;
- virtual compositionengine::LayerFECompositionState* editCompositionState();
+ compositionengine::LayerFECompositionState* editCompositionState();
// If we have received a new buffer this frame, we will pass its surface
// damage down to hardware composer. Otherwise, we must send a region with
// one empty rect.
- virtual void useSurfaceDamage() {}
- virtual void useEmptyDamage() {}
+ void useSurfaceDamage();
+ void useEmptyDamage();
Region getVisibleRegion(const DisplayDevice*) const;
/*
@@ -415,18 +408,18 @@
* pixel format includes an alpha channel) and the "opaque" flag set
* on the layer. It does not examine the current plane alpha value.
*/
- virtual bool isOpaque(const Layer::State&) const { return false; }
+ bool isOpaque(const Layer::State&) const;
/*
* Returns whether this layer can receive input.
*/
- virtual bool canReceiveInput() const;
+ bool canReceiveInput() const;
/*
* isProtected - true if the layer may contain protected contents in the
* GRALLOC_USAGE_PROTECTED sense.
*/
- virtual bool isProtected() const { return false; }
+ bool isProtected() const;
/*
* isFixedSize - true if content has a fixed size
@@ -436,7 +429,7 @@
/*
* usesSourceCrop - true if content should use a source crop
*/
- virtual bool usesSourceCrop() const { return false; }
+ bool usesSourceCrop() const { return hasBufferOrSidebandStream(); }
// Most layers aren't created from the main thread, and therefore need to
// grab the SF state lock to access HWC, but ContainerLayer does, so we need
@@ -447,8 +440,8 @@
Region getActiveTransparentRegion(const Layer::State& s) const {
return s.transparentRegionHint;
}
- virtual Rect getCrop(const Layer::State& s) const { return s.crop; }
- virtual bool needsFiltering(const DisplayDevice*) const { return false; }
+ Rect getCrop(const Layer::State& s) const { return s.crop; }
+ bool needsFiltering(const DisplayDevice*) const;
// True if this layer requires filtering
// This method is distinct from needsFiltering() in how the filter
@@ -459,25 +452,25 @@
// different.
// If the parent transform needs to be undone when capturing the layer, then
// the inverse parent transform is also required.
- virtual bool needsFilteringForScreenshots(const DisplayDevice*, const ui::Transform&) const {
- return false;
- }
+ bool needsFilteringForScreenshots(const DisplayDevice*, const ui::Transform&) const;
- virtual void updateCloneBufferInfo(){};
+ // from graphics API
+ ui::Dataspace translateDataspace(ui::Dataspace dataspace);
+ void updateCloneBufferInfo();
+ uint64_t mPreviousFrameNumber = 0;
- virtual bool isHdrY410() const { return false; }
+ bool isHdrY410() const;
/*
* called after composition.
* returns true if the layer latched a new buffer this frame.
*/
- virtual void onPostComposition(const DisplayDevice*,
- const std::shared_ptr<FenceTime>& /*glDoneFence*/,
- const std::shared_ptr<FenceTime>& /*presentFence*/,
- const CompositorTiming&) {}
+ void onPostComposition(const DisplayDevice*, const std::shared_ptr<FenceTime>& /*glDoneFence*/,
+ const std::shared_ptr<FenceTime>& /*presentFence*/,
+ const CompositorTiming&);
// If a buffer was replaced this frame, release the former buffer
- virtual void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/) { }
+ void releasePendingBuffer(nsecs_t /*dequeueReadyTime*/);
/*
* latchBuffer - called each time the screen is redrawn and returns whether
@@ -485,54 +478,55 @@
* operation, so this should be set only if needed). Typically this is used
* to figure out if the content or size of a surface has changed.
*/
- virtual bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/) {
- return false;
- }
+ bool latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/);
- virtual void latchAndReleaseBuffer() {}
+ /*
+ * Calls latchBuffer if the buffer has a frame queued and then releases the buffer.
+ * This is used if the buffer is just latched and releases to free up the buffer
+ * and will not be shown on screen.
+ * Should only be called on the main thread.
+ */
+ void latchAndReleaseBuffer();
/*
* returns the rectangle that crops the content of the layer and scales it
* to the layer's size.
*/
- virtual Rect getBufferCrop() const { return Rect(); }
+ Rect getBufferCrop() const;
/*
* Returns the transform applied to the buffer.
*/
- virtual uint32_t getBufferTransform() const { return 0; }
+ uint32_t getBufferTransform() const;
- virtual sp<GraphicBuffer> getBuffer() const { return nullptr; }
- virtual const std::shared_ptr<renderengine::ExternalTexture>& getExternalTexture() const {
- return mDrawingState.buffer;
- };
+ sp<GraphicBuffer> getBuffer() const;
+ const std::shared_ptr<renderengine::ExternalTexture>& getExternalTexture() const;
- virtual ui::Transform::RotationFlags getTransformHint() const { return ui::Transform::ROT_0; }
+ ui::Transform::RotationFlags getTransformHint() const { return mTransformHint; }
/*
* Returns if a frame is ready
*/
- virtual bool hasReadyFrame() const { return false; }
+ bool hasReadyFrame() const;
virtual int32_t getQueuedFrameCount() const { return 0; }
/**
* Returns active buffer size in the correct orientation. Buffer size is determined by undoing
- * any buffer transformations. If the layer has no buffer then return INVALID_RECT.
+ * any buffer transformations. Returns Rect::INVALID_RECT if the layer has no buffer or the
+ * layer does not have a display frame and its parent is not bounded.
*/
- virtual Rect getBufferSize(const Layer::State&) const { return Rect::INVALID_RECT; }
+ Rect getBufferSize(const Layer::State&) const;
/**
* Returns the source bounds. If the bounds are not defined, it is inferred from the
* buffer size. Failing that, the bounds are determined from the passed in parent bounds.
* For the root layer, this is the display viewport size.
*/
- virtual FloatRect computeSourceBounds(const FloatRect& parentBounds) const {
- return parentBounds;
- }
+ FloatRect computeSourceBounds(const FloatRect& parentBounds) const;
virtual FrameRate getFrameRateForLayerTree() const;
- virtual bool getTransformToDisplayInverse() const { return false; }
+ bool getTransformToDisplayInverse() const;
// Returns how rounded corners should be drawn for this layer.
// A layer can override its parent's rounded corner settings if the parent's rounded
@@ -541,26 +535,50 @@
bool hasRoundedCorners() const override { return getRoundedCornerState().hasRoundedCorners(); }
- virtual PixelFormat getPixelFormat() const { return PIXEL_FORMAT_NONE; }
+ PixelFormat getPixelFormat() const;
/**
- * Return whether this layer needs an input info. For most layer types
- * this is only true if they explicitly set an input-info but BufferLayer
- * overrides this so we can generate input-info for Buffered layers that don't
- * have them (for input occlusion detection checks).
+ * Return whether this layer needs an input info. We generate InputWindowHandles for all
+ * non-cursor buffered layers regardless of whether they have an InputChannel. This is to enable
+ * the InputDispatcher to do PID based occlusion detection.
*/
- virtual bool needsInputInfo() const { return hasInputInfo(); }
+ bool needsInputInfo() const {
+ return (hasInputInfo() || hasBufferOrSidebandStream()) && !mPotentialCursor;
+ }
// Implements RefBase.
void onFirstRef() override;
- // implements compositionengine::LayerFE
- const compositionengine::LayerFECompositionState* getCompositionState() const override;
- bool onPreComposition(nsecs_t) override;
- void prepareCompositionState(compositionengine::LayerFE::StateSubset subset) override;
+ struct BufferInfo {
+ nsecs_t mDesiredPresentTime;
+ std::shared_ptr<FenceTime> mFenceTime;
+ sp<Fence> mFence;
+ uint32_t mTransform{0};
+ ui::Dataspace mDataspace{ui::Dataspace::UNKNOWN};
+ Rect mCrop;
+ uint32_t mScaleMode{NATIVE_WINDOW_SCALING_MODE_FREEZE};
+ Region mSurfaceDamage;
+ HdrMetadata mHdrMetadata;
+ int mApi;
+ PixelFormat mPixelFormat{PIXEL_FORMAT_NONE};
+ bool mTransformToDisplayInverse{false};
+ std::shared_ptr<renderengine::ExternalTexture> mBuffer;
+ uint64_t mFrameNumber;
+ int mBufferSlot{BufferQueue::INVALID_BUFFER_SLOT};
+
+ bool mFrameLatencyNeeded{false};
+ };
+
+ BufferInfo mBufferInfo;
+
+ // implements compositionengine::LayerFE
+ const compositionengine::LayerFECompositionState* getCompositionState() const;
+ bool fenceHasSignaled() const;
+ // Called before composition. updatingOutputGeometryThisFrame is used by ARC++'s Layer subclass.
+ bool onPreComposition(nsecs_t refreshStartTime, bool updatingOutputGeometryThisFrame);
std::optional<compositionengine::LayerFE::LayerSettings> prepareClientComposition(
compositionengine::LayerFE::ClientCompositionTargetSettings&) const override;
- void onLayerDisplayed(ftl::SharedFuture<FenceResult>) override;
+ void onLayerDisplayed(ftl::SharedFuture<FenceResult>);
void setWasClientComposed(const sp<Fence>& fence) override {
mLastClientCompositionFence = fence;
@@ -838,13 +856,18 @@
float getBorderWidth();
const half4& getBorderColor();
- virtual bool setBufferCrop(const Rect& /* bufferCrop */) { return false; }
- virtual bool setDestinationFrame(const Rect& /* destinationFrame */) { return false; }
- virtual std::atomic<int32_t>* getPendingBufferCounter() { return nullptr; }
- virtual std::string getPendingBufferCounterName() { return ""; }
- virtual bool updateGeometry() { return false; }
+ bool setBufferCrop(const Rect& /* bufferCrop */);
+ bool setDestinationFrame(const Rect& /* destinationFrame */);
+ // See mPendingBufferTransactions
+ void decrementPendingBufferCount();
+ std::atomic<int32_t>* getPendingBufferCounter() { return &mPendingBufferTransactions; }
+ std::string getPendingBufferCounterName() { return mBlastTransactionName; }
+ bool updateGeometry();
- virtual bool simpleBufferUpdate(const layer_state_t&) const { return false; }
+ bool simpleBufferUpdate(const layer_state_t&) const;
+
+ static bool isOpaqueFormat(PixelFormat format);
+ void updateSnapshot(bool updateGeometry);
protected:
friend class impl::SurfaceInterceptor;
@@ -858,9 +881,12 @@
friend class TransactionSurfaceFrameTest;
virtual void setInitialValuesForClone(const sp<Layer>& clonedFrom);
- virtual void preparePerFrameCompositionState();
+ void preparePerFrameCompositionState();
+ void preparePerFrameBufferCompositionState();
+ void preparePerFrameEffectsCompositionState();
virtual void commitTransaction(State& stateToCommit);
- virtual void onSurfaceFrameCreated(const std::shared_ptr<frametimeline::SurfaceFrame>&) {}
+ void gatherBufferInfo();
+ void onSurfaceFrameCreated(const std::shared_ptr<frametimeline::SurfaceFrame>&);
sp<compositionengine::LayerFE> asLayerFE() const;
sp<Layer> getClonedFrom() { return mClonedFrom != nullptr ? mClonedFrom.promote() : nullptr; }
@@ -913,7 +939,7 @@
* "replaceTouchableRegionWithCrop" is specified. In this case, the layer will receive input
* in this layer's space, regardless of the specified crop layer.
*/
- virtual Rect getInputBounds() const;
+ Rect getInputBounds() const;
// constant
sp<SurfaceFlinger> mFlinger;
@@ -984,7 +1010,14 @@
sp<Fence> mLastClientCompositionFence;
bool mClearClientCompositionFenceOnLayerDisplayed = false;
private:
- virtual void setTransformHint(ui::Transform::RotationFlags) {}
+ friend class SlotGenerationTest;
+ friend class TransactionFrameTracerTest;
+ friend class TransactionSurfaceFrameTest;
+
+ bool getAutoRefresh() const { return mDrawingState.autoRefresh; }
+ bool getSidebandStreamChanged() const { return mSidebandStreamChanged; }
+
+ std::atomic<bool> mSidebandStreamChanged{false};
// Returns true if the layer can draw shadows on its border.
virtual bool canDrawShadows() const { return true; }
@@ -1029,6 +1062,52 @@
// Fills in the frame and transform info for the gui::WindowInfo.
void fillInputFrameInfo(gui::WindowInfo&, const ui::Transform& screenToDisplay);
+ // Computes the transform matrix using the setFilteringEnabled to determine whether the
+ // transform matrix should be computed for use with bilinear filtering.
+ void getDrawingTransformMatrix(bool filteringEnabled, float outMatrix[16]) const;
+
+ inline void tracePendingBufferCount(int32_t pendingBuffers);
+
+ // Latch sideband stream and returns true if the dirty region should be updated.
+ bool latchSidebandStream(bool& recomputeVisibleRegions);
+
+ bool hasFrameUpdate() const;
+
+ void updateTexImage(nsecs_t latchTime);
+
+ // Crop that applies to the buffer
+ Rect computeBufferCrop(const State& s);
+
+ bool willPresentCurrentTransaction() const;
+
+ // Returns true if the transformed buffer size does not match the layer size and we need
+ // to apply filtering.
+ bool bufferNeedsFiltering() const;
+
+ void callReleaseBufferCallback(const sp<ITransactionCompletedListener>& listener,
+ const sp<GraphicBuffer>& buffer, uint64_t framenumber,
+ const sp<Fence>& releaseFence,
+ uint32_t currentMaxAcquiredBufferCount);
+
+ std::optional<compositionengine::LayerFE::LayerSettings> prepareClientCompositionInternal(
+ compositionengine::LayerFE::ClientCompositionTargetSettings&) const;
+ // Returns true if there is a valid color to fill.
+ bool fillsColor() const;
+ // Returns true if this layer has a blur value.
+ bool hasBlur() const;
+ bool hasEffect() const { return fillsColor() || drawShadows() || hasBlur(); }
+ bool hasBufferOrSidebandStream() const {
+ return ((mSidebandStream != nullptr) || (mBufferInfo.mBuffer != nullptr));
+ }
+
+ bool hasSomethingToDraw() const { return hasEffect() || hasBufferOrSidebandStream(); }
+ void prepareBufferStateClientComposition(
+ compositionengine::LayerFE::LayerSettings&,
+ compositionengine::LayerFE::ClientCompositionTargetSettings&) const;
+ void prepareEffectsClientComposition(
+ compositionengine::LayerFE::LayerSettings&,
+ compositionengine::LayerFE::ClientCompositionTargetSettings&) const;
+
// Cached properties computed from drawing state
// Effective transform taking into account parent transforms and any parent scaling, which is
// a transform from the current layer coordinate space to display(screen) coordinate space.
@@ -1078,6 +1157,49 @@
bool mBorderEnabled = false;
float mBorderWidth;
half4 mBorderColor;
+
+ void setTransformHint(ui::Transform::RotationFlags);
+
+ const uint32_t mTextureName;
+
+ // Transform hint provided to the producer. This must be accessed holding
+ // the mStateLock.
+ ui::Transform::RotationFlags mTransformHint = ui::Transform::ROT_0;
+
+ std::unique_ptr<compositionengine::LayerFECompositionState> mCompositionState;
+
+ ReleaseCallbackId mPreviousReleaseCallbackId = ReleaseCallbackId::INVALID_ID;
+ uint64_t mPreviousReleasedFrameNumber = 0;
+
+ uint64_t mPreviousBarrierFrameNumber = 0;
+
+ bool mReleasePreviousBuffer = false;
+
+ // Stores the last set acquire fence signal time used to populate the callback handle's acquire
+ // time.
+ std::variant<nsecs_t, sp<Fence>> mCallbackHandleAcquireTimeOrFence = -1;
+
+ std::deque<std::shared_ptr<android::frametimeline::SurfaceFrame>> mPendingJankClassifications;
+ // An upper bound on the number of SurfaceFrames in the pending classifications deque.
+ static constexpr int kPendingClassificationMaxSurfaceFrames = 25;
+
+ const std::string mBlastTransactionName{"BufferTX - " + mName};
+ // This integer is incremented everytime a buffer arrives at the server for this layer,
+ // and decremented when a buffer is dropped or latched. When changed the integer is exported
+ // to systrace with ATRACE_INT and mBlastTransactionName. This way when debugging perf it is
+ // possible to see when a buffer arrived at the server, and in which frame it latched.
+ //
+ // You can understand the trace this way:
+ // - If the integer increases, a buffer arrived at the server.
+ // - If the integer decreases in latchBuffer, that buffer was latched
+ // - If the integer decreases in setBuffer or doTransaction, a buffer was dropped
+ std::atomic<int32_t> mPendingBufferTransactions{0};
+
+ // Contains requested position and matrix updates. This will be applied if the client does
+ // not specify a destination frame.
+ ui::Transform mRequestedTransform;
+
+ sp<HwcSlotGenerator> mHwcSlotGenerator;
};
std::ostream& operator<<(std::ostream& stream, const Layer::FrameRate& rate);
diff --git a/services/surfaceflinger/LayerRenderArea.cpp b/services/surfaceflinger/LayerRenderArea.cpp
index e17b01f..6bc7dc1 100644
--- a/services/surfaceflinger/LayerRenderArea.cpp
+++ b/services/surfaceflinger/LayerRenderArea.cpp
@@ -18,7 +18,6 @@
#include <ui/Transform.h>
#include "DisplayDevice.h"
-#include "EffectLayer.h"
#include "Layer.h"
#include "LayerRenderArea.h"
#include "SurfaceFlinger.h"
@@ -110,7 +109,7 @@
// layer which has no properties set and which does not draw.
// We hold the statelock as the reparent-for-drawing operation modifies the
// hierarchy and there could be readers on Binder threads, like dump.
- sp<EffectLayer> screenshotParentLayer = mFlinger.getFactory().createEffectLayer(
+ auto screenshotParentLayer = mFlinger.getFactory().createEffectLayer(
{&mFlinger, nullptr, "Screenshot Parent"s, ISurfaceComposerClient::eNoColorFill,
LayerMetadata()});
{
diff --git a/services/surfaceflinger/OWNERS b/services/surfaceflinger/OWNERS
index 2ece51c..6011d0d 100644
--- a/services/surfaceflinger/OWNERS
+++ b/services/surfaceflinger/OWNERS
@@ -2,6 +2,7 @@
alecmouri@google.com
chaviw@google.com
lpy@google.com
+pdwilliams@google.com
racarr@google.com
scroggo@google.com
-vishnun@google.com
\ No newline at end of file
+vishnun@google.com
diff --git a/services/surfaceflinger/Scheduler/DispSyncSource.cpp b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
index 747032b..4af1f5c 100644
--- a/services/surfaceflinger/Scheduler/DispSyncSource.cpp
+++ b/services/surfaceflinger/Scheduler/DispSyncSource.cpp
@@ -188,10 +188,10 @@
VSyncSource::VSyncData DispSyncSource::getLatestVSyncData() const {
std::lock_guard lock(mVsyncMutex);
- nsecs_t expectedPresentTime = mVSyncTracker.nextAnticipatedVSyncTimeFrom(
+ nsecs_t expectedPresentationTime = mVSyncTracker.nextAnticipatedVSyncTimeFrom(
systemTime() + mWorkDuration.get().count() + mReadyDuration.count());
- nsecs_t deadline = expectedPresentTime - mWorkDuration.get().count() - mReadyDuration.count();
- return {expectedPresentTime, deadline};
+ nsecs_t deadline = expectedPresentationTime - mReadyDuration.count();
+ return {expectedPresentationTime, deadline};
}
void DispSyncSource::dump(std::string& result) const {
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
index 6426478..00886f0 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
@@ -27,6 +27,7 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <ftl/enum.h>
+#include <ftl/fake_guard.h>
#include <utils/Trace.h>
#include "../SurfaceFlingerProperties.h"
@@ -279,6 +280,15 @@
ATRACE_CALL();
ALOGV("%s: %zu layers", __func__, layers.size());
+ const auto& activeMode = *getActiveModeItLocked()->second;
+
+ // Keep the display at max refresh rate for the duration of powering on the display.
+ if (signals.powerOnImminent) {
+ ALOGV("Power On Imminent");
+ const auto& max = getMaxRefreshRateByPolicyLocked(activeMode.getGroup());
+ return {max, GlobalSignals{.powerOnImminent = true}};
+ }
+
int noVoteLayers = 0;
int minVoteLayers = 0;
int maxVoteLayers = 0;
@@ -325,6 +335,7 @@
const Policy* policy = getCurrentPolicyLocked();
const auto& defaultMode = mDisplayModes.get(policy->defaultMode)->get();
+
// If the default mode group is different from the group of current mode,
// this means a layer requesting a seamed mode switch just disappeared and
// we should switch back to the default group.
@@ -332,7 +343,7 @@
// of the current mode, in order to prevent unnecessary seamed mode switches
// (e.g. when pausing a video playback).
const auto anchorGroup =
- seamedFocusedLayers > 0 ? mActiveModeIt->second->getGroup() : defaultMode->getGroup();
+ seamedFocusedLayers > 0 ? activeMode.getGroup() : defaultMode->getGroup();
// Consider the touch event if there are no Explicit* layers. Otherwise wait until after we've
// selected a refresh rate to see if we should apply touch boost.
@@ -387,12 +398,12 @@
for (auto& [modeIt, overallScore, fixedRateBelowThresholdLayersScore] : scores) {
const auto& [id, mode] = *modeIt;
- const bool isSeamlessSwitch = mode->getGroup() == mActiveModeIt->second->getGroup();
+ const bool isSeamlessSwitch = mode->getGroup() == activeMode.getGroup();
if (layer.seamlessness == Seamlessness::OnlySeamless && !isSeamlessSwitch) {
ALOGV("%s ignores %s to avoid non-seamless switch. Current mode = %s",
formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
- to_string(*mActiveModeIt->second).c_str());
+ to_string(activeMode).c_str());
continue;
}
@@ -401,7 +412,7 @@
ALOGV("%s ignores %s because it's not focused and the switch is going to be seamed."
" Current mode = %s",
formatLayerInfo(layer, weight).c_str(), to_string(*mode).c_str(),
- to_string(*mActiveModeIt->second).c_str());
+ to_string(activeMode).c_str());
continue;
}
@@ -413,7 +424,7 @@
const bool isInPolicyForDefault = mode->getGroup() == anchorGroup;
if (layer.seamlessness == Seamlessness::Default && !isInPolicyForDefault) {
ALOGV("%s ignores %s. Current mode = %s", formatLayerInfo(layer, weight).c_str(),
- to_string(*mode).c_str(), to_string(*mActiveModeIt->second).c_str());
+ to_string(*mode).c_str(), to_string(activeMode).c_str());
continue;
}
@@ -431,7 +442,7 @@
calculateLayerScoreLocked(layer, mode->getFps(), isSeamlessSwitch);
const float weightedLayerScore = weight * layerScore;
- // Layer with fixed source has a special consideration depends on the
+ // Layer with fixed source has a special consideration which depends on the
// mConfig.frameRateMultipleThreshold. We don't want these layers to score
// refresh rates above the threshold, but we also don't want to favor the lower
// ones by having a greater number of layers scoring them. Instead, we calculate
@@ -454,9 +465,9 @@
const bool layerBelowThreshold = mConfig.frameRateMultipleThreshold != 0 &&
layer.desiredRefreshRate <
Fps::fromValue(mConfig.frameRateMultipleThreshold / 2);
- const bool modeAboveThreshold = layerBelowThreshold &&
- mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
if (fixedSourceLayer && layerBelowThreshold) {
+ const bool modeAboveThreshold =
+ mode->getFps() >= Fps::fromValue(mConfig.frameRateMultipleThreshold);
if (modeAboveThreshold) {
ALOGV("%s gives %s fixed source (above threshold) score of %.4f",
formatLayerInfo(layer, weight).c_str(), to_string(mode->getFps()).c_str(),
@@ -676,7 +687,7 @@
const DisplayModePtr& current = desiredActiveModeId
? mDisplayModes.get(*desiredActiveModeId)->get()
- : mActiveModeIt->second;
+ : getActiveModeItLocked()->second;
const DisplayModePtr& min = mMinRefreshRateModeIt->second;
if (current == min) {
@@ -688,16 +699,17 @@
}
const DisplayModePtr& RefreshRateConfigs::getMinRefreshRateByPolicyLocked() const {
+ const auto& activeMode = *getActiveModeItLocked()->second;
+
for (const DisplayModeIterator modeIt : mPrimaryRefreshRates) {
const auto& mode = modeIt->second;
- if (mActiveModeIt->second->getGroup() == mode->getGroup()) {
+ if (activeMode.getGroup() == mode->getGroup()) {
return mode;
}
}
- ALOGE("Can't find min refresh rate by policy with the same mode group"
- " as the current mode %s",
- to_string(*mActiveModeIt->second).c_str());
+ ALOGE("Can't find min refresh rate by policy with the same mode group as the current mode %s",
+ to_string(activeMode).c_str());
// Default to the lowest refresh rate.
return mPrimaryRefreshRates.front()->second;
@@ -708,6 +720,11 @@
return getMaxRefreshRateByPolicyLocked();
}
+const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked() const {
+ const int anchorGroup = getActiveModeItLocked()->second->getGroup();
+ return getMaxRefreshRateByPolicyLocked(anchorGroup);
+}
+
const DisplayModePtr& RefreshRateConfigs::getMaxRefreshRateByPolicyLocked(int anchorGroup) const {
for (auto it = mPrimaryRefreshRates.rbegin(); it != mPrimaryRefreshRates.rend(); ++it) {
const auto& mode = (*it)->second;
@@ -716,17 +733,28 @@
}
}
- ALOGE("Can't find max refresh rate by policy with the same mode group"
- " as the current mode %s",
- to_string(*mActiveModeIt->second).c_str());
+ const auto& activeMode = *getActiveModeItLocked()->second;
+ ALOGE("Can't find max refresh rate by policy with the same mode group as the current mode %s",
+ to_string(activeMode).c_str());
// Default to the highest refresh rate.
return mPrimaryRefreshRates.back()->second;
}
-DisplayModePtr RefreshRateConfigs::getActiveMode() const {
+DisplayModePtr RefreshRateConfigs::getActiveModePtr() const {
std::lock_guard lock(mLock);
- return mActiveModeIt->second;
+ return getActiveModeItLocked()->second;
+}
+
+const DisplayMode& RefreshRateConfigs::getActiveMode() const {
+ // Reads from kMainThreadContext do not require mLock.
+ ftl::FakeGuard guard(mLock);
+ return *mActiveModeIt->second;
+}
+
+DisplayModeIterator RefreshRateConfigs::getActiveModeItLocked() const {
+ // Reads under mLock do not require kMainThreadContext.
+ return FTL_FAKE_GUARD(kMainThreadContext, mActiveModeIt);
}
void RefreshRateConfigs::setActiveModeId(DisplayModeId modeId) {
@@ -744,7 +772,7 @@
Config config)
: mKnownFrameRates(constructKnownFrameRates(modes)), mConfig(config) {
initializeIdleTimer();
- updateDisplayModes(std::move(modes), activeModeId);
+ FTL_FAKE_GUARD(kMainThreadContext, updateDisplayModes(std::move(modes), activeModeId));
}
void RefreshRateConfigs::initializeIdleTimer() {
@@ -976,7 +1004,7 @@
std::lock_guard lock(mLock);
- const auto activeModeId = mActiveModeIt->first;
+ const auto activeModeId = getActiveModeItLocked()->first;
result += " activeModeId="s;
result += std::to_string(activeModeId.value());
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index a79002e..19bcb94 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -31,6 +31,7 @@
#include "DisplayHardware/HWComposer.h"
#include "Scheduler/OneShotTimer.h"
#include "Scheduler/StrongTyping.h"
+#include "ThreadContext.h"
namespace android::scheduler {
@@ -184,9 +185,13 @@
bool touch = false;
// True if the system hasn't seen any buffers posted to layers recently.
bool idle = false;
+ // Whether the display is about to be powered on, or has been in PowerMode::ON
+ // within the timeout of DisplayPowerTimer.
+ bool powerOnImminent = false;
bool operator==(GlobalSignals other) const {
- return touch == other.touch && idle == other.idle;
+ return touch == other.touch && idle == other.idle &&
+ powerOnImminent == other.powerOnImminent;
}
};
@@ -207,8 +212,11 @@
// uses the primary range, not the app request range.
DisplayModePtr getMaxRefreshRateByPolicy() const EXCLUDES(mLock);
- void setActiveModeId(DisplayModeId) EXCLUDES(mLock);
- DisplayModePtr getActiveMode() const EXCLUDES(mLock);
+ void setActiveModeId(DisplayModeId) EXCLUDES(mLock) REQUIRES(kMainThreadContext);
+
+ // See mActiveModeIt for thread safety.
+ DisplayModePtr getActiveModePtr() const EXCLUDES(mLock);
+ const DisplayMode& getActiveMode() const REQUIRES(kMainThreadContext);
// Returns a known frame rate that is the closest to frameRate
Fps findClosestKnownFrameRate(Fps frameRate) const;
@@ -332,6 +340,9 @@
void constructAvailableRefreshRates() REQUIRES(mLock);
+ // See mActiveModeIt for thread safety.
+ DisplayModeIterator getActiveModeItLocked() const REQUIRES(mLock);
+
std::pair<DisplayModePtr, GlobalSignals> getBestRefreshRateLocked(
const std::vector<LayerRequirement>&, GlobalSignals) const REQUIRES(mLock);
@@ -345,10 +356,8 @@
// Returns the highest refresh rate according to the current policy. May change at runtime. Only
// uses the primary range, not the app request range.
+ const DisplayModePtr& getMaxRefreshRateByPolicyLocked() const REQUIRES(mLock);
const DisplayModePtr& getMaxRefreshRateByPolicyLocked(int anchorGroup) const REQUIRES(mLock);
- const DisplayModePtr& getMaxRefreshRateByPolicyLocked() const REQUIRES(mLock) {
- return getMaxRefreshRateByPolicyLocked(mActiveModeIt->second->getGroup());
- }
const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
bool isPolicyValidLocked(const Policy& policy) const REQUIRES(mLock);
@@ -361,7 +370,8 @@
float calculateNonExactMatchingLayerScoreLocked(const LayerRequirement&, Fps refreshRate) const
REQUIRES(mLock);
- void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock);
+ void updateDisplayModes(DisplayModes, DisplayModeId activeModeId) EXCLUDES(mLock)
+ REQUIRES(kMainThreadContext);
void initializeIdleTimer();
@@ -377,7 +387,10 @@
// is also dependent, so must be reset as well.
DisplayModes mDisplayModes GUARDED_BY(mLock);
- DisplayModeIterator mActiveModeIt GUARDED_BY(mLock);
+ // Written under mLock exclusively from kMainThreadContext, so reads from kMainThreadContext
+ // need not be under mLock.
+ DisplayModeIterator mActiveModeIt GUARDED_BY(mLock) GUARDED_BY(kMainThreadContext);
+
DisplayModeIterator mMinRefreshRateModeIt GUARDED_BY(mLock);
DisplayModeIterator mMaxRefreshRateModeIt GUARDED_BY(mLock);
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 55ae013..ff6b461 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -182,7 +182,7 @@
impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction() const {
return [this](uid_t uid) {
- const Fps refreshRate = holdRefreshRateConfigs()->getActiveMode()->getFps();
+ const Fps refreshRate = holdRefreshRateConfigs()->getActiveModePtr()->getFps();
const nsecs_t currentPeriod = mVsyncSchedule->period().ns() ?: refreshRate.getPeriodNsecs();
const auto frameRate = getFrameRateOverride(uid);
@@ -320,7 +320,7 @@
// mode change is in progress. In that case we shouldn't dispatch an event
// as it will be dispatched when the current mode changes.
if (std::scoped_lock lock(mRefreshRateConfigsLock);
- mRefreshRateConfigs->getActiveMode() != mPolicy.mode) {
+ mRefreshRateConfigs->getActiveModePtr() != mPolicy.mode) {
return;
}
@@ -453,7 +453,7 @@
if (now - last > kIgnoreDelay) {
const auto refreshRate = [&] {
std::scoped_lock lock(mRefreshRateConfigsLock);
- return mRefreshRateConfigs->getActiveMode()->getFps();
+ return mRefreshRateConfigs->getActiveModePtr()->getFps();
}();
resyncToHardwareVsync(false, refreshRate);
}
@@ -577,7 +577,7 @@
// magic number
const Fps refreshRate = [&] {
std::scoped_lock lock(mRefreshRateConfigsLock);
- return mRefreshRateConfigs->getActiveMode()->getFps();
+ return mRefreshRateConfigs->getActiveModePtr()->getFps();
}();
constexpr Fps FPS_THRESHOLD_FOR_KERNEL_TIMER = 65_Hz;
@@ -704,17 +704,13 @@
const auto configs = holdRefreshRateConfigs();
- // If Display Power is not in normal operation we want to be in performance mode. When coming
- // back to normal mode, a grace period is given with DisplayPowerTimer.
- if (mDisplayPowerTimer &&
- (mPolicy.displayPowerMode != hal::PowerMode::ON ||
- mPolicy.displayPowerTimer == TimerState::Reset)) {
- constexpr GlobalSignals kNoSignals;
- return {configs->getMaxRefreshRateByPolicy(), kNoSignals};
- }
+ const bool powerOnImminent = mDisplayPowerTimer &&
+ (mPolicy.displayPowerMode != hal::PowerMode::ON ||
+ mPolicy.displayPowerTimer == TimerState::Reset);
const GlobalSignals signals{.touch = mTouchTimer && mPolicy.touch == TouchState::Active,
- .idle = mPolicy.idleTimer == TimerState::Expired};
+ .idle = mPolicy.idleTimer == TimerState::Expired,
+ .powerOnImminent = powerOnImminent};
return configs->getBestRefreshRate(mPolicy.contentRequirements, signals);
}
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index eb3856d..afb3459 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -229,7 +229,7 @@
nsecs_t getVsyncPeriodFromRefreshRateConfigs() const EXCLUDES(mRefreshRateConfigsLock) {
std::scoped_lock lock(mRefreshRateConfigsLock);
- return mRefreshRateConfigs->getActiveMode()->getFps().getPeriodNsecs();
+ return mRefreshRateConfigs->getActiveModePtr()->getFps().getPeriodNsecs();
}
// Returns the framerate of the layer with the given sequence ID
diff --git a/services/surfaceflinger/Scheduler/VSyncReactor.cpp b/services/surfaceflinger/Scheduler/VSyncReactor.cpp
index 13cd304..e23945d 100644
--- a/services/surfaceflinger/Scheduler/VSyncReactor.cpp
+++ b/services/surfaceflinger/Scheduler/VSyncReactor.cpp
@@ -19,6 +19,7 @@
#define LOG_TAG "VSyncReactor"
//#define LOG_NDEBUG 0
+#include <assert.h>
#include <cutils/properties.h>
#include <log/log.h>
#include <utils/Trace.h>
diff --git a/services/surfaceflinger/Scheduler/include/scheduler/Time.h b/services/surfaceflinger/Scheduler/include/scheduler/Time.h
index f00d456..2ca55d4 100644
--- a/services/surfaceflinger/Scheduler/include/scheduler/Time.h
+++ b/services/surfaceflinger/Scheduler/include/scheduler/Time.h
@@ -41,6 +41,8 @@
static constexpr TimePoint fromNs(nsecs_t);
+ static TimePoint now() { return scheduler::SchedulerClock::now(); };
+
nsecs_t ns() const;
};
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index bdc8406..e31490c 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -53,9 +53,10 @@
#include <configstore/Utils.h>
#include <cutils/compiler.h>
#include <cutils/properties.h>
+#include <ftl/algorithm.h>
#include <ftl/fake_guard.h>
#include <ftl/future.h>
-#include <ftl/small_map.h>
+#include <ftl/unit.h>
#include <gui/AidlStatusUtil.h>
#include <gui/BufferQueue.h>
#include <gui/DebugEGLImageTracker.h>
@@ -108,6 +109,7 @@
#include "BufferStateLayer.h"
#include "Client.h"
#include "Colorizer.h"
+#include "Display/DisplayMap.h"
#include "DisplayDevice.h"
#include "DisplayHardware/ComposerHal.h"
#include "DisplayHardware/FramebufferSurface.h"
@@ -116,7 +118,6 @@
#include "DisplayHardware/PowerAdvisor.h"
#include "DisplayHardware/VirtualDisplaySurface.h"
#include "DisplayRenderArea.h"
-#include "EffectLayer.h"
#include "Effects/Daltonizer.h"
#include "FlagManager.h"
#include "FpsReporter.h"
@@ -172,6 +173,8 @@
OutputCompositionState::CompositionStrategyPredictionState;
using base::StringAppendF;
+using display::PhysicalDisplay;
+using display::PhysicalDisplays;
using gui::DisplayInfo;
using gui::GameMode;
using gui::IDisplayEventConnection;
@@ -594,12 +597,12 @@
std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdsLocked() const {
std::vector<PhysicalDisplayId> displayIds;
- displayIds.reserve(mPhysicalDisplayTokens.size());
+ displayIds.reserve(mPhysicalDisplays.size());
const auto defaultDisplayId = getDefaultDisplayDeviceLocked()->getPhysicalId();
displayIds.push_back(defaultDisplayId);
- for (const auto& [id, token] : mPhysicalDisplayTokens) {
+ for (const auto& [id, display] : mPhysicalDisplays) {
if (id != defaultDisplayId) {
displayIds.push_back(id);
}
@@ -608,6 +611,12 @@
return displayIds;
}
+std::optional<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIdLocked(
+ const sp<display::DisplayToken>& displayToken) const {
+ return ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_key<PhysicalDisplays>);
+}
+
sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
Mutex::Autolock lock(mStateLock);
return getPhysicalDisplayTokenLocked(displayId);
@@ -932,16 +941,19 @@
Mutex::Autolock lock(mStateLock);
- const auto display = getDisplayDeviceLocked(displayToken);
- if (!display) {
+ const auto displayOpt = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
+ .and_then(getDisplayDeviceAndSnapshot());
+
+ if (!displayOpt) {
return NAME_NOT_FOUND;
}
- if (const auto connectionType = display->getConnectionType())
- info->connectionType = *connectionType;
- else {
- return INVALID_OPERATION;
- }
+ const auto& [display, snapshotRef] = *displayOpt;
+ const auto& snapshot = snapshotRef.get();
+
+ info->connectionType = snapshot.connectionType();
+ info->deviceProductInfo = snapshot.deviceProductInfo();
if (mEmulatedDisplayDensity) {
info->density = mEmulatedDisplayDensity;
@@ -953,7 +965,6 @@
info->density /= ACONFIGURATION_DENSITY_MEDIUM;
info->secure = display->isSecure();
- info->deviceProductInfo = display->getDeviceProductInfo();
info->installOrientation = display->getPhysicalOrientation();
return NO_ERROR;
@@ -967,23 +978,22 @@
Mutex::Autolock lock(mStateLock);
- const auto display = getDisplayDeviceLocked(displayToken);
- if (!display) {
+ const auto displayOpt = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
+ .and_then(getDisplayDeviceAndSnapshot());
+ if (!displayOpt) {
return NAME_NOT_FOUND;
}
- const auto displayId = PhysicalDisplayId::tryCast(display->getId());
- if (!displayId) {
- return INVALID_OPERATION;
- }
+ const auto& [display, snapshotRef] = *displayOpt;
+ const auto& snapshot = snapshotRef.get();
- info->activeDisplayModeId = display->getActiveMode()->getId().value();
+ const auto& displayModes = snapshot.displayModes();
- const auto& supportedModes = display->getSupportedModes();
info->supportedDisplayModes.clear();
- info->supportedDisplayModes.reserve(supportedModes.size());
+ info->supportedDisplayModes.reserve(displayModes.size());
- for (const auto& [id, mode] : supportedModes) {
+ for (const auto& [id, mode] : displayModes) {
ui::DisplayMode outMode;
outMode.id = static_cast<int32_t>(id.value());
@@ -1027,21 +1037,24 @@
info->supportedDisplayModes.push_back(outMode);
}
+ const PhysicalDisplayId displayId = snapshot.displayId();
+
+ info->activeDisplayModeId = display->getActiveMode()->getId().value();
info->activeColorMode = display->getCompositionDisplay()->getState().colorMode;
- info->supportedColorModes = getDisplayColorModes(*display);
+ info->supportedColorModes = getDisplayColorModes(displayId);
info->hdrCapabilities = display->getHdrCapabilities();
info->autoLowLatencyModeSupported =
- getHwComposer().hasDisplayCapability(*displayId,
+ getHwComposer().hasDisplayCapability(displayId,
DisplayCapability::AUTO_LOW_LATENCY_MODE);
info->gameContentTypeSupported =
- getHwComposer().supportsContentType(*displayId, hal::ContentType::GAME);
+ getHwComposer().supportsContentType(displayId, hal::ContentType::GAME);
info->preferredBootDisplayMode = static_cast<ui::DisplayModeId>(-1);
if (getHwComposer().hasCapability(Capability::BOOT_DISPLAY_CONFIG)) {
- if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(*displayId)) {
- if (const auto modeId = display->translateModeId(*hwcId)) {
+ if (const auto hwcId = getHwComposer().getPreferredBootDisplayMode(displayId)) {
+ if (const auto modeId = snapshot.translateModeId(*hwcId)) {
info->preferredBootDisplayMode = modeId->value();
}
}
@@ -1056,7 +1069,7 @@
}
const auto& schedule = mScheduler->getVsyncSchedule();
- outStats->vsyncTime = schedule.vsyncDeadlineAfter(scheduler::SchedulerClock::now()).ns();
+ outStats->vsyncTime = schedule.vsyncDeadlineAfter(TimePoint::now()).ns();
outStats->vsyncPeriod = schedule.period().ns();
return NO_ERROR;
}
@@ -1089,39 +1102,44 @@
}
}
-status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int modeId) {
+status_t SurfaceFlinger::setActiveModeFromBackdoor(const sp<display::DisplayToken>& displayToken,
+ DisplayModeId modeId) {
ATRACE_CALL();
if (!displayToken) {
return BAD_VALUE;
}
+ const char* const whence = __func__;
auto future = mScheduler->schedule([=]() -> status_t {
- const auto display = FTL_FAKE_GUARD(mStateLock, getDisplayDeviceLocked(displayToken));
- if (!display) {
- ALOGE("Attempt to set allowed display modes for invalid display token %p",
- displayToken.get());
+ const auto displayOpt =
+ FTL_FAKE_GUARD(mStateLock,
+ ftl::find_if(mPhysicalDisplays,
+ PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
+ .and_then(getDisplayDeviceAndSnapshot()));
+ if (!displayOpt) {
+ ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
return NAME_NOT_FOUND;
}
- if (display->isVirtual()) {
- ALOGW("Attempt to set allowed display modes for virtual display");
- return INVALID_OPERATION;
- }
+ const auto& [display, snapshotRef] = *displayOpt;
+ const auto& snapshot = snapshotRef.get();
- const auto mode = display->getMode(DisplayModeId{modeId});
- if (!mode) {
- ALOGW("Attempt to switch to an unsupported mode %d.", modeId);
+ const auto fpsOpt = snapshot.displayModes().get(modeId).transform(
+ [](const DisplayModePtr& mode) { return mode->getFps(); });
+
+ if (!fpsOpt) {
+ ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
+ to_string(snapshot.displayId()).c_str());
return BAD_VALUE;
}
- const auto fps = mode->getFps();
+ const Fps fps = *fpsOpt;
// Keep the old switching type.
- const auto allowGroupSwitching =
+ const bool allowGroupSwitching =
display->refreshRateConfigs().getCurrentPolicy().allowGroupSwitching;
- const scheduler::RefreshRateConfigs::Policy policy{mode->getId(),
- allowGroupSwitching,
- {fps, fps}};
+ const scheduler::RefreshRateConfigs::Policy policy{modeId, allowGroupSwitching, {fps, fps}};
constexpr bool kOverridePolicy = false;
return setDesiredDisplayModeSpecsInternal(display, policy, kOverridePolicy);
@@ -1138,9 +1156,7 @@
return;
}
- const auto upcomingModeInfo =
- FTL_FAKE_GUARD(kMainThreadContext, display->getUpcomingActiveMode());
-
+ const auto upcomingModeInfo = display->getUpcomingActiveMode();
if (!upcomingModeInfo.mode) {
// There is no pending mode change. This can happen if the active
// display changed and the mode change happened on a different display.
@@ -1159,9 +1175,12 @@
return;
}
- // We just created this display so we can call even if we are not on the main thread.
- ftl::FakeGuard guard(kMainThreadContext);
- display->setActiveMode(upcomingModeInfo.mode->getId());
+ mPhysicalDisplays.get(display->getPhysicalId())
+ .transform(&PhysicalDisplay::snapshotRef)
+ .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
+ FTL_FAKE_GUARD(kMainThreadContext,
+ display->setActiveMode(upcomingModeInfo.mode->getId(), snapshot));
+ }));
const Fps refreshRate = upcomingModeInfo.mode->getFps();
mRefreshRateStats->setRefreshRate(refreshRate);
@@ -1191,12 +1210,16 @@
std::optional<PhysicalDisplayId> displayToUpdateImmediately;
- for (const auto& iter : mDisplays) {
- const auto& display = iter.second;
- if (!display || !display->isInternal()) {
+ for (const auto& [id, physical] : mPhysicalDisplays) {
+ const auto& snapshot = physical.snapshot();
+
+ if (snapshot.connectionType() != ui::DisplayConnectionType::Internal) {
continue;
}
+ const auto display = getDisplayDeviceLocked(id);
+ if (!display) continue;
+
// Store the local variable to release the lock.
const auto desiredActiveMode = display->getDesiredActiveMode();
if (!desiredActiveMode) {
@@ -1210,20 +1233,23 @@
continue;
}
- const auto desiredMode = display->getMode(desiredActiveMode->mode->getId());
- if (!desiredMode) {
+ const auto desiredModeId = desiredActiveMode->mode->getId();
+ const auto refreshRateOpt =
+ snapshot.displayModes()
+ .get(desiredModeId)
+ .transform([](const DisplayModePtr& mode) { return mode->getFps(); });
+
+ if (!refreshRateOpt) {
ALOGW("Desired display mode is no longer supported. Mode ID = %d",
- desiredActiveMode->mode->getId().value());
+ desiredModeId.value());
clearDesiredActiveModeState(display);
continue;
}
- const auto refreshRate = desiredMode->getFps();
- ALOGV("%s changing active mode to %d(%s) for display %s", __func__,
- desiredMode->getId().value(), to_string(refreshRate).c_str(),
- to_string(display->getId()).c_str());
+ ALOGV("%s changing active mode to %d(%s) for display %s", __func__, desiredModeId.value(),
+ to_string(*refreshRateOpt).c_str(), to_string(display->getId()).c_str());
- if (display->getActiveMode()->getId() == desiredActiveMode->mode->getId()) {
+ if (display->getActiveMode()->getId() == desiredModeId) {
// we are already in the requested mode, there is nothing left to do
desiredActiveModeChangeDone(display);
continue;
@@ -1232,8 +1258,7 @@
// Desired active mode was set, it is different than the mode currently in use, however
// allowed modes might have changed by the time we process the refresh.
// Make sure the desired mode is still allowed
- const auto displayModeAllowed =
- display->refreshRateConfigs().isModeAllowed(desiredActiveMode->mode->getId());
+ const auto displayModeAllowed = display->refreshRateConfigs().isModeAllowed(desiredModeId);
if (!displayModeAllowed) {
clearDesiredActiveModeState(display);
continue;
@@ -1245,9 +1270,8 @@
constraints.seamlessRequired = false;
hal::VsyncPeriodChangeTimeline outTimeline;
- const auto status = FTL_FAKE_GUARD(kMainThreadContext,
- display->initiateModeChange(*desiredActiveMode,
- constraints, &outTimeline));
+ const auto status =
+ display->initiateModeChange(*desiredActiveMode, constraints, &outTimeline);
if (status != NO_ERROR) {
// initiateModeChange may fail if a hotplug event is just about
@@ -1295,15 +1319,18 @@
future.wait();
}
-std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(const DisplayDevice& display) {
- auto modes = getHwComposer().getColorModes(display.getPhysicalId());
+std::vector<ColorMode> SurfaceFlinger::getDisplayColorModes(PhysicalDisplayId displayId) {
+ auto modes = getHwComposer().getColorModes(displayId);
+
+ const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
+ .transform(&PhysicalDisplay::isInternal)
+ .value_or(false);
// If the display is internal and the configuration claims it's not wide color capable,
// filter out all wide color modes. The typical reason why this happens is that the
// hardware is not good enough to support GPU composition of wide color, and thus the
// OEMs choose to disable this capability.
- if (display.getConnectionType() == ui::DisplayConnectionType::Internal &&
- !hasWideColorDisplay) {
+ if (isInternalDisplay && !hasWideColorDisplay) {
const auto newEnd = std::remove_if(modes.begin(), modes.end(), isWideColorMode);
modes.erase(newEnd, modes.end());
}
@@ -1319,13 +1346,13 @@
Mutex::Autolock lock(mStateLock);
- const auto display = getDisplayDeviceLocked(displayToken);
+ const auto display = ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_mapped_ref<PhysicalDisplays>);
if (!display) {
return NAME_NOT_FOUND;
}
- const auto connectionType = display->getConnectionType();
- if (connectionType != ui::DisplayConnectionType::Internal) {
+ if (!display.transform(&PhysicalDisplay::isInternal).value()) {
return INVALID_OPERATION;
}
@@ -1353,7 +1380,7 @@
return INVALID_OPERATION;
}
- const auto modes = getDisplayColorModes(*display);
+ const auto modes = getDisplayColorModes(display->getPhysicalId());
const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end();
if (mode < ColorMode::NATIVE || !exists) {
@@ -1381,30 +1408,31 @@
return NO_ERROR;
}
-status_t SurfaceFlinger::setBootDisplayMode(const sp<IBinder>& displayToken,
- ui::DisplayModeId modeId) {
+status_t SurfaceFlinger::setBootDisplayMode(const sp<display::DisplayToken>& displayToken,
+ DisplayModeId modeId) {
const char* const whence = __func__;
auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) -> status_t {
- const auto display = getDisplayDeviceLocked(displayToken);
- if (!display) {
- ALOGE("%s: Invalid display token %p", whence, displayToken.get());
+ const auto snapshotOpt =
+ ftl::find_if(mPhysicalDisplays, PhysicalDisplay::hasToken(displayToken))
+ .transform(&ftl::to_mapped_ref<PhysicalDisplays>)
+ .transform(&PhysicalDisplay::snapshotRef);
+
+ if (!snapshotOpt) {
+ ALOGE("%s: Invalid physical display token %p", whence, displayToken.get());
return NAME_NOT_FOUND;
}
- if (display->isVirtual()) {
- ALOGE("%s: Invalid operation on virtual display", whence);
- return INVALID_OPERATION;
- }
+ const auto& snapshot = snapshotOpt->get();
+ const auto hwcIdOpt = snapshot.displayModes().get(modeId).transform(
+ [](const DisplayModePtr& mode) { return mode->getHwcId(); });
- const auto displayId = display->getPhysicalId();
- const auto mode = display->getMode(DisplayModeId{modeId});
- if (!mode) {
- ALOGE("%s: Invalid mode %d for display %s", whence, modeId,
- to_string(displayId).c_str());
+ if (!hwcIdOpt) {
+ ALOGE("%s: Invalid mode %d for display %s", whence, modeId.value(),
+ to_string(snapshot.displayId()).c_str());
return BAD_VALUE;
}
- return getHwComposer().setBootDisplayMode(displayId, mode->getHwcId());
+ return getHwComposer().setBootDisplayMode(snapshot.displayId(), *hwcIdOpt);
});
return future.get();
}
@@ -1972,7 +2000,7 @@
: calculateExpectedPresentTime(frameTime);
ATRACE_FORMAT("%s %" PRId64 " vsyncIn %.2fms%s", __func__, vsyncId.value,
- ticks<std::milli, float>(mExpectedPresentTime - scheduler::SchedulerClock::now()),
+ ticks<std::milli, float>(mExpectedPresentTime - TimePoint::now()),
mExpectedPresentTime == expectedVsyncTime ? "" : " (adjusted)");
const Period vsyncPeriod = mScheduler->getVsyncSchedule().period();
@@ -2059,16 +2087,16 @@
activeDisplay->getPowerMode() == hal::PowerMode::ON;
if (mPowerHintSessionEnabled) {
const auto& display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()).get();
- const nsecs_t vsyncPeriod = display->getActiveMode()->getVsyncPeriod();
- mPowerAdvisor->setCommitStart(frameTime.ns());
- mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime.ns());
+ const Period vsyncPeriod = Period::fromNs(display->getActiveMode()->getVsyncPeriod());
+ mPowerAdvisor->setCommitStart(frameTime);
+ mPowerAdvisor->setExpectedPresentTime(mExpectedPresentTime);
// Frame delay is how long we should have minus how long we actually have.
const Duration idealSfWorkDuration = mVsyncModulator->getVsyncConfig().sfWorkDuration;
const Duration frameDelay = idealSfWorkDuration - (mExpectedPresentTime - frameTime);
- mPowerAdvisor->setFrameDelay(frameDelay.ns());
- mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration.ns());
+ mPowerAdvisor->setFrameDelay(frameDelay);
+ mPowerAdvisor->setTotalFrameTargetWorkDuration(idealSfWorkDuration);
mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
// Send early hint here to make sure there's not another frame pending
@@ -2129,7 +2157,7 @@
// Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
// and may eventually call to ~Layer() if it holds the last reference
{
- Mutex::Autolock _l(mStateLock);
+ Mutex::Autolock lock(mStateLock);
mScheduler->chooseRefreshRateForContent();
setActiveModeInHwcIfNeeded();
}
@@ -2161,10 +2189,6 @@
displayIds.push_back(display->getId());
}
mPowerAdvisor->setDisplays(displayIds);
- mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
- if (auto layerFE = layer->getCompositionEngineLayerFE())
- refreshArgs.layers.push_back(layerFE);
- });
if (DOES_CONTAIN_BORDER) {
refreshArgs.borderInfoList.clear();
@@ -2195,6 +2219,12 @@
refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
refreshArgs.updatingGeometryThisFrame = mGeometryDirty.exchange(false) || mVisibleRegionsDirty;
+ mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
+ layer->updateSnapshot(refreshArgs.updatingGeometryThisFrame);
+ if (auto layerFE = layer->getCompositionEngineLayerFE()) {
+ refreshArgs.layers.push_back(layerFE);
+ }
+ });
refreshArgs.blursAreExpensive = mBlursAreExpensive;
refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
@@ -2228,8 +2258,9 @@
// Send a power hint hint after presentation is finished
if (mPowerHintSessionEnabled) {
- mPowerAdvisor->setSfPresentTiming(mPreviousPresentFences[0].fenceTime->getSignalTime(),
- systemTime());
+ mPowerAdvisor->setSfPresentTiming(TimePoint::fromNs(mPreviousPresentFences[0]
+ .fenceTime->getSignalTime()),
+ TimePoint::now());
if (mPowerHintSessionMode.late) {
mPowerAdvisor->sendActualWorkDuration();
}
@@ -2279,7 +2310,7 @@
}
if (mPowerHintSessionEnabled) {
- mPowerAdvisor->setCompositeEnd(systemTime());
+ mPowerAdvisor->setCompositeEnd(TimePoint::now());
}
}
@@ -2376,7 +2407,7 @@
auto presentFenceTime = std::make_shared<FenceTime>(presentFence);
mPreviousPresentFences[0] = {presentFence, presentFenceTime};
- const TimePoint presentTime = scheduler::SchedulerClock::now();
+ const TimePoint presentTime = TimePoint::now();
// Set presentation information before calling Layer::releasePendingBuffer, such that jank
// information from previous' frame classification is already available when sending jank info
@@ -2466,7 +2497,13 @@
mTimeStats->incrementTotalFrames();
mTimeStats->setPresentFenceGlobal(presentFenceTime);
- if (display && display->isInternal() && display->getPowerMode() == hal::PowerMode::ON &&
+ const bool isInternalDisplay = display &&
+ FTL_FAKE_GUARD(mStateLock, mPhysicalDisplays)
+ .get(display->getPhysicalId())
+ .transform(&PhysicalDisplay::isInternal)
+ .value_or(false);
+
+ if (isInternalDisplay && display && display->getPowerMode() == hal::PowerMode::ON &&
presentFenceTime->isValid()) {
mScheduler->addPresentFence(std::move(presentFenceTime));
}
@@ -2600,10 +2637,11 @@
return {};
}
- DisplayModes oldModes;
- if (const auto token = getPhysicalDisplayTokenLocked(displayId)) {
- oldModes = getDisplayDeviceLocked(token)->getSupportedModes();
- }
+ const DisplayModes oldModes = mPhysicalDisplays.get(displayId)
+ .transform([](const PhysicalDisplay& display) {
+ return display.snapshot().displayModes();
+ })
+ .value_or(DisplayModes{});
ui::DisplayModeId nextModeId = 1 +
std::accumulate(oldModes.begin(), oldModes.end(), static_cast<ui::DisplayModeId>(-1),
@@ -2668,21 +2706,22 @@
const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId,
hal::HWDisplayId hwcDisplayId, bool connected,
DisplayIdentificationInfo&& info) {
- const auto tokenOpt = mPhysicalDisplayTokens.get(displayId);
+ const auto displayOpt = mPhysicalDisplays.get(displayId);
if (!connected) {
- LOG_ALWAYS_FATAL_IF(!tokenOpt);
+ LOG_ALWAYS_FATAL_IF(!displayOpt);
+ const auto& display = displayOpt->get();
- if (const ssize_t index = mCurrentState.displays.indexOfKey(tokenOpt->get()); index >= 0) {
+ if (const ssize_t index = mCurrentState.displays.indexOfKey(display.token()); index >= 0) {
const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
mInterceptor->saveDisplayDeletion(state.sequenceId);
mCurrentState.displays.removeItemsAt(index);
}
- mPhysicalDisplayTokens.erase(displayId);
+ mPhysicalDisplays.erase(displayId);
return "Disconnecting";
}
- auto [supportedModes, activeMode] = loadDisplayModes(displayId);
+ auto [displayModes, activeMode] = loadDisplayModes(displayId);
if (!activeMode) {
// TODO(b/241286153): Report hotplug failure to the framework.
ALOGE("Failed to hotplug display %s", to_string(displayId).c_str());
@@ -2690,30 +2729,42 @@
return nullptr;
}
- if (tokenOpt) {
- auto& state = mCurrentState.displays.editValueFor(tokenOpt->get());
- state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
- state.physical->supportedModes = std::move(supportedModes);
- state.physical->activeMode = std::move(activeMode);
+ if (displayOpt) {
+ const auto& display = displayOpt->get();
+ const auto& snapshot = display.snapshot();
+
+ std::optional<DeviceProductInfo> deviceProductInfo;
if (getHwComposer().updatesDeviceProductInfoOnHotplugReconnect()) {
- state.physical->deviceProductInfo = std::move(info.deviceProductInfo);
+ deviceProductInfo = std::move(info.deviceProductInfo);
+ } else {
+ deviceProductInfo = snapshot.deviceProductInfo();
}
+
+ const auto it =
+ mPhysicalDisplays.try_replace(displayId, display.token(), displayId,
+ snapshot.connectionType(), std::move(displayModes),
+ std::move(deviceProductInfo));
+
+ auto& state = mCurrentState.displays.editValueFor(it->second.token());
+ state.sequenceId = DisplayDeviceState{}.sequenceId; // Generate new sequenceId.
+ state.physical->activeMode = std::move(activeMode);
return "Reconnecting";
}
+ const sp<IBinder> token = sp<BBinder>::make();
+
+ mPhysicalDisplays.try_emplace(displayId, token, displayId,
+ getHwComposer().getDisplayConnectionType(displayId),
+ std::move(displayModes), std::move(info.deviceProductInfo));
+
DisplayDeviceState state;
state.physical = {.id = displayId,
- .type = getHwComposer().getDisplayConnectionType(displayId),
.hwcDisplayId = hwcDisplayId,
- .deviceProductInfo = std::move(info.deviceProductInfo),
- .supportedModes = std::move(supportedModes),
.activeMode = std::move(activeMode)};
state.isSecure = true; // All physical displays are currently considered secure.
state.displayName = std::move(info.name);
- sp<IBinder> token = sp<BBinder>::make();
mCurrentState.displays.add(token, state);
- mPhysicalDisplayTokens.try_emplace(displayId, std::move(token));
mInterceptor->saveDisplayCreation(state);
return "Connecting";
}
@@ -2738,8 +2789,6 @@
creationArgs.supportedPerFrameMetadata = 0;
if (const auto& physical = state.physical) {
- creationArgs.connectionType = physical->type;
- creationArgs.supportedModes = physical->supportedModes;
creationArgs.activeModeId = physical->activeMode->getId();
const auto [kernelIdleTimerController, idleTimerTimeoutMs] =
getKernelIdleTimerProperties(compositionDisplay->getId());
@@ -2750,9 +2799,17 @@
base::GetIntProperty("debug.sf.frame_rate_multiple_threshold", 0),
.idleTimerTimeout = idleTimerTimeoutMs,
.kernelIdleTimerController = kernelIdleTimerController};
+
creationArgs.refreshRateConfigs =
- std::make_shared<scheduler::RefreshRateConfigs>(creationArgs.supportedModes,
- creationArgs.activeModeId, config);
+ mPhysicalDisplays.get(physical->id)
+ .transform(&PhysicalDisplay::snapshotRef)
+ .transform([&](const display::DisplaySnapshot& snapshot) {
+ return std::make_shared<
+ scheduler::RefreshRateConfigs>(snapshot.displayModes(),
+ creationArgs.activeModeId,
+ config);
+ })
+ .value_or(nullptr);
}
if (const auto id = PhysicalDisplayId::tryCast(compositionDisplay->getId())) {
@@ -2793,7 +2850,8 @@
ALOGV("Display Orientation: %s", toCString(creationArgs.physicalOrientation));
// virtual displays are always considered enabled
- creationArgs.initialPowerMode = state.isVirtual() ? hal::PowerMode::ON : hal::PowerMode::OFF;
+ creationArgs.initialPowerMode =
+ state.isVirtual() ? std::make_optional(hal::PowerMode::ON) : std::nullopt;
sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
@@ -2809,13 +2867,17 @@
compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
RenderIntent::COLORIMETRIC,
Dataspace::UNKNOWN});
- if (!state.isVirtual()) {
- FTL_FAKE_GUARD(kMainThreadContext,
- display->setActiveMode(state.physical->activeMode->getId()));
- display->setDeviceProductInfo(state.physical->deviceProductInfo);
+
+ if (const auto& physical = state.physical) {
+ mPhysicalDisplays.get(physical->id)
+ .transform(&PhysicalDisplay::snapshotRef)
+ .transform(ftl::unit_fn([&](const display::DisplaySnapshot& snapshot) {
+ FTL_FAKE_GUARD(kMainThreadContext,
+ display->setActiveMode(physical->activeMode->getId(), snapshot));
+ }));
}
- display->setLayerStack(state.layerStack);
+ display->setLayerFilter(makeLayerFilterForDisplay(display->getId(), state.layerStack));
display->setProjection(state.orientation, state.layerStackSpaceRect,
state.orientedDisplaySpaceRect);
display->setDisplayName(state.displayName);
@@ -2971,7 +3033,8 @@
if (const auto display = getDisplayDeviceLocked(displayToken)) {
if (currentState.layerStack != drawingState.layerStack) {
- display->setLayerStack(currentState.layerStack);
+ display->setLayerFilter(
+ makeLayerFilterForDisplay(display->getId(), currentState.layerStack));
}
if (currentState.flags != drawingState.flags) {
display->setFlags(currentState.flags);
@@ -2995,9 +3058,10 @@
}
}
}
+
void SurfaceFlinger::updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay) {
mVsyncConfiguration->reset();
- const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode()->getFps();
+ const Fps refreshRate = activeDisplay->refreshRateConfigs().getActiveMode().getFps();
updatePhaseConfiguration(refreshRate);
mRefreshRateStats->setRefreshRate(refreshRate);
}
@@ -3217,7 +3281,7 @@
void SurfaceFlinger::buildWindowInfos(std::vector<WindowInfo>& outWindowInfos,
std::vector<DisplayInfo>& outDisplayInfos) {
- ftl::SmallMap<ui::LayerStack, DisplayDevice::InputInfo, 4> displayInputInfos;
+ display::DisplayMap<ui::LayerStack, DisplayDevice::InputInfo> displayInputInfos;
for (const auto& [_, display] : FTL_FAKE_GUARD(mStateLock, mDisplays)) {
const auto layerStack = display->getLayerStack();
@@ -3570,15 +3634,16 @@
return NO_MEMORY;
}
+ layer->updateTransformHint(mActiveDisplayTransformHint);
+ if (outTransformHint) {
+ *outTransformHint = mActiveDisplayTransformHint;
+ }
+
{
std::scoped_lock<std::mutex> lock(mCreatedLayersLock);
mCreatedLayers.emplace_back(layer, parent, addToRoot);
}
- layer->updateTransformHint(mActiveDisplayTransformHint);
- if (outTransformHint) {
- *outTransformHint = mActiveDisplayTransformHint;
- }
// attach this layer to the client
if (client != nullptr) {
client->attachLayer(handle, layer);
@@ -4574,7 +4639,11 @@
switch (args.flags & ISurfaceComposerClient::eFXSurfaceMask) {
case ISurfaceComposerClient::eFXSurfaceBufferQueue:
- case ISurfaceComposerClient::eFXSurfaceBufferState: {
+ case ISurfaceComposerClient::eFXSurfaceContainer:
+ case ISurfaceComposerClient::eFXSurfaceBufferState:
+ args.flags |= ISurfaceComposerClient::eNoColorFill;
+ FMT_FALLTHROUGH;
+ case ISurfaceComposerClient::eFXSurfaceEffect: {
result = createBufferStateLayer(args, outHandle, &layer);
std::atomic<int32_t>* pendingBufferCounter = layer->getPendingBufferCounter();
if (pendingBufferCounter) {
@@ -4583,12 +4652,6 @@
pendingBufferCounter);
}
} break;
- case ISurfaceComposerClient::eFXSurfaceContainer:
- args.flags |= ISurfaceComposerClient::eNoColorFill;
- FMT_FALLTHROUGH;
- case ISurfaceComposerClient::eFXSurfaceEffect:
- result = createEffectLayer(args, outHandle, &layer);
- break;
default:
result = BAD_VALUE;
break;
@@ -4660,8 +4723,6 @@
}
}
-// ---------------------------------------------------------------------------
-
void SurfaceFlinger::onInitializeDisplays() {
const auto display = getDefaultDisplayDeviceLocked();
if (!display) return;
@@ -4699,8 +4760,9 @@
void SurfaceFlinger::initializeDisplays() {
// Async since we may be called from the main thread.
- static_cast<void>(
- mScheduler->schedule([this]() FTL_FAKE_GUARD(mStateLock) { onInitializeDisplays(); }));
+ static_cast<void>(mScheduler->schedule(
+ [this]() FTL_FAKE_GUARD(mStateLock)
+ FTL_FAKE_GUARD(kMainThreadContext) { onInitializeDisplays(); }));
}
void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode) {
@@ -4712,13 +4774,17 @@
const auto displayId = display->getPhysicalId();
ALOGD("Setting power mode %d on display %s", mode, to_string(displayId).c_str());
- const hal::PowerMode currentMode = display->getPowerMode();
- if (mode == currentMode) {
+ std::optional<hal::PowerMode> currentMode = display->getPowerMode();
+ if (currentMode.has_value() && mode == *currentMode) {
return;
}
+ const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
+ .transform(&PhysicalDisplay::isInternal)
+ .value_or(false);
+
const auto activeDisplay = getDisplayDeviceLocked(mActiveDisplayToken);
- if (activeDisplay != display && display->isInternal() && activeDisplay &&
+ if (isInternalDisplay && activeDisplay != display && activeDisplay &&
activeDisplay->isPoweredOn()) {
ALOGW("Trying to change power mode on non active display while the active display is ON");
}
@@ -4728,10 +4794,10 @@
if (mInterceptor->isEnabled()) {
mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast<int32_t>(mode));
}
- const auto refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
- if (currentMode == hal::PowerMode::OFF) {
+ const auto refreshRate = display->refreshRateConfigs().getActiveMode().getFps();
+ if (*currentMode == hal::PowerMode::OFF) {
// Turn on the display
- if (display->isInternal() && (!activeDisplay || !activeDisplay->isPoweredOn())) {
+ if (isInternalDisplay && (!activeDisplay || !activeDisplay->isPoweredOn())) {
onActiveDisplayChangedLocked(display);
}
// Keep uclamp in a separate syscall and set it before changing to RT due to b/190237315.
@@ -4759,7 +4825,7 @@
if (SurfaceFlinger::setSchedAttr(false) != NO_ERROR) {
ALOGW("Couldn't set uclamp.min on display off: %s\n", strerror(errno));
}
- if (isDisplayActiveLocked(display) && currentMode != hal::PowerMode::DOZE_SUSPEND) {
+ if (isDisplayActiveLocked(display) && *currentMode != hal::PowerMode::DOZE_SUSPEND) {
mScheduler->disableHardwareVsync(true);
mScheduler->onScreenReleased(mAppConnectionHandle);
}
@@ -4773,7 +4839,7 @@
} else if (mode == hal::PowerMode::DOZE || mode == hal::PowerMode::ON) {
// Update display while dozing
getHwComposer().setPowerMode(displayId, mode);
- if (isDisplayActiveLocked(display) && currentMode == hal::PowerMode::DOZE_SUSPEND) {
+ if (isDisplayActiveLocked(display) && *currentMode == hal::PowerMode::DOZE_SUSPEND) {
ALOGI("Force repainting for DOZE_SUSPEND -> DOZE or ON.");
mVisibleRegionsDirty = true;
scheduleRepaint();
@@ -4802,7 +4868,8 @@
}
void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
- auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) {
+ auto future = mScheduler->schedule([=]() FTL_FAKE_GUARD(mStateLock) FTL_FAKE_GUARD(
+ kMainThreadContext) {
const auto display = getDisplayDeviceLocked(displayToken);
if (!display) {
ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
@@ -4990,10 +5057,20 @@
}
void SurfaceFlinger::dumpDisplays(std::string& result) const {
- for (const auto& [token, display] : mDisplays) {
- display->dump(result);
+ for (const auto& [id, display] : mPhysicalDisplays) {
+ if (const auto device = getDisplayDeviceLocked(id)) {
+ device->dump(result);
+ }
+ display.snapshot().dump(result);
result += '\n';
}
+
+ for (const auto& [token, display] : mDisplays) {
+ if (display->isVirtual()) {
+ display->dump(result);
+ result += '\n';
+ }
+ }
}
void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
@@ -5792,7 +5869,7 @@
}();
mDebugDisplayModeSetByBackdoor = false;
- const status_t result = setActiveModeFromBackdoor(display, modeId);
+ const status_t result = setActiveModeFromBackdoor(display, DisplayModeId{modeId});
mDebugDisplayModeSetByBackdoor = result == NO_ERROR;
return result;
}
@@ -6439,7 +6516,7 @@
std::unique_ptr<RenderArea> renderArea = renderAreaFuture.get();
if (!renderArea) {
ALOGW("Skipping screen capture because of invalid render area.");
- captureResults.result = NO_MEMORY;
+ captureResults.fenceResult = base::unexpected(NO_MEMORY);
captureListener->onScreenCaptureCompleted(captureResults);
return ftl::yield<FenceResult>(base::unexpected(NO_ERROR)).share();
}
@@ -6456,9 +6533,7 @@
return ftl::Future(std::move(renderFuture))
.then([captureListener, captureResults = std::move(captureResults)](
FenceResult fenceResult) mutable -> FenceResult {
- // TODO(b/232535621): Change ScreenCaptureResults to store a FenceResult.
- captureResults.result = fenceStatus(fenceResult);
- captureResults.fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
+ captureResults.fenceResult = std::move(fenceResult);
captureListener->onScreenCaptureCompleted(captureResults);
return base::unexpected(NO_ERROR);
})
@@ -6668,6 +6743,20 @@
}
}
+std::optional<DisplayModePtr> SurfaceFlinger::getPreferredDisplayMode(
+ PhysicalDisplayId displayId, DisplayModeId defaultModeId) const {
+ if (const auto schedulerMode = mScheduler->getPreferredDisplayMode();
+ schedulerMode && schedulerMode->getPhysicalDisplayId() == displayId) {
+ return schedulerMode;
+ }
+
+ return mPhysicalDisplays.get(displayId)
+ .transform(&PhysicalDisplay::snapshotRef)
+ .and_then([&](const display::DisplaySnapshot& snapshot) {
+ return snapshot.displayModes().get(defaultModeId);
+ });
+}
+
status_t SurfaceFlinger::setDesiredDisplayModeSpecsInternal(
const sp<DisplayDevice>& display,
const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
@@ -6686,7 +6775,7 @@
return NO_ERROR;
}
- scheduler::RefreshRateConfigs::Policy currentPolicy =
+ const scheduler::RefreshRateConfigs::Policy currentPolicy =
display->refreshRateConfigs().getCurrentPolicy();
ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
@@ -6701,27 +6790,25 @@
mScheduler->onNonPrimaryDisplayModeChanged(mAppConnectionHandle, activeMode);
}
- const DisplayModePtr preferredDisplayMode = [&] {
- const auto schedulerMode = mScheduler->getPreferredDisplayMode();
- if (schedulerMode && schedulerMode->getPhysicalDisplayId() == display->getPhysicalId()) {
- return schedulerMode;
- }
-
- return display->getMode(currentPolicy.defaultMode);
- }();
-
- ALOGV("trying to switch to Scheduler preferred mode %d (%s)",
- preferredDisplayMode->getId().value(), to_string(preferredDisplayMode->getFps()).c_str());
-
- if (display->refreshRateConfigs().isModeAllowed(preferredDisplayMode->getId())) {
- ALOGV("switching to Scheduler preferred display mode %d",
- preferredDisplayMode->getId().value());
- setDesiredActiveMode({preferredDisplayMode, DisplayModeEvent::Changed});
- } else {
- LOG_ALWAYS_FATAL("Desired display mode not allowed: %d",
- preferredDisplayMode->getId().value());
+ auto preferredModeOpt =
+ getPreferredDisplayMode(display->getPhysicalId(), currentPolicy.defaultMode);
+ if (!preferredModeOpt) {
+ ALOGE("%s: Preferred mode is unknown", __func__);
+ return NAME_NOT_FOUND;
}
+ auto preferredMode = std::move(*preferredModeOpt);
+ const auto preferredModeId = preferredMode->getId();
+
+ ALOGV("Switching to Scheduler preferred mode %d (%s)", preferredModeId.value(),
+ to_string(preferredMode->getFps()).c_str());
+
+ if (!display->refreshRateConfigs().isModeAllowed(preferredModeId)) {
+ ALOGE("%s: Preferred mode %d is disallowed", __func__, preferredModeId.value());
+ return INVALID_OPERATION;
+ }
+
+ setDesiredActiveMode({std::move(preferredMode), DisplayModeEvent::Changed});
return NO_ERROR;
}
@@ -6880,9 +6967,11 @@
}
void SurfaceFlinger::enableRefreshRateOverlay(bool enable) {
- for (const auto& [ignored, display] : mDisplays) {
- if (display->isInternal()) {
- display->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
+ for (const auto& [id, display] : mPhysicalDisplays) {
+ if (display.snapshot().connectionType() == ui::DisplayConnectionType::Internal) {
+ if (const auto device = getDisplayDeviceLocked(id)) {
+ device->enableRefreshRateOverlay(enable, mRefreshRateOverlaySpinner);
+ }
}
}
}
@@ -6931,7 +7020,7 @@
refreshRate = *frameRateOverride;
} else if (!getHwComposer().isHeadless()) {
if (const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked())) {
- refreshRate = display->refreshRateConfigs().getActiveMode()->getFps();
+ refreshRate = display->refreshRateConfigs().getActiveModePtr()->getFps();
}
}
@@ -7368,8 +7457,7 @@
int displayModeId) {
status_t status = checkAccessPermission();
if (status == OK) {
- status = mFlinger->setBootDisplayMode(display,
- static_cast<ui::DisplayModeId>(displayModeId));
+ status = mFlinger->setBootDisplayMode(display, DisplayModeId{displayModeId});
}
return binderStatusFromStatusT(status);
}
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 3101885..f7684a0 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -29,7 +29,6 @@
#include <cutils/atomic.h>
#include <cutils/compiler.h>
#include <ftl/future.h>
-#include <ftl/small_map.h>
#include <gui/BufferQueue.h>
#include <gui/CompositorTiming.h>
#include <gui/FrameTimestamps.h>
@@ -59,6 +58,8 @@
#include <ui/FenceResult.h>
#include "ClientCache.h"
+#include "Display/DisplayMap.h"
+#include "Display/PhysicalDisplay.h"
#include "DisplayDevice.h"
#include "DisplayHardware/HWC2.h"
#include "DisplayHardware/PowerAdvisor.h"
@@ -515,7 +516,7 @@
status_t getDisplayNativePrimaries(const sp<IBinder>& displayToken, ui::DisplayPrimaries&);
status_t setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode colorMode);
status_t getBootDisplayModeSupport(bool* outSupport) const;
- status_t setBootDisplayMode(const sp<IBinder>& displayToken, ui::DisplayModeId id);
+ status_t setBootDisplayMode(const sp<display::DisplayToken>&, DisplayModeId);
status_t clearBootDisplayMode(const sp<IBinder>& displayToken);
void setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on);
void setGameContentType(const sp<IBinder>& displayToken, bool on);
@@ -647,34 +648,39 @@
// Show spinner with refresh rate overlay
bool mRefreshRateOverlaySpinner = false;
- // Called on the main thread in response to initializeDisplays()
- void onInitializeDisplays() REQUIRES(mStateLock);
// Sets the desired active mode bit. It obtains the lock, and sets mDesiredActiveMode.
void setDesiredActiveMode(const ActiveModeInfo& info) REQUIRES(mStateLock);
- status_t setActiveModeFromBackdoor(const sp<IBinder>& displayToken, int id);
+ status_t setActiveModeFromBackdoor(const sp<display::DisplayToken>&, DisplayModeId);
// Sets the active mode and a new refresh rate in SF.
- void updateInternalStateWithChangedMode() REQUIRES(mStateLock);
+ void updateInternalStateWithChangedMode() REQUIRES(mStateLock, kMainThreadContext);
// Calls to setActiveMode on the main thread if there is a pending mode change
// that needs to be applied.
- void setActiveModeInHwcIfNeeded() REQUIRES(mStateLock);
+ void setActiveModeInHwcIfNeeded() REQUIRES(mStateLock, kMainThreadContext);
void clearDesiredActiveModeState(const sp<DisplayDevice>&) REQUIRES(mStateLock);
// Called when active mode is no longer is progress
void desiredActiveModeChangeDone(const sp<DisplayDevice>&) REQUIRES(mStateLock);
// Called on the main thread in response to setPowerMode()
void setPowerModeInternal(const sp<DisplayDevice>& display, hal::PowerMode mode)
- REQUIRES(mStateLock);
+ REQUIRES(mStateLock, kMainThreadContext);
// Returns true if the display has a visible HDR layer in its layer stack.
bool hasVisibleHdrLayer(const sp<DisplayDevice>& display) REQUIRES(mStateLock);
+ // Returns the preferred mode for PhysicalDisplayId if the Scheduler has selected one for that
+ // display. Falls back to the display's defaultModeId otherwise.
+ std::optional<DisplayModePtr> getPreferredDisplayMode(PhysicalDisplayId,
+ DisplayModeId defaultModeId) const
+ REQUIRES(mStateLock);
+
// Sets the desired display mode specs.
status_t setDesiredDisplayModeSpecsInternal(
const sp<DisplayDevice>& display,
const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy)
EXCLUDES(mStateLock);
- void commitTransactions() EXCLUDES(mStateLock);
- void commitTransactionsLocked(uint32_t transactionFlags) REQUIRES(mStateLock);
+ void commitTransactions() EXCLUDES(mStateLock) REQUIRES(kMainThreadContext);
+ void commitTransactionsLocked(uint32_t transactionFlags)
+ REQUIRES(mStateLock, kMainThreadContext);
void doCommitTransactions() REQUIRES(mStateLock);
// Returns whether a new buffer has been latched.
@@ -817,8 +823,14 @@
/*
* Display and layer stack management
*/
- // called when starting, or restarting after system_server death
+
+ // Called during boot, and restart after system_server death.
void initializeDisplays();
+ void onInitializeDisplays() REQUIRES(mStateLock, kMainThreadContext);
+
+ bool isDisplayActiveLocked(const sp<const DisplayDevice>& display) const REQUIRES(mStateLock) {
+ return display->getDisplayToken() == mActiveDisplayToken;
+ }
sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const
REQUIRES(mStateLock) {
@@ -867,6 +879,21 @@
return getDefaultDisplayDeviceLocked();
}
+ using DisplayDeviceAndSnapshot =
+ std::pair<sp<DisplayDevice>, display::PhysicalDisplay::SnapshotRef>;
+
+ // Combinator for ftl::Optional<PhysicalDisplay>::and_then.
+ auto getDisplayDeviceAndSnapshot() REQUIRES(mStateLock) {
+ return [this](const display::PhysicalDisplay& display) REQUIRES(
+ mStateLock) -> ftl::Optional<DisplayDeviceAndSnapshot> {
+ if (auto device = getDisplayDeviceLocked(display.snapshot().displayId())) {
+ return std::make_pair(std::move(device), display.snapshotRef());
+ }
+
+ return {};
+ };
+ }
+
// Returns the first display that matches a `bool(const DisplayDevice&)` predicate.
template <typename Predicate>
sp<DisplayDevice> findDisplay(Predicate p) const REQUIRES(mStateLock) {
@@ -882,8 +909,13 @@
// region of all screens presenting this layer stack.
void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
- bool isDisplayActiveLocked(const sp<const DisplayDevice>& display) const REQUIRES(mStateLock) {
- return display->getDisplayToken() == mActiveDisplayToken;
+ ui::LayerFilter makeLayerFilterForDisplay(DisplayId displayId, ui::LayerStack layerStack)
+ REQUIRES(mStateLock) {
+ return {layerStack,
+ PhysicalDisplayId::tryCast(displayId)
+ .and_then(display::getPhysicalDisplay(mPhysicalDisplays))
+ .transform(&display::PhysicalDisplay::isInternal)
+ .value_or(false)};
}
/*
@@ -926,11 +958,12 @@
const DisplayDeviceState& state,
const sp<compositionengine::DisplaySurface>& displaySurface,
const sp<IGraphicBufferProducer>& producer) REQUIRES(mStateLock);
- void processDisplayChangesLocked() REQUIRES(mStateLock);
+ void processDisplayChangesLocked() REQUIRES(mStateLock, kMainThreadContext);
void processDisplayRemoved(const wp<IBinder>& displayToken) REQUIRES(mStateLock);
void processDisplayChanged(const wp<IBinder>& displayToken,
const DisplayDeviceState& currentState,
- const DisplayDeviceState& drawingState) REQUIRES(mStateLock);
+ const DisplayDeviceState& drawingState)
+ REQUIRES(mStateLock, kMainThreadContext);
void dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected);
@@ -959,21 +992,16 @@
/*
* Display identification
*/
- sp<IBinder> getPhysicalDisplayTokenLocked(PhysicalDisplayId displayId) const
+ sp<display::DisplayToken> getPhysicalDisplayTokenLocked(PhysicalDisplayId displayId) const
REQUIRES(mStateLock) {
- const sp<IBinder> nullToken;
- return mPhysicalDisplayTokens.get(displayId).value_or(std::cref(nullToken));
+ const sp<display::DisplayToken> nullToken;
+ return mPhysicalDisplays.get(displayId)
+ .transform([](const display::PhysicalDisplay& display) { return display.token(); })
+ .value_or(std::cref(nullToken));
}
std::optional<PhysicalDisplayId> getPhysicalDisplayIdLocked(
- const sp<IBinder>& displayToken) const REQUIRES(mStateLock) {
- for (const auto& [id, token] : mPhysicalDisplayTokens) {
- if (token == displayToken) {
- return id;
- }
- }
- return {};
- }
+ const sp<display::DisplayToken>&) const REQUIRES(mStateLock);
// Returns the first display connected at boot.
//
@@ -996,7 +1024,8 @@
VirtualDisplayId acquireVirtualDisplay(ui::Size, ui::PixelFormat) REQUIRES(mStateLock);
void releaseVirtualDisplay(VirtualDisplayId);
- void onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay) REQUIRES(mStateLock);
+ void onActiveDisplayChangedLocked(const sp<DisplayDevice>& activeDisplay)
+ REQUIRES(mStateLock, kMainThreadContext);
void onActiveDisplaySizeChanged(const sp<DisplayDevice>& activeDisplay);
@@ -1063,14 +1092,14 @@
/*
* Misc
*/
- std::vector<ui::ColorMode> getDisplayColorModes(const DisplayDevice&) REQUIRES(mStateLock);
+ std::vector<ui::ColorMode> getDisplayColorModes(PhysicalDisplayId) REQUIRES(mStateLock);
static int calculateMaxAcquiredBufferCount(Fps refreshRate,
std::chrono::nanoseconds presentLatency);
int getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const;
void updateInternalDisplayVsyncLocked(const sp<DisplayDevice>& activeDisplay)
- REQUIRES(mStateLock);
+ REQUIRES(mStateLock, kMainThreadContext);
bool isHdrLayer(Layer* layer) const;
@@ -1164,12 +1193,10 @@
// Displays are composited in `mDisplays` order. Internal displays are inserted at boot and
// never removed, so take precedence over external and virtual displays.
//
- // The static capacities were chosen to exceed a typical number of physical/virtual displays.
- //
// May be read from any thread, but must only be written from the main thread.
- ftl::SmallMap<wp<IBinder>, const sp<DisplayDevice>, 5> mDisplays GUARDED_BY(mStateLock);
- ftl::SmallMap<PhysicalDisplayId, const sp<IBinder>, 3> mPhysicalDisplayTokens
- GUARDED_BY(mStateLock);
+ display::DisplayMap<wp<IBinder>, const sp<DisplayDevice>> mDisplays GUARDED_BY(mStateLock);
+
+ display::PhysicalDisplays mPhysicalDisplays GUARDED_BY(mStateLock);
struct {
DisplayIdGenerator<GpuVirtualDisplayId> gpu;
diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
index 5c96f35..319d014 100644
--- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
+++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp
@@ -24,7 +24,6 @@
#include "BufferStateLayer.h"
#include "DisplayDevice.h"
-#include "EffectLayer.h"
#include "FrameTracer/FrameTracer.h"
#include "Layer.h"
#include "NativeWindowSurface.h"
@@ -34,6 +33,7 @@
#include "SurfaceInterceptor.h"
#include "DisplayHardware/ComposerHal.h"
+#include "FrameTimeline/FrameTimeline.h"
#include "Scheduler/Scheduler.h"
#include "Scheduler/VsyncConfiguration.h"
#include "Scheduler/VsyncController.h"
@@ -93,8 +93,8 @@
return sp<BufferStateLayer>::make(args);
}
-sp<EffectLayer> DefaultFactory::createEffectLayer(const LayerCreationArgs& args) {
- return sp<EffectLayer>::make(args);
+sp<Layer> DefaultFactory::createEffectLayer(const LayerCreationArgs& args) {
+ return sp<Layer>::make(args);
}
std::unique_ptr<FrameTracer> DefaultFactory::createFrameTracer() {
diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
index 8d00379..6602240 100644
--- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
+++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h
@@ -42,7 +42,7 @@
const sp<IGraphicBufferProducer>&) override;
std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() override;
sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs& args) override;
- sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) override;
+ sp<Layer> createEffectLayer(const LayerCreationArgs& args) override;
std::unique_ptr<FrameTracer> createFrameTracer() override;
std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid) override;
diff --git a/services/surfaceflinger/SurfaceFlingerFactory.h b/services/surfaceflinger/SurfaceFlingerFactory.h
index 291838f..dc2afd3 100644
--- a/services/surfaceflinger/SurfaceFlingerFactory.h
+++ b/services/surfaceflinger/SurfaceFlingerFactory.h
@@ -33,7 +33,6 @@
class BufferLayerConsumer;
class BufferStateLayer;
class DisplayDevice;
-class EffectLayer;
class FrameTracer;
class GraphicBuffer;
class HWComposer;
@@ -91,7 +90,7 @@
virtual std::unique_ptr<compositionengine::CompositionEngine> createCompositionEngine() = 0;
virtual sp<BufferStateLayer> createBufferStateLayer(const LayerCreationArgs& args) = 0;
- virtual sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) = 0;
+ virtual sp<Layer> createEffectLayer(const LayerCreationArgs& args) = 0;
virtual std::unique_ptr<FrameTracer> createFrameTracer() = 0;
virtual std::unique_ptr<frametimeline::FrameTimeline> createFrameTimeline(
std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid) = 0;
diff --git a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
index 312d4ab..6501e20 100644
--- a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
+++ b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp
@@ -84,9 +84,7 @@
return sp<BufferStateLayer>::make(args);
}
- sp<EffectLayer> createEffectLayer(const LayerCreationArgs& args) {
- return sp<EffectLayer>::make(args);
- }
+ sp<Layer> createEffectLayer(const LayerCreationArgs& args) { return sp<Layer>::make(args); }
std::unique_ptr<FrameTracer> createFrameTracer() override {
return std::make_unique<testing::NiceMock<mock::FrameTracer>>();
diff --git a/services/surfaceflinger/fuzzer/README.md b/services/surfaceflinger/fuzzer/README.md
index 7a5f229..a06c41b 100644
--- a/services/surfaceflinger/fuzzer/README.md
+++ b/services/surfaceflinger/fuzzer/README.md
@@ -78,9 +78,8 @@
Layer supports the following parameters:
1. Display Connection Types (parameter name: `fakeDisplay`)
2. State Sets (parameter name: `traverseInZOrder`)
-3. State Subsets (parameter name: `prepareCompositionState`)
-4. Disconnect modes (parameter name: `disconnect`)
-5. Data Spaces (parameter name: `setDataspace`)
+3. Disconnect modes (parameter name: `disconnect`)
+4. Data Spaces (parameter name: `setDataspace`)
You can find the possible values in the fuzzer's source code.
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
index 28b875a..79112bd 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp
@@ -237,7 +237,8 @@
mTestableFlinger.enableHalVirtualDisplays(mFdp.ConsumeBool());
- mTestableFlinger.commitTransactionsLocked(mFdp.ConsumeIntegral<uint32_t>());
+ FTL_FAKE_GUARD(kMainThreadContext,
+ mTestableFlinger.commitTransactionsLocked(mFdp.ConsumeIntegral<uint32_t>()));
mTestableFlinger.notifyPowerBoost(mFdp.ConsumeIntegral<int32_t>());
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
index 3aa3633..2297618 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h
@@ -33,7 +33,6 @@
#include "BufferStateLayer.h"
#include "DisplayDevice.h"
#include "DisplayHardware/ComposerHal.h"
-#include "EffectLayer.h"
#include "FrameTimeline/FrameTimeline.h"
#include "FrameTracer/FrameTracer.h"
#include "Layer.h"
@@ -360,8 +359,8 @@
return nullptr;
}
- sp<EffectLayer> createEffectLayer(const LayerCreationArgs &args) override {
- return sp<EffectLayer>::make(args);
+ sp<Layer> createEffectLayer(const LayerCreationArgs &args) override {
+ return sp<Layer>::make(args);
}
std::unique_ptr<FrameTracer> createFrameTracer() override {
@@ -600,14 +599,18 @@
mFlinger->binderDied(display);
mFlinger->onFirstRef();
- mFlinger->commitTransactions();
mFlinger->updateInputFlinger();
mFlinger->updateCursorAsync();
setVsyncConfig(&mFdp);
- FTL_FAKE_GUARD(kMainThreadContext,
- mFlinger->flushTransactionQueues(getFuzzedVsyncId(mFdp)));
+ {
+ ftl::FakeGuard guard(kMainThreadContext);
+
+ mFlinger->commitTransactions();
+ mFlinger->flushTransactionQueues(getFuzzedVsyncId(mFdp));
+ mFlinger->postComposition();
+ }
mFlinger->setTransactionFlags(mFdp.ConsumeIntegral<uint32_t>());
mFlinger->clearTransactionFlags(mFdp.ConsumeIntegral<uint32_t>());
@@ -624,8 +627,6 @@
mFlinger->getMaxAcquiredBufferCountForCurrentRefreshRate(mFdp.ConsumeIntegral<uid_t>());
- FTL_FAKE_GUARD(kMainThreadContext, mFlinger->postComposition());
-
mFlinger->calculateExpectedPresentTime({});
mFlinger->enableHalVirtualDisplays(mFdp.ConsumeBool());
@@ -664,7 +665,8 @@
}
mRefreshRateConfigs = std::make_shared<scheduler::RefreshRateConfigs>(modes, kModeId60);
- const auto fps = mRefreshRateConfigs->getActiveMode()->getFps();
+ const auto fps =
+ FTL_FAKE_GUARD(kMainThreadContext, mRefreshRateConfigs->getActiveMode().getFps());
mFlinger->mVsyncConfiguration = mFactory.createVsyncConfiguration(fps);
mFlinger->mVsyncModulator = sp<scheduler::VsyncModulator>::make(
mFlinger->mVsyncConfiguration->getCurrentConfigs());
@@ -715,9 +717,9 @@
void enableHalVirtualDisplays(bool enable) { mFlinger->enableHalVirtualDisplays(enable); }
- auto commitTransactionsLocked(uint32_t transactionFlags) {
+ void commitTransactionsLocked(uint32_t transactionFlags) FTL_FAKE_GUARD(kMainThreadContext) {
Mutex::Autolock lock(mFlinger->mStateLock);
- return mFlinger->commitTransactionsLocked(transactionFlags);
+ mFlinger->commitTransactionsLocked(transactionFlags);
}
auto setDisplayStateLocked(const DisplayState &s) {
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
index aeccc52..9ece260 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp
@@ -17,7 +17,6 @@
#include <BufferStateLayer.h>
#include <Client.h>
#include <DisplayDevice.h>
-#include <EffectLayer.h>
#include <LayerRenderArea.h>
#include <ftl/future.h>
#include <fuzzer/FuzzedDataProvider.h>
@@ -79,13 +78,13 @@
TestableSurfaceFlinger flinger;
sp<Client> client = sp<Client>::make(sp<SurfaceFlinger>::fromExisting(flinger.flinger()));
const LayerCreationArgs layerCreationArgs = createLayerCreationArgs(&flinger, client);
- sp<EffectLayer> effectLayer = sp<EffectLayer>::make(layerCreationArgs);
+ sp<Layer> effectLayer = sp<Layer>::make(layerCreationArgs);
effectLayer->setColor({(mFdp.ConsumeFloatingPointInRange<float>(0, 255) /*x*/,
mFdp.ConsumeFloatingPointInRange<float>(0, 255) /*y*/,
mFdp.ConsumeFloatingPointInRange<float>(0, 255) /*z*/)});
effectLayer->setDataspace(mFdp.PickValueInArray(kDataspaces));
- sp<EffectLayer> parent = sp<EffectLayer>::make(layerCreationArgs);
+ sp<Layer> parent = sp<Layer>::make(layerCreationArgs);
effectLayer->setChildrenDrawingParent(parent);
const FrameTimelineInfo frameInfo = getFuzzedFrameTimelineInfo();
@@ -149,7 +148,8 @@
layer->computeSourceBounds(getFuzzedFloatRect(&mFdp));
layer->fenceHasSignaled();
- layer->onPreComposition(mFdp.ConsumeIntegral<int64_t>());
+ layer->onPreComposition(mFdp.ConsumeIntegral<int64_t>(),
+ false /*updatingOutputGeometryThisFrame*/);
const std::vector<sp<CallbackHandle>> callbacks;
layer->setTransactionCompletedListeners(callbacks);
diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
index 9584492..3fc2b7e 100644
--- a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
+++ b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp
@@ -366,7 +366,7 @@
{modeId,
{Fps::fromValue(mFdp.ConsumeFloatingPoint<float>()),
Fps::fromValue(mFdp.ConsumeFloatingPoint<float>())}});
- refreshRateConfigs.setActiveModeId(modeId);
+ FTL_FAKE_GUARD(kMainThreadContext, refreshRateConfigs.setActiveModeId(modeId));
RefreshRateConfigs::isFractionalPairOrMultiple(Fps::fromValue(
mFdp.ConsumeFloatingPoint<float>()),
diff --git a/services/surfaceflinger/tests/Android.bp b/services/surfaceflinger/tests/Android.bp
index 276431e..13ce65d 100644
--- a/services/surfaceflinger/tests/Android.bp
+++ b/services/surfaceflinger/tests/Android.bp
@@ -23,7 +23,10 @@
cc_test {
name: "SurfaceFlinger_test",
- defaults: ["surfaceflinger_defaults"],
+ defaults: [
+ "android.hardware.graphics.common-ndk_shared",
+ "surfaceflinger_defaults",
+ ],
test_suites: ["device-tests"],
srcs: [
"BootDisplayMode_test.cpp",
@@ -64,7 +67,6 @@
"android.hardware.graphics.composer@2.1",
],
shared_libs: [
- "android.hardware.graphics.common-V3-ndk",
"android.hardware.graphics.common@1.2",
"libandroid",
"libbase",
diff --git a/services/surfaceflinger/tests/Credentials_test.cpp b/services/surfaceflinger/tests/Credentials_test.cpp
index 353b813..775de4a 100644
--- a/services/surfaceflinger/tests/Credentials_test.cpp
+++ b/services/surfaceflinger/tests/Credentials_test.cpp
@@ -55,19 +55,12 @@
#pragma clang diagnostic ignored "-Wconversion"
class CredentialsTest : public ::testing::Test {
protected:
- void SetUp() override {
- // Start the tests as root.
- seteuid(AID_ROOT);
-
- ASSERT_NO_FATAL_FAILURE(initClient());
- }
+ void SetUp() override { ASSERT_NO_FATAL_FAILURE(initClient()); }
void TearDown() override {
mComposerClient->dispose();
mBGSurfaceControl.clear();
mComposerClient.clear();
- // Finish the tests as root.
- seteuid(AID_ROOT);
}
sp<IBinder> mDisplay;
@@ -102,31 +95,6 @@
}
/**
- * Sets UID to imitate Graphic's process.
- */
- void setGraphicsUID() {
- seteuid(AID_ROOT);
- seteuid(AID_GRAPHICS);
- }
-
- /**
- * Sets UID to imitate System's process.
- */
- void setSystemUID() {
- seteuid(AID_ROOT);
- seteuid(AID_SYSTEM);
- }
-
- /**
- * Sets UID to imitate a process that doesn't have any special privileges in
- * our code.
- */
- void setBinUID() {
- seteuid(AID_ROOT);
- seteuid(AID_BIN);
- }
-
- /**
* Template function the check a condition for different types of users: root
* graphics, system, and non-supported user. Root, graphics, and system should
* always equal privilegedValue, and non-supported user should equal unprivilegedValue.
@@ -134,24 +102,34 @@
template <typename T>
void checkWithPrivileges(std::function<T()> condition, T privilegedValue, T unprivilegedValue) {
// Check with root.
- seteuid(AID_ROOT);
- ASSERT_EQ(privilegedValue, condition());
+ {
+ UIDFaker f(AID_SYSTEM);
+ ASSERT_EQ(privilegedValue, condition());
+ }
// Check as a Graphics user.
- setGraphicsUID();
- ASSERT_EQ(privilegedValue, condition());
+ {
+ UIDFaker f(AID_GRAPHICS);
+ ASSERT_EQ(privilegedValue, condition());
+ }
// Check as a system user.
- setSystemUID();
- ASSERT_EQ(privilegedValue, condition());
+ {
+ UIDFaker f(AID_SYSTEM);
+ ASSERT_EQ(privilegedValue, condition());
+ }
// Check as a non-supported user.
- setBinUID();
- ASSERT_EQ(unprivilegedValue, condition());
+ {
+ UIDFaker f(AID_BIN);
+ ASSERT_EQ(unprivilegedValue, condition());
+ }
// Check as shell since shell has some additional permissions
- seteuid(AID_SHELL);
- ASSERT_EQ(unprivilegedValue, condition());
+ {
+ UIDFaker f(AID_SHELL);
+ ASSERT_EQ(privilegedValue, condition());
+ }
}
};
@@ -160,17 +138,23 @@
ASSERT_NO_FATAL_FAILURE(initClient());
// Graphics can init the client.
- setGraphicsUID();
- ASSERT_NO_FATAL_FAILURE(initClient());
+ {
+ UIDFaker f(AID_GRAPHICS);
+ ASSERT_NO_FATAL_FAILURE(initClient());
+ }
// System can init the client.
- setSystemUID();
- ASSERT_NO_FATAL_FAILURE(initClient());
+ {
+ UIDFaker f(AID_SYSTEM);
+ ASSERT_NO_FATAL_FAILURE(initClient());
+ }
// Anyone else can init the client.
- setBinUID();
- mComposerClient = sp<SurfaceComposerClient>::make();
- ASSERT_NO_FATAL_FAILURE(initClient());
+ {
+ UIDFaker f(AID_BIN);
+ mComposerClient = sp<SurfaceComposerClient>::make();
+ ASSERT_NO_FATAL_FAILURE(initClient());
+ }
}
TEST_F(CredentialsTest, GetBuiltInDisplayAccessTest) {
@@ -184,7 +168,7 @@
TEST_F(CredentialsTest, AllowedGetterMethodsTest) {
// The following methods are tested with a UID that is not root, graphics,
// or system, to show that anyone can access them.
- setBinUID();
+ UIDFaker f(AID_BIN);
const auto display = SurfaceComposerClient::getInternalDisplayToken();
ASSERT_TRUE(display != nullptr);
@@ -253,24 +237,34 @@
};
// Check with root.
- seteuid(AID_ROOT);
- ASSERT_FALSE(condition());
+ {
+ UIDFaker f(AID_ROOT);
+ ASSERT_FALSE(condition());
+ }
// Check as a Graphics user.
- setGraphicsUID();
- ASSERT_TRUE(condition());
+ {
+ UIDFaker f(AID_GRAPHICS);
+ ASSERT_TRUE(condition());
+ }
// Check as a system user.
- setSystemUID();
- ASSERT_TRUE(condition());
+ {
+ UIDFaker f(AID_SYSTEM);
+ ASSERT_TRUE(condition());
+ }
// Check as a non-supported user.
- setBinUID();
- ASSERT_FALSE(condition());
+ {
+ UIDFaker f(AID_BIN);
+ ASSERT_FALSE(condition());
+ }
// Check as shell since shell has some additional permissions
- seteuid(AID_SHELL);
- ASSERT_FALSE(condition());
+ {
+ UIDFaker f(AID_SHELL);
+ ASSERT_FALSE(condition());
+ }
condition = [=]() {
sp<IBinder> testDisplay = SurfaceComposerClient::createDisplay(DISPLAY_NAME, false);
@@ -315,21 +309,27 @@
// Historically, only root and shell can access the getLayerDebugInfo which
// is called when we call dumpsys. I don't see a reason why we should change this.
std::vector<LayerDebugInfo> outLayers;
+ binder::Status status = binder::Status::ok();
// Check with root.
- seteuid(AID_ROOT);
- binder::Status status = sf->getLayerDebugInfo(&outLayers);
- ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status));
+ {
+ UIDFaker f(AID_ROOT);
+ status = sf->getLayerDebugInfo(&outLayers);
+ ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status));
+ }
// Check as a shell.
- seteuid(AID_SHELL);
- status = sf->getLayerDebugInfo(&outLayers);
- ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status));
+ {
+ UIDFaker f(AID_SHELL);
+ status = sf->getLayerDebugInfo(&outLayers);
+ ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status));
+ }
// Check as anyone else.
- seteuid(AID_ROOT);
- seteuid(AID_BIN);
- status = sf->getLayerDebugInfo(&outLayers);
- ASSERT_EQ(PERMISSION_DENIED, statusTFromBinderStatus(status));
+ {
+ UIDFaker f(AID_BIN);
+ status = sf->getLayerDebugInfo(&outLayers);
+ ASSERT_EQ(PERMISSION_DENIED, statusTFromBinderStatus(status));
+ }
}
TEST_F(CredentialsTest, IsWideColorDisplayBasicCorrectness) {
diff --git a/services/surfaceflinger/tests/LayerState_test.cpp b/services/surfaceflinger/tests/LayerState_test.cpp
index fbbf322..2181370 100644
--- a/services/surfaceflinger/tests/LayerState_test.cpp
+++ b/services/surfaceflinger/tests/LayerState_test.cpp
@@ -90,13 +90,12 @@
ASSERT_EQ(args.grayscale, args2.grayscale);
}
-TEST(LayerStateTest, ParcellingScreenCaptureResults) {
+TEST(LayerStateTest, ParcellingScreenCaptureResultsWithFence) {
ScreenCaptureResults results;
results.buffer = sp<GraphicBuffer>::make(100u, 200u, PIXEL_FORMAT_RGBA_8888, 1u, 0u);
- results.fence = sp<Fence>::make(dup(fileno(tmpfile())));
+ results.fenceResult = sp<Fence>::make(dup(fileno(tmpfile())));
results.capturedSecureLayers = true;
results.capturedDataspace = ui::Dataspace::DISPLAY_P3;
- results.result = BAD_VALUE;
Parcel p;
results.writeToParcel(&p);
@@ -110,10 +109,41 @@
ASSERT_EQ(results.buffer->getWidth(), results2.buffer->getWidth());
ASSERT_EQ(results.buffer->getHeight(), results2.buffer->getHeight());
ASSERT_EQ(results.buffer->getPixelFormat(), results2.buffer->getPixelFormat());
- ASSERT_EQ(results.fence->isValid(), results2.fence->isValid());
+ ASSERT_TRUE(results.fenceResult.ok());
+ ASSERT_TRUE(results2.fenceResult.ok());
+ ASSERT_EQ(results.fenceResult.value()->isValid(), results2.fenceResult.value()->isValid());
ASSERT_EQ(results.capturedSecureLayers, results2.capturedSecureLayers);
ASSERT_EQ(results.capturedDataspace, results2.capturedDataspace);
- ASSERT_EQ(results.result, results2.result);
+}
+
+TEST(LayerStateTest, ParcellingScreenCaptureResultsWithNoFenceOrError) {
+ ScreenCaptureResults results;
+
+ Parcel p;
+ results.writeToParcel(&p);
+ p.setDataPosition(0);
+
+ ScreenCaptureResults results2;
+ results2.readFromParcel(&p);
+
+ ASSERT_TRUE(results2.fenceResult.ok());
+ ASSERT_EQ(results2.fenceResult.value(), Fence::NO_FENCE);
+}
+
+TEST(LayerStateTest, ParcellingScreenCaptureResultsWithFenceError) {
+ ScreenCaptureResults results;
+ results.fenceResult = base::unexpected(BAD_VALUE);
+
+ Parcel p;
+ results.writeToParcel(&p);
+ p.setDataPosition(0);
+
+ ScreenCaptureResults results2;
+ results2.readFromParcel(&p);
+
+ ASSERT_FALSE(results.fenceResult.ok());
+ ASSERT_FALSE(results2.fenceResult.ok());
+ ASSERT_EQ(results.fenceResult.error(), results2.fenceResult.error());
}
} // namespace test
diff --git a/services/surfaceflinger/tests/LayerTransaction_test.cpp b/services/surfaceflinger/tests/LayerTransaction_test.cpp
index 513fdc3..c206e1f 100644
--- a/services/surfaceflinger/tests/LayerTransaction_test.cpp
+++ b/services/surfaceflinger/tests/LayerTransaction_test.cpp
@@ -154,6 +154,36 @@
ASSERT_EQ(OK, producer->disconnect(NATIVE_WINDOW_API_CPU));
}
+
+// b/245052266 - we possible could support blur and a buffer at the same layer but
+// might break existing assumptions at higher level. This test captures the current
+// expectations. A layer drawing a buffer will not support blur.
+TEST_F(LayerTransactionTest, BufferTakesPriorityOverBlur) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
+ Transaction().setBackgroundBlurRadius(layer, 5).apply();
+ {
+ SCOPED_TRACE("BufferTakesPriorityOverBlur");
+ const Rect rect(0, 0, 32, 32);
+ auto shot = screenshot();
+ shot->expectColor(rect, Color::RED);
+ }
+}
+
+TEST_F(LayerTransactionTest, BufferTakesPriorityOverColor) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
+ Transaction().setColor(layer, {Color::GREEN.r, Color::GREEN.g, Color::GREEN.b}).apply();
+ {
+ SCOPED_TRACE("BufferTakesPriorityOverColor");
+ const Rect rect(0, 0, 32, 32);
+ auto shot = screenshot();
+ shot->expectColor(rect, Color::RED);
+ }
+}
+
} // namespace android
// TODO(b/129481165): remove the #pragma below and fix conversion issues
diff --git a/services/surfaceflinger/tests/fakehwc/Android.bp b/services/surfaceflinger/tests/fakehwc/Android.bp
index 704815d..06afdb1 100644
--- a/services/surfaceflinger/tests/fakehwc/Android.bp
+++ b/services/surfaceflinger/tests/fakehwc/Android.bp
@@ -9,7 +9,10 @@
cc_test {
name: "sffakehwc_test",
- defaults: ["surfaceflinger_defaults"],
+ defaults: [
+ "android.hardware.graphics.composer3-ndk_shared",
+ "surfaceflinger_defaults",
+ ],
test_suites: ["device-tests"],
srcs: [
"FakeComposerClient.cpp",
@@ -23,7 +26,6 @@
"android.hardware.graphics.composer@2.2",
"android.hardware.graphics.composer@2.3",
"android.hardware.graphics.composer@2.4",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.graphics.mapper@2.0",
"android.hardware.graphics.mapper@3.0",
"android.hardware.graphics.mapper@4.0",
diff --git a/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp b/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
index 69d30c4..513f779 100644
--- a/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
+++ b/services/surfaceflinger/tests/unittests/AidlPowerHalWrapperTest.cpp
@@ -50,10 +50,8 @@
sp<NiceMock<MockIPower>> mMockHal = nullptr;
sp<NiceMock<MockIPowerHintSession>> mMockSession = nullptr;
void verifyAndClearExpectations();
- void sendActualWorkDurationGroup(std::vector<WorkDuration> durations,
- std::chrono::nanoseconds sleepBeforeLastSend);
- std::chrono::nanoseconds mAllowedDeviation;
- std::chrono::nanoseconds mStaleTimeout;
+ void sendActualWorkDurationGroup(std::vector<WorkDuration> durations);
+ static constexpr std::chrono::duration kStaleTimeout = 100ms;
};
void AidlPowerHalWrapperTest::SetUp() {
@@ -61,9 +59,6 @@
mMockSession = sp<NiceMock<MockIPowerHintSession>>::make();
ON_CALL(*mMockHal.get(), getHintSessionPreferredRate(_)).WillByDefault(Return(Status::ok()));
mWrapper = std::make_unique<AidlPowerHalWrapper>(mMockHal);
- mWrapper->setAllowedActualDeviation(std::chrono::nanoseconds{10ms}.count());
- mAllowedDeviation = std::chrono::nanoseconds{mWrapper->mAllowedActualDeviation};
- mStaleTimeout = AidlPowerHalWrapper::kStaleTimeout;
}
void AidlPowerHalWrapperTest::verifyAndClearExpectations() {
@@ -71,14 +66,11 @@
Mock::VerifyAndClearExpectations(mMockSession.get());
}
-void AidlPowerHalWrapperTest::sendActualWorkDurationGroup(
- std::vector<WorkDuration> durations, std::chrono::nanoseconds sleepBeforeLastSend) {
+void AidlPowerHalWrapperTest::sendActualWorkDurationGroup(std::vector<WorkDuration> durations) {
for (size_t i = 0; i < durations.size(); i++) {
- if (i == durations.size() - 1) {
- std::this_thread::sleep_for(sleepBeforeLastSend);
- }
auto duration = durations[i];
- mWrapper->sendActualWorkDuration(duration.durationNanos, duration.timeStampNanos);
+ mWrapper->sendActualWorkDuration(Duration::fromNs(duration.durationNanos),
+ TimePoint::fromNs(duration.timeStampNanos));
}
}
@@ -164,13 +156,13 @@
for (const auto& test : testCases) {
// reset to 100ms baseline
- mWrapper->setTargetWorkDuration(1);
- mWrapper->setTargetWorkDuration(base.count());
+ mWrapper->setTargetWorkDuration(1ns);
+ mWrapper->setTargetWorkDuration(base);
- auto target = test.first;
+ std::chrono::nanoseconds target = test.first;
EXPECT_CALL(*mMockSession.get(), updateTargetWorkDuration(target.count()))
.Times(test.second ? 1 : 0);
- mWrapper->setTargetWorkDuration(target.count());
+ mWrapper->setTargetWorkDuration(target);
verifyAndClearExpectations();
}
}
@@ -187,7 +179,7 @@
EXPECT_CALL(*mMockSession.get(), updateTargetWorkDuration(1))
.WillOnce(Return(Status::fromExceptionCode(Status::Exception::EX_ILLEGAL_STATE)));
- mWrapper->setTargetWorkDuration(1);
+ mWrapper->setTargetWorkDuration(1ns);
EXPECT_TRUE(mWrapper->shouldReconnectHAL());
}
@@ -206,58 +198,24 @@
// 100ms
const std::vector<std::pair<std::vector<std::pair<std::chrono::nanoseconds, nsecs_t>>, bool>>
testCases = {{{{-1ms, 100}}, false},
- {{{100ms - (mAllowedDeviation / 2), 100}}, false},
- {{{100ms + (mAllowedDeviation / 2), 100}}, false},
- {{{100ms + (mAllowedDeviation + 1ms), 100}}, true},
- {{{100ms - (mAllowedDeviation + 1ms), 100}}, true},
+ {{{50ms, 100}}, true},
{{{100ms, 100}, {200ms, 200}}, true},
{{{100ms, 500}, {100ms, 600}, {3ms, 600}}, true}};
for (const auto& test : testCases) {
// reset actual duration
- sendActualWorkDurationGroup({base}, mStaleTimeout);
+ sendActualWorkDurationGroup({base});
auto raw = test.first;
std::vector<WorkDuration> durations(raw.size());
std::transform(raw.begin(), raw.end(), durations.begin(),
[](auto d) { return toWorkDuration(d); });
- EXPECT_CALL(*mMockSession.get(), reportActualWorkDuration(durations))
- .Times(test.second ? 1 : 0);
- sendActualWorkDurationGroup(durations, 0ms);
- verifyAndClearExpectations();
- }
-}
-
-TEST_F(AidlPowerHalWrapperTest, sendActualWorkDuration_exceedsStaleTime) {
- ASSERT_TRUE(mWrapper->supportsPowerHintSession());
-
- std::vector<int32_t> threadIds = {1, 2};
- mWrapper->setPowerHintSessionThreadIds(threadIds);
- EXPECT_CALL(*mMockHal.get(), createHintSession(_, _, threadIds, _, _))
- .WillOnce(DoAll(SetArgPointee<4>(mMockSession), Return(Status::ok())));
- ASSERT_TRUE(mWrapper->startPowerHintSession());
- verifyAndClearExpectations();
-
- auto base = toWorkDuration(100ms, 0);
- // test cases with actual work durations and whether it should update hint against baseline
- // 100ms
- const std::vector<std::tuple<std::vector<std::pair<std::chrono::nanoseconds, nsecs_t>>,
- std::chrono::nanoseconds, bool>>
- testCases = {{{{100ms, 100}}, mStaleTimeout, true},
- {{{100ms + (mAllowedDeviation / 2), 100}}, mStaleTimeout, true},
- {{{100ms, 100}}, mStaleTimeout / 2, false}};
-
- for (const auto& test : testCases) {
- // reset actual duration
- sendActualWorkDurationGroup({base}, mStaleTimeout);
-
- auto raw = std::get<0>(test);
- std::vector<WorkDuration> durations(raw.size());
- std::transform(raw.begin(), raw.end(), durations.begin(),
- [](auto d) { return toWorkDuration(d); });
- EXPECT_CALL(*mMockSession.get(), reportActualWorkDuration(durations))
- .Times(std::get<2>(test) ? 1 : 0);
- sendActualWorkDurationGroup(durations, std::get<1>(test));
+ for (auto& duration : durations) {
+ EXPECT_CALL(*mMockSession.get(),
+ reportActualWorkDuration(std::vector<WorkDuration>{duration}))
+ .Times(test.second ? 1 : 0);
+ }
+ sendActualWorkDurationGroup(durations);
verifyAndClearExpectations();
}
}
@@ -275,7 +233,7 @@
duration.durationNanos = 1;
EXPECT_CALL(*mMockSession.get(), reportActualWorkDuration(_))
.WillOnce(Return(Status::fromExceptionCode(Status::Exception::EX_ILLEGAL_STATE)));
- sendActualWorkDurationGroup({duration}, 0ms);
+ sendActualWorkDurationGroup({duration});
EXPECT_TRUE(mWrapper->shouldReconnectHAL());
}
diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp
index 004f31c..dec14d0 100644
--- a/services/surfaceflinger/tests/unittests/Android.bp
+++ b/services/surfaceflinger/tests/unittests/Android.bp
@@ -135,15 +135,17 @@
cc_defaults {
name: "libsurfaceflinger_mocks_defaults",
+ defaults: [
+ "android.hardware.graphics.common-ndk_static",
+ "android.hardware.graphics.composer3-ndk_static",
+ ],
static_libs: [
"android.hardware.common-V2-ndk",
"android.hardware.common.fmq-V1-ndk",
- "android.hardware.graphics.common-V3-ndk",
"android.hardware.graphics.composer@2.1",
"android.hardware.graphics.composer@2.2",
"android.hardware.graphics.composer@2.3",
"android.hardware.graphics.composer@2.4",
- "android.hardware.graphics.composer3-V1-ndk",
"android.hardware.power@1.0",
"android.hardware.power@1.1",
"android.hardware.power@1.2",
diff --git a/services/surfaceflinger/tests/unittests/CompositionTest.cpp b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
index 77625b3..9485f48 100644
--- a/services/surfaceflinger/tests/unittests/CompositionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
@@ -38,7 +38,6 @@
#include <utils/String8.h>
#include "DisplayRenderArea.h"
-#include "EffectLayer.h"
#include "Layer.h"
#include "TestableSurfaceFlinger.h"
#include "mock/DisplayHardware/MockComposer.h"
@@ -309,16 +308,20 @@
compositionengine::impl::createDisplay(test->mFlinger.getCompositionEngine(),
ceDisplayArgs);
+ constexpr auto kDisplayConnectionType = ui::DisplayConnectionType::Internal;
+ constexpr bool kIsPrimary = true;
+
test->mDisplay = FakeDisplayDeviceInjector(test->mFlinger, compositionDisplay,
- ui::DisplayConnectionType::Internal, HWC_DISPLAY,
- true /* isPrimary */)
+ kDisplayConnectionType, HWC_DISPLAY, kIsPrimary)
.setDisplaySurface(test->mDisplaySurface)
.setNativeWindow(test->mNativeWindow)
.setSecure(Derived::IS_SECURE)
.setPowerMode(Derived::INIT_POWER_MODE)
.inject();
Mock::VerifyAndClear(test->mNativeWindow.get());
- test->mDisplay->setLayerStack(LAYER_STACK);
+
+ constexpr bool kIsInternal = kDisplayConnectionType == ui::DisplayConnectionType::Internal;
+ test->mDisplay->setLayerFilter({LAYER_STACK, kIsInternal});
}
template <typename Case>
@@ -853,13 +856,13 @@
template <typename LayerProperties>
struct EffectLayerVariant : public BaseLayerVariant<LayerProperties> {
using Base = BaseLayerVariant<LayerProperties>;
- using FlingerLayerType = sp<EffectLayer>;
+ using FlingerLayerType = sp<Layer>;
static FlingerLayerType createLayer(CompositionTest* test) {
- FlingerLayerType layer = Base::template createLayerWithFactory<EffectLayer>(test, [test]() {
- return sp<EffectLayer>::make(
- LayerCreationArgs(test->mFlinger.flinger(), sp<Client>(), "test-layer",
- LayerProperties::LAYER_FLAGS, LayerMetadata()));
+ FlingerLayerType layer = Base::template createLayerWithFactory<Layer>(test, [test]() {
+ return sp<Layer>::make(LayerCreationArgs(test->mFlinger.flinger(), sp<Client>(),
+ "test-layer", LayerProperties::LAYER_FLAGS,
+ LayerMetadata()));
});
auto& layerDrawingState = test->mFlinger.mutableLayerDrawingState(layer);
@@ -941,12 +944,12 @@
template <typename LayerProperties>
struct ContainerLayerVariant : public BaseLayerVariant<LayerProperties> {
using Base = BaseLayerVariant<LayerProperties>;
- using FlingerLayerType = sp<EffectLayer>;
+ using FlingerLayerType = sp<Layer>;
static FlingerLayerType createLayer(CompositionTest* test) {
LayerCreationArgs args(test->mFlinger.flinger(), sp<Client>(), "test-container-layer",
LayerProperties::LAYER_FLAGS, LayerMetadata());
- FlingerLayerType layer = sp<EffectLayer>::make(args);
+ FlingerLayerType layer = sp<Layer>::make(args);
Base::template initLayerDrawingStateAndComputeBounds(test, layer);
return layer;
}
diff --git a/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp b/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
index ec27eda..67ace1a 100644
--- a/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DispSyncSourceTest.cpp
@@ -292,9 +292,10 @@
TEST_F(DispSyncSourceTest, getLatestVsyncData) {
const nsecs_t now = systemTime();
- const nsecs_t vsyncInternalDuration = mWorkDuration.count() + mReadyDuration.count();
+ const nsecs_t expectedPresentationTime =
+ now + mWorkDuration.count() + mReadyDuration.count() + 1;
EXPECT_CALL(*mVSyncTracker, nextAnticipatedVSyncTimeFrom(_))
- .WillOnce(Return(now + vsyncInternalDuration + 1));
+ .WillOnce(Return(expectedPresentationTime));
{
InSequence seq;
EXPECT_CALL(*mVSyncDispatch, registerCallback(_, mName)).Times(1);
@@ -306,10 +307,8 @@
EXPECT_TRUE(mDispSyncSource);
const auto vsyncData = mDispSyncSource->getLatestVSyncData();
- ASSERT_GT(vsyncData.deadlineTimestamp, now);
- ASSERT_GT(vsyncData.expectedPresentationTime, vsyncData.deadlineTimestamp);
- EXPECT_EQ(vsyncData.deadlineTimestamp,
- vsyncData.expectedPresentationTime - vsyncInternalDuration);
+ ASSERT_EQ(vsyncData.expectedPresentationTime, expectedPresentationTime);
+ EXPECT_EQ(vsyncData.deadlineTimestamp, expectedPresentationTime - mReadyDuration.count());
}
} // namespace
diff --git a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
index 0b4e196..9789df5 100644
--- a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
+++ b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp
@@ -25,7 +25,6 @@
#include <gui/LayerMetadata.h>
#include "BufferStateLayer.h"
-#include "EffectLayer.h"
#include "FpsReporter.h"
#include "Layer.h"
#include "TestableSurfaceFlinger.h"
diff --git a/services/surfaceflinger/tests/unittests/LayerTest.cpp b/services/surfaceflinger/tests/unittests/LayerTest.cpp
index 4974f90..95e54f6 100644
--- a/services/surfaceflinger/tests/unittests/LayerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerTest.cpp
@@ -17,7 +17,6 @@
#undef LOG_TAG
#define LOG_TAG "LibSurfaceFlingerUnittests"
-#include <EffectLayer.h>
#include <gtest/gtest.h>
#include <ui/FloatRect.h>
#include <ui/Transform.h>
diff --git a/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp b/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
index b7a8a93..14304d1 100644
--- a/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
+++ b/services/surfaceflinger/tests/unittests/LayerTestUtils.cpp
@@ -35,7 +35,7 @@
sp<Layer> EffectLayerFactory::createLayer(TestableSurfaceFlinger& flinger) {
sp<Client> client;
LayerCreationArgs args(flinger.flinger(), client, "color-layer", LAYER_FLAGS, LayerMetadata());
- return sp<EffectLayer>::make(args);
+ return sp<Layer>::make(args);
}
std::string PrintToStringParamName(
diff --git a/services/surfaceflinger/tests/unittests/LayerTestUtils.h b/services/surfaceflinger/tests/unittests/LayerTestUtils.h
index fc9b6a2..ab446fa 100644
--- a/services/surfaceflinger/tests/unittests/LayerTestUtils.h
+++ b/services/surfaceflinger/tests/unittests/LayerTestUtils.h
@@ -23,8 +23,6 @@
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
-#include "BufferStateLayer.h"
-#include "EffectLayer.h"
#include "Layer.h"
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic pop // ignored "-Wconversion"
diff --git a/services/surfaceflinger/tests/unittests/PowerAdvisorTest.cpp b/services/surfaceflinger/tests/unittests/PowerAdvisorTest.cpp
index 8711a42..2d66d3c 100644
--- a/services/surfaceflinger/tests/unittests/PowerAdvisorTest.cpp
+++ b/services/surfaceflinger/tests/unittests/PowerAdvisorTest.cpp
@@ -39,15 +39,15 @@
public:
void SetUp() override;
void startPowerHintSession();
- void fakeBasicFrameTiming(nsecs_t startTime, nsecs_t vsyncPeriod);
- void setExpectedTiming(nsecs_t startTime, nsecs_t vsyncPeriod);
- nsecs_t getFenceWaitDelayDuration(bool skipValidate);
+ void fakeBasicFrameTiming(TimePoint startTime, Duration vsyncPeriod);
+ void setExpectedTiming(Duration totalFrameTargetDuration, TimePoint expectedPresentTime);
+ Duration getFenceWaitDelayDuration(bool skipValidate);
protected:
TestableSurfaceFlinger mFlinger;
std::unique_ptr<PowerAdvisor> mPowerAdvisor;
NiceMock<MockAidlPowerHalWrapper>* mMockAidlWrapper;
- nsecs_t kErrorMargin = std::chrono::nanoseconds(1ms).count();
+ Duration kErrorMargin = 1ms;
};
void PowerAdvisorTest::SetUp() FTL_FAKE_GUARD(mPowerAdvisor->mPowerHalMutex) {
@@ -67,21 +67,21 @@
mPowerAdvisor->startPowerHintSession(threadIds);
}
-void PowerAdvisorTest::setExpectedTiming(nsecs_t totalFrameTarget, nsecs_t expectedPresentTime) {
- mPowerAdvisor->setTotalFrameTargetWorkDuration(totalFrameTarget);
+void PowerAdvisorTest::setExpectedTiming(Duration totalFrameTargetDuration,
+ TimePoint expectedPresentTime) {
+ mPowerAdvisor->setTotalFrameTargetWorkDuration(totalFrameTargetDuration);
mPowerAdvisor->setExpectedPresentTime(expectedPresentTime);
}
-void PowerAdvisorTest::fakeBasicFrameTiming(nsecs_t startTime, nsecs_t vsyncPeriod) {
+void PowerAdvisorTest::fakeBasicFrameTiming(TimePoint startTime, Duration vsyncPeriod) {
mPowerAdvisor->setCommitStart(startTime);
- mPowerAdvisor->setFrameDelay(0);
+ mPowerAdvisor->setFrameDelay(0ns);
mPowerAdvisor->setTargetWorkDuration(vsyncPeriod);
}
-nsecs_t PowerAdvisorTest::getFenceWaitDelayDuration(bool skipValidate) {
+Duration PowerAdvisorTest::getFenceWaitDelayDuration(bool skipValidate) {
return (skipValidate ? PowerAdvisor::kFenceWaitStartDelaySkippedValidate
- : PowerAdvisor::kFenceWaitStartDelayValidated)
- .count();
+ : PowerAdvisor::kFenceWaitStartDelayValidated);
}
namespace {
@@ -93,11 +93,11 @@
std::vector<DisplayId> displayIds{PhysicalDisplayId::fromPort(42u)};
// 60hz
- const nsecs_t vsyncPeriod = std::chrono::nanoseconds(1s).count() / 60;
- const nsecs_t presentDuration = std::chrono::nanoseconds(5ms).count();
- const nsecs_t postCompDuration = std::chrono::nanoseconds(1ms).count();
+ const Duration vsyncPeriod{std::chrono::nanoseconds(1s) / 60};
+ const Duration presentDuration = 5ms;
+ const Duration postCompDuration = 1ms;
- nsecs_t startTime = 100;
+ TimePoint startTime{100ns};
// advisor only starts on frame 2 so do an initial no-op frame
fakeBasicFrameTiming(startTime, vsyncPeriod);
@@ -109,14 +109,14 @@
// increment the frame
startTime += vsyncPeriod;
- const nsecs_t expectedDuration = kErrorMargin + presentDuration + postCompDuration;
+ const Duration expectedDuration = kErrorMargin + presentDuration + postCompDuration;
EXPECT_CALL(*mMockAidlWrapper, sendActualWorkDuration(Eq(expectedDuration), _)).Times(1);
fakeBasicFrameTiming(startTime, vsyncPeriod);
setExpectedTiming(vsyncPeriod, startTime + vsyncPeriod);
mPowerAdvisor->setDisplays(displayIds);
- mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1000000, startTime + 1500000);
- mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2000000, startTime + 2500000);
+ mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1ms, startTime + 1500us);
+ mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2ms, startTime + 2500us);
mPowerAdvisor->setSfPresentTiming(startTime, startTime + presentDuration);
mPowerAdvisor->sendActualWorkDuration();
}
@@ -128,12 +128,12 @@
std::vector<DisplayId> displayIds{PhysicalDisplayId::fromPort(42u)};
// 60hz
- const nsecs_t vsyncPeriod = std::chrono::nanoseconds(1s).count() / 60;
- const nsecs_t presentDuration = std::chrono::nanoseconds(5ms).count();
- const nsecs_t postCompDuration = std::chrono::nanoseconds(1ms).count();
- const nsecs_t hwcBlockedDuration = std::chrono::nanoseconds(500us).count();
+ const Duration vsyncPeriod{std::chrono::nanoseconds(1s) / 60};
+ const Duration presentDuration = 5ms;
+ const Duration postCompDuration = 1ms;
+ const Duration hwcBlockedDuration = 500us;
- nsecs_t startTime = 100;
+ TimePoint startTime{100ns};
// advisor only starts on frame 2 so do an initial no-op frame
fakeBasicFrameTiming(startTime, vsyncPeriod);
@@ -145,17 +145,17 @@
// increment the frame
startTime += vsyncPeriod;
- const nsecs_t expectedDuration = kErrorMargin + presentDuration +
+ const Duration expectedDuration = kErrorMargin + presentDuration +
getFenceWaitDelayDuration(false) - hwcBlockedDuration + postCompDuration;
EXPECT_CALL(*mMockAidlWrapper, sendActualWorkDuration(Eq(expectedDuration), _)).Times(1);
fakeBasicFrameTiming(startTime, vsyncPeriod);
setExpectedTiming(vsyncPeriod, startTime + vsyncPeriod);
mPowerAdvisor->setDisplays(displayIds);
- mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1000000, startTime + 1500000);
- mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2000000, startTime + 3000000);
+ mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1ms, startTime + 1500us);
+ mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2ms, startTime + 3ms);
// now report the fence as having fired during the display HWC time
- mPowerAdvisor->setSfPresentTiming(startTime + 2000000 + hwcBlockedDuration,
+ mPowerAdvisor->setSfPresentTiming(startTime + 2ms + hwcBlockedDuration,
startTime + presentDuration);
mPowerAdvisor->sendActualWorkDuration();
}
@@ -168,12 +168,12 @@
GpuVirtualDisplayId(1)};
// 60hz
- const nsecs_t vsyncPeriod = std::chrono::nanoseconds(1s).count() / 60;
+ const Duration vsyncPeriod{std::chrono::nanoseconds(1s) / 60};
// make present duration much later than the hwc display by itself will account for
- const nsecs_t presentDuration = std::chrono::nanoseconds(10ms).count();
- const nsecs_t postCompDuration = std::chrono::nanoseconds(1ms).count();
+ const Duration presentDuration{10ms};
+ const Duration postCompDuration{1ms};
- nsecs_t startTime = 100;
+ TimePoint startTime{100ns};
// advisor only starts on frame 2 so do an initial no-op frame
fakeBasicFrameTiming(startTime, vsyncPeriod);
@@ -185,7 +185,7 @@
// increment the frame
startTime += vsyncPeriod;
- const nsecs_t expectedDuration = kErrorMargin + presentDuration + postCompDuration;
+ const Duration expectedDuration = kErrorMargin + presentDuration + postCompDuration;
EXPECT_CALL(*mMockAidlWrapper, sendActualWorkDuration(Eq(expectedDuration), _)).Times(1);
fakeBasicFrameTiming(startTime, vsyncPeriod);
@@ -193,8 +193,8 @@
mPowerAdvisor->setDisplays(displayIds);
// don't report timing for the gpu displays since they don't use hwc
- mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1000000, startTime + 1500000);
- mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2000000, startTime + 2500000);
+ mPowerAdvisor->setHwcValidateTiming(displayIds[0], startTime + 1ms, startTime + 1500us);
+ mPowerAdvisor->setHwcPresentTiming(displayIds[0], startTime + 2ms, startTime + 2500us);
mPowerAdvisor->setSfPresentTiming(startTime, startTime + presentDuration);
mPowerAdvisor->sendActualWorkDuration();
}
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index 188fd58..5d9b2a8 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -18,6 +18,7 @@
#define LOG_TAG "SchedulerUnittests"
#include <ftl/enum.h>
+#include <ftl/fake_guard.h>
#include <gmock/gmock.h>
#include <log/log.h>
#include <ui/Size.h>
@@ -41,6 +42,16 @@
struct TestableRefreshRateConfigs : RefreshRateConfigs {
using RefreshRateConfigs::RefreshRateConfigs;
+ void setActiveModeId(DisplayModeId modeId) {
+ ftl::FakeGuard guard(kMainThreadContext);
+ return RefreshRateConfigs::setActiveModeId(modeId);
+ }
+
+ const DisplayMode& getActiveMode() const {
+ ftl::FakeGuard guard(kMainThreadContext);
+ return RefreshRateConfigs::getActiveMode();
+ }
+
DisplayModePtr getMinSupportedRefreshRate() const {
std::lock_guard lock(mLock);
return mMinRefreshRateModeIt->second;
@@ -243,20 +254,20 @@
TEST_F(RefreshRateConfigsTest, twoModes_getActiveMode) {
TestableRefreshRateConfigs configs(kModes_60_90, kModeId60);
{
- const auto mode = configs.getActiveMode();
- EXPECT_EQ(mode->getId(), kModeId60);
+ const auto& mode = configs.getActiveMode();
+ EXPECT_EQ(mode.getId(), kModeId60);
}
configs.setActiveModeId(kModeId90);
{
- const auto mode = configs.getActiveMode();
- EXPECT_EQ(mode->getId(), kModeId90);
+ const auto& mode = configs.getActiveMode();
+ EXPECT_EQ(mode.getId(), kModeId90);
}
EXPECT_GE(configs.setDisplayManagerPolicy({kModeId90, {90_Hz, 90_Hz}}), 0);
{
- const auto mode = configs.getActiveMode();
- EXPECT_EQ(mode->getId(), kModeId90);
+ const auto& mode = configs.getActiveMode();
+ EXPECT_EQ(mode.getId(), kModeId90);
}
}
@@ -966,6 +977,32 @@
EXPECT_EQ(kMode90, configs.getBestRefreshRate(layers));
}
+TEST_F(RefreshRateConfigsTest, powerOnImminentConsidered) {
+ RefreshRateConfigs configs(kModes_60_90, kModeId60);
+
+ auto [refreshRate, signals] = configs.getBestRefreshRate({}, {});
+ EXPECT_FALSE(signals.powerOnImminent);
+ EXPECT_EQ(kMode90, refreshRate);
+
+ std::tie(refreshRate, signals) = configs.getBestRefreshRate({}, {.powerOnImminent = true});
+ EXPECT_TRUE(signals.powerOnImminent);
+ EXPECT_EQ(kMode90, refreshRate);
+
+ std::vector<LayerRequirement> layers = {{.weight = 1.f}};
+ auto& lr1 = layers[0];
+ lr1.vote = LayerVoteType::ExplicitExactOrMultiple;
+ lr1.desiredRefreshRate = 60_Hz;
+ lr1.name = "60Hz ExplicitExactOrMultiple";
+
+ std::tie(refreshRate, signals) = configs.getBestRefreshRate(layers, {.powerOnImminent = false});
+ EXPECT_FALSE(signals.powerOnImminent);
+ EXPECT_EQ(kMode60, refreshRate);
+
+ std::tie(refreshRate, signals) = configs.getBestRefreshRate(layers, {.powerOnImminent = true});
+ EXPECT_TRUE(signals.powerOnImminent);
+ EXPECT_EQ(kMode90, refreshRate);
+}
+
TEST_F(RefreshRateConfigsTest, touchConsidered) {
RefreshRateConfigs configs(kModes_60_90, kModeId60);
@@ -1898,30 +1935,30 @@
}
TEST_F(RefreshRateConfigsTest, getFrameRateDivisor) {
- RefreshRateConfigs configs(kModes_30_60_72_90_120, kModeId30);
+ TestableRefreshRateConfigs configs(kModes_30_60_72_90_120, kModeId30);
const auto frameRate = 30_Hz;
- Fps displayRefreshRate = configs.getActiveMode()->getFps();
+ Fps displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(1, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, frameRate));
configs.setActiveModeId(kModeId60);
- displayRefreshRate = configs.getActiveMode()->getFps();
+ displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(2, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, frameRate));
configs.setActiveModeId(kModeId72);
- displayRefreshRate = configs.getActiveMode()->getFps();
+ displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(0, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, frameRate));
configs.setActiveModeId(kModeId90);
- displayRefreshRate = configs.getActiveMode()->getFps();
+ displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(3, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, frameRate));
configs.setActiveModeId(kModeId120);
- displayRefreshRate = configs.getActiveMode()->getFps();
+ displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(4, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, frameRate));
configs.setActiveModeId(kModeId90);
- displayRefreshRate = configs.getActiveMode()->getFps();
+ displayRefreshRate = configs.getActiveMode().getFps();
EXPECT_EQ(4, RefreshRateConfigs::getFrameRateDivisor(displayRefreshRate, 22.5_Hz));
EXPECT_EQ(0, RefreshRateConfigs::getFrameRateDivisor(24_Hz, 25_Hz));
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
index 6752a39..abf1786 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateSelectionTest.cpp
@@ -22,7 +22,6 @@
#include <gui/LayerMetadata.h>
#include "BufferStateLayer.h"
-#include "EffectLayer.h"
#include "Layer.h"
#include "TestableSurfaceFlinger.h"
#include "mock/DisplayHardware/MockComposer.h"
@@ -60,7 +59,7 @@
void setupScheduler();
sp<BufferStateLayer> createBufferStateLayer();
- sp<EffectLayer> createEffectLayer();
+ sp<Layer> createEffectLayer();
void setParent(Layer* child, Layer* parent);
void commitTransaction(Layer* layer);
@@ -96,10 +95,10 @@
return sp<BufferStateLayer>::make(args);
}
-sp<EffectLayer> RefreshRateSelectionTest::createEffectLayer() {
+sp<Layer> RefreshRateSelectionTest::createEffectLayer() {
sp<Client> client;
LayerCreationArgs args(mFlinger.flinger(), client, "color-layer", LAYER_FLAGS, LayerMetadata());
- return sp<EffectLayer>::make(args);
+ return sp<Layer>::make(args);
}
void RefreshRateSelectionTest::setParent(Layer* child, Layer* parent) {
diff --git a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
index 6ee8174..51c6bea 100644
--- a/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SetFrameRateTest.cpp
@@ -25,7 +25,6 @@
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wconversion"
#include "BufferStateLayer.h"
-#include "EffectLayer.h"
#include "Layer.h"
// TODO(b/129481165): remove the #pragma below and fix conversion issues
#pragma clang diagnostic pop // ignored "-Wconversion"
@@ -374,11 +373,6 @@
const auto& layerFactory = GetParam();
auto parent = mLayers.emplace_back(layerFactory->createLayer(mFlinger));
- if (!parent->isVisible()) {
- // This is a hack as all the test layers except EffectLayer are not visible,
- // but since the logic is unified in Layer, it should be fine.
- return;
- }
auto child = mLayers.emplace_back(layerFactory->createLayer(mFlinger));
addChild(parent, child);
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
index 71f1a2b..73f654b 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp
@@ -118,9 +118,7 @@
ASSERT_TRUE(displayId);
const auto hwcDisplayId = Case::Display::HWC_DISPLAY_ID_OPT::value;
ASSERT_TRUE(hwcDisplayId);
- expectedPhysical = {.id = *displayId,
- .type = *connectionType,
- .hwcDisplayId = *hwcDisplayId};
+ expectedPhysical = {.id = *displayId, .hwcDisplayId = *hwcDisplayId};
}
// The display should have been set up in the current display state
@@ -145,10 +143,13 @@
const auto displayId = Case::Display::DISPLAY_ID::get();
ASSERT_TRUE(PhysicalDisplayId::tryCast(displayId));
- const auto displayTokenOpt = mFlinger.mutablePhysicalDisplayTokens().get(displayId);
- ASSERT_TRUE(displayTokenOpt);
+ const auto displayOpt = mFlinger.mutablePhysicalDisplays().get(displayId);
+ ASSERT_TRUE(displayOpt);
- verifyDisplayIsConnected<Case>(displayTokenOpt->get());
+ const auto& display = displayOpt->get();
+ EXPECT_EQ(Case::Display::CONNECTION_TYPE::value, display.snapshot().connectionType());
+
+ verifyDisplayIsConnected<Case>(display.token());
}
void DisplayTransactionCommitTest::verifyDisplayIsNotConnected(const sp<IBinder>& displayToken) {
@@ -247,10 +248,10 @@
// HWComposer should not have an entry for the display
EXPECT_FALSE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
- // SF should not have a display token.
+ // SF should not have a PhysicalDisplay.
const auto displayId = Case::Display::DISPLAY_ID::get();
ASSERT_TRUE(PhysicalDisplayId::tryCast(displayId));
- ASSERT_FALSE(mFlinger.mutablePhysicalDisplayTokens().contains(displayId));
+ ASSERT_FALSE(mFlinger.mutablePhysicalDisplays().contains(displayId));
// The existing token should have been removed.
verifyDisplayIsNotConnected(existing.token());
@@ -329,10 +330,10 @@
// HWComposer should not have an entry for the display
EXPECT_FALSE(hasPhysicalHwcDisplay(Case::Display::HWC_DISPLAY_ID));
- // SF should not have a display token.
+ // SF should not have a PhysicalDisplay.
const auto displayId = Case::Display::DISPLAY_ID::get();
ASSERT_TRUE(PhysicalDisplayId::tryCast(displayId));
- ASSERT_FALSE(mFlinger.mutablePhysicalDisplayTokens().contains(displayId));
+ ASSERT_FALSE(mFlinger.mutablePhysicalDisplays().contains(displayId));
}(),
testing::KilledBySignal(SIGABRT), "Primary display cannot be disconnected.");
}
@@ -376,9 +377,9 @@
const auto displayId = Case::Display::DISPLAY_ID::get();
ASSERT_TRUE(PhysicalDisplayId::tryCast(displayId));
- const auto displayTokenOpt = mFlinger.mutablePhysicalDisplayTokens().get(displayId);
- ASSERT_TRUE(displayTokenOpt);
- EXPECT_NE(existing.token(), displayTokenOpt->get());
+ const auto displayOpt = mFlinger.mutablePhysicalDisplays().get(displayId);
+ ASSERT_TRUE(displayOpt);
+ EXPECT_NE(existing.token(), displayOpt->get().token());
// A new display should be connected in its place.
verifyPhysicalDisplayIsConnected<Case>();
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
index 1756368..9e54083 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
@@ -253,14 +253,16 @@
using DispSync = DispSyncVariant;
using Transition = TransitionVariant;
- static auto injectDisplayWithInitialPowerMode(DisplayTransactionTest* test, PowerMode mode) {
+ static sp<DisplayDevice> injectDisplayWithInitialPowerMode(DisplayTransactionTest* test,
+ PowerMode mode) {
Display::injectHwcDisplayWithNoDefaultCapabilities(test);
- auto display = Display::makeFakeExistingDisplayInjector(test);
- display.inject();
- display.mutableDisplayDevice()->setPowerMode(mode);
- if (display.mutableDisplayDevice()->isInternal()) {
- test->mFlinger.mutableActiveDisplayToken() =
- display.mutableDisplayDevice()->getDisplayToken();
+ auto injector = Display::makeFakeExistingDisplayInjector(test);
+ const auto display = injector.inject();
+ display->setPowerMode(mode);
+ if (injector.physicalDisplay()
+ .transform(&display::PhysicalDisplay::isInternal)
+ .value_or(false)) {
+ test->mFlinger.mutableActiveDisplayToken() = display->getDisplayToken();
}
return display;
@@ -353,8 +355,7 @@
// --------------------------------------------------------------------
// Invocation
- mFlinger.setPowerModeInternal(display.mutableDisplayDevice(),
- Case::Transition::TARGET_POWER_MODE);
+ mFlinger.setPowerModeInternal(display, Case::Transition::TARGET_POWER_MODE);
// --------------------------------------------------------------------
// Postconditions
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
index 6aeb3fe..ec2c2b4 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp
@@ -246,11 +246,14 @@
.setDpiY(DEFAULT_DPI)
.setGroup(0)
.build();
+
state.physical = {.id = *displayId,
- .type = *connectionType,
.hwcDisplayId = *hwcDisplayId,
- .supportedModes = makeModes(activeMode),
- .activeMode = std::move(activeMode)};
+ .activeMode = activeMode};
+
+ mFlinger.mutablePhysicalDisplays().emplace_or_replace(*displayId, displayToken, *displayId,
+ *connectionType,
+ makeModes(activeMode), std::nullopt);
}
state.isSecure = static_cast<bool>(Case::Display::SECURE);
@@ -264,7 +267,6 @@
ASSERT_TRUE(device != nullptr);
EXPECT_EQ(Case::Display::DISPLAY_ID::get(), device->getId());
- EXPECT_EQ(Case::Display::CONNECTION_TYPE::value, device->getConnectionType());
EXPECT_EQ(static_cast<bool>(Case::Display::VIRTUAL), device->isVirtual());
EXPECT_EQ(static_cast<bool>(Case::Display::SECURE), device->isSecure());
EXPECT_EQ(static_cast<bool>(Case::Display::PRIMARY), device->isPrimary());
@@ -280,7 +282,6 @@
device->receivesInput());
if constexpr (Case::Display::CONNECTION_TYPE::value) {
- EXPECT_EQ(1, device->getSupportedModes().size());
EXPECT_NE(nullptr, device->getActiveMode());
EXPECT_EQ(Case::Display::HWC_ACTIVE_CONFIG_ID, device->getActiveMode()->getHwcId());
}
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 42585b5..1ce6e18 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -32,7 +32,6 @@
#include "BufferStateLayer.h"
#include "DisplayDevice.h"
-#include "EffectLayer.h"
#include "FakeVsyncConfiguration.h"
#include "FrameTracer/FrameTracer.h"
#include "Layer.h"
@@ -125,7 +124,7 @@
return nullptr;
}
- sp<EffectLayer> createEffectLayer(const LayerCreationArgs&) override { return nullptr; }
+ sp<Layer> createEffectLayer(const LayerCreationArgs&) override { return nullptr; }
std::unique_ptr<FrameTracer> createFrameTracer() override {
return std::make_unique<mock::FrameTracer>();
@@ -223,7 +222,7 @@
configs = std::make_shared<scheduler::RefreshRateConfigs>(modes, kModeId60);
}
- const auto fps = configs->getActiveMode()->getFps();
+ const auto fps = FTL_FAKE_GUARD(kMainThreadContext, configs->getActiveMode().getFps());
mFlinger->mVsyncConfiguration = mFactory.createVsyncConfiguration(fps);
mFlinger->mVsyncModulator = sp<scheduler::VsyncModulator>::make(
mFlinger->mVsyncConfiguration->getCurrentConfigs());
@@ -371,6 +370,7 @@
void commitTransactionsLocked(uint32_t transactionFlags) {
Mutex::Autolock lock(mFlinger->mStateLock);
+ ftl::FakeGuard guard(kMainThreadContext);
mFlinger->commitTransactionsLocked(transactionFlags);
}
@@ -464,6 +464,7 @@
void onActiveDisplayChanged(const sp<DisplayDevice>& activeDisplay) {
Mutex::Autolock lock(mFlinger->mStateLock);
+ ftl::FakeGuard guard(kMainThreadContext);
mFlinger->onActiveDisplayChangedLocked(activeDisplay);
}
@@ -503,6 +504,7 @@
*/
const auto& displays() const { return mFlinger->mDisplays; }
+ const auto& physicalDisplays() const { return mFlinger->mPhysicalDisplays; }
const auto& currentState() const { return mFlinger->mCurrentState; }
const auto& drawingState() const { return mFlinger->mDrawingState; }
const auto& transactionFlags() const { return mFlinger->mTransactionFlags; }
@@ -515,12 +517,12 @@
auto& mutableCurrentState() { return mFlinger->mCurrentState; }
auto& mutableDisplayColorSetting() { return mFlinger->mDisplayColorSetting; }
auto& mutableDisplays() { return mFlinger->mDisplays; }
+ auto& mutablePhysicalDisplays() { return mFlinger->mPhysicalDisplays; }
auto& mutableDrawingState() { return mFlinger->mDrawingState; }
auto& mutableGeometryDirty() { return mFlinger->mGeometryDirty; }
auto& mutableInterceptor() { return mFlinger->mInterceptor; }
auto& mutableMainThreadId() { return mFlinger->mMainThreadId; }
auto& mutablePendingHotplugEvents() { return mFlinger->mPendingHotplugEvents; }
- auto& mutablePhysicalDisplayTokens() { return mFlinger->mPhysicalDisplayTokens; }
auto& mutableTexturePool() { return mFlinger->mTexturePool; }
auto& mutableTransactionFlags() { return mFlinger->mTransactionFlags; }
auto& mutableDebugDisableHWC() { return mFlinger->mDebugDisableHWC; }
@@ -725,13 +727,20 @@
: mFlinger(flinger),
mCreationArgs(flinger.mFlinger, flinger.mFlinger->getHwComposer(), mDisplayToken,
display),
+ mConnectionType(connectionType),
mHwcDisplayId(hwcDisplayId) {
- mCreationArgs.connectionType = connectionType;
mCreationArgs.isPrimary = isPrimary;
+ mCreationArgs.initialPowerMode = hal::PowerMode::ON;
}
sp<IBinder> token() const { return mDisplayToken; }
+ auto physicalDisplay() const {
+ return ftl::Optional(mCreationArgs.compositionDisplay->getDisplayId())
+ .and_then(&PhysicalDisplayId::tryCast)
+ .and_then(display::getPhysicalDisplay(mFlinger.physicalDisplays()));
+ }
+
DisplayDeviceState& mutableDrawingDisplayState() {
return mFlinger.mutableDrawingState().displays.editValueFor(mDisplayToken);
}
@@ -759,7 +768,7 @@
// the `configs` parameter in favor of an alternative setRefreshRateConfigs API.
auto& setDisplayModes(DisplayModes modes, DisplayModeId activeModeId,
std::shared_ptr<scheduler::RefreshRateConfigs> configs = nullptr) {
- mCreationArgs.supportedModes = std::move(modes);
+ mDisplayModes = std::move(modes);
mCreationArgs.activeModeId = activeModeId;
mCreationArgs.refreshRateConfigs = std::move(configs);
return *this;
@@ -805,7 +814,7 @@
sp<DisplayDevice> inject() NO_THREAD_SAFETY_ANALYSIS {
const auto displayId = mCreationArgs.compositionDisplay->getDisplayId();
- auto& modes = mCreationArgs.supportedModes;
+ auto& modes = mDisplayModes;
auto& activeModeId = mCreationArgs.activeModeId;
if (displayId && !mCreationArgs.refreshRateConfigs) {
@@ -833,8 +842,13 @@
}
}
+ sp<DisplayDevice> display = sp<DisplayDevice>::make(mCreationArgs);
+ mFlinger.mutableDisplays().emplace_or_replace(mDisplayToken, display);
+
DisplayDeviceState state;
- if (const auto type = mCreationArgs.connectionType) {
+ state.isSecure = mCreationArgs.isSecure;
+
+ if (mConnectionType) {
LOG_ALWAYS_FATAL_IF(!displayId);
const auto physicalId = PhysicalDisplayId::tryCast(*displayId);
LOG_ALWAYS_FATAL_IF(!physicalId);
@@ -844,29 +858,21 @@
LOG_ALWAYS_FATAL_IF(!activeMode);
state.physical = {.id = *physicalId,
- .type = *type,
.hwcDisplayId = *mHwcDisplayId,
- .deviceProductInfo = {},
- .supportedModes = modes,
.activeMode = activeMode->get()};
- }
- state.isSecure = mCreationArgs.isSecure;
+ const auto it = mFlinger.mutablePhysicalDisplays()
+ .emplace_or_replace(*physicalId, mDisplayToken, *physicalId,
+ *mConnectionType, std::move(modes),
+ std::nullopt)
+ .first;
- sp<DisplayDevice> display = sp<DisplayDevice>::make(mCreationArgs);
- if (!display->isVirtual()) {
- display->setActiveMode(activeModeId);
+ display->setActiveMode(activeModeId, it->second.snapshot());
}
- mFlinger.mutableDisplays().emplace_or_replace(mDisplayToken, display);
mFlinger.mutableCurrentState().displays.add(mDisplayToken, state);
mFlinger.mutableDrawingState().displays.add(mDisplayToken, state);
- if (const auto& physical = state.physical) {
- mFlinger.mutablePhysicalDisplayTokens().emplace_or_replace(physical->id,
- mDisplayToken);
- }
-
return display;
}
@@ -874,6 +880,8 @@
TestableSurfaceFlinger& mFlinger;
sp<BBinder> mDisplayToken = sp<BBinder>::make();
DisplayDeviceCreationArgs mCreationArgs;
+ DisplayModes mDisplayModes;
+ const std::optional<ui::DisplayConnectionType> mConnectionType;
const std::optional<hal::HWDisplayId> mHwcDisplayId;
};
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockAidlPowerHalWrapper.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockAidlPowerHalWrapper.h
index 657ced3..c2c3d77 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockAidlPowerHalWrapper.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockAidlPowerHalWrapper.h
@@ -17,6 +17,7 @@
#pragma once
#include <gmock/gmock.h>
+#include <scheduler/Time.h>
#include "DisplayHardware/PowerAdvisor.h"
@@ -42,8 +43,8 @@
MOCK_METHOD(void, setPowerHintSessionThreadIds, (const std::vector<int32_t>& threadIds),
(override));
MOCK_METHOD(bool, startPowerHintSession, (), (override));
- MOCK_METHOD(void, setTargetWorkDuration, (nsecs_t targetDuration), (override));
- MOCK_METHOD(void, sendActualWorkDuration, (nsecs_t actualDuration, nsecs_t timestamp),
+ MOCK_METHOD(void, setTargetWorkDuration, (Duration targetDuration), (override));
+ MOCK_METHOD(void, sendActualWorkDuration, (Duration actualDuration, TimePoint timestamp),
(override));
MOCK_METHOD(bool, shouldReconnectHAL, (), (override));
};
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
index aede250..fb1b394 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockPowerAdvisor.h
@@ -36,7 +36,7 @@
MOCK_METHOD(bool, usePowerHintSession, (), (override));
MOCK_METHOD(bool, supportsPowerHintSession, (), (override));
MOCK_METHOD(bool, isPowerHintSessionRunning, (), (override));
- MOCK_METHOD(void, setTargetWorkDuration, (int64_t targetDuration), (override));
+ MOCK_METHOD(void, setTargetWorkDuration, (Duration targetDuration), (override));
MOCK_METHOD(void, sendActualWorkDuration, (), (override));
MOCK_METHOD(void, sendPredictedWorkDuration, (), (override));
MOCK_METHOD(void, enablePowerHint, (bool enabled), (override));
@@ -44,25 +44,24 @@
MOCK_METHOD(void, setGpuFenceTime,
(DisplayId displayId, std::unique_ptr<FenceTime>&& fenceTime), (override));
MOCK_METHOD(void, setHwcValidateTiming,
- (DisplayId displayId, nsecs_t valiateStartTime, nsecs_t validateEndTime),
+ (DisplayId displayId, TimePoint validateStartTime, TimePoint validateEndTime),
(override));
MOCK_METHOD(void, setHwcPresentTiming,
- (DisplayId displayId, nsecs_t presentStartTime, nsecs_t presentEndTime),
+ (DisplayId displayId, TimePoint presentStartTime, TimePoint presentEndTime),
(override));
MOCK_METHOD(void, setSkippedValidate, (DisplayId displayId, bool skipped), (override));
MOCK_METHOD(void, setRequiresClientComposition,
(DisplayId displayId, bool requiresClientComposition), (override));
- MOCK_METHOD(void, setExpectedPresentTime, (nsecs_t expectedPresentTime), (override));
- MOCK_METHOD(void, setSfPresentTiming, (nsecs_t presentFenceTime, nsecs_t presentEndTime),
+ MOCK_METHOD(void, setExpectedPresentTime, (TimePoint expectedPresentTime), (override));
+ MOCK_METHOD(void, setSfPresentTiming, (TimePoint presentFenceTime, TimePoint presentEndTime),
(override));
MOCK_METHOD(void, setHwcPresentDelayedTime,
- (DisplayId displayId,
- std::chrono::steady_clock::time_point earliestFrameStartTime));
- MOCK_METHOD(void, setFrameDelay, (nsecs_t frameDelayDuration), (override));
- MOCK_METHOD(void, setCommitStart, (nsecs_t commitStartTime), (override));
- MOCK_METHOD(void, setCompositeEnd, (nsecs_t compositeEndtime), (override));
+ (DisplayId displayId, TimePoint earliestFrameStartTime));
+ MOCK_METHOD(void, setFrameDelay, (Duration frameDelayDuration), (override));
+ MOCK_METHOD(void, setCommitStart, (TimePoint commitStartTime), (override));
+ MOCK_METHOD(void, setCompositeEnd, (TimePoint compositeEndTime), (override));
MOCK_METHOD(void, setDisplays, (std::vector<DisplayId> & displayIds), (override));
- MOCK_METHOD(void, setTotalFrameTargetWorkDuration, (int64_t targetDuration), (override));
+ MOCK_METHOD(void, setTotalFrameTargetWorkDuration, (Duration targetDuration), (override));
};
} // namespace android::Hwc2::mock
diff --git a/services/surfaceflinger/tests/unittests/mock/MockLayer.h b/services/surfaceflinger/tests/unittests/mock/MockLayer.h
index d086d79..48d05cb 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockLayer.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockLayer.h
@@ -18,14 +18,14 @@
#include <gmock/gmock.h>
-#include "Layer.h"
+#include "BufferStateLayer.h"
namespace android::mock {
-class MockLayer : public Layer {
+class MockLayer : public BufferStateLayer {
public:
MockLayer(SurfaceFlinger* flinger, std::string name)
- : Layer(LayerCreationArgs(flinger, nullptr, std::move(name), 0, {})) {
+ : BufferStateLayer(LayerCreationArgs(flinger, nullptr, std::move(name), 0, {})) {
EXPECT_CALL(*this, getDefaultFrameRateCompatibility())
.WillOnce(testing::Return(scheduler::LayerInfo::FrameRateCompatibility::Default));
}
diff --git a/services/surfaceflinger/tests/utils/ScreenshotUtils.h b/services/surfaceflinger/tests/utils/ScreenshotUtils.h
index cb7040a..224868c 100644
--- a/services/surfaceflinger/tests/utils/ScreenshotUtils.h
+++ b/services/surfaceflinger/tests/utils/ScreenshotUtils.h
@@ -18,6 +18,7 @@
#include <gui/AidlStatusUtil.h>
#include <gui/SyncScreenCaptureListener.h>
#include <private/gui/ComposerServiceAIDL.h>
+#include <ui/FenceResult.h>
#include <ui/Rect.h>
#include <utils/String8.h>
#include <functional>
@@ -46,7 +47,7 @@
return err;
}
captureResults = captureListener->waitForResults();
- return captureResults.result;
+ return fenceStatus(captureResults.fenceResult);
}
static void captureScreen(std::unique_ptr<ScreenCapture>* sc) {
@@ -80,7 +81,7 @@
return err;
}
captureResults = captureListener->waitForResults();
- return captureResults.result;
+ return fenceStatus(captureResults.fenceResult);
}
static void captureLayers(std::unique_ptr<ScreenCapture>* sc, LayerCaptureArgs& captureArgs) {
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index 1815c46..9c6d19f 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -19,6 +19,8 @@
#include <android/hardware/graphics/common/1.0/types.h>
#include <grallocusage/GrallocUsageConversion.h>
#include <graphicsenv/GraphicsEnv.h>
+#include <hardware/gralloc.h>
+#include <hardware/gralloc1.h>
#include <log/log.h>
#include <sync/sync.h>
#include <system/window.h>
@@ -42,6 +44,26 @@
namespace {
+static uint64_t convertGralloc1ToBufferUsage(uint64_t producerUsage,
+ uint64_t consumerUsage) {
+ static_assert(uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) ==
+ uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_READ_OFTEN),
+ "expected ConsumerUsage and ProducerUsage CPU_READ_OFTEN "
+ "bits to match");
+ uint64_t merged = producerUsage | consumerUsage;
+ if ((merged & (GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN)) ==
+ GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN) {
+ merged &= ~uint64_t(GRALLOC1_CONSUMER_USAGE_CPU_READ_OFTEN);
+ merged |= BufferUsage::CPU_READ_OFTEN;
+ }
+ if ((merged & (GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN)) ==
+ GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN) {
+ merged &= ~uint64_t(GRALLOC1_PRODUCER_USAGE_CPU_WRITE_OFTEN);
+ merged |= BufferUsage::CPU_WRITE_OFTEN;
+ }
+ return merged;
+}
+
const VkSurfaceTransformFlagsKHR kSupportedTransforms =
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR |
VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR |
@@ -1337,7 +1359,7 @@
num_images = 1;
}
- int32_t legacy_usage = 0;
+ uint64_t native_usage = 0;
if (dispatch.GetSwapchainGrallocUsage2ANDROID) {
uint64_t consumer_usage, producer_usage;
ATRACE_BEGIN("GetSwapchainGrallocUsage2ANDROID");
@@ -1349,10 +1371,11 @@
ALOGE("vkGetSwapchainGrallocUsage2ANDROID failed: %d", result);
return VK_ERROR_SURFACE_LOST_KHR;
}
- legacy_usage =
- android_convertGralloc1To0Usage(producer_usage, consumer_usage);
+ native_usage =
+ convertGralloc1ToBufferUsage(consumer_usage, producer_usage);
} else if (dispatch.GetSwapchainGrallocUsageANDROID) {
ATRACE_BEGIN("GetSwapchainGrallocUsageANDROID");
+ int32_t legacy_usage = 0;
result = dispatch.GetSwapchainGrallocUsageANDROID(
device, create_info->imageFormat, create_info->imageUsage,
&legacy_usage);
@@ -1361,8 +1384,9 @@
ALOGE("vkGetSwapchainGrallocUsageANDROID failed: %d", result);
return VK_ERROR_SURFACE_LOST_KHR;
}
+ native_usage = static_cast<uint64_t>(legacy_usage);
}
- uint64_t native_usage = static_cast<uint64_t>(legacy_usage);
+ native_usage |= surface.consumer_usage;
bool createProtectedSwapchain = false;
if (create_info->flags & VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR) {