Merge "Add native MotionPredictor"
diff --git a/cmds/atrace/README.md b/cmds/atrace/README.md
new file mode 100644
index 0000000..faa43b2
--- /dev/null
+++ b/cmds/atrace/README.md
@@ -0,0 +1,48 @@
+# Atrace categories
+
+The atrace command (and the perfetto configuration) allow listing **categories**
+to select subsets of events to be traced.
+
+Each category can include some userspace events and some ftrace events.
+
+## Vendor categories
+
+It's possible to extend exiting categories (or to define new categories) from
+the /vendor partition in order to add hardware specific ftrace events.
+
+Since android 14, if the file `/vendor/etc/atrace/atrace_categories.txt`, atrace
+and perfetto will consider the categories and ftrace events listed there.
+
+The file contains a list of categories, and for each category (on the following
+lines, indented with one or more spaces of time), a list of ftrace events that
+should be enabled when the category is enabled.
+
+Each ftrace event should be a subdirectory in `/sys/kernel/tracing/events/` and
+should be of the form `group/event`. Listing a whole group is not supported,
+each event needs to be listed explicitly.
+
+It is not an error if an ftrace event is listed in the file, but not present on
+the tracing file system.
+
+Example:
+
+```
+gfx
+ mali/gpu_power_state
+ mali/mali_pm_status
+thermal_tj
+ thermal_exynos/thermal_cpu_pressure
+ thermal_exynos/thermal_exynos_arm_update
+```
+
+The file lists two categories (`gfx` and `thermal_tj`). When the `gfx` category
+is enabled, atrace (or perfetto) will enable
+`/sys/kernel/tracing/events/mali/gpu_power_state` and
+`/sys/kernel/tracing/events/mali/mali_pm_status`. When the `thermal_tj` category
+is enabled, atrace (or perfetto) will enable
+`/sys/kernel/tracing/events/thermal_exynos/thermal_cpu_pressure` and
+`/sys/kernel/tracing/events/thermal_exynos/thermal_exynos_arm_update`.
+
+Since android 14, if the file `/vendor/etc/atrace/atrace_categories.txt` exists
+on the file system, perfetto and atrace do not query the android.hardware.atrace
+HAL (which is deprecated).
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 48d48ac..8105626 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -49,6 +49,7 @@
#include <android-base/file.h>
#include <android-base/macros.h>
#include <android-base/properties.h>
+#include <android-base/strings.h>
#include <android-base/stringprintf.h>
using namespace android;
@@ -62,7 +63,7 @@
using std::string;
-#define MAX_SYS_FILES 12
+#define MAX_SYS_FILES 13
const char* k_traceTagsProperty = "debug.atrace.tags.enableflags";
const char* k_userInitiatedTraceProperty = "debug.atrace.user_initiated";
@@ -73,7 +74,9 @@
const char* k_pdxServiceCategory = "pdx";
const char* k_coreServicesProp = "ro.atrace.core.services";
-typedef enum { OPT, REQ } requiredness ;
+const char* kVendorCategoriesPath = "/vendor/etc/atrace/atrace_categories.txt";
+
+typedef enum { OPT, REQ } requiredness;
struct TracingCategory {
// The name identifying the category.
@@ -189,6 +192,8 @@
{ OPT, "events/f2fs/f2fs_sync_file_exit/enable" },
{ OPT, "events/f2fs/f2fs_write_begin/enable" },
{ OPT, "events/f2fs/f2fs_write_end/enable" },
+ { OPT, "events/f2fs/f2fs_iostat/enable" },
+ { OPT, "events/f2fs/f2fs_iostat_latency/enable" },
{ OPT, "events/ext4/ext4_da_write_begin/enable" },
{ OPT, "events/ext4/ext4_da_write_end/enable" },
{ OPT, "events/ext4/ext4_sync_file_enter/enable" },
@@ -253,7 +258,20 @@
} },
};
-struct TracingVendorCategory {
+// A category in the vendor categories file.
+struct TracingVendorFileCategory {
+ // The name identifying the category.
+ std::string name;
+
+ // If the category is enabled through command.
+ bool enabled = false;
+
+ // Paths to the ftrace enable files (relative to g_traceFolder).
+ std::vector<std::string> ftrace_enable_paths;
+};
+
+// A category in the vendor HIDL HAL.
+struct TracingVendorHalCategory {
// The name identifying the category.
std::string name;
@@ -263,11 +281,8 @@
// If the category is enabled through command.
bool enabled;
- TracingVendorCategory(string &&name, string &&description, bool enabled)
- : name(std::move(name))
- , description(std::move(description))
- , enabled(enabled)
- {}
+ TracingVendorHalCategory(string&& name, string&& description, bool enabled)
+ : name(std::move(name)), description(std::move(description)), enabled(enabled) {}
};
/* Command line options */
@@ -287,8 +302,9 @@
static bool g_traceAborted = false;
static bool g_categoryEnables[arraysize(k_categories)] = {};
static std::string g_traceFolder;
+static std::vector<TracingVendorFileCategory> g_vendorFileCategories;
static sp<IAtraceDevice> g_atraceHal;
-static std::vector<TracingVendorCategory> g_vendorCategories;
+static std::vector<TracingVendorHalCategory> g_vendorHalCategories;
/* Sys file paths */
static const char* k_traceClockPath =
@@ -645,6 +661,13 @@
}
}
}
+ for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
+ for (const std::string& path : c.ftrace_enable_paths) {
+ if (fileIsWritable(path.c_str())) {
+ ok &= setKernelOptionEnable(path.c_str(), false);
+ }
+ }
+ }
return ok;
}
@@ -724,7 +747,13 @@
static bool setCategoryEnable(const char* name)
{
bool vendor_found = false;
- for (auto &c : g_vendorCategories) {
+ for (auto& c : g_vendorFileCategories) {
+ if (strcmp(name, c.name.c_str()) == 0) {
+ c.enabled = true;
+ vendor_found = true;
+ }
+ }
+ for (auto& c : g_vendorHalCategories) {
if (strcmp(name, c.name.c_str()) == 0) {
c.enabled = true;
vendor_found = true;
@@ -870,6 +899,16 @@
}
}
+ for (const TracingVendorFileCategory& c : g_vendorFileCategories) {
+ if (c.enabled) {
+ for (const std::string& path : c.ftrace_enable_paths) {
+ if (fileIsWritable(path.c_str())) {
+ ok &= setKernelOptionEnable(path.c_str(), true);
+ }
+ }
+ }
+ }
+
return ok;
}
@@ -1055,7 +1094,10 @@
printf(" %10s - %s\n", c.name, c.longname);
}
}
- for (const auto &c : g_vendorCategories) {
+ for (const auto& c : g_vendorFileCategories) {
+ printf(" %10s - (VENDOR)\n", c.name.c_str());
+ }
+ for (const auto& c : g_vendorHalCategories) {
printf(" %10s - %s (HAL)\n", c.name.c_str(), c.description.c_str());
}
}
@@ -1114,8 +1156,38 @@
return true;
}
-void initVendorCategories()
-{
+void initVendorCategoriesFromFile() {
+ std::ifstream is(kVendorCategoriesPath);
+ for (std::string line; std::getline(is, line);) {
+ if (line.empty()) {
+ continue;
+ }
+ if (android::base::StartsWith(line, ' ') || android::base::StartsWith(line, '\t')) {
+ if (g_vendorFileCategories.empty()) {
+ fprintf(stderr, "Malformed vendor categories file\n");
+ exit(1);
+ return;
+ }
+ std::string_view path = std::string_view(line).substr(1);
+ while (android::base::StartsWith(path, ' ') || android::base::StartsWith(path, '\t')) {
+ path.remove_prefix(1);
+ }
+ if (path.empty()) {
+ continue;
+ }
+ std::string enable_path = "events/";
+ enable_path += path;
+ enable_path += "/enable";
+ g_vendorFileCategories.back().ftrace_enable_paths.push_back(std::move(enable_path));
+ } else {
+ TracingVendorFileCategory cat;
+ cat.name = line;
+ g_vendorFileCategories.push_back(std::move(cat));
+ }
+ }
+}
+
+void initVendorCategoriesFromHal() {
g_atraceHal = IAtraceDevice::getService();
if (g_atraceHal == nullptr) {
@@ -1123,27 +1195,34 @@
return;
}
- Return<void> ret = g_atraceHal->listCategories(
- [](const auto& list) {
- g_vendorCategories.reserve(list.size());
- for (const auto& category : list) {
- g_vendorCategories.emplace_back(category.name, category.description, false);
- }
- });
+ Return<void> ret = g_atraceHal->listCategories([](const auto& list) {
+ g_vendorHalCategories.reserve(list.size());
+ for (const auto& category : list) {
+ g_vendorHalCategories.emplace_back(category.name, category.description, false);
+ }
+ });
if (!ret.isOk()) {
fprintf(stderr, "calling atrace HAL failed: %s\n", ret.description().c_str());
}
}
-static bool setUpVendorTracing()
-{
+void initVendorCategories() {
+ // If kVendorCategoriesPath exists on the filesystem, do not use the HAL.
+ if (access(kVendorCategoriesPath, F_OK) != -1) {
+ initVendorCategoriesFromFile();
+ } else {
+ initVendorCategoriesFromHal();
+ }
+}
+
+static bool setUpVendorTracingWithHal() {
if (g_atraceHal == nullptr) {
// No atrace HAL
return true;
}
std::vector<hidl_string> categories;
- for (const auto &c : g_vendorCategories) {
+ for (const auto& c : g_vendorHalCategories) {
if (c.enabled) {
categories.emplace_back(c.name);
}
@@ -1164,15 +1243,14 @@
return true;
}
-static bool cleanUpVendorTracing()
-{
+static bool cleanUpVendorTracingWithHal() {
if (g_atraceHal == nullptr) {
// No atrace HAL
return true;
}
- if (!g_vendorCategories.size()) {
- // No vendor categories
+ if (!g_vendorHalCategories.size()) {
+ // No vendor HAL categories
return true;
}
@@ -1326,7 +1404,7 @@
if (ok && traceStart && !onlyUserspace) {
ok &= setUpKernelTracing();
- ok &= setUpVendorTracing();
+ ok &= setUpVendorTracingWithHal();
ok &= startTrace();
}
@@ -1397,7 +1475,7 @@
if (traceStop) {
cleanUpUserspaceTracing();
if (!onlyUserspace) {
- cleanUpVendorTracing();
+ cleanUpVendorTracingWithHal();
cleanUpKernelTracing();
}
}
diff --git a/include/android/keycodes.h b/include/android/keycodes.h
index e5b5db2..d4ba321 100644
--- a/include/android/keycodes.h
+++ b/include/android/keycodes.h
@@ -829,6 +829,8 @@
AKEYCODE_STYLUS_BUTTON_TERTIARY = 310,
/** A button on the tail end of a stylus. */
AKEYCODE_STYLUS_BUTTON_TAIL = 311,
+ /** Key to open recent apps (a.k.a. Overview) */
+ AKEYCODE_RECENT_APPS = 312,
// 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/performance_hint.h b/include/android/performance_hint.h
index eed6b33..4a5bd5e 100644
--- a/include/android/performance_hint.h
+++ b/include/android/performance_hint.h
@@ -88,36 +88,6 @@
typedef struct APerformanceHintSession APerformanceHintSession;
/**
- * Hints for the session used by {@link APerformanceHint_sendHint} to signal upcoming changes
- * in the mode or workload.
- */
-enum SessionHint {
- /**
- * This hint indicates a sudden increase in CPU workload intensity. It means
- * that this hint session needs extra CPU resources immediately to meet the
- * target duration for the current work cycle.
- */
- CPU_LOAD_UP = 0,
- /**
- * This hint indicates a decrease in CPU workload intensity. It means that
- * this hint session can reduce CPU resources and still meet the target duration.
- */
- CPU_LOAD_DOWN = 1,
- /*
- * This hint indicates an upcoming CPU workload that is completely changed and
- * unknown. It means that the hint session should reset CPU resources to a known
- * baseline to prepare for an arbitrary load, and must wake up if inactive.
- */
- CPU_LOAD_RESET = 2,
- /*
- * This hint indicates that the most recent CPU workload is resuming after a
- * period of inactivity. It means that the hint session should allocate similar
- * CPU resources to what was used previously, and must wake up if inactive.
- */
- CPU_LOAD_RESUME = 3,
-};
-
-/**
* Acquire an instance of the performance hint manager.
*
* @return manager instance on success, nullptr on failure.
@@ -190,15 +160,21 @@
APerformanceHintSession* session) __INTRODUCED_IN(__ANDROID_API_T__);
/**
- * Sends performance hints to inform the hint session of changes in the workload.
+ * Set a list of threads to the performance hint session. This operation will replace
+ * the current list of threads with the given list of threads.
*
- * @param session The performance hint session instance to update.
- * @param hint The hint to send to the session.
- * @return 0 on success
+ * @param session The performance hint session instance for the threads.
+ * @param threadIds The list of threads to be associated with this session. They must be part of
+ * this app's thread group.
+ * @param size the size of the list of threadIds.
+ * @return 0 on success.
+ * EINVAL if the list of thread ids is empty or if any of the thread ids is not part of the thread group.
* EPIPE if communication with the system service has failed.
*/
-int APerformanceHint_sendHint(
- APerformanceHintSession* session, int hint) __INTRODUCED_IN(__ANDROID_API_U__);
+int APerformanceHint_setThreads(
+ APerformanceHintSession* session,
+ const int32_t* threadIds,
+ size_t size) __INTRODUCED_IN(__ANDROID_API_U__);
__END_DECLS
diff --git a/include/audiomanager/AudioManager.h b/include/audiomanager/AudioManager.h
index 6794fbf..43048db 100644
--- a/include/audiomanager/AudioManager.h
+++ b/include/audiomanager/AudioManager.h
@@ -40,9 +40,17 @@
PLAYER_UPDATE_DEVICE_ID = 5,
PLAYER_UPDATE_PORT_ID = 6,
PLAYER_UPDATE_MUTED = 7,
+ PLAYER_UPDATE_FORMAT = 8,
} player_state_t;
static constexpr char
+ kExtraPlayerEventSpatializedKey[] = "android.media.extra.PLAYER_EVENT_SPATIALIZED";
+static constexpr char
+ kExtraPlayerEventSampleRateKey[] = "android.media.extra.PLAYER_EVENT_SAMPLE_RATE";
+static constexpr char
+ kExtraPlayerEventChannelMaskKey[] = "android.media.extra.PLAYER_EVENT_CHANNEL_MASK";
+
+static constexpr char
kExtraPlayerEventMuteKey[] = "android.media.extra.PLAYER_EVENT_MUTE";
enum {
PLAYER_MUTE_MASTER = (1 << 0),
diff --git a/include/input/Input.h b/include/input/Input.h
index 015efdd..1a35196 100644
--- a/include/input/Input.h
+++ b/include/input/Input.h
@@ -203,6 +203,13 @@
*/
vec2 transformWithoutTranslation(const ui::Transform& transform, const vec2& xy);
+/*
+ * Transform an angle on the x-y plane. An angle of 0 radians corresponds to "north" or
+ * pointing upwards in the negative Y direction, a positive angle points towards the right, and a
+ * negative angle points towards the left.
+ */
+float transformAngle(const ui::Transform& transform, float angleRadians);
+
const char* inputEventTypeToString(int32_t type);
std::string inputEventSourceToString(int32_t source);
diff --git a/include/input/InputDevice.h b/include/input/InputDevice.h
index e911734..5fa9fda 100644
--- a/include/input/InputDevice.h
+++ b/include/input/InputDevice.h
@@ -205,6 +205,16 @@
int32_t id;
};
+struct KeyboardLayoutInfo {
+ explicit KeyboardLayoutInfo(std::string languageTag, std::string layoutType)
+ : languageTag(languageTag), layoutType(layoutType) {}
+
+ // A BCP 47 conformant language tag such as "en-US".
+ std::string languageTag;
+ // The layout type such as QWERTY or AZERTY.
+ std::string layoutType;
+};
+
/*
* Describes the characteristics and capabilities of an input device.
*/
@@ -256,6 +266,11 @@
void setKeyboardType(int32_t keyboardType);
inline int32_t getKeyboardType() const { return mKeyboardType; }
+ void setKeyboardLayoutInfo(KeyboardLayoutInfo keyboardLayoutInfo);
+ inline const std::optional<KeyboardLayoutInfo>& getKeyboardLayoutInfo() const {
+ return mKeyboardLayoutInfo;
+ }
+
inline void setKeyCharacterMap(const std::shared_ptr<KeyCharacterMap> value) {
mKeyCharacterMap = value;
}
@@ -296,6 +311,7 @@
bool mIsExternal;
bool mHasMic;
hardware::input::InputDeviceCountryCode mCountryCode;
+ std::optional<KeyboardLayoutInfo> mKeyboardLayoutInfo;
uint32_t mSources;
int32_t mKeyboardType;
std::shared_ptr<KeyCharacterMap> mKeyCharacterMap;
diff --git a/include/private/performance_hint_private.h b/include/private/performance_hint_private.h
index f27f5f1..eaf3b5e 100644
--- a/include/private/performance_hint_private.h
+++ b/include/private/performance_hint_private.h
@@ -24,6 +24,51 @@
*/
void APerformanceHint_setIHintManagerForTesting(void* iManager);
+/**
+ * Hints for the session used to signal upcoming changes in the mode or workload.
+ */
+enum SessionHint {
+ /**
+ * This hint indicates a sudden increase in CPU workload intensity. It means
+ * that this hint session needs extra CPU resources immediately to meet the
+ * target duration for the current work cycle.
+ */
+ CPU_LOAD_UP = 0,
+ /**
+ * This hint indicates a decrease in CPU workload intensity. It means that
+ * this hint session can reduce CPU resources and still meet the target duration.
+ */
+ CPU_LOAD_DOWN = 1,
+ /*
+ * This hint indicates an upcoming CPU workload that is completely changed and
+ * unknown. It means that the hint session should reset CPU resources to a known
+ * baseline to prepare for an arbitrary load, and must wake up if inactive.
+ */
+ CPU_LOAD_RESET = 2,
+ /*
+ * This hint indicates that the most recent CPU workload is resuming after a
+ * period of inactivity. It means that the hint session should allocate similar
+ * CPU resources to what was used previously, and must wake up if inactive.
+ */
+ CPU_LOAD_RESUME = 3,
+};
+
+/**
+ * Sends performance hints to inform the hint session of changes in the workload.
+ *
+ * @param session The performance hint session instance to update.
+ * @param hint The hint to send to the session.
+ * @return 0 on success
+ * EPIPE if communication with the system service has failed.
+ */
+int APerformanceHint_sendHint(void* session, int hint);
+
+/**
+ * Return the list of thread ids, this API should only be used for testing only.
+ */
+int APerformanceHint_getThreadIds(void* aPerformanceHintSession,
+ int32_t* const threadIds, size_t* const size);
+
__END_DECLS
#endif // ANDROID_PRIVATE_NATIVE_PERFORMANCE_HINT_PRIVATE_H
diff --git a/libs/binder/IPCThreadState.cpp b/libs/binder/IPCThreadState.cpp
index c0f3e30..6d64e1e 100644
--- a/libs/binder/IPCThreadState.cpp
+++ b/libs/binder/IPCThreadState.cpp
@@ -132,12 +132,21 @@
} else {
out << "\ttarget.ptr=" << btd->target.ptr;
}
- out << "\t (cookie " << btd->cookie << ")"
- << "\n"
+ out << "\t (cookie " << btd->cookie << ")\n"
<< "\tcode=" << TypeCode(btd->code) << ", flags=" << (void*)(uint64_t)btd->flags << "\n"
- << "\tdata=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size << " bytes)"
- << "\n"
- << "\toffsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size << " bytes)";
+ << "\tdata=" << btd->data.ptr.buffer << " (" << (void*)btd->data_size << " bytes)\n"
+ << "\toffsets=" << btd->data.ptr.offsets << " (" << (void*)btd->offsets_size << " bytes)\n";
+ return btd + 1;
+}
+
+static const void* printBinderTransactionDataSecCtx(std::ostream& out, const void* data) {
+ const binder_transaction_data_secctx* btd = (const binder_transaction_data_secctx*)data;
+
+ printBinderTransactionData(out, &btd->transaction_data);
+
+ char* secctx = (char*)btd->secctx;
+ out << "\tsecctx=" << secctx << "\n";
+
return btd+1;
}
@@ -156,6 +165,11 @@
out << "\t" << kReturnStrings[cmdIndex];
switch (code) {
+ case BR_TRANSACTION_SEC_CTX: {
+ out << ": ";
+ cmd = (const int32_t*)printBinderTransactionDataSecCtx(out, cmd);
+ } break;
+
case BR_TRANSACTION:
case BR_REPLY: {
out << ": ";
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index ee081c4..44ff62b 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -1475,7 +1475,7 @@
#ifdef BINDER_WITH_KERNEL_IPC
flat_binder_object obj;
obj.hdr.type = BINDER_TYPE_FD;
- obj.flags = 0x7f | FLAT_BINDER_FLAG_ACCEPTS_FDS;
+ obj.flags = 0;
obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
obj.handle = fd;
obj.cookie = takeOwnership ? 1 : 0;
diff --git a/libs/binder/RpcServer.cpp b/libs/binder/RpcServer.cpp
index 0820cd1..0d06e9e 100644
--- a/libs/binder/RpcServer.cpp
+++ b/libs/binder/RpcServer.cpp
@@ -50,7 +50,8 @@
RpcServer::RpcServer(std::unique_ptr<RpcTransportCtx> ctx) : mCtx(std::move(ctx)) {}
RpcServer::~RpcServer() {
- (void)shutdown();
+ RpcMutexUniqueLock _l(mLock);
+ LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Must call shutdown() before destructor");
}
sp<RpcServer> RpcServer::make(std::unique_ptr<RpcTransportCtxFactory> rpcTransportCtxFactory) {
@@ -70,11 +71,8 @@
return setupSocketServer(UnixSocketAddress(path));
}
-status_t RpcServer::setupVsockServer(unsigned int port) {
- // realizing value w/ this type at compile time to avoid ubsan abort
- constexpr unsigned int kAnyCid = VMADDR_CID_ANY;
-
- return setupSocketServer(VsockSocketAddress(kAnyCid, port));
+status_t RpcServer::setupVsockServer(unsigned int bindCid, unsigned int port) {
+ return setupSocketServer(VsockSocketAddress(bindCid, port));
}
status_t RpcServer::setupInetServer(const char* address, unsigned int port,
@@ -157,6 +155,12 @@
mRootObjectFactory = std::move(makeObject);
}
+void RpcServer::setConnectionFilter(std::function<bool(const void*, size_t)>&& filter) {
+ RpcMutexLockGuard _l(mLock);
+ LOG_ALWAYS_FATAL_IF(mShutdownTrigger != nullptr, "Already joined");
+ mConnectionFilter = std::move(filter);
+}
+
sp<IBinder> RpcServer::getRootObject() {
RpcMutexLockGuard _l(mLock);
bool hasWeak = mRootObjectWeak.unsafe_get();
@@ -200,11 +204,15 @@
iovec iov{&zero, sizeof(zero)};
std::vector<std::variant<base::unique_fd, base::borrowed_fd>> fds;
- if (receiveMessageFromSocket(server.mServer, &iov, 1, &fds) < 0) {
+ ssize_t num_bytes = receiveMessageFromSocket(server.mServer, &iov, 1, &fds);
+ if (num_bytes < 0) {
int savedErrno = errno;
ALOGE("Failed recvmsg: %s", strerror(savedErrno));
return -savedErrno;
}
+ if (num_bytes == 0) {
+ return DEAD_OBJECT;
+ }
if (fds.size() != 1) {
ALOGE("Expected exactly one fd from recvmsg, got %zu", fds.size());
return -EINVAL;
@@ -239,16 +247,25 @@
socklen_t addrLen = addr.size();
RpcTransportFd clientSocket;
- if (mAcceptFn(*this, &clientSocket) != OK) {
- continue;
+ if ((status = mAcceptFn(*this, &clientSocket)) != OK) {
+ if (status == DEAD_OBJECT)
+ break;
+ else
+ continue;
}
+
+ LOG_RPC_DETAIL("accept on fd %d yields fd %d", mServer.fd.get(), clientSocket.fd.get());
+
if (getpeername(clientSocket.fd.get(), reinterpret_cast<sockaddr*>(addr.data()),
&addrLen)) {
ALOGE("Could not getpeername socket: %s", strerror(errno));
continue;
}
- LOG_RPC_DETAIL("accept on fd %d yields fd %d", mServer.fd.get(), clientSocket.fd.get());
+ if (mConnectionFilter != nullptr && !mConnectionFilter(addr.data(), addrLen)) {
+ ALOGE("Dropped client connection fd %d", clientSocket.fd.get());
+ continue;
+ }
{
RpcMutexLockGuard _l(mLock);
diff --git a/libs/binder/RpcTransportTipcAndroid.cpp b/libs/binder/RpcTransportTipcAndroid.cpp
index 453279c..8b3ddfb 100644
--- a/libs/binder/RpcTransportTipcAndroid.cpp
+++ b/libs/binder/RpcTransportTipcAndroid.cpp
@@ -63,12 +63,14 @@
if (pfd.revents & POLLERR) {
return DEAD_OBJECT;
}
+ if (pfd.revents & POLLIN) {
+ // Copied from FdTrigger.cpp: Even though POLLHUP may also be set,
+ // treat it as a success condition to ensure data is drained.
+ return OK;
+ }
if (pfd.revents & POLLHUP) {
return DEAD_OBJECT;
}
- if (pfd.revents & POLLIN) {
- return OK;
- }
return WOULD_BLOCK;
}
diff --git a/libs/binder/include/binder/IServiceManager.h b/libs/binder/include/binder/IServiceManager.h
index 79e771f..2af512e 100644
--- a/libs/binder/include/binder/IServiceManager.h
+++ b/libs/binder/include/binder/IServiceManager.h
@@ -67,7 +67,8 @@
* a system property, or in the case of services in the VINTF manifest, it can be checked
* with isDeclared).
*/
- virtual sp<IBinder> getService( const String16& name) const = 0;
+ [[deprecated("this polls for 5s, prefer waitForService or checkService")]]
+ virtual sp<IBinder> getService(const String16& name) const = 0;
/**
* Retrieve an existing service, non-blocking.
diff --git a/libs/binder/include/binder/RpcServer.h b/libs/binder/include/binder/RpcServer.h
index 4ad0a47..25193a3 100644
--- a/libs/binder/include/binder/RpcServer.h
+++ b/libs/binder/include/binder/RpcServer.h
@@ -81,9 +81,9 @@
[[nodiscard]] status_t setupRawSocketServer(base::unique_fd socket_fd);
/**
- * Creates an RPC server at the current port.
+ * Creates an RPC server binding to the given CID at the given port.
*/
- [[nodiscard]] status_t setupVsockServer(unsigned int port);
+ [[nodiscard]] status_t setupVsockServer(unsigned int bindCid, unsigned int port);
/**
* Creates an RPC server at the current port using IPv4.
@@ -171,6 +171,16 @@
sp<IBinder> getRootObject();
/**
+ * Set optional filter of incoming connections based on the peer's address.
+ *
+ * Takes one argument: a callable that is invoked on each accept()-ed
+ * connection and returns false if the connection should be dropped.
+ * See the description of setPerSessionRootObject() for details about
+ * the callable's arguments.
+ */
+ void setConnectionFilter(std::function<bool(const void*, size_t)>&& filter);
+
+ /**
* See RpcTransportCtx::getCertificate
*/
std::vector<uint8_t> getCertificate(RpcCertificateFormat);
@@ -253,6 +263,7 @@
sp<IBinder> mRootObject;
wp<IBinder> mRootObjectWeak;
std::function<sp<IBinder>(const void*, size_t)> mRootObjectFactory;
+ std::function<bool(const void*, size_t)> mConnectionFilter;
std::map<std::vector<uint8_t>, sp<RpcSession>> mSessions;
std::unique_ptr<FdTrigger> mShutdownTrigger;
RpcConditionVariable mShutdownCv;
diff --git a/libs/binder/include_rpc_unstable/binder_rpc_unstable.hpp b/libs/binder/include_rpc_unstable/binder_rpc_unstable.hpp
index f08bde8..3ebbed6 100644
--- a/libs/binder/include_rpc_unstable/binder_rpc_unstable.hpp
+++ b/libs/binder/include_rpc_unstable/binder_rpc_unstable.hpp
@@ -23,11 +23,22 @@
struct AIBinder;
struct ARpcServer;
+struct ARpcSession;
+
+enum class ARpcSession_FileDescriptorTransportMode {
+ None,
+ Unix,
+ Trusty,
+};
// Starts an RPC server on a given port and a given root IBinder object.
+// The server will only accept connections from the given CID.
+// Set `cid` to VMADDR_CID_ANY to accept connections from any client.
+// Set `cid` to VMADDR_CID_LOCAL to only bind to the local vsock interface.
// Returns an opaque handle to the running server instance, or null if the server
// could not be started.
-[[nodiscard]] ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int port);
+[[nodiscard]] ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int cid,
+ unsigned int port);
// Starts a Unix domain RPC server with a given init-managed Unix domain `name`
// and a given root IBinder object.
@@ -36,6 +47,22 @@
// could not be started.
[[nodiscard]] ARpcServer* ARpcServer_newInitUnixDomain(AIBinder* service, const char* name);
+// Starts an RPC server that bootstraps sessions using an existing Unix domain
+// socket pair, with a given root IBinder object.
+// Callers should create a pair of SOCK_STREAM Unix domain sockets, pass one to
+// this function and the other to UnixDomainBootstrapClient(). Multiple client
+// session can be created from the client end of the pair.
+// Does not take ownership of `service`.
+// Returns an opaque handle to the running server instance, or null if the server
+// could not be started.
+[[nodiscard]] ARpcServer* ARpcServer_newUnixDomainBootstrap(AIBinder* service, int bootstrapFd);
+
+// Sets the list of supported file descriptor transport modes of this RPC server.
+void ARpcServer_setSupportedFileDescriptorTransportModes(
+ ARpcServer* handle,
+ const ARpcSession_FileDescriptorTransportMode modes[],
+ size_t modes_len);
+
// Runs ARpcServer_join() in a background thread. Immediately returns.
void ARpcServer_start(ARpcServer* server);
@@ -46,34 +73,52 @@
void ARpcServer_join(ARpcServer* server);
// Shuts down any running ARpcServer_join().
-void ARpcServer_shutdown(ARpcServer* server);
+[[nodiscard]] bool ARpcServer_shutdown(ARpcServer* server);
// Frees the ARpcServer handle and drops the reference count on the underlying
// RpcServer instance. The handle must not be reused afterwards.
// This automatically calls ARpcServer_shutdown().
void ARpcServer_free(ARpcServer* server);
-// Starts an RPC server on a given port and a given root IBinder factory.
-// RunVsockRpcServerWithFactory acts like RunVsockRpcServerCallback, but instead of
-// assigning single root IBinder object to all connections, factory is called
-// whenever a client connects, making it possible to assign unique IBinder
-// object to each client.
-bool RunVsockRpcServerWithFactory(AIBinder* (*factory)(unsigned int cid, void* context),
- void* factoryContext, unsigned int port);
+// Allocates a new RpcSession object and returns an opaque handle to it.
+[[nodiscard]] ARpcSession* ARpcSession_new();
-AIBinder* VsockRpcClient(unsigned int cid, unsigned int port);
+// Connects to an RPC server over vsock at a given CID on a given port.
+// Returns the root Binder object of the server.
+AIBinder* ARpcSession_setupVsockClient(ARpcSession* session, unsigned int cid,
+ unsigned int port);
-// Gets the service via the RPC binder with Unix domain socket with the given
-// Unix socket `name`.
-// The final Unix domain socket path name is /dev/socket/`name`.
-AIBinder* UnixDomainRpcClient(const char* name);
+// Connects to an RPC server over a Unix Domain Socket of the given name.
+// The final Unix Domain Socket path name is /dev/socket/`name`.
+// Returns the root Binder object of the server.
+AIBinder* ARpcSession_setupUnixDomainClient(ARpcSession* session, const char* name);
-// Connect to an RPC server with preconnected file descriptors.
+// Connects to an RPC server over the given bootstrap Unix domain socket.
+// Does NOT take ownership of `bootstrapFd`.
+AIBinder* ARpcSession_setupUnixDomainBootstrapClient(ARpcSession* session,
+ int bootstrapFd);
+
+// Connects to an RPC server with preconnected file descriptors.
//
// requestFd should connect to the server and return a valid file descriptor, or
// -1 if connection fails.
//
// param will be passed to requestFd. Callers can use param to pass contexts to
// the requestFd function.
-AIBinder* RpcPreconnectedClient(int (*requestFd)(void* param), void* param);
+AIBinder* ARpcSession_setupPreconnectedClient(ARpcSession* session,
+ int (*requestFd)(void* param),
+ void* param);
+
+// Sets the file descriptor transport mode for this session.
+void ARpcSession_setFileDescriptorTransportMode(ARpcSession* session,
+ ARpcSession_FileDescriptorTransportMode mode);
+
+// Sets the maximum number of incoming threads.
+void ARpcSession_setMaxIncomingThreads(ARpcSession* session, size_t threads);
+
+// Sets the maximum number of outgoing threads.
+void ARpcSession_setMaxOutgoingThreads(ARpcSession* session, size_t threads);
+
+// Decrements the refcount of the underlying RpcSession object.
+void ARpcSession_free(ARpcSession* session);
}
diff --git a/libs/binder/libbinder_rpc_unstable.cpp b/libs/binder/libbinder_rpc_unstable.cpp
index f55c779..78dae4b 100644
--- a/libs/binder/libbinder_rpc_unstable.cpp
+++ b/libs/binder/libbinder_rpc_unstable.cpp
@@ -35,55 +35,74 @@
// Opaque handle for RpcServer.
struct ARpcServer {};
-static sp<RpcServer> toRpcServer(ARpcServer* handle) {
- auto ref = reinterpret_cast<RpcServer*>(handle);
- return sp<RpcServer>::fromExisting(ref);
-}
+// Opaque handle for RpcSession.
+struct ARpcSession {};
-static ARpcServer* createRpcServerHandle(sp<RpcServer>& server) {
+template <typename A, typename T>
+static A* createObjectHandle(sp<T>& server) {
auto ref = server.get();
ref->incStrong(ref);
- return reinterpret_cast<ARpcServer*>(ref);
+ return reinterpret_cast<A*>(ref);
}
-static void freeRpcServerHandle(ARpcServer* handle) {
- auto ref = reinterpret_cast<RpcServer*>(handle);
+template <typename T, typename A>
+static void freeObjectHandle(A* handle) {
+ LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
+ auto ref = reinterpret_cast<T*>(handle);
ref->decStrong(ref);
}
+template <typename T, typename A>
+static sp<T> handleToStrongPointer(A* handle) {
+ LOG_ALWAYS_FATAL_IF(handle == nullptr, "Handle cannot be null");
+ auto ref = reinterpret_cast<T*>(handle);
+ return sp<T>::fromExisting(ref);
+}
+
+RpcSession::FileDescriptorTransportMode toTransportMode(
+ ARpcSession_FileDescriptorTransportMode mode) {
+ switch (mode) {
+ case ARpcSession_FileDescriptorTransportMode::None:
+ return RpcSession::FileDescriptorTransportMode::NONE;
+ case ARpcSession_FileDescriptorTransportMode::Unix:
+ return RpcSession::FileDescriptorTransportMode::UNIX;
+ case ARpcSession_FileDescriptorTransportMode::Trusty:
+ return RpcSession::FileDescriptorTransportMode::TRUSTY;
+ default:
+ return RpcSession::FileDescriptorTransportMode::NONE;
+ }
+}
+
extern "C" {
-bool RunVsockRpcServerWithFactory(AIBinder* (*factory)(unsigned int cid, void* context),
- void* factoryContext, unsigned int port) {
+ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int cid, unsigned int port) {
auto server = RpcServer::make();
- if (status_t status = server->setupVsockServer(port); status != OK) {
- LOG(ERROR) << "Failed to set up vsock server with port " << port
- << " error: " << statusToString(status).c_str();
- return false;
+
+ unsigned int bindCid = VMADDR_CID_ANY; // bind to the remote interface
+ if (cid == VMADDR_CID_LOCAL) {
+ bindCid = VMADDR_CID_LOCAL; // bind to the local interface
+ cid = VMADDR_CID_ANY; // no need for a connection filter
}
- server->setPerSessionRootObject([=](const void* addr, size_t addrlen) {
- LOG_ALWAYS_FATAL_IF(addrlen < sizeof(sockaddr_vm), "sockaddr is truncated");
- const sockaddr_vm* vaddr = reinterpret_cast<const sockaddr_vm*>(addr);
- LOG_ALWAYS_FATAL_IF(vaddr->svm_family != AF_VSOCK, "address is not a vsock");
- return AIBinder_toPlatformBinder(factory(vaddr->svm_cid, factoryContext));
- });
- server->join();
-
- // Shutdown any open sessions since server failed.
- (void)server->shutdown();
- return true;
-}
-
-ARpcServer* ARpcServer_newVsock(AIBinder* service, unsigned int port) {
- auto server = RpcServer::make();
- if (status_t status = server->setupVsockServer(port); status != OK) {
+ if (status_t status = server->setupVsockServer(bindCid, port); status != OK) {
LOG(ERROR) << "Failed to set up vsock server with port " << port
<< " error: " << statusToString(status).c_str();
return nullptr;
}
+ if (cid != VMADDR_CID_ANY) {
+ server->setConnectionFilter([=](const void* addr, size_t addrlen) {
+ LOG_ALWAYS_FATAL_IF(addrlen < sizeof(sockaddr_vm), "sockaddr is truncated");
+ const sockaddr_vm* vaddr = reinterpret_cast<const sockaddr_vm*>(addr);
+ LOG_ALWAYS_FATAL_IF(vaddr->svm_family != AF_VSOCK, "address is not a vsock");
+ if (cid != vaddr->svm_cid) {
+ LOG(ERROR) << "Rejected vsock connection from CID " << vaddr->svm_cid;
+ return false;
+ }
+ return true;
+ });
+ }
server->setRootObject(AIBinder_toPlatformBinder(service));
- return createRpcServerHandle(server);
+ return createObjectHandle<ARpcServer>(server);
}
ARpcServer* ARpcServer_newInitUnixDomain(AIBinder* service, const char* name) {
@@ -99,27 +118,67 @@
return nullptr;
}
server->setRootObject(AIBinder_toPlatformBinder(service));
- return createRpcServerHandle(server);
+ return createObjectHandle<ARpcServer>(server);
+}
+
+ARpcServer* ARpcServer_newUnixDomainBootstrap(AIBinder* service, int bootstrapFd) {
+ auto server = RpcServer::make();
+ auto fd = unique_fd(bootstrapFd);
+ if (!fd.ok()) {
+ LOG(ERROR) << "Invalid bootstrap fd " << bootstrapFd;
+ return nullptr;
+ }
+ if (status_t status = server->setupUnixDomainSocketBootstrapServer(std::move(fd));
+ status != OK) {
+ LOG(ERROR) << "Failed to set up Unix Domain RPC server with bootstrap fd " << bootstrapFd
+ << " error: " << statusToString(status).c_str();
+ return nullptr;
+ }
+ server->setRootObject(AIBinder_toPlatformBinder(service));
+ return createObjectHandle<ARpcServer>(server);
+}
+
+void ARpcServer_setSupportedFileDescriptorTransportModes(
+ ARpcServer* handle, const ARpcSession_FileDescriptorTransportMode modes[],
+ size_t modes_len) {
+ auto server = handleToStrongPointer<RpcServer>(handle);
+ std::vector<RpcSession::FileDescriptorTransportMode> modevec;
+ for (size_t i = 0; i < modes_len; i++) {
+ modevec.push_back(toTransportMode(modes[i]));
+ }
+ server->setSupportedFileDescriptorTransportModes(modevec);
}
void ARpcServer_start(ARpcServer* handle) {
- toRpcServer(handle)->start();
+ handleToStrongPointer<RpcServer>(handle)->start();
}
void ARpcServer_join(ARpcServer* handle) {
- toRpcServer(handle)->join();
+ handleToStrongPointer<RpcServer>(handle)->join();
}
-void ARpcServer_shutdown(ARpcServer* handle) {
- toRpcServer(handle)->shutdown();
+bool ARpcServer_shutdown(ARpcServer* handle) {
+ return handleToStrongPointer<RpcServer>(handle)->shutdown();
}
void ARpcServer_free(ARpcServer* handle) {
- freeRpcServerHandle(handle);
+ // Ignore the result of ARpcServer_shutdown - either it had been called
+ // earlier, or the RpcServer destructor will panic.
+ (void)ARpcServer_shutdown(handle);
+ freeObjectHandle<RpcServer>(handle);
}
-AIBinder* VsockRpcClient(unsigned int cid, unsigned int port) {
+ARpcSession* ARpcSession_new() {
auto session = RpcSession::make();
+ return createObjectHandle<ARpcSession>(session);
+}
+
+void ARpcSession_free(ARpcSession* handle) {
+ freeObjectHandle<RpcSession>(handle);
+}
+
+AIBinder* ARpcSession_setupVsockClient(ARpcSession* handle, unsigned int cid, unsigned int port) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
if (status_t status = session->setupVsockClient(cid, port); status != OK) {
LOG(ERROR) << "Failed to set up vsock client with CID " << cid << " and port " << port
<< " error: " << statusToString(status).c_str();
@@ -128,10 +187,10 @@
return AIBinder_fromPlatformBinder(session->getRootObject());
}
-AIBinder* UnixDomainRpcClient(const char* name) {
+AIBinder* ARpcSession_setupUnixDomainClient(ARpcSession* handle, const char* name) {
std::string pathname(name);
pathname = ANDROID_SOCKET_DIR "/" + pathname;
- auto session = RpcSession::make();
+ auto session = handleToStrongPointer<RpcSession>(handle);
if (status_t status = session->setupUnixDomainClient(pathname.c_str()); status != OK) {
LOG(ERROR) << "Failed to set up Unix Domain RPC client with path: " << pathname
<< " error: " << statusToString(status).c_str();
@@ -140,8 +199,25 @@
return AIBinder_fromPlatformBinder(session->getRootObject());
}
-AIBinder* RpcPreconnectedClient(int (*requestFd)(void* param), void* param) {
- auto session = RpcSession::make();
+AIBinder* ARpcSession_setupUnixDomainBootstrapClient(ARpcSession* handle, int bootstrapFd) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
+ auto fd = unique_fd(dup(bootstrapFd));
+ if (!fd.ok()) {
+ LOG(ERROR) << "Invalid bootstrap fd " << bootstrapFd;
+ return nullptr;
+ }
+ if (status_t status = session->setupUnixDomainSocketBootstrapClient(std::move(fd));
+ status != OK) {
+ LOG(ERROR) << "Failed to set up Unix Domain RPC client with bootstrap fd: " << bootstrapFd
+ << " error: " << statusToString(status).c_str();
+ return nullptr;
+ }
+ return AIBinder_fromPlatformBinder(session->getRootObject());
+}
+
+AIBinder* ARpcSession_setupPreconnectedClient(ARpcSession* handle, int (*requestFd)(void* param),
+ void* param) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
auto request = [=] { return unique_fd{requestFd(param)}; };
if (status_t status = session->setupPreconnectedClient(unique_fd{}, request); status != OK) {
LOG(ERROR) << "Failed to set up vsock client. error: " << statusToString(status).c_str();
@@ -149,4 +225,20 @@
}
return AIBinder_fromPlatformBinder(session->getRootObject());
}
+
+void ARpcSession_setFileDescriptorTransportMode(ARpcSession* handle,
+ ARpcSession_FileDescriptorTransportMode mode) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
+ session->setFileDescriptorTransportMode(toTransportMode(mode));
+}
+
+void ARpcSession_setMaxIncomingThreads(ARpcSession* handle, size_t threads) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
+ session->setMaxIncomingThreads(threads);
+}
+
+void ARpcSession_setMaxOutgoingThreads(ARpcSession* handle, size_t threads) {
+ auto session = handleToStrongPointer<RpcSession>(handle);
+ session->setMaxOutgoingThreads(threads);
+}
}
diff --git a/libs/binder/ndk/ibinder.cpp b/libs/binder/ndk/ibinder.cpp
index 28d1f16..d0de7b9 100644
--- a/libs/binder/ndk/ibinder.cpp
+++ b/libs/binder/ndk/ibinder.cpp
@@ -75,12 +75,48 @@
AIBinder::AIBinder(const AIBinder_Class* clazz) : mClazz(clazz) {}
AIBinder::~AIBinder() {}
-std::optional<bool> AIBinder::associateClassInternal(const AIBinder_Class* clazz,
- const String16& newDescriptor, bool set) {
+// b/175635923 libcxx causes "implicit-conversion" with a string with invalid char
+static std::string SanitizeString(const String16& str) {
+ std::string sanitized{String8(str)};
+ for (auto& c : sanitized) {
+ if (!isprint(c)) {
+ c = '?';
+ }
+ }
+ return sanitized;
+}
+
+bool AIBinder::associateClass(const AIBinder_Class* clazz) {
+ if (clazz == nullptr) return false;
+
+ // If mClazz is non-null, this must have been called and cached
+ // already. So, we can safely call this first. Due to the implementation
+ // of getInterfaceDescriptor (at time of writing), two simultaneous calls
+ // may lead to extra binder transactions, but this is expected to be
+ // exceedingly rare. Once we have a binder, when we get it again later,
+ // we won't make another binder transaction here.
+ const String16& descriptor = getBinder()->getInterfaceDescriptor();
+ const String16& newDescriptor = clazz->getInterfaceDescriptor();
+
std::lock_guard<std::mutex> lock(mClazzMutex);
if (mClazz == clazz) return true;
- if (mClazz != nullptr) {
+ // If this is an ABpBinder, the first class object becomes the canonical one. The implication
+ // of this is that no API can require a proxy information to get information on how to behave.
+ // from the class itself - which should only store the interface descriptor. The functionality
+ // should be implemented by adding AIBinder_* APIs to set values on binders themselves, by
+ // setting things on AIBinder_Class which get transferred along with the binder, so that they
+ // can be read along with the BpBinder, or by modifying APIs directly (e.g. an option in
+ // onTransact).
+ //
+ // While this check is required to support linkernamespaces, one downside of it is that
+ // you may parcel code to communicate between things in the same process. However, comms
+ // between linkernamespaces like this already happen for cross-language calls like Java<->C++
+ // or Rust<->Java, and there are good stability guarantees here. This interacts with
+ // binder Stability checks exactly like any other in-process call. The stability is known
+ // to the IBinder object, so that it doesn't matter if a class object comes from
+ // a different stability level.
+ if (mClazz != nullptr && !asABpBinder()) {
const String16& currentDescriptor = mClazz->getInterfaceDescriptor();
if (newDescriptor == currentDescriptor) {
LOG(ERROR) << __func__ << ": Class descriptors '" << currentDescriptor
@@ -97,37 +133,10 @@
return false;
}
- if (set) {
- // if this is a local object, it's not one known to libbinder_ndk
- mClazz = clazz;
- return true;
- }
-
- return {};
-}
-
-// b/175635923 libcxx causes "implicit-conversion" with a string with invalid char
-static std::string SanitizeString(const String16& str) {
- std::string sanitized{String8(str)};
- for (auto& c : sanitized) {
- if (!isprint(c)) {
- c = '?';
- }
- }
- return sanitized;
-}
-
-bool AIBinder::associateClass(const AIBinder_Class* clazz) {
- if (clazz == nullptr) return false;
-
- const String16& newDescriptor = clazz->getInterfaceDescriptor();
-
- auto result = associateClassInternal(clazz, newDescriptor, false);
- if (result.has_value()) return *result;
-
- CHECK(asABpBinder() != nullptr); // ABBinder always has a descriptor
-
- const String16& descriptor = getBinder()->getInterfaceDescriptor();
+ // This will always be an O(n) comparison, but it's expected to be extremely rare.
+ // since it's an error condition. Do the comparison after we take the lock and
+ // check the pointer equality fast path. By always taking the lock, it's also
+ // more flake-proof. However, the check is not dependent on the lock.
if (descriptor != newDescriptor) {
if (getBinder()->isBinderAlive()) {
LOG(ERROR) << __func__ << ": Expecting binder to have class '" << newDescriptor
@@ -141,7 +150,14 @@
return false;
}
- return associateClassInternal(clazz, newDescriptor, true).value();
+ // A local binder being set for the first time OR
+ // ignoring a proxy binder which is set multiple time, by considering the first
+ // associated class as the canonical one.
+ if (mClazz == nullptr) {
+ mClazz = clazz;
+ }
+
+ return true;
}
ABBinder::ABBinder(const AIBinder_Class* clazz, void* userData)
@@ -325,6 +341,10 @@
return lhs->binder < rhs->binder;
}
+// WARNING: When multiple classes exist with the same interface descriptor in different
+// linkernamespaces, the first one to be associated with mClazz becomes the canonical one
+// and the only requirement on this is that the interface descriptors match. If this
+// is an ABpBinder, no other state can be referenced from mClazz.
AIBinder_Class::AIBinder_Class(const char* interfaceDescriptor, AIBinder_Class_onCreate onCreate,
AIBinder_Class_onDestroy onDestroy,
AIBinder_Class_onTransact onTransact)
@@ -632,6 +652,10 @@
(*in)->get()->markForBinder(binder->getBinder());
status_t status = android::OK;
+
+ // note - this is the only read of a value in clazz, and it comes with a warning
+ // on the API itself. Do not copy this design. Instead, attach data in a new
+ // version of the prepareTransaction function.
if (clazz->writeHeader) {
status = (*in)->get()->writeInterfaceToken(clazz->getInterfaceDescriptor());
}
diff --git a/libs/binder/ndk/ibinder_internal.h b/libs/binder/ndk/ibinder_internal.h
index d7098e8..67bb092 100644
--- a/libs/binder/ndk/ibinder_internal.h
+++ b/libs/binder/ndk/ibinder_internal.h
@@ -53,12 +53,14 @@
}
private:
- std::optional<bool> associateClassInternal(const AIBinder_Class* clazz,
- const ::android::String16& newDescriptor, bool set);
-
// AIBinder instance is instance of this class for a local object. In order to transact on a
// remote object, this also must be set for simplicity (although right now, only the
// interfaceDescriptor from it is used).
+ //
+ // WARNING: When multiple classes exist with the same interface descriptor in different
+ // linkernamespaces, the first one to be associated with mClazz becomes the canonical one
+ // and the only requirement on this is that the interface descriptors match. If this
+ // is an ABpBinder, no other state can be referenced from mClazz.
const AIBinder_Class* mClazz;
std::mutex mClazzMutex;
};
diff --git a/libs/binder/ndk/include_ndk/android/binder_ibinder.h b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
index 1af2119..05677a8 100644
--- a/libs/binder/ndk/include_ndk/android/binder_ibinder.h
+++ b/libs/binder/ndk/include_ndk/android/binder_ibinder.h
@@ -229,6 +229,11 @@
*
* Available since API level 33.
*
+ * WARNING: this API interacts badly with linkernamespaces. For correct behavior, you must
+ * use it on all instances of a class in the same process which share the same interface
+ * descriptor. In general, it is recommended you do not use this API, because it is disabling
+ * type safety.
+ *
* \param clazz class to disable interface header on.
*/
void AIBinder_Class_disableInterfaceTokenHeader(AIBinder_Class* clazz) __INTRODUCED_IN(33);
diff --git a/libs/binder/ndk/tests/iface.cpp b/libs/binder/ndk/tests/iface.cpp
index 2afe5d2..76acff5 100644
--- a/libs/binder/ndk/tests/iface.cpp
+++ b/libs/binder/ndk/tests/iface.cpp
@@ -72,6 +72,11 @@
AIBinder_Class* IFoo::kClass = AIBinder_Class_define(kIFooDescriptor, IFoo_Class_onCreate,
IFoo_Class_onDestroy, IFoo_Class_onTransact);
+// Defines the same class. Ordinarly, you would never want to do this, but it's done here
+// to simulate what would happen when multiple linker namespaces interact.
+AIBinder_Class* IFoo::kClassDupe = AIBinder_Class_define(
+ kIFooDescriptor, IFoo_Class_onCreate, IFoo_Class_onDestroy, IFoo_Class_onTransact);
+
class BpFoo : public IFoo {
public:
explicit BpFoo(AIBinder* binder) : mBinder(binder) {}
diff --git a/libs/binder/ndk/tests/include/iface/iface.h b/libs/binder/ndk/tests/include/iface/iface.h
index 7408d0c..0a562f0 100644
--- a/libs/binder/ndk/tests/include/iface/iface.h
+++ b/libs/binder/ndk/tests/include/iface/iface.h
@@ -30,8 +30,13 @@
static const char* kIFooDescriptor;
static AIBinder_Class* kClass;
+ static AIBinder_Class* kClassDupe;
// binder representing this interface with one reference count
+ // NOTE - this will create a new binder if it already exists. If you use
+ // getService for instance, you must pull outBinder. Don't use this without
+ // verifying isRemote or pointer equality. This is not a very good testing API - don't
+ // copy it - consider the AIDL-generated APIs instead.
AIBinder* getBinder();
// Takes ownership of IFoo
diff --git a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
index 9d5ef68..5b2532a 100644
--- a/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
+++ b/libs/binder/ndk/tests/libbinder_ndk_unit_test.cpp
@@ -55,6 +55,18 @@
constexpr unsigned int kShutdownWaitTime = 10;
constexpr uint64_t kContextTestValue = 0xb4e42fb4d9a1d715;
+class MyTestFoo : public IFoo {
+ binder_status_t doubleNumber(int32_t in, int32_t* out) override {
+ *out = 2 * in;
+ LOG(INFO) << "doubleNumber (" << in << ") => " << *out;
+ return STATUS_OK;
+ }
+ binder_status_t die() override {
+ ADD_FAILURE() << "die called on local instance";
+ return STATUS_OK;
+ }
+};
+
class MyBinderNdkUnitTest : public aidl::BnBinderNdkUnitTest {
ndk::ScopedAStatus repeatInt(int32_t in, int32_t* out) {
*out = in;
@@ -296,11 +308,10 @@
}
TEST(NdkBinder, UnimplementedDump) {
- sp<IFoo> foo = IFoo::getService(IFoo::kSomeInstanceName);
+ ndk::SpAIBinder binder;
+ sp<IFoo> foo = IFoo::getService(IFoo::kSomeInstanceName, binder.getR());
ASSERT_NE(foo, nullptr);
- AIBinder* binder = foo->getBinder();
- EXPECT_EQ(OK, AIBinder_dump(binder, STDOUT_FILENO, nullptr, 0));
- AIBinder_decStrong(binder);
+ EXPECT_EQ(OK, AIBinder_dump(binder.get(), STDOUT_FILENO, nullptr, 0));
}
TEST(NdkBinder, UnimplementedShell) {
@@ -324,6 +335,24 @@
EXPECT_EQ(2, out);
}
+TEST(NdkBinder, ReassociateBpBinderWithSameDescriptor) {
+ ndk::SpAIBinder binder;
+ sp<IFoo> foo = IFoo::getService(IFoo::kSomeInstanceName, binder.getR());
+
+ EXPECT_TRUE(AIBinder_isRemote(binder.get()));
+
+ EXPECT_TRUE(AIBinder_associateClass(binder.get(), IFoo::kClassDupe));
+}
+
+TEST(NdkBinder, CantHaveTwoLocalBinderClassesWithSameDescriptor) {
+ sp<IFoo> foo = sp<MyTestFoo>::make();
+ ndk::SpAIBinder binder(foo->getBinder());
+
+ EXPECT_FALSE(AIBinder_isRemote(binder.get()));
+
+ EXPECT_FALSE(AIBinder_associateClass(binder.get(), IFoo::kClassDupe));
+}
+
TEST(NdkBinder, GetTestServiceStressTest) {
// libbinder has some complicated logic to make sure only one instance of
// ABpBinder is associated with each binder.
@@ -545,18 +574,6 @@
AIBinder_decStrong(binder);
}
-class MyTestFoo : public IFoo {
- binder_status_t doubleNumber(int32_t in, int32_t* out) override {
- *out = 2 * in;
- LOG(INFO) << "doubleNumber (" << in << ") => " << *out;
- return STATUS_OK;
- }
- binder_status_t die() override {
- ADD_FAILURE() << "die called on local instance";
- return STATUS_OK;
- }
-};
-
TEST(NdkBinder, SetInheritRt) {
// functional test in binderLibTest
sp<IFoo> foo = sp<MyTestFoo>::make();
@@ -597,7 +614,8 @@
sp<IFoo> foo = new MyTestFoo;
EXPECT_EQ(EX_NONE, foo->addService(kInstanceName));
- sp<IFoo> getFoo = IFoo::getService(kInstanceName);
+ ndk::SpAIBinder binder;
+ sp<IFoo> getFoo = IFoo::getService(kInstanceName, binder.getR());
EXPECT_EQ(foo.get(), getFoo.get());
int32_t out;
diff --git a/libs/binder/rust/rpcbinder/Android.bp b/libs/binder/rust/rpcbinder/Android.bp
index f70ebfc..afb73e9 100644
--- a/libs/binder/rust/rpcbinder/Android.bp
+++ b/libs/binder/rust/rpcbinder/Android.bp
@@ -68,10 +68,13 @@
visibility: [":__subpackages__"],
source_stem: "bindings",
bindgen_flags: [
+ "--size_t-is-usize",
"--blocklist-type",
"AIBinder",
"--raw-line",
"use binder_ndk_sys::AIBinder;",
+ "--rustified-enum",
+ "ARpcSession_FileDescriptorTransportMode",
],
rustlibs: [
"libbinder_ndk_sys",
diff --git a/libs/binder/rust/rpcbinder/src/client.rs b/libs/binder/rust/rpcbinder/src/client.rs
deleted file mode 100644
index 48c787b..0000000
--- a/libs/binder/rust/rpcbinder/src/client.rs
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * 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.
- */
-
-use binder::{unstable_api::new_spibinder, FromIBinder, SpIBinder, StatusCode, Strong};
-use std::ffi::CString;
-use std::os::{
- raw::{c_int, c_void},
- unix::io::RawFd,
-};
-
-/// Connects to an RPC Binder server over vsock.
-pub fn get_vsock_rpc_service(cid: u32, port: u32) -> Option<SpIBinder> {
- // SAFETY: AIBinder returned by VsockRpcClient has correct reference count,
- // and the ownership can safely be taken by new_spibinder.
- unsafe { new_spibinder(binder_rpc_unstable_bindgen::VsockRpcClient(cid, port)) }
-}
-
-/// Connects to an RPC Binder server for a particular interface over vsock.
-pub fn get_vsock_rpc_interface<T: FromIBinder + ?Sized>(
- cid: u32,
- port: u32,
-) -> Result<Strong<T>, StatusCode> {
- interface_cast(get_vsock_rpc_service(cid, port))
-}
-
-/// Connects to an RPC Binder server over Unix domain socket.
-pub fn get_unix_domain_rpc_service(socket_name: &str) -> Option<SpIBinder> {
- let socket_name = match CString::new(socket_name) {
- Ok(s) => s,
- Err(e) => {
- log::error!("Cannot convert {} to CString. Error: {:?}", socket_name, e);
- return None;
- }
- };
- // SAFETY: AIBinder returned by UnixDomainRpcClient has correct reference count,
- // and the ownership can safely be taken by new_spibinder.
- unsafe { new_spibinder(binder_rpc_unstable_bindgen::UnixDomainRpcClient(socket_name.as_ptr())) }
-}
-
-/// Connects to an RPC Binder server for a particular interface over Unix domain socket.
-pub fn get_unix_domain_rpc_interface<T: FromIBinder + ?Sized>(
- socket_name: &str,
-) -> Result<Strong<T>, StatusCode> {
- interface_cast(get_unix_domain_rpc_service(socket_name))
-}
-
-/// Connects to an RPC Binder server, using the given callback to get (and take ownership of)
-/// file descriptors already connected to it.
-pub fn get_preconnected_rpc_service(
- mut request_fd: impl FnMut() -> Option<RawFd>,
-) -> Option<SpIBinder> {
- // Double reference the factory because trait objects aren't FFI safe.
- let mut request_fd_ref: RequestFd = &mut request_fd;
- let param = &mut request_fd_ref as *mut RequestFd as *mut c_void;
-
- // SAFETY: AIBinder returned by RpcPreconnectedClient has correct reference count, and the
- // ownership can be safely taken by new_spibinder. RpcPreconnectedClient does not take ownership
- // of param, only passing it to request_fd_wrapper.
- unsafe {
- new_spibinder(binder_rpc_unstable_bindgen::RpcPreconnectedClient(
- Some(request_fd_wrapper),
- param,
- ))
- }
-}
-
-type RequestFd<'a> = &'a mut dyn FnMut() -> Option<RawFd>;
-
-unsafe extern "C" fn request_fd_wrapper(param: *mut c_void) -> c_int {
- // SAFETY: This is only ever called by RpcPreconnectedClient, within the lifetime of the
- // BinderFdFactory reference, with param being a properly aligned non-null pointer to an
- // initialized instance.
- let request_fd_ptr = param as *mut RequestFd;
- let request_fd = request_fd_ptr.as_mut().unwrap();
- if let Some(fd) = request_fd() {
- fd
- } else {
- -1
- }
-}
-
-/// Connects to an RPC Binder server for a particular interface, using the given callback to get
-/// (and take ownership of) file descriptors already connected to it.
-pub fn get_preconnected_rpc_interface<T: FromIBinder + ?Sized>(
- request_fd: impl FnMut() -> Option<RawFd>,
-) -> Result<Strong<T>, StatusCode> {
- interface_cast(get_preconnected_rpc_service(request_fd))
-}
-
-fn interface_cast<T: FromIBinder + ?Sized>(
- service: Option<SpIBinder>,
-) -> Result<Strong<T>, StatusCode> {
- if let Some(service) = service {
- FromIBinder::try_from(service)
- } else {
- Err(StatusCode::NAME_NOT_FOUND)
- }
-}
diff --git a/libs/binder/rust/rpcbinder/src/lib.rs b/libs/binder/rust/rpcbinder/src/lib.rs
index 1b719aa..a957385 100644
--- a/libs/binder/rust/rpcbinder/src/lib.rs
+++ b/libs/binder/rust/rpcbinder/src/lib.rs
@@ -16,11 +16,8 @@
//! API for RPC Binder services.
-mod client;
mod server;
+mod session;
-pub use client::{
- get_preconnected_rpc_interface, get_preconnected_rpc_service, get_unix_domain_rpc_interface,
- get_unix_domain_rpc_service, get_vsock_rpc_interface, get_vsock_rpc_service,
-};
-pub use server::{run_vsock_rpc_server_with_factory, RpcServer, RpcServerRef};
+pub use server::{RpcServer, RpcServerRef};
+pub use session::{FileDescriptorTransportMode, RpcSession, RpcSessionRef};
diff --git a/libs/binder/rust/rpcbinder/src/server.rs b/libs/binder/rust/rpcbinder/src/server.rs
index 42f5567..761b306 100644
--- a/libs/binder/rust/rpcbinder/src/server.rs
+++ b/libs/binder/rust/rpcbinder/src/server.rs
@@ -14,14 +14,13 @@
* limitations under the License.
*/
-use binder::{
- unstable_api::{AIBinder, AsNative},
- SpIBinder,
-};
+use crate::session::FileDescriptorTransportMode;
+use binder::{unstable_api::AsNative, SpIBinder};
use binder_rpc_unstable_bindgen::ARpcServer;
use foreign_types::{foreign_type, ForeignType, ForeignTypeRef};
+use std::ffi::CString;
use std::io::{Error, ErrorKind};
-use std::{ffi::CString, os::raw, ptr::null_mut};
+use std::os::unix::io::{IntoRawFd, OwnedFd};
foreign_type! {
type CType = binder_rpc_unstable_bindgen::ARpcServer;
@@ -41,14 +40,19 @@
impl RpcServer {
/// Creates a binder RPC server, serving the supplied binder service implementation on the given
- /// vsock port.
- pub fn new_vsock(mut service: SpIBinder, port: u32) -> Result<RpcServer, Error> {
+ /// vsock port. Only connections from the given CID are accepted.
+ ///
+ // Set `cid` to libc::VMADDR_CID_ANY to accept connections from any client.
+ // Set `cid` to libc::VMADDR_CID_LOCAL to only bind to the local vsock interface.
+ pub fn new_vsock(mut service: SpIBinder, cid: u32, port: u32) -> Result<RpcServer, Error> {
let service = service.as_native_mut();
// SAFETY: Service ownership is transferring to the server and won't be valid afterward.
// Plus the binder objects are threadsafe.
unsafe {
- Self::checked_from_ptr(binder_rpc_unstable_bindgen::ARpcServer_newVsock(service, port))
+ Self::checked_from_ptr(binder_rpc_unstable_bindgen::ARpcServer_newVsock(
+ service, cid, port,
+ ))
}
}
@@ -77,6 +81,27 @@
}
}
+ /// Creates a binder RPC server that bootstraps sessions using an existing Unix domain socket
+ /// pair, with a given root IBinder object. Callers should create a pair of SOCK_STREAM Unix
+ /// domain sockets, pass one to the server and the other to the client. Multiple client session
+ /// can be created from the client end of the pair.
+ pub fn new_unix_domain_bootstrap(
+ mut service: SpIBinder,
+ bootstrap_fd: OwnedFd,
+ ) -> Result<RpcServer, Error> {
+ let service = service.as_native_mut();
+
+ // SAFETY: Service ownership is transferring to the server and won't be valid afterward.
+ // Plus the binder objects are threadsafe.
+ // The server takes ownership of the bootstrap FD.
+ unsafe {
+ Self::checked_from_ptr(binder_rpc_unstable_bindgen::ARpcServer_newUnixDomainBootstrap(
+ service,
+ bootstrap_fd.into_raw_fd(),
+ ))
+ }
+ }
+
unsafe fn checked_from_ptr(ptr: *mut ARpcServer) -> Result<RpcServer, Error> {
if ptr.is_null() {
return Err(Error::new(ErrorKind::Other, "Failed to start server"));
@@ -86,6 +111,22 @@
}
impl RpcServerRef {
+ /// Sets the list of file descriptor transport modes supported by this server.
+ pub fn set_supported_file_descriptor_transport_modes(
+ &self,
+ modes: &[FileDescriptorTransportMode],
+ ) {
+ // SAFETY - Does not keep the pointer after returning does, nor does it
+ // read past its boundary. Only passes the 'self' pointer as an opaque handle.
+ unsafe {
+ binder_rpc_unstable_bindgen::ARpcServer_setSupportedFileDescriptorTransportModes(
+ self.as_ptr(),
+ modes.as_ptr(),
+ modes.len(),
+ )
+ }
+ }
+
/// Starts a new background thread and calls join(). Returns immediately.
pub fn start(&self) {
unsafe { binder_rpc_unstable_bindgen::ARpcServer_start(self.as_ptr()) };
@@ -99,51 +140,11 @@
/// Shuts down the running RpcServer. Can be called multiple times and from
/// multiple threads. Called automatically during drop().
- pub fn shutdown(&self) {
- unsafe { binder_rpc_unstable_bindgen::ARpcServer_shutdown(self.as_ptr()) };
- }
-}
-
-type RpcServerFactoryRef<'a> = &'a mut (dyn FnMut(u32) -> Option<SpIBinder> + Send + Sync);
-
-/// Runs a binder RPC server, using the given factory function to construct a binder service
-/// implementation for each connection.
-///
-/// The current thread is joined to the binder thread pool to handle incoming messages.
-///
-/// Returns true if the server has shutdown normally, false if it failed in some way.
-pub fn run_vsock_rpc_server_with_factory(
- port: u32,
- mut factory: impl FnMut(u32) -> Option<SpIBinder> + Send + Sync,
-) -> bool {
- // Double reference the factory because trait objects aren't FFI safe.
- // NB: The type annotation is necessary to ensure that we have a `dyn` rather than an `impl`.
- let mut factory_ref: RpcServerFactoryRef = &mut factory;
- let context = &mut factory_ref as *mut RpcServerFactoryRef as *mut raw::c_void;
-
- // SAFETY: `factory_wrapper` is only ever called by `RunVsockRpcServerWithFactory`, with context
- // taking the pointer value above (so a properly aligned non-null pointer to an initialized
- // `RpcServerFactoryRef`), within the lifetime of `factory_ref` (i.e. no more calls will be made
- // after `RunVsockRpcServerWithFactory` returns).
- unsafe {
- binder_rpc_unstable_bindgen::RunVsockRpcServerWithFactory(
- Some(factory_wrapper),
- context,
- port,
- )
- }
-}
-
-unsafe extern "C" fn factory_wrapper(cid: u32, context: *mut raw::c_void) -> *mut AIBinder {
- // SAFETY: `context` was created from an `&mut RpcServerFactoryRef` by
- // `run_vsock_rpc_server_with_factory`, and we are still within the lifetime of the value it is
- // pointing to.
- let factory_ptr = context as *mut RpcServerFactoryRef;
- let factory = factory_ptr.as_mut().unwrap();
-
- if let Some(mut service) = factory(cid) {
- service.as_native_mut()
- } else {
- null_mut()
+ pub fn shutdown(&self) -> Result<(), Error> {
+ if unsafe { binder_rpc_unstable_bindgen::ARpcServer_shutdown(self.as_ptr()) } {
+ Ok(())
+ } else {
+ Err(Error::from(ErrorKind::UnexpectedEof))
+ }
}
}
diff --git a/libs/binder/rust/rpcbinder/src/session.rs b/libs/binder/rust/rpcbinder/src/session.rs
new file mode 100644
index 0000000..62fedb1
--- /dev/null
+++ b/libs/binder/rust/rpcbinder/src/session.rs
@@ -0,0 +1,190 @@
+/*
+ * 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.
+ */
+
+use binder::unstable_api::new_spibinder;
+use binder::{FromIBinder, SpIBinder, StatusCode, Strong};
+use foreign_types::{foreign_type, ForeignType, ForeignTypeRef};
+use std::ffi::CString;
+use std::os::{
+ raw::{c_int, c_void},
+ unix::io::{AsRawFd, BorrowedFd, RawFd},
+};
+
+pub use binder_rpc_unstable_bindgen::ARpcSession_FileDescriptorTransportMode as FileDescriptorTransportMode;
+
+foreign_type! {
+ type CType = binder_rpc_unstable_bindgen::ARpcSession;
+ fn drop = binder_rpc_unstable_bindgen::ARpcSession_free;
+
+ /// A type that represents a foreign instance of RpcSession.
+ #[derive(Debug)]
+ pub struct RpcSession;
+ /// A borrowed RpcSession.
+ pub struct RpcSessionRef;
+}
+
+/// SAFETY - The opaque handle can be cloned freely.
+unsafe impl Send for RpcSession {}
+/// SAFETY - The underlying C++ RpcSession class is thread-safe.
+unsafe impl Sync for RpcSession {}
+
+impl RpcSession {
+ /// Allocates a new RpcSession object.
+ pub fn new() -> RpcSession {
+ // SAFETY - Takes ownership of the returned handle, which has correct refcount.
+ unsafe { RpcSession::from_ptr(binder_rpc_unstable_bindgen::ARpcSession_new()) }
+ }
+}
+
+impl Default for RpcSession {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl RpcSessionRef {
+ /// Sets the file descriptor transport mode for this session.
+ pub fn set_file_descriptor_transport_mode(&self, mode: FileDescriptorTransportMode) {
+ // SAFETY - Only passes the 'self' pointer as an opaque handle.
+ unsafe {
+ binder_rpc_unstable_bindgen::ARpcSession_setFileDescriptorTransportMode(
+ self.as_ptr(),
+ mode,
+ )
+ };
+ }
+
+ /// Sets the maximum number of incoming threads.
+ pub fn set_max_incoming_threads(&self, threads: usize) {
+ // SAFETY - Only passes the 'self' pointer as an opaque handle.
+ unsafe {
+ binder_rpc_unstable_bindgen::ARpcSession_setMaxIncomingThreads(self.as_ptr(), threads)
+ };
+ }
+
+ /// Sets the maximum number of outgoing threads.
+ pub fn set_max_outgoing_threads(&self, threads: usize) {
+ // SAFETY - Only passes the 'self' pointer as an opaque handle.
+ unsafe {
+ binder_rpc_unstable_bindgen::ARpcSession_setMaxOutgoingThreads(self.as_ptr(), threads)
+ };
+ }
+
+ /// Connects to an RPC Binder server over vsock for a particular interface.
+ pub fn setup_vsock_client<T: FromIBinder + ?Sized>(
+ &self,
+ cid: u32,
+ port: u32,
+ ) -> Result<Strong<T>, StatusCode> {
+ // SAFETY: AIBinder returned by ARpcSession_setupVsockClient has correct
+ // reference count, and the ownership can safely be taken by new_spibinder.
+ let service = unsafe {
+ new_spibinder(binder_rpc_unstable_bindgen::ARpcSession_setupVsockClient(
+ self.as_ptr(),
+ cid,
+ port,
+ ))
+ };
+ Self::get_interface(service)
+ }
+
+ /// Connects to an RPC Binder server over a names Unix Domain Socket for
+ /// a particular interface.
+ pub fn setup_unix_domain_client<T: FromIBinder + ?Sized>(
+ &self,
+ socket_name: &str,
+ ) -> Result<Strong<T>, StatusCode> {
+ let socket_name = match CString::new(socket_name) {
+ Ok(s) => s,
+ Err(e) => {
+ log::error!("Cannot convert {} to CString. Error: {:?}", socket_name, e);
+ return Err(StatusCode::NAME_NOT_FOUND);
+ }
+ };
+
+ // SAFETY: AIBinder returned by ARpcSession_setupUnixDomainClient has correct
+ // reference count, and the ownership can safely be taken by new_spibinder.
+ let service = unsafe {
+ new_spibinder(binder_rpc_unstable_bindgen::ARpcSession_setupUnixDomainClient(
+ self.as_ptr(),
+ socket_name.as_ptr(),
+ ))
+ };
+ Self::get_interface(service)
+ }
+
+ /// Connects to an RPC Binder server over a bootstrap Unix Domain Socket
+ /// for a particular interface.
+ pub fn setup_unix_domain_bootstrap_client<T: FromIBinder + ?Sized>(
+ &self,
+ bootstrap_fd: BorrowedFd,
+ ) -> Result<Strong<T>, StatusCode> {
+ // SAFETY: ARpcSession_setupUnixDomainBootstrapClient does not take
+ // ownership of bootstrap_fd. The returned AIBinder has correct
+ // reference count, and the ownership can safely be taken by new_spibinder.
+ let service = unsafe {
+ new_spibinder(binder_rpc_unstable_bindgen::ARpcSession_setupUnixDomainBootstrapClient(
+ self.as_ptr(),
+ bootstrap_fd.as_raw_fd(),
+ ))
+ };
+ Self::get_interface(service)
+ }
+
+ /// Connects to an RPC Binder server, using the given callback to get (and
+ /// take ownership of) file descriptors already connected to it.
+ pub fn setup_preconnected_client<T: FromIBinder + ?Sized>(
+ &self,
+ mut request_fd: impl FnMut() -> Option<RawFd>,
+ ) -> Result<Strong<T>, StatusCode> {
+ // Double reference the factory because trait objects aren't FFI safe.
+ let mut request_fd_ref: RequestFd = &mut request_fd;
+ let param = &mut request_fd_ref as *mut RequestFd as *mut c_void;
+
+ // SAFETY: AIBinder returned by RpcPreconnectedClient has correct reference count, and the
+ // ownership can be safely taken by new_spibinder. RpcPreconnectedClient does not take ownership
+ // of param, only passing it to request_fd_wrapper.
+ let service = unsafe {
+ new_spibinder(binder_rpc_unstable_bindgen::ARpcSession_setupPreconnectedClient(
+ self.as_ptr(),
+ Some(request_fd_wrapper),
+ param,
+ ))
+ };
+ Self::get_interface(service)
+ }
+
+ fn get_interface<T: FromIBinder + ?Sized>(
+ service: Option<SpIBinder>,
+ ) -> Result<Strong<T>, StatusCode> {
+ if let Some(service) = service {
+ FromIBinder::try_from(service)
+ } else {
+ Err(StatusCode::NAME_NOT_FOUND)
+ }
+ }
+}
+
+type RequestFd<'a> = &'a mut dyn FnMut() -> Option<RawFd>;
+
+unsafe extern "C" fn request_fd_wrapper(param: *mut c_void) -> c_int {
+ // SAFETY: This is only ever called by RpcPreconnectedClient, within the lifetime of the
+ // BinderFdFactory reference, with param being a properly aligned non-null pointer to an
+ // initialized instance.
+ let request_fd_ptr = param as *mut RequestFd;
+ let request_fd = request_fd_ptr.as_mut().unwrap();
+ request_fd().unwrap_or(-1)
+}
diff --git a/libs/binder/tests/binderRpcTest.cpp b/libs/binder/tests/binderRpcTest.cpp
index 02aa45f..739c217 100644
--- a/libs/binder/tests/binderRpcTest.cpp
+++ b/libs/binder/tests/binderRpcTest.cpp
@@ -1342,7 +1342,7 @@
} break;
case SocketType::VSOCK: {
auto port = allocateVsockPort();
- auto status = rpcServer->setupVsockServer(port);
+ auto status = rpcServer->setupVsockServer(VMADDR_CID_LOCAL, port);
if (status != OK) {
return AssertionFailure() << "setupVsockServer: " << statusToString(status);
}
diff --git a/libs/binder/tests/binderRpcTestService.cpp b/libs/binder/tests/binderRpcTestService.cpp
index 995e761..cc9726b 100644
--- a/libs/binder/tests/binderRpcTestService.cpp
+++ b/libs/binder/tests/binderRpcTestService.cpp
@@ -58,7 +58,7 @@
CHECK_EQ(OK, server->setupRawSocketServer(std::move(socketFd)));
break;
case SocketType::VSOCK:
- CHECK_EQ(OK, server->setupVsockServer(serverConfig.vsockPort));
+ CHECK_EQ(OK, server->setupVsockServer(VMADDR_CID_LOCAL, serverConfig.vsockPort));
break;
case SocketType::INET: {
CHECK_EQ(OK, server->setupInetServer(kLocalInetAddress, 0, &outPort));
diff --git a/libs/binder/trusty/RpcTransportTipcTrusty.cpp b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
index 58bfe71..d249b2e 100644
--- a/libs/binder/trusty/RpcTransportTipcTrusty.cpp
+++ b/libs/binder/trusty/RpcTransportTipcTrusty.cpp
@@ -239,6 +239,12 @@
}
if (!(uevt.event & IPC_HANDLE_POLL_MSG)) {
/* No message, terminate here and leave mHaveMessage false */
+ if (uevt.event & IPC_HANDLE_POLL_HUP) {
+ // Peer closed the connection. We need to preserve the order
+ // between MSG and HUP from FdTrigger.cpp, which means that
+ // getting MSG&HUP should return OK instead of DEAD_OBJECT.
+ return DEAD_OBJECT;
+ }
return OK;
}
diff --git a/libs/binder/trusty/kernel/rules.mk b/libs/binder/trusty/kernel/rules.mk
new file mode 100644
index 0000000..ab7a50d
--- /dev/null
+++ b/libs/binder/trusty/kernel/rules.mk
@@ -0,0 +1,83 @@
+# 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.
+#
+
+LOCAL_DIR := $(GET_LOCAL_DIR)
+
+MODULE := $(LOCAL_DIR)
+
+LIBBINDER_DIR := frameworks/native/libs/binder
+LIBBASE_DIR := system/libbase
+LIBCUTILS_DIR := system/core/libcutils
+LIBUTILS_DIR := system/core/libutils
+FMTLIB_DIR := external/fmtlib
+
+MODULE_SRCS := \
+ $(LOCAL_DIR)/../logging.cpp \
+ $(LOCAL_DIR)/../TrustyStatus.cpp \
+ $(LIBBINDER_DIR)/Binder.cpp \
+ $(LIBBINDER_DIR)/BpBinder.cpp \
+ $(LIBBINDER_DIR)/FdTrigger.cpp \
+ $(LIBBINDER_DIR)/IInterface.cpp \
+ $(LIBBINDER_DIR)/IResultReceiver.cpp \
+ $(LIBBINDER_DIR)/Parcel.cpp \
+ $(LIBBINDER_DIR)/Stability.cpp \
+ $(LIBBINDER_DIR)/Status.cpp \
+ $(LIBBINDER_DIR)/Utils.cpp \
+ $(LIBBASE_DIR)/hex.cpp \
+ $(LIBBASE_DIR)/stringprintf.cpp \
+ $(LIBUTILS_DIR)/Errors.cpp \
+ $(LIBUTILS_DIR)/misc.cpp \
+ $(LIBUTILS_DIR)/RefBase.cpp \
+ $(LIBUTILS_DIR)/StrongPointer.cpp \
+ $(LIBUTILS_DIR)/Unicode.cpp \
+
+# TODO: remove the following when libbinder supports std::string
+# instead of String16 and String8 for Status and descriptors
+MODULE_SRCS += \
+ $(LIBUTILS_DIR)/SharedBuffer.cpp \
+ $(LIBUTILS_DIR)/String16.cpp \
+ $(LIBUTILS_DIR)/String8.cpp \
+
+# TODO: disable dump() transactions to get rid of Vector
+MODULE_SRCS += \
+ $(LIBUTILS_DIR)/VectorImpl.cpp \
+
+MODULE_DEFINES += \
+ LK_DEBUGLEVEL_NO_ALIASES=1 \
+
+MODULE_INCLUDES += \
+ $(LOCAL_DIR)/.. \
+
+GLOBAL_INCLUDES += \
+ $(LOCAL_DIR)/include \
+ $(LOCAL_DIR)/../include \
+ $(LIBBINDER_DIR)/include \
+ $(LIBBINDER_DIR)/ndk/include_cpp \
+ $(LIBBASE_DIR)/include \
+ $(LIBCUTILS_DIR)/include \
+ $(LIBUTILS_DIR)/include \
+ $(FMTLIB_DIR)/include \
+
+GLOBAL_COMPILEFLAGS += \
+ -DANDROID_BASE_UNIQUE_FD_DISABLE_IMPLICIT_CONVERSION \
+ -DBINDER_NO_KERNEL_IPC \
+ -DBINDER_RPC_SINGLE_THREADED \
+ -D__ANDROID_VNDK__ \
+
+MODULE_DEPS += \
+ trusty/kernel/lib/libcxx-trusty \
+ trusty/kernel/lib/libcxxabi-trusty \
+
+include make/module.mk
diff --git a/libs/graphicsenv/GpuStatsInfo.cpp b/libs/graphicsenv/GpuStatsInfo.cpp
index 858739c..7b74214 100644
--- a/libs/graphicsenv/GpuStatsInfo.cpp
+++ b/libs/graphicsenv/GpuStatsInfo.cpp
@@ -89,6 +89,14 @@
if ((status = parcel->writeBool(falsePrerotation)) != OK) return status;
if ((status = parcel->writeBool(gles1InUse)) != OK) return status;
if ((status = parcel->writeBool(angleInUse)) != OK) return status;
+ if ((status = parcel->writeBool(createdGlesContext)) != OK) return status;
+ if ((status = parcel->writeBool(createdVulkanDevice)) != OK) return status;
+ if ((status = parcel->writeBool(createdVulkanSwapchain)) != OK) return status;
+ if ((status = parcel->writeUint32(vulkanApiVersion)) != OK) return status;
+ if ((status = parcel->writeUint64(vulkanDeviceFeaturesEnabled)) != OK) return status;
+ if ((status = parcel->writeInt32Vector(vulkanInstanceExtensions)) != OK) return status;
+ if ((status = parcel->writeInt32Vector(vulkanDeviceExtensions)) != OK) return status;
+
return OK;
}
@@ -103,6 +111,14 @@
if ((status = parcel->readBool(&falsePrerotation)) != OK) return status;
if ((status = parcel->readBool(&gles1InUse)) != OK) return status;
if ((status = parcel->readBool(&angleInUse)) != OK) return status;
+ if ((status = parcel->readBool(&createdGlesContext)) != OK) return status;
+ if ((status = parcel->readBool(&createdVulkanDevice)) != OK) return status;
+ if ((status = parcel->readBool(&createdVulkanSwapchain)) != OK) return status;
+ if ((status = parcel->readUint32(&vulkanApiVersion)) != OK) return status;
+ if ((status = parcel->readUint64(&vulkanDeviceFeaturesEnabled)) != OK) return status;
+ if ((status = parcel->readInt32Vector(&vulkanInstanceExtensions)) != OK) return status;
+ if ((status = parcel->readInt32Vector(&vulkanDeviceExtensions)) != OK) return status;
+
return OK;
}
@@ -114,6 +130,12 @@
StringAppendF(&result, "falsePrerotation = %d\n", falsePrerotation);
StringAppendF(&result, "gles1InUse = %d\n", gles1InUse);
StringAppendF(&result, "angleInUse = %d\n", angleInUse);
+ StringAppendF(&result, "createdGlesContext = %d\n", createdGlesContext);
+ StringAppendF(&result, "createdVulkanDevice = %d\n", createdVulkanDevice);
+ StringAppendF(&result, "createdVulkanSwapchain = %d\n", createdVulkanSwapchain);
+ StringAppendF(&result, "vulkanApiVersion = 0x%" PRIx32 "\n", vulkanApiVersion);
+ StringAppendF(&result, "vulkanDeviceFeaturesEnabled = 0x%" PRIx64 "\n",
+ vulkanDeviceFeaturesEnabled);
result.append("glDriverLoadingTime:");
for (int32_t loadingTime : glDriverLoadingTime) {
StringAppendF(&result, " %d", loadingTime);
@@ -129,6 +151,16 @@
StringAppendF(&result, " %d", loadingTime);
}
result.append("\n");
+ result.append("vulkanInstanceExtensions:");
+ for (int32_t extension : vulkanInstanceExtensions) {
+ StringAppendF(&result, " 0x%x", extension);
+ }
+ result.append("\n");
+ result.append("vulkanDeviceExtensions:");
+ for (int32_t extension : vulkanDeviceExtensions) {
+ StringAppendF(&result, " 0x%x", extension);
+ }
+ result.append("\n");
return result;
}
diff --git a/libs/graphicsenv/GraphicsEnv.cpp b/libs/graphicsenv/GraphicsEnv.cpp
index 5f5f85a..46dd62d 100644
--- a/libs/graphicsenv/GraphicsEnv.cpp
+++ b/libs/graphicsenv/GraphicsEnv.cpp
@@ -259,6 +259,57 @@
sendGpuStatsLocked(api, isDriverLoaded, driverLoadingTime);
}
+// Hash function to calculate hash for null-terminated Vulkan extension names
+// We store hash values of the extensions, rather than the actual names or
+// indices to be able to support new extensions easily, avoid creating
+// a table of 'known' extensions inside Android and reduce the runtime overhead.
+static uint64_t calculateExtensionHash(const char* word) {
+ if (!word) {
+ return 0;
+ }
+ const size_t wordLen = strlen(word);
+ const uint32_t seed = 167;
+ uint64_t hash = 0;
+ for (size_t i = 0; i < wordLen; i++) {
+ hash = (hash * seed) + word[i];
+ }
+ return hash;
+}
+
+void GraphicsEnv::setVulkanInstanceExtensions(uint32_t enabledExtensionCount,
+ const char* const* ppEnabledExtensionNames) {
+ ATRACE_CALL();
+ if (enabledExtensionCount == 0 || ppEnabledExtensionNames == nullptr) {
+ return;
+ }
+
+ const uint32_t maxNumStats = android::GpuStatsAppInfo::MAX_NUM_EXTENSIONS;
+ uint64_t extensionHashes[maxNumStats];
+ const uint32_t numStats = std::min(enabledExtensionCount, maxNumStats);
+ for(uint32_t i = 0; i < numStats; i++) {
+ extensionHashes[i] = calculateExtensionHash(ppEnabledExtensionNames[i]);
+ }
+ setTargetStatsArray(android::GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ extensionHashes, numStats);
+}
+
+void GraphicsEnv::setVulkanDeviceExtensions(uint32_t enabledExtensionCount,
+ const char* const* ppEnabledExtensionNames) {
+ ATRACE_CALL();
+ if (enabledExtensionCount == 0 || ppEnabledExtensionNames == nullptr) {
+ return;
+ }
+
+ const uint32_t maxNumStats = android::GpuStatsAppInfo::MAX_NUM_EXTENSIONS;
+ uint64_t extensionHashes[maxNumStats];
+ const uint32_t numStats = std::min(enabledExtensionCount, maxNumStats);
+ for(uint32_t i = 0; i < numStats; i++) {
+ extensionHashes[i] = calculateExtensionHash(ppEnabledExtensionNames[i]);
+ }
+ setTargetStatsArray(android::GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ extensionHashes, numStats);
+}
+
static sp<IGpuService> getGpuService() {
static const sp<IBinder> binder = defaultServiceManager()->checkService(String16("gpu"));
if (!binder) {
@@ -276,6 +327,11 @@
}
void GraphicsEnv::setTargetStats(const GpuStatsInfo::Stats stats, const uint64_t value) {
+ return setTargetStatsArray(stats, &value, 1);
+}
+
+void GraphicsEnv::setTargetStatsArray(const GpuStatsInfo::Stats stats, const uint64_t* values,
+ const uint32_t valueCount) {
ATRACE_CALL();
std::lock_guard<std::mutex> lock(mStatsLock);
@@ -283,8 +339,8 @@
const sp<IGpuService> gpuService = getGpuService();
if (gpuService) {
- gpuService->setTargetStats(mGpuStats.appPackageName, mGpuStats.driverVersionCode, stats,
- value);
+ gpuService->setTargetStatsArray(mGpuStats.appPackageName, mGpuStats.driverVersionCode,
+ stats, values, valueCount);
}
}
diff --git a/libs/graphicsenv/IGpuService.cpp b/libs/graphicsenv/IGpuService.cpp
index fa25c55..ceb52f7 100644
--- a/libs/graphicsenv/IGpuService.cpp
+++ b/libs/graphicsenv/IGpuService.cpp
@@ -61,6 +61,14 @@
remote()->transact(BnGpuService::SET_TARGET_STATS, data, &reply, IBinder::FLAG_ONEWAY);
}
+ void setTargetStatsArray(const std::string& appPackageName, const uint64_t driverVersionCode,
+ const GpuStatsInfo::Stats stats, const uint64_t* values,
+ const uint32_t valueCount) override {
+ for (uint32_t i = 0; i < valueCount; i++) {
+ setTargetStats(appPackageName, driverVersionCode, stats, values[i]);
+ }
+ }
+
void setUpdatableDriverPath(const std::string& driverPath) override {
Parcel data, reply;
data.writeInterfaceToken(IGpuService::getInterfaceDescriptor());
diff --git a/libs/graphicsenv/include/graphicsenv/GpuStatsInfo.h b/libs/graphicsenv/include/graphicsenv/GpuStatsInfo.h
index 5b513d2..47607a0 100644
--- a/libs/graphicsenv/include/graphicsenv/GpuStatsInfo.h
+++ b/libs/graphicsenv/include/graphicsenv/GpuStatsInfo.h
@@ -58,6 +58,9 @@
*/
class GpuStatsAppInfo : public Parcelable {
public:
+ // This limits the worst case number of extensions to be tracked.
+ static const uint32_t MAX_NUM_EXTENSIONS = 100;
+
GpuStatsAppInfo() = default;
GpuStatsAppInfo(const GpuStatsAppInfo&) = default;
virtual ~GpuStatsAppInfo() = default;
@@ -74,6 +77,13 @@
bool falsePrerotation = false;
bool gles1InUse = false;
bool angleInUse = false;
+ bool createdGlesContext = false;
+ bool createdVulkanDevice = false;
+ bool createdVulkanSwapchain = false;
+ uint32_t vulkanApiVersion = 0;
+ uint64_t vulkanDeviceFeaturesEnabled = 0;
+ std::vector<int32_t> vulkanInstanceExtensions = {};
+ std::vector<int32_t> vulkanDeviceExtensions = {};
std::chrono::time_point<std::chrono::system_clock> lastAccessTime;
};
@@ -101,6 +111,13 @@
CPU_VULKAN_IN_USE = 0,
FALSE_PREROTATION = 1,
GLES_1_IN_USE = 2,
+ CREATED_GLES_CONTEXT = 3,
+ CREATED_VULKAN_API_VERSION = 4,
+ CREATED_VULKAN_DEVICE = 5,
+ CREATED_VULKAN_SWAPCHAIN = 6,
+ VULKAN_DEVICE_FEATURES_ENABLED = 7,
+ VULKAN_INSTANCE_EXTENSION = 8,
+ VULKAN_DEVICE_EXTENSION = 9,
};
GpuStatsInfo() = default;
diff --git a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
index 73d3196..b58a6d9 100644
--- a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
+++ b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
@@ -71,10 +71,19 @@
const std::string& appPackageName, const int32_t vulkanVersion);
// Set stats for target GpuStatsInfo::Stats type.
void setTargetStats(const GpuStatsInfo::Stats stats, const uint64_t value = 0);
+ // Set array of stats for target GpuStatsInfo::Stats type.
+ void setTargetStatsArray(const GpuStatsInfo::Stats stats, const uint64_t* values,
+ const uint32_t valueCount);
// Set which driver is intended to load.
void setDriverToLoad(GpuStatsInfo::Driver driver);
// Set which driver is actually loaded.
void setDriverLoaded(GpuStatsInfo::Api api, bool isDriverLoaded, int64_t driverLoadingTime);
+ // Set which instance extensions are enabled for the app.
+ void setVulkanInstanceExtensions(uint32_t enabledExtensionCount,
+ const char* const* ppEnabledExtensionNames);
+ // Set which device extensions are enabled for the app.
+ void setVulkanDeviceExtensions(uint32_t enabledExtensionCount,
+ const char* const* ppEnabledExtensionNames);
/*
* Api for Vk/GL layer injection. Presently, drivers enable certain
diff --git a/libs/graphicsenv/include/graphicsenv/IGpuService.h b/libs/graphicsenv/include/graphicsenv/IGpuService.h
index 2d59fa0..b708b0f 100644
--- a/libs/graphicsenv/include/graphicsenv/IGpuService.h
+++ b/libs/graphicsenv/include/graphicsenv/IGpuService.h
@@ -42,6 +42,10 @@
// set target stats.
virtual void setTargetStats(const std::string& appPackageName, const uint64_t driverVersionCode,
const GpuStatsInfo::Stats stats, const uint64_t value = 0) = 0;
+ virtual void setTargetStatsArray(const std::string& appPackageName,
+ const uint64_t driverVersionCode,
+ const GpuStatsInfo::Stats stats, const uint64_t* values,
+ const uint32_t valueCount) = 0;
// setter and getter for updatable driver path.
virtual void setUpdatableDriverPath(const std::string& driverPath) = 0;
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index a988e39..6c9c28a 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -192,6 +192,7 @@
"BitTube.cpp",
"BLASTBufferQueue.cpp",
"BufferItemConsumer.cpp",
+ "Choreographer.cpp",
"CompositorTiming.cpp",
"ConsumerBase.cpp",
"CpuConsumer.cpp",
@@ -234,6 +235,7 @@
export_header_lib_headers: [
"libgui_aidl_headers",
+ "jni_headers",
],
aidl: {
@@ -241,6 +243,7 @@
},
header_libs: [
+ "jni_headers",
"libdvr_headers",
"libgui_aidl_headers",
"libpdx_headers",
diff --git a/libs/nativedisplay/Choreographer.cpp b/libs/gui/Choreographer.cpp
similarity index 99%
rename from libs/nativedisplay/Choreographer.cpp
rename to libs/gui/Choreographer.cpp
index 01e9f04..6b25b26 100644
--- a/libs/nativedisplay/Choreographer.cpp
+++ b/libs/gui/Choreographer.cpp
@@ -16,8 +16,8 @@
// #define LOG_NDEBUG 0
+#include <gui/Choreographer.h>
#include <jni.h>
-#include <nativedisplay/Choreographer.h>
#undef LOG_TAG
#define LOG_TAG "AChoreographer"
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index d741c99..a2ed8aa 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -982,14 +982,16 @@
class SyncCallback {
public:
- static void function(void* callbackContext, nsecs_t /* latchTime */,
- const sp<Fence>& /* presentFence */,
- const std::vector<SurfaceControlStats>& /* stats */) {
- if (!callbackContext) {
- ALOGE("failed to get callback context for SyncCallback");
- }
- SyncCallback* helper = static_cast<SyncCallback*>(callbackContext);
- LOG_ALWAYS_FATAL_IF(sem_post(&helper->mSemaphore), "sem_post failed");
+ static auto getCallback(std::shared_ptr<SyncCallback>& callbackContext) {
+ return [callbackContext](void* /* unused context */, nsecs_t /* latchTime */,
+ const sp<Fence>& /* presentFence */,
+ const std::vector<SurfaceControlStats>& /* stats */) {
+ if (!callbackContext) {
+ ALOGE("failed to get callback context for SyncCallback");
+ return;
+ }
+ LOG_ALWAYS_FATAL_IF(sem_post(&callbackContext->mSemaphore), "sem_post failed");
+ };
}
~SyncCallback() {
if (mInitialized) {
@@ -1024,10 +1026,11 @@
return mStatus;
}
- SyncCallback syncCallback;
+ std::shared_ptr<SyncCallback> syncCallback = std::make_shared<SyncCallback>();
if (synchronous) {
- syncCallback.init();
- addTransactionCommittedCallback(syncCallback.function, syncCallback.getContext());
+ syncCallback->init();
+ addTransactionCommittedCallback(SyncCallback::getCallback(syncCallback),
+ /*callbackContext=*/nullptr);
}
bool hasListenerCallbacks = !mListenerCallbacks.empty();
@@ -1103,7 +1106,7 @@
clear();
if (synchronous) {
- syncCallback.wait();
+ syncCallback->wait();
}
mStatus = NO_ERROR;
@@ -2155,6 +2158,12 @@
mStatus = NO_INIT;
}
+status_t SurfaceComposerClient::bootFinished() {
+ sp<gui::ISurfaceComposer> sf(ComposerServiceAIDL::getComposerService());
+ binder::Status status = sf->bootFinished();
+ return statusTFromBinderStatus(status);
+}
+
sp<SurfaceControl> SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h,
PixelFormat format, int32_t flags,
const sp<IBinder>& parentHandle,
diff --git a/libs/gui/TEST_MAPPING b/libs/gui/TEST_MAPPING
index 1c43530..9415035 100644
--- a/libs/gui/TEST_MAPPING
+++ b/libs/gui/TEST_MAPPING
@@ -3,5 +3,11 @@
{
"path": "frameworks/native/libs/nativewindow"
}
+ ],
+ "postsubmit": [
+ {
+ // TODO(257123981): move this to presubmit after dealing with existing breakages.
+ "name": "libgui_test"
+ }
]
}
diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl
index 488a148..a0b613c 100644
--- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl
+++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl
@@ -62,8 +62,6 @@
* Signal that we're done booting.
* Requires ACCESS_SURFACE_FLINGER permission
*/
- // Note this must be the 1st method, so IBinder::FIRST_CALL_TRANSACTION
- // is assigned, as it is called from Java by ActivityManagerService.
void bootFinished();
/**
diff --git a/libs/nativedisplay/include/nativedisplay/Choreographer.h b/libs/gui/include/gui/Choreographer.h
similarity index 98%
rename from libs/nativedisplay/include/nativedisplay/Choreographer.h
rename to libs/gui/include/gui/Choreographer.h
index bb63f29..89a7058 100644
--- a/libs/nativedisplay/include/nativedisplay/Choreographer.h
+++ b/libs/gui/include/gui/Choreographer.h
@@ -16,8 +16,9 @@
#pragma once
+#include <android/choreographer.h>
#include <gui/DisplayEventDispatcher.h>
-#include <private/android/choreographer.h>
+#include <jni.h>
#include <utils/Looper.h>
#include <mutex>
diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h
index d70a7f0..06a246e 100644
--- a/libs/gui/include/gui/ISurfaceComposer.h
+++ b/libs/gui/include/gui/ISurfaceComposer.h
@@ -103,7 +103,7 @@
// (sf vsync offset - debug.sf.early_phase_offset_ns). SurfaceFlinger will continue to be
// in the early configuration until it receives eEarlyWakeupEnd. These flags are
// expected to be used by WindowManager only and are guarded by
- // android.permission.ACCESS_SURFACE_FLINGER
+ // android.permission.WAKEUP_SURFACE_FLINGER
eEarlyWakeupStart = 0x08,
eEarlyWakeupEnd = 0x10,
eOneWay = 0x20
diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h
index 96d3a23..cc459c5 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -158,6 +158,9 @@
status_t linkToComposerDeath(const sp<IBinder::DeathRecipient>& recipient,
void* cookie = nullptr, uint32_t flags = 0);
+ // Notify the SurfaceComposerClient that the boot procedure has completed
+ static status_t bootFinished();
+
// Get transactional state of given display.
static status_t getDisplayState(const sp<IBinder>& display, ui::DisplayState*);
diff --git a/libs/input/Input.cpp b/libs/input/Input.cpp
index 9e8ebf3..d893cb9 100644
--- a/libs/input/Input.cpp
+++ b/libs/input/Input.cpp
@@ -46,25 +46,6 @@
namespace {
-float transformAngle(const ui::Transform& transform, float angleRadians) {
- // Construct and transform a vector oriented at the specified clockwise angle from vertical.
- // Coordinate system: down is increasing Y, right is increasing X.
- float x = sinf(angleRadians);
- float y = -cosf(angleRadians);
- vec2 transformedPoint = transform.transform(x, y);
-
- // Determine how the origin is transformed by the matrix so that we
- // can transform orientation vectors.
- const vec2 origin = transform.transform(0, 0);
-
- transformedPoint.x -= origin.x;
- transformedPoint.y -= origin.y;
-
- // Derive the transformed vector's clockwise angle from vertical.
- // The return value of atan2f is in range [-pi, pi] which conforms to the orientation API.
- return atan2f(transformedPoint.x, -transformedPoint.y);
-}
-
bool shouldDisregardTransformation(uint32_t source) {
// Do not apply any transformations to axes from joysticks, touchpads, or relative mice.
return isFromSource(source, AINPUT_SOURCE_CLASS_JOYSTICK) ||
@@ -172,6 +153,25 @@
return transformedXy - transformedOrigin;
}
+float transformAngle(const ui::Transform& transform, float angleRadians) {
+ // Construct and transform a vector oriented at the specified clockwise angle from vertical.
+ // Coordinate system: down is increasing Y, right is increasing X.
+ float x = sinf(angleRadians);
+ float y = -cosf(angleRadians);
+ vec2 transformedPoint = transform.transform(x, y);
+
+ // Determine how the origin is transformed by the matrix so that we
+ // can transform orientation vectors.
+ const vec2 origin = transform.transform(0, 0);
+
+ transformedPoint.x -= origin.x;
+ transformedPoint.y -= origin.y;
+
+ // Derive the transformed vector's clockwise angle from vertical.
+ // The return value of atan2f is in range [-pi, pi] which conforms to the orientation API.
+ return atan2f(transformedPoint.x, -transformedPoint.y);
+}
+
const char* inputEventTypeToString(int32_t type) {
switch (type) {
case AINPUT_EVENT_TYPE_KEY: {
diff --git a/libs/input/InputDevice.cpp b/libs/input/InputDevice.cpp
index 4751a7d..fb6c590 100644
--- a/libs/input/InputDevice.cpp
+++ b/libs/input/InputDevice.cpp
@@ -179,6 +179,7 @@
mIsExternal(other.mIsExternal),
mHasMic(other.mHasMic),
mCountryCode(other.mCountryCode),
+ mKeyboardLayoutInfo(other.mKeyboardLayoutInfo),
mSources(other.mSources),
mKeyboardType(other.mKeyboardType),
mKeyCharacterMap(other.mKeyCharacterMap),
@@ -270,6 +271,10 @@
mKeyboardType = std::max(mKeyboardType, keyboardType);
}
+void InputDeviceInfo::setKeyboardLayoutInfo(KeyboardLayoutInfo layoutInfo) {
+ mKeyboardLayoutInfo = std::move(layoutInfo);
+}
+
std::vector<InputDeviceSensorInfo> InputDeviceInfo::getSensors() {
std::vector<InputDeviceSensorInfo> infos;
infos.reserve(mSensors.size());
diff --git a/libs/input/InputEventLabels.cpp b/libs/input/InputEventLabels.cpp
index b78fae3..dd7cbb5 100644
--- a/libs/input/InputEventLabels.cpp
+++ b/libs/input/InputEventLabels.cpp
@@ -339,7 +339,8 @@
DEFINE_KEYCODE(STYLUS_BUTTON_PRIMARY), \
DEFINE_KEYCODE(STYLUS_BUTTON_SECONDARY), \
DEFINE_KEYCODE(STYLUS_BUTTON_TERTIARY), \
- DEFINE_KEYCODE(STYLUS_BUTTON_TAIL)
+ DEFINE_KEYCODE(STYLUS_BUTTON_TAIL), \
+ DEFINE_KEYCODE(RECENT_APPS)
// 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/jpegrecoverymap/include/jpegrecoverymap/jpegdecoder.h b/libs/jpegrecoverymap/include/jpegrecoverymap/jpegdecoder.h
index 5c9c8b6..39c79c9 100644
--- a/libs/jpegrecoverymap/include/jpegrecoverymap/jpegdecoder.h
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/jpegdecoder.h
@@ -47,7 +47,7 @@
*/
void* getDecompressedImagePtr();
/*
- * Returns the decompressed raw image buffer size. This method must be called only after
+ * Returns the decompressed raw image buffer size. This mgit ethod must be called only after
* calling decompressImage().
*/
size_t getDecompressedImageSize();
@@ -67,14 +67,35 @@
void* getXMPPtr();
/*
* Returns the decompressed XMP buffer size. This method must be called only after
- * calling decompressImage().
+ * calling decompressImage() or getCompressedImageParameters().
*/
size_t getXMPSize();
-
+ /*
+ * Returns the EXIF data from the image.
+ */
+ void* getEXIFPtr();
+ /*
+ * Returns the decompressed EXIF buffer size. This method must be called only after
+ * calling decompressImage() or getCompressedImageParameters().
+ */
+ size_t getEXIFSize();
+ /*
+ * Returns the position offset of EXIF package
+ * (4 bypes offset to FF sign, the byte after FF E1 XX XX <this byte>),
+ * or -1 if no EXIF exists.
+ */
+ int getEXIFPos() { return mExifPos; }
+ /*
+ * Decompresses metadata of the image.
+ */
bool getCompressedImageParameters(const void* image, int length,
- size_t* pWidth, size_t* pHeight,
- std::vector<uint8_t>* &iccData,
- std::vector<uint8_t>* &exifData);
+ size_t* pWidth, size_t* pHeight,
+ std::vector<uint8_t>* &iccData,
+ std::vector<uint8_t>* &exifData);
+ /*
+ * Extracts EXIF package and updates the EXIF position / length without decoding the image.
+ */
+ bool extractEXIF(const void* image, int length);
private:
bool decode(const void* image, int length);
@@ -89,10 +110,14 @@
std::vector<JOCTET> mResultBuffer;
// The buffer that holds XMP Data.
std::vector<JOCTET> mXMPBuffer;
+ // The buffer that holds EXIF Data.
+ std::vector<JOCTET> mEXIFBuffer;
// Resolution of the decompressed image.
size_t mWidth;
size_t mHeight;
+ // Position of EXIF package, default value is -1 which means no EXIF package appears.
+ size_t mExifPos;
};
} /* namespace android */
diff --git a/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymap.h b/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymap.h
index 74f9776..905bf16 100644
--- a/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymap.h
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymap.h
@@ -30,8 +30,9 @@
// Transfer functions as defined for XMP metadata
typedef enum {
- JPEGR_TF_HLG = 0,
- JPEGR_TF_PQ = 1,
+ JPEGR_TF_LINEAR = 0,
+ JPEGR_TF_HLG = 1,
+ JPEGR_TF_PQ = 2,
} jpegr_transfer_function;
struct jpegr_info_struct {
@@ -250,16 +251,6 @@
jr_info_ptr jpegr_info);
private:
/*
- * This method is called in the decoding pipeline. It will decode the recovery map.
- *
- * @param compressed_recovery_map compressed recovery map
- * @param dest decoded recover map
- * @return NO_ERROR if decoding succeeds, error code if error occurs.
- */
- status_t decompressRecoveryMap(jr_compressed_ptr compressed_recovery_map,
- jr_uncompressed_ptr dest);
-
- /*
* This method is called in the encoding pipeline. It will encode the recovery map.
*
* @param uncompressed_recovery_map uncompressed recovery map
@@ -334,57 +325,18 @@
*
* @param compressed_jpeg_image compressed 8-bit JPEG image
* @param compress_recovery_map compressed recover map
+ * @param exif EXIF package
* @param metadata JPEG/R metadata to encode in XMP of the jpeg
* @param dest compressed JPEGR image
* @return NO_ERROR if calculation succeeds, error code if error occurs.
*/
status_t appendRecoveryMap(jr_compressed_ptr compressed_jpeg_image,
jr_compressed_ptr compressed_recovery_map,
+ jr_exif_ptr exif,
jr_metadata_ptr metadata,
jr_compressed_ptr dest);
/*
- * This method generates XMP metadata.
- *
- * below is an example of the XMP metadata that this function generates where
- * secondary_image_length = 1000
- * range_scaling_factor = 1.25
- *
- * <x:xmpmeta
- * xmlns:x="adobe:ns:meta/"
- * x:xmptk="Adobe XMP Core 5.1.2">
- * <rdf:RDF
- * xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
- * <rdf:Description
- * xmlns:GContainer="http://ns.google.com/photos/1.0/container/">
- * <GContainer:Version>1</GContainer:Version>
- * <GContainer:RangeScalingFactor>1.25</GContainer:RangeScalingFactor>
- * <GContainer:Directory>
- * <rdf:Seq>
- * <rdf:li>
- * <GContainer:Item
- * Item:Semantic="Primary"
- * Item:Mime="image/jpeg"/>
- * </rdf:li>
- * <rdf:li>
- * <GContainer:Item
- * Item:Semantic="RecoveryMap"
- * Item:Mime="image/jpeg"
- * Item:Length="1000"/>
- * </rdf:li>
- * </rdf:Seq>
- * </GContainer:Directory>
- * </rdf:Description>
- * </rdf:RDF>
- * </x:xmpmeta>
- *
- * @param secondary_image_length length of secondary image
- * @param metadata JPEG/R metadata to encode as XMP
- * @return XMP metadata in type of string
- */
- std::string generateXmp(int secondary_image_length, jpegr_metadata& metadata);
-
- /*
* This method will tone map a HDR image to an SDR image.
*
* @param uncompressed_p010_image (input) uncompressed P010 image
diff --git a/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymaputils.h b/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymaputils.h
index e35f2d7..e61d0c4 100644
--- a/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymaputils.h
+++ b/libs/jpegrecoverymap/include/jpegrecoverymap/recoverymaputils.h
@@ -17,10 +17,11 @@
#ifndef ANDROID_JPEGRECOVERYMAP_RECOVERYMAPUTILS_H
#define ANDROID_JPEGRECOVERYMAP_RECOVERYMAPUTILS_H
+#include <sstream>
#include <stdint.h>
+#include <string>
#include <cstdio>
-
namespace android::recoverymap {
struct jpegr_metadata;
@@ -35,6 +36,53 @@
*/
bool getMetadataFromXMP(uint8_t* xmp_data, size_t xmp_size, jpegr_metadata* metadata);
+/*
+ * This method generates XMP metadata.
+ *
+ * below is an example of the XMP metadata that this function generates where
+ * secondary_image_length = 1000
+ * range_scaling_factor = 1.25
+ *
+ * <x:xmpmeta
+ * xmlns:x="adobe:ns:meta/"
+ * x:xmptk="Adobe XMP Core 5.1.2">
+ * <rdf:RDF
+ * xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
+ * <rdf:Description
+ * xmlns:GContainer="http://ns.google.com/photos/1.0/container/"
+ * xmlns:RecoveryMap="http://ns.google.com/photos/1.0/recoverymap/">
+ * <GContainer:Version>1</GContainer:Version>
+ * <GContainer:Directory>
+ * <rdf:Seq>
+ * <rdf:li>
+ * <GContainer:Item
+ * Item:Semantic="Primary"
+ * Item:Mime="image/jpeg"
+ * RecoveryMap:Version=”1”
+ * RecoveryMap:RangeScalingFactor=”1.25”
+ * RecoveryMap:TransferFunction=”2”/>
+ * <RecoveryMap:HDR10Metadata
+ * // some attributes
+ * // some elements
+ * </RecoveryMap:HDR10Metadata>
+ * </rdf:li>
+ * <rdf:li>
+ * <GContainer:Item
+ * Item:Semantic="RecoveryMap"
+ * Item:Mime="image/jpeg"
+ * Item:Length="1000"/>
+ * </rdf:li>
+ * </rdf:Seq>
+ * </GContainer:Directory>
+ * </rdf:Description>
+ * </rdf:RDF>
+ * </x:xmpmeta>
+ *
+ * @param secondary_image_length length of secondary image
+ * @param metadata JPEG/R metadata to encode as XMP
+ * @return XMP metadata in type of string
+ */
+std::string generateXmp(int secondary_image_length, jpegr_metadata& metadata);
}
#endif //ANDROID_JPEGRECOVERYMAP_RECOVERYMAPUTILS_H
\ No newline at end of file
diff --git a/libs/jpegrecoverymap/jpegdecoder.cpp b/libs/jpegrecoverymap/jpegdecoder.cpp
index 0185e55..c2a8f45 100644
--- a/libs/jpegrecoverymap/jpegdecoder.cpp
+++ b/libs/jpegrecoverymap/jpegdecoder.cpp
@@ -26,8 +26,12 @@
namespace android::recoverymap {
-const uint32_t kExifMarker = JPEG_APP0 + 1;
-const uint32_t kICCMarker = JPEG_APP0 + 2;
+const uint32_t kAPP0Marker = JPEG_APP0; // JFIF
+const uint32_t kAPP1Marker = JPEG_APP0 + 1; // EXIF, XMP
+const uint32_t kAPP2Marker = JPEG_APP0 + 2; // ICC
+
+const std::string kXmpNameSpace = "http://ns.adobe.com/xap/1.0/";
+const std::string kExifIdCode = "Exif";
struct jpegr_source_mgr : jpeg_source_mgr {
jpegr_source_mgr(const uint8_t* ptr, int len);
@@ -83,6 +87,7 @@
}
JpegDecoder::JpegDecoder() {
+ mExifPos = 0;
}
JpegDecoder::~JpegDecoder() {
@@ -119,6 +124,13 @@
return mXMPBuffer.size();
}
+void* JpegDecoder::getEXIFPtr() {
+ return mEXIFBuffer.data();
+}
+
+size_t JpegDecoder::getEXIFSize() {
+ return mEXIFBuffer.size();
+}
size_t JpegDecoder::getDecompressedImageWidth() {
return mWidth;
@@ -132,7 +144,6 @@
jpeg_decompress_struct cinfo;
jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
jpegrerror_mgr myerr;
- string nameSpace = "http://ns.adobe.com/xap/1.0/";
cinfo.err = jpeg_std_error(&myerr.pub);
myerr.pub.error_exit = jpegrerror_exit;
@@ -143,26 +154,59 @@
}
jpeg_create_decompress(&cinfo);
- jpeg_save_markers(&cinfo, kExifMarker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP0Marker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
cinfo.src = &mgr;
jpeg_read_header(&cinfo, TRUE);
- // Save XMP Data
- for (jpeg_marker_struct* marker = cinfo.marker_list; marker; marker = marker->next) {
- if (marker->marker == kExifMarker) {
- const unsigned int len = marker->data_length;
- if (len > nameSpace.size() &&
- !strncmp(reinterpret_cast<const char*>(marker->data),
- nameSpace.c_str(), nameSpace.size())) {
- mXMPBuffer.resize(len+1, 0);
- memcpy(static_cast<void*>(mXMPBuffer.data()), marker->data, len);
- break;
- }
+ // Save XMP data and EXIF data.
+ // Here we only handle the first XMP / EXIF package.
+ // The parameter pos is used for capturing start offset of EXIF, which is hacky, but working...
+ // We assume that all packages are starting with two bytes marker (eg FF E1 for EXIF package),
+ // two bytes of package length which is stored in marker->original_length, and the real data
+ // which is stored in marker->data. The pos is adding up all previous package lengths (
+ // 4 bytes marker and length, marker->original_length) before EXIF appears. Note that here we
+ // we are using marker->original_length instead of marker->data_length because in case the real
+ // package length is larger than the limitation, jpeg-turbo will only copy the data within the
+ // limitation (represented by data_length) and this may vary from original_length / real offset.
+ // A better solution is making jpeg_marker_struct holding the offset, but currently it doesn't.
+ bool exifAppears = false;
+ bool xmpAppears = false;
+ size_t pos = 2; // position after SOI
+ for (jpeg_marker_struct* marker = cinfo.marker_list;
+ marker && !(exifAppears && xmpAppears);
+ marker = marker->next) {
+
+ pos += 4;
+ pos += marker->original_length;
+
+ if (marker->marker != kAPP1Marker) {
+ continue;
+ }
+
+ const unsigned int len = marker->data_length;
+ if (!xmpAppears &&
+ len > kXmpNameSpace.size() &&
+ !strncmp(reinterpret_cast<const char*>(marker->data),
+ kXmpNameSpace.c_str(),
+ kXmpNameSpace.size())) {
+ mXMPBuffer.resize(len+1, 0);
+ memcpy(static_cast<void*>(mXMPBuffer.data()), marker->data, len);
+ xmpAppears = true;
+ } else if (!exifAppears &&
+ len > kExifIdCode.size() &&
+ !strncmp(reinterpret_cast<const char*>(marker->data),
+ kExifIdCode.c_str(),
+ kExifIdCode.size())) {
+ mEXIFBuffer.resize(len, 0);
+ memcpy(static_cast<void*>(mEXIFBuffer.data()), marker->data, len);
+ exifAppears = true;
+ mExifPos = pos - marker->original_length;
}
}
-
mWidth = cinfo.image_width;
mHeight = cinfo.image_height;
@@ -189,6 +233,60 @@
return true;
}
+// TODO (Fyodor/Dichen): merge this method with getCompressedImageParameters() since they have
+// similar functionality. Yet Dichen is not familiar with who's calling
+// getCompressedImageParameters(), looks like it's used by some pending CLs.
+bool JpegDecoder::extractEXIF(const void* image, int length) {
+ jpeg_decompress_struct cinfo;
+ jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
+ jpegrerror_mgr myerr;
+
+ cinfo.err = jpeg_std_error(&myerr.pub);
+ myerr.pub.error_exit = jpegrerror_exit;
+
+ if (setjmp(myerr.setjmp_buffer)) {
+ jpeg_destroy_decompress(&cinfo);
+ return false;
+ }
+ jpeg_create_decompress(&cinfo);
+
+ jpeg_save_markers(&cinfo, kAPP0Marker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
+
+ cinfo.src = &mgr;
+ jpeg_read_header(&cinfo, TRUE);
+
+ bool exifAppears = false;
+ size_t pos = 2; // position after SOI
+ for (jpeg_marker_struct* marker = cinfo.marker_list;
+ marker && !exifAppears;
+ marker = marker->next) {
+
+ pos += 4;
+ pos += marker->original_length;
+
+ if (marker->marker != kAPP1Marker) {
+ continue;
+ }
+
+ const unsigned int len = marker->data_length;
+ if (!exifAppears &&
+ len > kExifIdCode.size() &&
+ !strncmp(reinterpret_cast<const char*>(marker->data),
+ kExifIdCode.c_str(),
+ kExifIdCode.size())) {
+ mEXIFBuffer.resize(len, 0);
+ memcpy(static_cast<void*>(mEXIFBuffer.data()), marker->data, len);
+ exifAppears = true;
+ mExifPos = pos - marker->original_length;
+ }
+ }
+
+ jpeg_destroy_decompress(&cinfo);
+ return true;
+}
+
bool JpegDecoder::decompress(jpeg_decompress_struct* cinfo, const uint8_t* dest,
bool isSingleChannel) {
if (isSingleChannel) {
@@ -212,8 +310,8 @@
}
jpeg_create_decompress(&cinfo);
- jpeg_save_markers(&cinfo, kExifMarker, 0xFFFF);
- jpeg_save_markers(&cinfo, kICCMarker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
+ jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
cinfo.src = &mgr;
if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
diff --git a/libs/jpegrecoverymap/recoverymap.cpp b/libs/jpegrecoverymap/recoverymap.cpp
index c9ac921..53fa8ce 100644
--- a/libs/jpegrecoverymap/recoverymap.cpp
+++ b/libs/jpegrecoverymap/recoverymap.cpp
@@ -21,7 +21,6 @@
#include <jpegrecoverymap/recoverymaputils.h>
#include <image_io/jpeg/jpeg_marker.h>
-#include <image_io/xml/xml_writer.h>
#include <image_io/jpeg/jpeg_info.h>
#include <image_io/jpeg/jpeg_scanner.h>
#include <image_io/jpeg/jpeg_info_builder.h>
@@ -65,19 +64,6 @@
};
/*
- * Helper function used for generating XMP metadata.
- *
- * @param prefix The prefix part of the name.
- * @param suffix The suffix part of the name.
- * @return A name of the form "prefix:suffix".
- */
-string Name(const string &prefix, const string &suffix) {
- std::stringstream ss;
- ss << prefix << ":" << suffix;
- return ss.str();
-}
-
-/*
* Helper function used for writing data to destination.
*
* @param destination destination of the data to be written.
@@ -96,12 +82,122 @@
return NO_ERROR;
}
+status_t Write(jr_exif_ptr destination, const void* source, size_t length, int &position) {
+ memcpy((uint8_t*)destination->data + sizeof(uint8_t) * position, source, length);
+ position += length;
+ return NO_ERROR;
+}
+
+// If the EXIF package doesn't exist in the input JPEG, we'll create one with one entry
+// where the length is represented by this value.
+const size_t PSEUDO_EXIF_PACKAGE_LENGTH = 28;
+// If the EXIF package exists in the input JPEG, we'll add an "JR" entry where the length is
+// represented by this value.
+const size_t EXIF_J_R_ENTRY_LENGTH = 12;
+
+/*
+ * Helper function
+ * Add J R entry to existing exif, or create a new one with J R entry if it's null.
+ * EXIF syntax / change:
+ * ori:
+ * FF E1 - APP1
+ * 01 FC - size of APP1 (to be calculated)
+ * -----------------------------------------------------
+ * 45 78 69 66 00 00 - Exif\0\0 "Exif header"
+ * 49 49 2A 00 - TIFF Header
+ * 08 00 00 00 - offset to the IFD (image file directory)
+ * 06 00 - 6 entries
+ * 00 01 - Width Tag
+ * 03 00 - 'Short' type
+ * 01 00 00 00 - one entry
+ * 00 05 00 00 - image with 0x500
+ *--------------------------------------------------------------------------
+ * new:
+ * FF E1 - APP1
+ * 02 08 - new size, equals to old size + EXIF_J_R_ENTRY_LENGTH (12)
+ *-----------------------------------------------------
+ * 45 78 69 66 00 00 - Exif\0\0 "Exif header"
+ * 49 49 2A 00 - TIFF Header
+ * 08 00 00 00 - offset to the IFD (image file directory)
+ * 07 00 - +1 entry
+ * 4A 52 Custom ('J''R') Tag
+ * 07 00 - Unknown type
+ * 01 00 00 00 - one element
+ * 00 00 00 00 - empty data
+ * 00 01 - Width Tag
+ * 03 00 - 'Short' type
+ * 01 00 00 00 - one entry
+ * 00 05 00 00 - image with 0x500
+ */
+status_t updateExif(jr_exif_ptr exif, jr_exif_ptr dest) {
+ if (exif == nullptr || exif->data == nullptr) {
+ uint8_t data[PSEUDO_EXIF_PACKAGE_LENGTH] = {
+ 0x45, 0x78, 0x69, 0x66, 0x00, 0x00,
+ 0x49, 0x49, 0x2A, 0x00,
+ 0x08, 0x00, 0x00, 0x00,
+ 0x01, 0x00,
+ 0x4A, 0x52,
+ 0x07, 0x00,
+ 0x01, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00};
+ int pos = 0;
+ Write(dest, data, PSEUDO_EXIF_PACKAGE_LENGTH, pos);
+ return NO_ERROR;
+ }
+
+ int num_entry = 0;
+ uint8_t num_entry_low = 0;
+ uint8_t num_entry_high = 0;
+ bool use_big_endian = false;
+ if (reinterpret_cast<uint16_t*>(exif->data)[3] == 0x4949) {
+ num_entry_low = reinterpret_cast<uint8_t*>(exif->data)[14];
+ num_entry_high = reinterpret_cast<uint8_t*>(exif->data)[15];
+ } else if (reinterpret_cast<uint16_t*>(exif->data)[3] == 0x4d4d) {
+ use_big_endian = true;
+ num_entry_high = reinterpret_cast<uint8_t*>(exif->data)[14];
+ num_entry_low = reinterpret_cast<uint8_t*>(exif->data)[15];
+ } else {
+ return ERROR_JPEGR_METADATA_ERROR;
+ }
+ num_entry = (num_entry_high << 8) | num_entry_low;
+ num_entry += 1;
+ num_entry_low = num_entry & 0xff;
+ num_entry_high = (num_entry << 8) & 0xff;
+
+ int pos = 0;
+ Write(dest, (uint8_t*)exif->data, 14, pos);
+
+ if (use_big_endian) {
+ Write(dest, &num_entry_high, 1, pos);
+ Write(dest, &num_entry_low, 1, pos);
+ uint8_t data[EXIF_J_R_ENTRY_LENGTH] = {
+ 0x4A, 0x52,
+ 0x07, 0x00,
+ 0x01, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00};
+ Write(dest, data, EXIF_J_R_ENTRY_LENGTH, pos);
+ } else {
+ Write(dest, &num_entry_low, 1, pos);
+ Write(dest, &num_entry_high, 1, pos);
+ uint8_t data[EXIF_J_R_ENTRY_LENGTH] = {
+ 0x4A, 0x52,
+ 0x00, 0x07,
+ 0x00, 0x00, 0x00, 0x01,
+ 0x00, 0x00, 0x00, 0x00};
+ Write(dest, data, EXIF_J_R_ENTRY_LENGTH, pos);
+ }
+
+ Write(dest, (uint8_t*)exif->data + 16, exif->length - 16, pos);
+
+ return NO_ERROR;
+}
+
/* Encode API-0 */
status_t RecoveryMap::encodeJPEGR(jr_uncompressed_ptr uncompressed_p010_image,
jpegr_transfer_function hdr_tf,
jr_compressed_ptr dest,
int quality,
- jr_exif_ptr /* exif */) {
+ jr_exif_ptr exif) {
if (uncompressed_p010_image == nullptr || dest == nullptr) {
return ERROR_JPEGR_INVALID_NULL_PTR;
}
@@ -143,7 +239,18 @@
jpeg.data = jpeg_encoder.getCompressedImagePtr();
jpeg.length = jpeg_encoder.getCompressedImageSize();
- JPEGR_CHECK(appendRecoveryMap(&jpeg, &compressed_map, &metadata, dest));
+ jpegr_exif_struct new_exif;
+ if (exif->data == nullptr) {
+ new_exif.length = PSEUDO_EXIF_PACKAGE_LENGTH;
+ } else {
+ new_exif.length = exif->length + EXIF_J_R_ENTRY_LENGTH;
+ }
+ new_exif.data = new uint8_t[new_exif.length];
+ std::unique_ptr<uint8_t[]> new_exif_data;
+ new_exif_data.reset(reinterpret_cast<uint8_t*>(new_exif.data));
+ JPEGR_CHECK(updateExif(exif, &new_exif));
+
+ JPEGR_CHECK(appendRecoveryMap(&jpeg, &compressed_map, &new_exif, &metadata, dest));
return NO_ERROR;
}
@@ -154,7 +261,7 @@
jpegr_transfer_function hdr_tf,
jr_compressed_ptr dest,
int quality,
- jr_exif_ptr /* exif */) {
+ jr_exif_ptr exif) {
if (uncompressed_p010_image == nullptr
|| uncompressed_yuv_420_image == nullptr
|| dest == nullptr) {
@@ -200,7 +307,19 @@
jpeg.data = jpeg_encoder.getCompressedImagePtr();
jpeg.length = jpeg_encoder.getCompressedImageSize();
- JPEGR_CHECK(appendRecoveryMap(&jpeg, &compressed_map, &metadata, dest));
+ jpegr_exif_struct new_exif;
+ if (exif == nullptr || exif->data == nullptr) {
+ new_exif.length = PSEUDO_EXIF_PACKAGE_LENGTH;
+ } else {
+ new_exif.length = exif->length + EXIF_J_R_ENTRY_LENGTH;
+ }
+
+ new_exif.data = new uint8_t[new_exif.length];
+ std::unique_ptr<uint8_t[]> new_exif_data;
+ new_exif_data.reset(reinterpret_cast<uint8_t*>(new_exif.data));
+ JPEGR_CHECK(updateExif(exif, &new_exif));
+
+ JPEGR_CHECK(appendRecoveryMap(&jpeg, &compressed_map, &new_exif, &metadata, dest));
return NO_ERROR;
}
@@ -242,7 +361,41 @@
compressed_map.data = compressed_map_data.get();
JPEGR_CHECK(compressRecoveryMap(&map, &compressed_map));
- JPEGR_CHECK(appendRecoveryMap(compressed_jpeg_image, &compressed_map, &metadata, dest));
+ // Extract EXIF from JPEG without decoding.
+ JpegDecoder jpeg_decoder;
+ if (!jpeg_decoder.extractEXIF(compressed_jpeg_image->data, compressed_jpeg_image->length)) {
+ return ERROR_JPEGR_DECODE_ERROR;
+ }
+
+ jpegr_exif_struct exif;
+ exif.data = nullptr;
+ exif.length = 0;
+ // Delete EXIF package if it appears, and update exif.
+ if (jpeg_decoder.getEXIFPos() != 0) {
+ int new_length = compressed_jpeg_image->length - jpeg_decoder.getEXIFSize() - 4;
+ memcpy((uint8_t*)compressed_jpeg_image->data + jpeg_decoder.getEXIFPos() - 4,
+ (uint8_t*)compressed_jpeg_image->data + jpeg_decoder.getEXIFPos()
+ + jpeg_decoder.getEXIFSize(),
+ compressed_jpeg_image->length - jpeg_decoder.getEXIFPos() - jpeg_decoder.getEXIFSize());
+ compressed_jpeg_image->length = new_length;
+ exif.data = jpeg_decoder.getEXIFPtr();
+ exif.length = jpeg_decoder.getEXIFSize();
+ }
+
+ jpegr_exif_struct new_exif;
+ if (exif.data == nullptr) {
+ new_exif.length = PSEUDO_EXIF_PACKAGE_LENGTH;
+ } else {
+ new_exif.length = exif.length + EXIF_J_R_ENTRY_LENGTH;
+ }
+
+ new_exif.data = new uint8_t[new_exif.length];
+ std::unique_ptr<uint8_t[]> new_exif_data;
+ new_exif_data.reset(reinterpret_cast<uint8_t*>(new_exif.data));
+ JPEGR_CHECK(updateExif(&exif, &new_exif));
+
+ JPEGR_CHECK(appendRecoveryMap(
+ compressed_jpeg_image, &compressed_map, &new_exif, &metadata, dest));
return NO_ERROR;
}
@@ -268,6 +421,32 @@
uncompressed_yuv_420_image.height = jpeg_decoder.getDecompressedImageHeight();
uncompressed_yuv_420_image.colorGamut = compressed_jpeg_image->colorGamut;
+ jpegr_exif_struct exif;
+ exif.data = nullptr;
+ exif.length = 0;
+ // Delete EXIF package if it appears, and update exif.
+ if (jpeg_decoder.getEXIFPos() != 0) {
+ int new_length = compressed_jpeg_image->length - jpeg_decoder.getEXIFSize() - 4;
+ memcpy((uint8_t*)compressed_jpeg_image->data + jpeg_decoder.getEXIFPos() - 4,
+ (uint8_t*)compressed_jpeg_image->data + jpeg_decoder.getEXIFPos()
+ + jpeg_decoder.getEXIFSize(),
+ compressed_jpeg_image->length - jpeg_decoder.getEXIFPos() - jpeg_decoder.getEXIFSize());
+ compressed_jpeg_image->length = new_length;
+ exif.data = jpeg_decoder.getEXIFPtr();
+ exif.length = jpeg_decoder.getEXIFSize();
+ }
+
+ jpegr_exif_struct new_exif;
+ if (exif.data == nullptr) {
+ new_exif.length = PSEUDO_EXIF_PACKAGE_LENGTH;
+ } else {
+ new_exif.length = exif.length + EXIF_J_R_ENTRY_LENGTH;
+ }
+ new_exif.data = new uint8_t[new_exif.length];
+ std::unique_ptr<uint8_t[]> new_exif_data;
+ new_exif_data.reset(reinterpret_cast<uint8_t*>(new_exif.data));
+ JPEGR_CHECK(updateExif(&exif, &new_exif));
+
if (uncompressed_p010_image->width != uncompressed_yuv_420_image.width
|| uncompressed_p010_image->height != uncompressed_yuv_420_image.height) {
return ERROR_JPEGR_RESOLUTION_MISMATCH;
@@ -292,7 +471,8 @@
compressed_map.data = compressed_map_data.get();
JPEGR_CHECK(compressRecoveryMap(&map, &compressed_map));
- JPEGR_CHECK(appendRecoveryMap(compressed_jpeg_image, &compressed_map, &metadata, dest));
+ JPEGR_CHECK(appendRecoveryMap(
+ compressed_jpeg_image, &compressed_map, &new_exif, &metadata, dest));
return NO_ERROR;
}
@@ -333,14 +513,24 @@
jpegr_metadata metadata;
JPEGR_CHECK(extractRecoveryMap(compressed_jpegr_image, &compressed_map));
- jpegr_uncompressed_struct map;
- JPEGR_CHECK(decompressRecoveryMap(&compressed_map, &map));
JpegDecoder jpeg_decoder;
if (!jpeg_decoder.decompressImage(compressed_jpegr_image->data, compressed_jpegr_image->length)) {
return ERROR_JPEGR_DECODE_ERROR;
}
+ JpegDecoder recovery_map_decoder;
+ if (!recovery_map_decoder.decompressImage(compressed_map.data,
+ compressed_map.length)) {
+ return ERROR_JPEGR_DECODE_ERROR;
+ }
+
+ jpegr_uncompressed_struct map;
+ map.data = recovery_map_decoder.getDecompressedImagePtr();
+ map.width = recovery_map_decoder.getDecompressedImageWidth();
+ map.height = recovery_map_decoder.getDecompressedImageHeight();
+
+
jpegr_uncompressed_struct uncompressed_yuv_420_image;
uncompressed_yuv_420_image.data = jpeg_decoder.getDecompressedImagePtr();
uncompressed_yuv_420_image.width = jpeg_decoder.getDecompressedImageWidth();
@@ -363,25 +553,6 @@
return NO_ERROR;
}
-status_t RecoveryMap::decompressRecoveryMap(jr_compressed_ptr compressed_recovery_map,
- jr_uncompressed_ptr dest) {
- if (compressed_recovery_map == nullptr || dest == nullptr) {
- return ERROR_JPEGR_INVALID_NULL_PTR;
- }
-
- JpegDecoder jpeg_decoder;
- if (!jpeg_decoder.decompressImage(compressed_recovery_map->data,
- compressed_recovery_map->length)) {
- return ERROR_JPEGR_DECODE_ERROR;
- }
-
- dest->data = jpeg_decoder.getDecompressedImagePtr();
- dest->width = jpeg_decoder.getDecompressedImageWidth();
- dest->height = jpeg_decoder.getDecompressedImageHeight();
-
- return NO_ERROR;
-}
-
status_t RecoveryMap::compressRecoveryMap(jr_uncompressed_ptr uncompressed_recovery_map,
jr_compressed_ptr dest) {
if (uncompressed_recovery_map == nullptr || dest == nullptr) {
@@ -447,6 +618,9 @@
ColorTransformFn hdrInvOetf = nullptr;
float hdr_white_nits = 0.0f;
switch (metadata->transferFunction) {
+ case JPEGR_TF_LINEAR:
+ hdrInvOetf = identityConversion;
+ break;
case JPEGR_TF_HLG:
hdrInvOetf = hlgInvOetf;
hdr_white_nits = kHlgMaxNits;
@@ -544,6 +718,9 @@
ColorTransformFn hdrOetf = nullptr;
switch (metadata->transferFunction) {
+ case JPEGR_TF_LINEAR:
+ hdrOetf = identityConversion;
+ break;
case JPEGR_TF_HLG:
hdrOetf = hlgOetf;
break;
@@ -562,7 +739,7 @@
float recovery = sampleMap(uncompressed_recovery_map, kMapDimensionScaleFactor, x, y);
Color rgb_hdr = applyRecovery(rgb_sdr, recovery, metadata->rangeScalingFactor);
- Color rgb_gamma_hdr = hdrOetf(rgb_hdr);
+ Color rgb_gamma_hdr = hdrOetf(rgb_hdr / metadata->rangeScalingFactor);
uint32_t rgba1010102 = colorToRgba1010102(rgb_gamma_hdr);
size_t pixel_idx = x + y * width;
@@ -631,106 +808,87 @@
return extractPrimaryImageAndRecoveryMap(compressed_jpegr_image, nullptr, dest);
}
+// JPEG/R structure:
+// SOI (ff d8)
+// APP1 (ff e1)
+// 2 bytes of length (2 + length of exif package)
+// EXIF package (this includes the first two bytes representing the package length)
+// APP1 (ff e1)
+// 2 bytes of length (2 + 29 + length of xmp package)
+// name space ("http://ns.adobe.com/xap/1.0/\0")
+// xmp
+// primary image (without the first two bytes (SOI) and without EXIF, may have other packages)
+// secondary image (the recovery map)
+//
+// Metadata versions we are using:
+// ECMA TR-98 for JFIF marker
+// Exif 2.2 spec for EXIF marker
+// Adobe XMP spec part 3 for XMP marker
+// ICC v4.3 spec for ICC
status_t RecoveryMap::appendRecoveryMap(jr_compressed_ptr compressed_jpeg_image,
jr_compressed_ptr compressed_recovery_map,
+ jr_exif_ptr exif,
jr_metadata_ptr metadata,
jr_compressed_ptr dest) {
if (compressed_jpeg_image == nullptr
|| compressed_recovery_map == nullptr
+ || exif == nullptr
|| metadata == nullptr
|| dest == nullptr) {
return ERROR_JPEGR_INVALID_NULL_PTR;
}
- const string xmp = generateXmp(compressed_recovery_map->length, *metadata);
- const string nameSpace = "http://ns.adobe.com/xap/1.0/\0";
- const int nameSpaceLength = nameSpace.size() + 1; // need to count the null terminator
-
- // 2 bytes: APP1 sign (ff e1)
- // 29 bytes: length of name space "http://ns.adobe.com/xap/1.0/\0",
- // x bytes: length of xmp packet
-
- const int length = 3 + nameSpaceLength + xmp.size();
- const uint8_t lengthH = ((length >> 8) & 0xff);
- const uint8_t lengthL = (length & 0xff);
-
int pos = 0;
- // JPEG/R structure:
- // SOI (ff d8)
- // APP1 (ff e1)
- // 2 bytes of length (2 + 29 + length of xmp packet)
- // name space ("http://ns.adobe.com/xap/1.0/\0")
- // xmp
- // primary image (without the first two bytes, the SOI sign)
- // secondary image (the recovery map)
+ // Write SOI
JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kStart, 1, pos));
JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kSOI, 1, pos));
- JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kStart, 1, pos));
- JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kAPP1, 1, pos));
- JPEGR_CHECK(Write(dest, &lengthH, 1, pos));
- JPEGR_CHECK(Write(dest, &lengthL, 1, pos));
- JPEGR_CHECK(Write(dest, (void*)nameSpace.c_str(), nameSpaceLength, pos));
- JPEGR_CHECK(Write(dest, (void*)xmp.c_str(), xmp.size(), pos));
+
+ // Write EXIF
+ {
+ const int length = 2 + exif->length;
+ const uint8_t lengthH = ((length >> 8) & 0xff);
+ const uint8_t lengthL = (length & 0xff);
+ JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kStart, 1, pos));
+ JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kAPP1, 1, pos));
+ JPEGR_CHECK(Write(dest, &lengthH, 1, pos));
+ JPEGR_CHECK(Write(dest, &lengthL, 1, pos));
+ JPEGR_CHECK(Write(dest, exif->data, exif->length, pos));
+ }
+
+ // Prepare and write XMP
+ {
+ const string xmp = generateXmp(compressed_recovery_map->length, *metadata);
+ const string nameSpace = "http://ns.adobe.com/xap/1.0/\0";
+ const int nameSpaceLength = nameSpace.size() + 1; // need to count the null terminator
+ // 2 bytes: representing the length of the package
+ // 29 bytes: length of name space "http://ns.adobe.com/xap/1.0/\0",
+ // x bytes: length of xmp packet
+ const int length = 3 + nameSpaceLength + xmp.size();
+ const uint8_t lengthH = ((length >> 8) & 0xff);
+ const uint8_t lengthL = (length & 0xff);
+ JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kStart, 1, pos));
+ JPEGR_CHECK(Write(dest, &photos_editing_formats::image_io::JpegMarker::kAPP1, 1, pos));
+ JPEGR_CHECK(Write(dest, &lengthH, 1, pos));
+ JPEGR_CHECK(Write(dest, &lengthL, 1, pos));
+ JPEGR_CHECK(Write(dest, (void*)nameSpace.c_str(), nameSpaceLength, pos));
+ JPEGR_CHECK(Write(dest, (void*)xmp.c_str(), xmp.size(), pos));
+ }
+
+ // Write primary image
JPEGR_CHECK(Write(dest,
(uint8_t*)compressed_jpeg_image->data + 2, compressed_jpeg_image->length - 2, pos));
+
+ // Write secondary image
JPEGR_CHECK(Write(dest, compressed_recovery_map->data, compressed_recovery_map->length, pos));
+
+ // Set back length
dest->length = pos;
+ // Done!
return NO_ERROR;
}
-string RecoveryMap::generateXmp(int secondary_image_length, jpegr_metadata& metadata) {
- const string kContainerPrefix = "GContainer";
- const string kContainerUri = "http://ns.google.com/photos/1.0/container/";
- const string kItemPrefix = "Item";
- const string kRecoveryMap = "RecoveryMap";
- const string kDirectory = "Directory";
- const string kImageJpeg = "image/jpeg";
- const string kItem = "Item";
- const string kLength = "Length";
- const string kMime = "Mime";
- const string kPrimary = "Primary";
- const string kSemantic = "Semantic";
- const string kVersion = "Version";
-
- const string kConDir = Name(kContainerPrefix, kDirectory);
- const string kContainerItem = Name(kContainerPrefix, kItem);
- const string kItemLength = Name(kItemPrefix, kLength);
- const string kItemMime = Name(kItemPrefix, kMime);
- const string kItemSemantic = Name(kItemPrefix, kSemantic);
-
- const vector<string> kConDirSeq({kConDir, string("rdf:Seq")});
- const vector<string> kLiItem({string("rdf:li"), kContainerItem});
-
- std::stringstream ss;
- photos_editing_formats::image_io::XmlWriter writer(ss);
- writer.StartWritingElement("x:xmpmeta");
- writer.WriteXmlns("x", "adobe:ns:meta/");
- writer.WriteAttributeNameAndValue("x:xmptk", "Adobe XMP Core 5.1.2");
- writer.StartWritingElement("rdf:RDF");
- writer.WriteXmlns("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
- writer.StartWritingElement("rdf:Description");
- writer.WriteXmlns(kContainerPrefix, kContainerUri);
- writer.WriteElementAndContent(Name(kContainerPrefix, kVersion), metadata.version);
- writer.WriteElementAndContent(Name(kContainerPrefix, "rangeScalingFactor"),
- metadata.rangeScalingFactor);
- // TODO: determine structure for hdr10 metadata
- // TODO: write rest of metadata
- writer.StartWritingElements(kConDirSeq);
- size_t item_depth = writer.StartWritingElements(kLiItem);
- writer.WriteAttributeNameAndValue(kItemSemantic, kPrimary);
- writer.WriteAttributeNameAndValue(kItemMime, kImageJpeg);
- writer.FinishWritingElementsToDepth(item_depth);
- writer.StartWritingElements(kLiItem);
- writer.WriteAttributeNameAndValue(kItemSemantic, kRecoveryMap);
- writer.WriteAttributeNameAndValue(kItemMime, kImageJpeg);
- writer.WriteAttributeNameAndValue(kItemLength, secondary_image_length);
- writer.FinishWriting();
-
- return ss.str();
-}
-
status_t RecoveryMap::toneMap(jr_uncompressed_ptr uncompressed_p010_image,
jr_uncompressed_ptr dest) {
if (uncompressed_p010_image == nullptr || dest == nullptr) {
diff --git a/libs/jpegrecoverymap/recoverymapmath.cpp b/libs/jpegrecoverymap/recoverymapmath.cpp
index e838f43..9ed2949 100644
--- a/libs/jpegrecoverymap/recoverymapmath.cpp
+++ b/libs/jpegrecoverymap/recoverymapmath.cpp
@@ -336,9 +336,9 @@
>> 6;
// Conversions include taking narrow-range into account.
- return {{{ static_cast<float>(y_uint) / 940.0f,
- (static_cast<float>(u_uint) - 64.0f) / 940.0f - 0.5f,
- (static_cast<float>(v_uint) - 64.0f) / 940.0f - 0.5f }}};
+ return {{{ (static_cast<float>(y_uint) - 64.0f) / 876.0f,
+ (static_cast<float>(u_uint) - 64.0f) / 896.0f - 0.5f,
+ (static_cast<float>(v_uint) - 64.0f) / 896.0f - 0.5f }}};
}
typedef Color (*getPixelFn)(jr_uncompressed_ptr, size_t, size_t);
diff --git a/libs/jpegrecoverymap/recoverymaputils.cpp b/libs/jpegrecoverymap/recoverymaputils.cpp
index fe46cba..63b25f7 100644
--- a/libs/jpegrecoverymap/recoverymaputils.cpp
+++ b/libs/jpegrecoverymap/recoverymaputils.cpp
@@ -17,26 +17,36 @@
#include <jpegrecoverymap/recoverymaputils.h>
#include <jpegrecoverymap/recoverymap.h>
#include <image_io/xml/xml_reader.h>
+#include <image_io/xml/xml_writer.h>
#include <image_io/base/message_handler.h>
#include <image_io/xml/xml_element_rules.h>
#include <image_io/xml/xml_handler.h>
#include <image_io/xml/xml_rule.h>
-#include <string>
-#include <sstream>
-
using namespace photos_editing_formats::image_io;
using namespace std;
namespace android::recoverymap {
+/*
+ * Helper function used for generating XMP metadata.
+ *
+ * @param prefix The prefix part of the name.
+ * @param suffix The suffix part of the name.
+ * @return A name of the form "prefix:suffix".
+ */
+string Name(const string &prefix, const string &suffix) {
+ std::stringstream ss;
+ ss << prefix << ":" << suffix;
+ return ss.str();
+}
// Extremely simple XML Handler - just searches for interesting elements
class XMPXmlHandler : public XmlHandler {
public:
XMPXmlHandler() : XmlHandler() {
- rangeScalingFactorState = NotStrarted;
+ gContainerItemState = NotStrarted;
}
enum ParseState {
@@ -48,11 +58,11 @@
virtual DataMatchResult StartElement(const XmlTokenContext& context) {
string val;
if (context.BuildTokenValue(&val)) {
- if (!val.compare(rangeScalingFactorName)) {
- rangeScalingFactorState = Started;
+ if (!val.compare(gContainerItemName)) {
+ gContainerItemState = Started;
} else {
- if (rangeScalingFactorState != Done) {
- rangeScalingFactorState = NotStrarted;
+ if (gContainerItemState != Done) {
+ gContainerItemState = NotStrarted;
}
}
}
@@ -60,24 +70,45 @@
}
virtual DataMatchResult FinishElement(const XmlTokenContext& context) {
- if (rangeScalingFactorState == Started) {
- rangeScalingFactorState = Done;
+ if (gContainerItemState == Started) {
+ gContainerItemState = Done;
+ lastAttributeName = "";
}
return context.GetResult();
}
- virtual DataMatchResult ElementContent(const XmlTokenContext& context) {
+ virtual DataMatchResult AttributeName(const XmlTokenContext& context) {
string val;
- if (rangeScalingFactorState == Started) {
+ if (gContainerItemState == Started) {
if (context.BuildTokenValue(&val)) {
- rangeScalingFactorStr.assign(val);
+ if (!val.compare(rangeScalingFactorAttrName)) {
+ lastAttributeName = rangeScalingFactorAttrName;
+ } else if (!val.compare(transferFunctionAttrName)) {
+ lastAttributeName = transferFunctionAttrName;
+ } else {
+ lastAttributeName = "";
+ }
+ }
+ }
+ return context.GetResult();
+ }
+
+ virtual DataMatchResult AttributeValue(const XmlTokenContext& context) {
+ string val;
+ if (gContainerItemState == Started) {
+ if (context.BuildTokenValue(&val, true)) {
+ if (!lastAttributeName.compare(rangeScalingFactorAttrName)) {
+ rangeScalingFactorStr = val;
+ } else if (!lastAttributeName.compare(transferFunctionAttrName)) {
+ transferFunctionStr = val;
+ }
}
}
return context.GetResult();
}
bool getRangeScalingFactor(float* scaling_factor) {
- if (rangeScalingFactorState == Done) {
+ if (gContainerItemState == Done) {
stringstream ss(rangeScalingFactorStr);
float val;
if (ss >> val) {
@@ -92,19 +123,67 @@
}
bool getTransferFunction(jpegr_transfer_function* transfer_function) {
- *transfer_function = JPEGR_TF_HLG;
+ if (gContainerItemState == Done) {
+ stringstream ss(transferFunctionStr);
+ int val;
+ if (ss >> val) {
+ *transfer_function = static_cast<jpegr_transfer_function>(val);
+ return true;
+ } else {
+ return false;
+ }
+ } else {
+ return false;
+ }
return true;
}
private:
- static const string rangeScalingFactorName;
+ static const string gContainerItemName;
+ static const string rangeScalingFactorAttrName;
+ static const string transferFunctionAttrName;
string rangeScalingFactorStr;
- ParseState rangeScalingFactorState;
+ string transferFunctionStr;
+ string lastAttributeName;
+ ParseState gContainerItemState;
};
-const string XMPXmlHandler::rangeScalingFactorName = "GContainer:rangeScalingFactor";
+const string XMPXmlHandler::gContainerItemName = "GContainer:Item";
+const string XMPXmlHandler::rangeScalingFactorAttrName = "RecoveryMap:RangeScalingFactor";
+const string XMPXmlHandler::transferFunctionAttrName = "RecoveryMap:TransferFunction";
+const string kContainerPrefix = "GContainer";
+const string kContainerUri = "http://ns.google.com/photos/1.0/container/";
+const string kRecoveryMapUri = "http://ns.google.com/photos/1.0/recoverymap/";
+const string kItemPrefix = "Item";
+const string kRecoveryMap = "RecoveryMap";
+const string kDirectory = "Directory";
+const string kImageJpeg = "image/jpeg";
+const string kItem = "Item";
+const string kLength = "Length";
+const string kMime = "Mime";
+const string kPrimary = "Primary";
+const string kSemantic = "Semantic";
+const string kVersion = "Version";
+const string kHdr10Metadata = "HDR10Metadata";
+const string kSt2086Metadata = "ST2086Metadata";
+const string kSt2086Coordinate = "ST2086Coordinate";
+const string kSt2086CoordinateX = "ST2086CoordinateX";
+const string kSt2086CoordinateY = "ST2086CoordinateY";
+const string kSt2086Primary = "ST2086Primary";
+const int kSt2086PrimaryRed = 0;
+const int kSt2086PrimaryGreen = 1;
+const int kSt2086PrimaryBlue = 2;
+const int kSt2086PrimaryWhite = 3;
+const int kGContainerVersion = 1;
+
+const string kConDir = Name(kContainerPrefix, kDirectory);
+const string kContainerItem = Name(kContainerPrefix, kItem);
+const string kItemLength = Name(kItemPrefix, kLength);
+const string kItemMime = Name(kItemPrefix, kMime);
+const string kItemSemantic = Name(kItemPrefix, kSemantic);
+
bool getMetadataFromXMP(uint8_t* xmp_data, size_t xmp_size, jpegr_metadata* metadata) {
string nameSpace = "http://ns.adobe.com/xap/1.0/\0";
@@ -150,4 +229,96 @@
return true;
}
+string generateXmp(int secondary_image_length, jpegr_metadata& metadata) {
+ const vector<string> kConDirSeq({kConDir, string("rdf:Seq")});
+ const vector<string> kLiItem({string("rdf:li"), kContainerItem});
+
+ std::stringstream ss;
+ photos_editing_formats::image_io::XmlWriter writer(ss);
+ writer.StartWritingElement("x:xmpmeta");
+ writer.WriteXmlns("x", "adobe:ns:meta/");
+ writer.WriteAttributeNameAndValue("x:xmptk", "Adobe XMP Core 5.1.2");
+ writer.StartWritingElement("rdf:RDF");
+ writer.WriteXmlns("rdf", "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
+ writer.StartWritingElement("rdf:Description");
+ writer.WriteXmlns(kContainerPrefix, kContainerUri);
+ writer.WriteXmlns(kRecoveryMap, kRecoveryMapUri);
+ writer.WriteElementAndContent(Name(kContainerPrefix, kVersion), kGContainerVersion);
+ writer.StartWritingElements(kConDirSeq);
+ size_t item_depth = writer.StartWritingElements(kLiItem);
+ writer.WriteAttributeNameAndValue(kItemSemantic, kPrimary);
+ writer.WriteAttributeNameAndValue(kItemMime, kImageJpeg);
+ writer.WriteAttributeNameAndValue(Name(kRecoveryMap, kVersion), metadata.version);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "RangeScalingFactor"), metadata.rangeScalingFactor);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "TransferFunction"), metadata.transferFunction);
+ if (metadata.transferFunction == JPEGR_TF_PQ) {
+ writer.StartWritingElement(Name(kRecoveryMap, kHdr10Metadata));
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "HDR10MaxFALL"), metadata.hdr10Metadata.maxFALL);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "HDR10MaxCLL"), metadata.hdr10Metadata.maxCLL);
+ writer.StartWritingElement(Name(kRecoveryMap, kSt2086Metadata));
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "ST2086MaxLuminance"),
+ metadata.hdr10Metadata.st2086Metadata.maxLuminance);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, "ST2086MinLuminance"),
+ metadata.hdr10Metadata.st2086Metadata.minLuminance);
+
+ // red
+ writer.StartWritingElement(Name(kRecoveryMap, kSt2086Coordinate));
+ writer.WriteAttributeNameAndValue(Name(kRecoveryMap, kSt2086Primary), kSt2086PrimaryRed);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateX),
+ metadata.hdr10Metadata.st2086Metadata.redPrimary.x);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateY),
+ metadata.hdr10Metadata.st2086Metadata.redPrimary.y);
+ writer.FinishWritingElement();
+
+ // green
+ writer.StartWritingElement(Name(kRecoveryMap, kSt2086Coordinate));
+ writer.WriteAttributeNameAndValue(Name(kRecoveryMap, kSt2086Primary), kSt2086PrimaryGreen);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateX),
+ metadata.hdr10Metadata.st2086Metadata.greenPrimary.x);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateY),
+ metadata.hdr10Metadata.st2086Metadata.greenPrimary.y);
+ writer.FinishWritingElement();
+
+ // blue
+ writer.StartWritingElement(Name(kRecoveryMap, kSt2086Coordinate));
+ writer.WriteAttributeNameAndValue(Name(kRecoveryMap, kSt2086Primary), kSt2086PrimaryBlue);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateX),
+ metadata.hdr10Metadata.st2086Metadata.bluePrimary.x);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateY),
+ metadata.hdr10Metadata.st2086Metadata.bluePrimary.y);
+ writer.FinishWritingElement();
+
+ // white
+ writer.StartWritingElement(Name(kRecoveryMap, kSt2086Coordinate));
+ writer.WriteAttributeNameAndValue(Name(kRecoveryMap, kSt2086Primary), kSt2086PrimaryWhite);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateX),
+ metadata.hdr10Metadata.st2086Metadata.whitePoint.x);
+ writer.WriteAttributeNameAndValue(
+ Name(kRecoveryMap, kSt2086CoordinateY),
+ metadata.hdr10Metadata.st2086Metadata.whitePoint.y);
+ writer.FinishWritingElement();
+ }
+ writer.FinishWritingElementsToDepth(item_depth);
+ writer.StartWritingElements(kLiItem);
+ writer.WriteAttributeNameAndValue(kItemSemantic, kRecoveryMap);
+ writer.WriteAttributeNameAndValue(kItemMime, kImageJpeg);
+ writer.WriteAttributeNameAndValue(kItemLength, secondary_image_length);
+ writer.FinishWriting();
+
+ return ss.str();
+}
+
} // namespace android::recoverymap
\ No newline at end of file
diff --git a/libs/jpegrecoverymap/tests/data/raw_yuv420_image.yuv420 b/libs/jpegrecoverymap/tests/data/raw_yuv420_image.yuv420
new file mode 100644
index 0000000..c043da6
--- /dev/null
+++ b/libs/jpegrecoverymap/tests/data/raw_yuv420_image.yuv420
Binary files differ
diff --git a/libs/jpegrecoverymap/tests/recoverymap_test.cpp b/libs/jpegrecoverymap/tests/recoverymap_test.cpp
index 0f96723..c3c6fd4 100644
--- a/libs/jpegrecoverymap/tests/recoverymap_test.cpp
+++ b/libs/jpegrecoverymap/tests/recoverymap_test.cpp
@@ -15,15 +15,18 @@
*/
#include <jpegrecoverymap/recoverymap.h>
+#include <jpegrecoverymap/recoverymaputils.h>
#include <fcntl.h>
#include <fstream>
#include <gtest/gtest.h>
#include <utils/Log.h>
#define RAW_P010_IMAGE "/sdcard/Documents/raw_p010_image.p010"
-#define RAW_P010_IMAGE_WIDTH 1280
-#define RAW_P010_IMAGE_HEIGHT 720
+#define RAW_YUV420_IMAGE "/sdcard/Documents/raw_yuv420_image.yuv420"
#define JPEG_IMAGE "/sdcard/Documents/jpeg_image.jpg"
+#define TEST_IMAGE_WIDTH 1280
+#define TEST_IMAGE_HEIGHT 720
+#define DEFAULT_JPEG_QUALITY 90
#define SAVE_ENCODING_RESULT true
#define SAVE_DECODING_RESULT true
@@ -39,6 +42,7 @@
virtual void TearDown();
struct jpegr_uncompressed_struct mRawP010Image;
+ struct jpegr_uncompressed_struct mRawYuv420Image;
struct jpegr_compressed_struct mJpegImage;
};
@@ -48,6 +52,7 @@
void RecoveryMapTest::SetUp() {}
void RecoveryMapTest::TearDown() {
free(mRawP010Image.data);
+ free(mRawYuv420Image.data);
free(mJpegImage.data);
}
@@ -94,24 +99,101 @@
recovery_map.decodeJPEGR(nullptr, nullptr, nullptr, false);
}
-TEST_F(RecoveryMapTest, encodeFromP010ThenDecode) {
+TEST_F(RecoveryMapTest, writeXmpThenRead) {
+ jpegr_metadata metadata_expected;
+ metadata_expected.transferFunction = JPEGR_TF_HLG;
+ metadata_expected.rangeScalingFactor = 1.25;
+ int length_expected = 1000;
+ std::string xmp = generateXmp(1000, metadata_expected);
+
+ jpegr_metadata metadata_read;
+ EXPECT_TRUE(getMetadataFromXMP(reinterpret_cast<uint8_t*>(xmp[0]), xmp.size(), &metadata_read));
+ ASSERT_EQ(metadata_expected.transferFunction, metadata_read.transferFunction);
+ ASSERT_EQ(metadata_expected.rangeScalingFactor, metadata_read.rangeScalingFactor);
+
+}
+
+/* Test Encode API-0 and decode */
+// TODO: enable when tonemapper is ready.
+//TEST_F(RecoveryMapTest, encodeFromP010ThenDecode) {
+// int ret;
+//
+// // Load input files.
+// if (!loadFile(RAW_P010_IMAGE, mRawP010Image.data, nullptr)) {
+// FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
+// }
+// mRawP010Image.width = TEST_IMAGE_WIDTH;
+// mRawP010Image.height = TEST_IMAGE_HEIGHT;
+// mRawP010Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT2100;
+//
+// RecoveryMap recoveryMap;
+//
+// jpegr_compressed_struct jpegR;
+// jpegR.maxLength = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * sizeof(uint8_t);
+// jpegR.data = malloc(jpegR.maxLength);
+// ret = recoveryMap.encodeJPEGR(
+// &mRawP010Image, jpegr_transfer_function::JPEGR_TF_HLG, &jpegR, 90, nullptr);
+// if (ret != OK) {
+// FAIL() << "Error code is " << ret;
+// }
+// if (SAVE_ENCODING_RESULT) {
+// // Output image data to file
+// std::string filePath = "/sdcard/Documents/encoded_from_jpeg_input.jpgr";
+// std::ofstream imageFile(filePath.c_str(), std::ofstream::binary);
+// if (!imageFile.is_open()) {
+// ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
+// }
+// imageFile.write((const char*)jpegR.data, jpegR.length);
+// }
+//
+// jpegr_uncompressed_struct decodedJpegR;
+// int decodedJpegRSize = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * 4;
+// decodedJpegR.data = malloc(decodedJpegRSize);
+// ret = recoveryMap.decodeJPEGR(&jpegR, &decodedJpegR);
+// if (ret != OK) {
+// FAIL() << "Error code is " << ret;
+// }
+// if (SAVE_DECODING_RESULT) {
+// // Output image data to file
+// std::string filePath = "/sdcard/Documents/decoded_from_jpeg_input.rgb10";
+// std::ofstream imageFile(filePath.c_str(), std::ofstream::binary);
+// if (!imageFile.is_open()) {
+// ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
+// }
+// imageFile.write((const char*)decodedJpegR.data, decodedJpegRSize);
+// }
+//
+// free(jpegR.data);
+// free(decodedJpegR.data);
+//}
+
+/* Test Encode API-1 and decode */
+TEST_F(RecoveryMapTest, encodeFromRawHdrAndSdrThenDecode) {
int ret;
// Load input files.
if (!loadFile(RAW_P010_IMAGE, mRawP010Image.data, nullptr)) {
FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
}
- mRawP010Image.width = RAW_P010_IMAGE_WIDTH;
- mRawP010Image.height = RAW_P010_IMAGE_HEIGHT;
+ mRawP010Image.width = TEST_IMAGE_WIDTH;
+ mRawP010Image.height = TEST_IMAGE_HEIGHT;
mRawP010Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT2100;
+ if (!loadFile(RAW_YUV420_IMAGE, mRawYuv420Image.data, nullptr)) {
+ FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
+ }
+ mRawYuv420Image.width = TEST_IMAGE_WIDTH;
+ mRawYuv420Image.height = TEST_IMAGE_HEIGHT;
+ mRawYuv420Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT709;
+
RecoveryMap recoveryMap;
jpegr_compressed_struct jpegR;
- jpegR.maxLength = RAW_P010_IMAGE_WIDTH * RAW_P010_IMAGE_HEIGHT * sizeof(uint8_t);
+ jpegR.maxLength = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * sizeof(uint8_t);
jpegR.data = malloc(jpegR.maxLength);
ret = recoveryMap.encodeJPEGR(
- &mRawP010Image, jpegr_transfer_function::JPEGR_TF_HLG, &jpegR, 90, nullptr);
+ &mRawP010Image, &mRawYuv420Image, jpegr_transfer_function::JPEGR_TF_HLG, &jpegR,
+ DEFAULT_JPEG_QUALITY, nullptr);
if (ret != OK) {
FAIL() << "Error code is " << ret;
}
@@ -126,7 +208,7 @@
}
jpegr_uncompressed_struct decodedJpegR;
- int decodedJpegRSize = RAW_P010_IMAGE_WIDTH * RAW_P010_IMAGE_HEIGHT * 4;
+ int decodedJpegRSize = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * 4;
decodedJpegR.data = malloc(decodedJpegRSize);
ret = recoveryMap.decodeJPEGR(&jpegR, &decodedJpegR);
if (ret != OK) {
@@ -146,6 +228,72 @@
free(decodedJpegR.data);
}
+/* Test Encode API-2 and decode */
+TEST_F(RecoveryMapTest, encodeFromRawHdrAndSdrAndJpegThenDecode) {
+ int ret;
+
+ // Load input files.
+ if (!loadFile(RAW_P010_IMAGE, mRawP010Image.data, nullptr)) {
+ FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
+ }
+ mRawP010Image.width = TEST_IMAGE_WIDTH;
+ mRawP010Image.height = TEST_IMAGE_HEIGHT;
+ mRawP010Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT2100;
+
+ if (!loadFile(RAW_YUV420_IMAGE, mRawYuv420Image.data, nullptr)) {
+ FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
+ }
+ mRawYuv420Image.width = TEST_IMAGE_WIDTH;
+ mRawYuv420Image.height = TEST_IMAGE_HEIGHT;
+ mRawYuv420Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT709;
+
+ if (!loadFile(JPEG_IMAGE, mJpegImage.data, &mJpegImage.length)) {
+ FAIL() << "Load file " << JPEG_IMAGE << " failed";
+ }
+ mJpegImage.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT709;
+
+ RecoveryMap recoveryMap;
+
+ jpegr_compressed_struct jpegR;
+ jpegR.maxLength = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * sizeof(uint8_t);
+ jpegR.data = malloc(jpegR.maxLength);
+ ret = recoveryMap.encodeJPEGR(
+ &mRawP010Image, &mRawYuv420Image, &mJpegImage, jpegr_transfer_function::JPEGR_TF_HLG, &jpegR);
+ if (ret != OK) {
+ FAIL() << "Error code is " << ret;
+ }
+ if (SAVE_ENCODING_RESULT) {
+ // Output image data to file
+ std::string filePath = "/sdcard/Documents/encoded_from_jpeg_input.jpgr";
+ std::ofstream imageFile(filePath.c_str(), std::ofstream::binary);
+ if (!imageFile.is_open()) {
+ ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
+ }
+ imageFile.write((const char*)jpegR.data, jpegR.length);
+ }
+
+ jpegr_uncompressed_struct decodedJpegR;
+ int decodedJpegRSize = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * 4;
+ decodedJpegR.data = malloc(decodedJpegRSize);
+ ret = recoveryMap.decodeJPEGR(&jpegR, &decodedJpegR);
+ if (ret != OK) {
+ FAIL() << "Error code is " << ret;
+ }
+ if (SAVE_DECODING_RESULT) {
+ // Output image data to file
+ std::string filePath = "/sdcard/Documents/decoded_from_jpeg_input.rgb10";
+ std::ofstream imageFile(filePath.c_str(), std::ofstream::binary);
+ if (!imageFile.is_open()) {
+ ALOGE("%s: Unable to create file %s", __FUNCTION__, filePath.c_str());
+ }
+ imageFile.write((const char*)decodedJpegR.data, decodedJpegRSize);
+ }
+
+ free(jpegR.data);
+ free(decodedJpegR.data);
+}
+
+/* Test Encode API-3 and decode */
TEST_F(RecoveryMapTest, encodeFromJpegThenDecode) {
int ret;
@@ -153,8 +301,8 @@
if (!loadFile(RAW_P010_IMAGE, mRawP010Image.data, nullptr)) {
FAIL() << "Load file " << RAW_P010_IMAGE << " failed";
}
- mRawP010Image.width = RAW_P010_IMAGE_WIDTH;
- mRawP010Image.height = RAW_P010_IMAGE_HEIGHT;
+ mRawP010Image.width = TEST_IMAGE_WIDTH;
+ mRawP010Image.height = TEST_IMAGE_HEIGHT;
mRawP010Image.colorGamut = jpegr_color_gamut::JPEGR_COLORGAMUT_BT2100;
if (!loadFile(JPEG_IMAGE, mJpegImage.data, &mJpegImage.length)) {
@@ -165,7 +313,7 @@
RecoveryMap recoveryMap;
jpegr_compressed_struct jpegR;
- jpegR.maxLength = RAW_P010_IMAGE_WIDTH * RAW_P010_IMAGE_HEIGHT * sizeof(uint8_t);
+ jpegR.maxLength = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * sizeof(uint8_t);
jpegR.data = malloc(jpegR.maxLength);
ret = recoveryMap.encodeJPEGR(
&mRawP010Image, &mJpegImage, jpegr_transfer_function::JPEGR_TF_HLG, &jpegR);
@@ -183,7 +331,7 @@
}
jpegr_uncompressed_struct decodedJpegR;
- int decodedJpegRSize = RAW_P010_IMAGE_WIDTH * RAW_P010_IMAGE_HEIGHT * 4;
+ int decodedJpegRSize = TEST_IMAGE_WIDTH * TEST_IMAGE_HEIGHT * 4;
decodedJpegR.data = malloc(decodedJpegRSize);
ret = recoveryMap.decodeJPEGR(&jpegR, &decodedJpegR);
if (ret != OK) {
diff --git a/libs/jpegrecoverymap/tests/recoverymapmath_test.cpp b/libs/jpegrecoverymap/tests/recoverymapmath_test.cpp
index 169201c..f8dd490 100644
--- a/libs/jpegrecoverymap/tests/recoverymapmath_test.cpp
+++ b/libs/jpegrecoverymap/tests/recoverymapmath_test.cpp
@@ -36,9 +36,9 @@
}
Color P010(uint16_t y, uint16_t u, uint16_t v) {
- return {{{ static_cast<float>(y) / 940.0f,
- (static_cast<float>(u) - 64.0f) / 940.0f - 0.5f,
- (static_cast<float>(v) - 64.0f) / 940.0f - 0.5f }}};
+ return {{{ (static_cast<float>(y) - 64.0f) / 876.0f,
+ (static_cast<float>(u) - 64.0f) / 896.0f - 0.5f,
+ (static_cast<float>(v) - 64.0f) / 896.0f - 0.5f }}};
}
float Map(uint8_t e) {
@@ -821,7 +821,6 @@
bt2100Luminance(RgbBlue()) * kPqMaxNits, LuminanceEpsilon());
}
-//Color Recover(Color yuv_gamma, float recovery, float range_scaling_factor) {
TEST_F(RecoveryMapMathTest, ApplyMap) {
EXPECT_RGB_EQ(Recover(YuvWhite(), 1.0f, 8.0f),
RgbWhite() * 8.0f);
diff --git a/libs/nativedisplay/AChoreographer.cpp b/libs/nativedisplay/AChoreographer.cpp
index e64165f..66a40f1 100644
--- a/libs/nativedisplay/AChoreographer.cpp
+++ b/libs/nativedisplay/AChoreographer.cpp
@@ -16,8 +16,8 @@
#include <android-base/thread_annotations.h>
#include <android/gui/ISurfaceComposer.h>
+#include <gui/Choreographer.h>
#include <jni.h>
-#include <nativedisplay/Choreographer.h>
#include <private/android/choreographer.h>
#include <utils/Looper.h>
#include <utils/Timers.h>
diff --git a/libs/nativedisplay/Android.bp b/libs/nativedisplay/Android.bp
index 70de33d..8d8a2bc 100644
--- a/libs/nativedisplay/Android.bp
+++ b/libs/nativedisplay/Android.bp
@@ -56,7 +56,6 @@
":libgui_frame_event_aidl",
"AChoreographer.cpp",
"ADisplay.cpp",
- "Choreographer.cpp",
"surfacetexture/surface_texture.cpp",
"surfacetexture/SurfaceTexture.cpp",
"surfacetexture/ImageConsumer.cpp",
diff --git a/libs/nativewindow/AHardwareBuffer.cpp b/libs/nativewindow/AHardwareBuffer.cpp
index bbafbff..cf927db 100644
--- a/libs/nativewindow/AHardwareBuffer.cpp
+++ b/libs/nativewindow/AHardwareBuffer.cpp
@@ -617,15 +617,27 @@
static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::R_8) ==
AHARDWAREBUFFER_FORMAT_R8_UNORM,
"HAL and AHardwareBuffer pixel format don't match");
+ static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::R_16_UINT) ==
+ AHARDWAREBUFFER_FORMAT_R16_UINT,
+ "HAL and AHardwareBuffer pixel format don't match");
+ static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::RG_1616_UINT) ==
+ AHARDWAREBUFFER_FORMAT_R16G16_UINT,
+ "HAL and AHardwareBuffer pixel format don't match");
+ static_assert(static_cast<int>(aidl::android::hardware::graphics::common::PixelFormat::RGBA_10101010) ==
+ AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM,
+ "HAL and AHardwareBuffer pixel format don't match");
switch (format) {
case AHARDWAREBUFFER_FORMAT_R8_UNORM:
+ case AHARDWAREBUFFER_FORMAT_R16_UINT:
+ case AHARDWAREBUFFER_FORMAT_R16G16_UINT:
case AHARDWAREBUFFER_FORMAT_R8G8B8A8_UNORM:
case AHARDWAREBUFFER_FORMAT_R8G8B8X8_UNORM:
case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM:
case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM:
case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:
case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM:
+ case AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM:
case AHARDWAREBUFFER_FORMAT_BLOB:
case AHARDWAREBUFFER_FORMAT_D16_UNORM:
case AHARDWAREBUFFER_FORMAT_D24_UNORM:
@@ -677,6 +689,7 @@
return 1;
case AHARDWAREBUFFER_FORMAT_R5G6B5_UNORM:
case AHARDWAREBUFFER_FORMAT_D16_UNORM:
+ case AHARDWAREBUFFER_FORMAT_R16_UINT:
return 2;
case AHARDWAREBUFFER_FORMAT_R8G8B8_UNORM:
case AHARDWAREBUFFER_FORMAT_D24_UNORM:
@@ -686,8 +699,10 @@
case AHARDWAREBUFFER_FORMAT_D32_FLOAT:
case AHARDWAREBUFFER_FORMAT_R10G10B10A2_UNORM:
case AHARDWAREBUFFER_FORMAT_D24_UNORM_S8_UINT:
+ case AHARDWAREBUFFER_FORMAT_R16G16_UINT:
return 4;
case AHARDWAREBUFFER_FORMAT_R16G16B16A16_FLOAT:
+ case AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM:
return 8;
default:
return 0;
diff --git a/libs/nativewindow/include/android/hardware_buffer.h b/libs/nativewindow/include/android/hardware_buffer.h
index c35507b..b2e8bea 100644
--- a/libs/nativewindow/include/android/hardware_buffer.h
+++ b/libs/nativewindow/include/android/hardware_buffer.h
@@ -173,6 +173,27 @@
* OpenGL ES: GR_GL_R8
*/
AHARDWAREBUFFER_FORMAT_R8_UNORM = 0x38,
+
+ /**
+ * Corresponding formats:
+ * Vulkan: VK_FORMAT_R16_UINT
+ * OpenGL ES: GR_GL_R16UI
+ */
+ AHARDWAREBUFFER_FORMAT_R16_UINT = 0x39,
+
+ /**
+ * Corresponding formats:
+ * Vulkan: VK_FORMAT_R16G16_UINT
+ * OpenGL ES: GR_GL_RG16UI
+ */
+ AHARDWAREBUFFER_FORMAT_R16G16_UINT = 0x3a,
+
+ /**
+ * Corresponding formats:
+ * Vulkan: VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16
+ * OpenGL ES: N/A
+ */
+ AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM = 0x3b,
};
/**
diff --git a/libs/renderengine/Android.bp b/libs/renderengine/Android.bp
index 04e24ed..b8fd1b2 100644
--- a/libs/renderengine/Android.bp
+++ b/libs/renderengine/Android.bp
@@ -111,14 +111,30 @@
],
}
+// Used to consolidate and simplify pulling Skia & Skia deps into targets that depend on
+// librenderengine. This allows shared deps to be deduplicated (e.g. Perfetto), which doesn't seem
+// possible if libskia_renderengine is just pulled into librenderengine via whole_static_libs.
+cc_defaults {
+ name: "librenderengine_deps",
+ defaults: ["skia_renderengine_deps"],
+ static_libs: ["libskia_renderengine"],
+}
+
+// Note: if compilation fails when adding librenderengine as a dependency, try adding
+// librenderengine_deps to the defaults field of your dependent target.
cc_library_static {
name: "librenderengine",
- defaults: ["librenderengine_defaults"],
+ defaults: [
+ "librenderengine_defaults",
+ "librenderengine_deps",
+ ],
double_loadable: true,
cflags: [
"-fvisibility=hidden",
"-Werror=format",
"-Wno-unused-parameter",
+ // TODO: Investigate reducing pinned-memory usage (b/263377839)
+ "-DRE_SKIAVK",
],
srcs: [
":librenderengine_sources",
@@ -132,7 +148,6 @@
include_dirs: [
"external/skia/src/gpu",
],
- whole_static_libs: ["libskia_renderengine"],
lto: {
thin: true,
},
diff --git a/libs/renderengine/benchmark/Android.bp b/libs/renderengine/benchmark/Android.bp
index afbe6cf..55c34cd 100644
--- a/libs/renderengine/benchmark/Android.bp
+++ b/libs/renderengine/benchmark/Android.bp
@@ -25,7 +25,7 @@
name: "librenderengine_bench",
defaults: [
"android.hardware.graphics.composer3-ndk_shared",
- "skia_deps",
+ "librenderengine_deps",
"surfaceflinger_defaults",
],
srcs: [
diff --git a/libs/renderengine/tests/Android.bp b/libs/renderengine/tests/Android.bp
index 6f328d7..50e166d 100644
--- a/libs/renderengine/tests/Android.bp
+++ b/libs/renderengine/tests/Android.bp
@@ -25,7 +25,7 @@
name: "librenderengine_test",
defaults: [
"android.hardware.graphics.composer3-ndk_shared",
- "skia_deps",
+ "librenderengine_deps",
"surfaceflinger_defaults",
],
test_suites: ["device-tests"],
diff --git a/libs/sensor/Sensor.cpp b/libs/sensor/Sensor.cpp
index ec0ced8..fb895f5 100644
--- a/libs/sensor/Sensor.cpp
+++ b/libs/sensor/Sensor.cpp
@@ -264,10 +264,6 @@
mStringType = SENSOR_STRING_TYPE_HEART_BEAT;
mFlags |= SENSOR_FLAG_SPECIAL_REPORTING_MODE;
break;
-
- // TODO: Placeholder for LLOB sensor type
-
-
case SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED:
mStringType = SENSOR_STRING_TYPE_ACCELEROMETER_UNCALIBRATED;
mFlags |= SENSOR_FLAG_CONTINUOUS_MODE;
diff --git a/libs/ui/PublicFormat.cpp b/libs/ui/PublicFormat.cpp
index 78e82da..c9663ed 100644
--- a/libs/ui/PublicFormat.cpp
+++ b/libs/ui/PublicFormat.cpp
@@ -14,14 +14,15 @@
* limitations under the License.
*/
-#include <ui/GraphicTypes.h> // ui::Dataspace
+#include "aidl/android/hardware/graphics/common/Dataspace.h"
#include <ui/PublicFormat.h>
+
// ----------------------------------------------------------------------------
namespace android {
// ----------------------------------------------------------------------------
-using ui::Dataspace;
+using ::aidl::android::hardware::graphics::common::Dataspace;
int mapPublicFormatToHalFormat(PublicFormat f) {
switch (f) {
@@ -29,6 +30,7 @@
case PublicFormat::DEPTH_POINT_CLOUD:
case PublicFormat::DEPTH_JPEG:
case PublicFormat::HEIC:
+ case PublicFormat::JPEG_R:
return HAL_PIXEL_FORMAT_BLOB;
case PublicFormat::DEPTH16:
return HAL_PIXEL_FORMAT_Y16;
@@ -47,7 +49,7 @@
Dataspace dataspace;
switch (f) {
case PublicFormat::JPEG:
- dataspace = Dataspace::V0_JFIF;
+ dataspace = Dataspace::JFIF;
break;
case PublicFormat::DEPTH_POINT_CLOUD:
case PublicFormat::DEPTH16:
@@ -64,7 +66,7 @@
case PublicFormat::YUV_420_888:
case PublicFormat::NV21:
case PublicFormat::YV12:
- dataspace = Dataspace::V0_JFIF;
+ dataspace = Dataspace::JFIF;
break;
case PublicFormat::DEPTH_JPEG:
dataspace = Dataspace::DYNAMIC_DEPTH;
@@ -72,6 +74,9 @@
case PublicFormat::HEIC:
dataspace = Dataspace::HEIF;
break;
+ case PublicFormat::JPEG_R:
+ dataspace = Dataspace::JPEG_R;
+ break;
default:
// Most formats map to UNKNOWN
dataspace = Dataspace::UNKNOWN;
@@ -139,14 +144,16 @@
switch (ds) {
case Dataspace::DEPTH:
return PublicFormat::DEPTH_POINT_CLOUD;
- case Dataspace::V0_JFIF:
+ case Dataspace::JFIF:
return PublicFormat::JPEG;
case Dataspace::HEIF:
return PublicFormat::HEIC;
default:
if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_DYNAMIC_DEPTH)) {
return PublicFormat::DEPTH_JPEG;
- } else {
+ } else if (dataSpace == static_cast<android_dataspace>(Dataspace::JPEG_R)) {
+ return PublicFormat::JPEG_R;
+ }else {
// Assume otherwise-marked blobs are also JPEG
return PublicFormat::JPEG;
}
diff --git a/libs/ui/include/ui/PixelFormat.h b/libs/ui/include/ui/PixelFormat.h
index f422ce4..cf5c2e8 100644
--- a/libs/ui/include/ui/PixelFormat.h
+++ b/libs/ui/include/ui/PixelFormat.h
@@ -53,16 +53,19 @@
// real pixel formats supported for rendering -----------------------------
- PIXEL_FORMAT_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888, // 4x8-bit RGBA
- PIXEL_FORMAT_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888, // 4x8-bit RGB0
- PIXEL_FORMAT_RGB_888 = HAL_PIXEL_FORMAT_RGB_888, // 3x8-bit RGB
- PIXEL_FORMAT_RGB_565 = HAL_PIXEL_FORMAT_RGB_565, // 16-bit RGB
- PIXEL_FORMAT_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, // 4x8-bit BGRA
- PIXEL_FORMAT_RGBA_5551 = 6, // 16-bit ARGB
- PIXEL_FORMAT_RGBA_4444 = 7, // 16-bit ARGB
- PIXEL_FORMAT_RGBA_FP16 = HAL_PIXEL_FORMAT_RGBA_FP16, // 64-bit RGBA
- PIXEL_FORMAT_RGBA_1010102 = HAL_PIXEL_FORMAT_RGBA_1010102, // 32-bit RGBA
- PIXEL_FORMAT_R_8 = 0x38,
+ PIXEL_FORMAT_RGBA_8888 = HAL_PIXEL_FORMAT_RGBA_8888, // 4x8-bit RGBA
+ PIXEL_FORMAT_RGBX_8888 = HAL_PIXEL_FORMAT_RGBX_8888, // 4x8-bit RGB0
+ PIXEL_FORMAT_RGB_888 = HAL_PIXEL_FORMAT_RGB_888, // 3x8-bit RGB
+ PIXEL_FORMAT_RGB_565 = HAL_PIXEL_FORMAT_RGB_565, // 16-bit RGB
+ PIXEL_FORMAT_BGRA_8888 = HAL_PIXEL_FORMAT_BGRA_8888, // 4x8-bit BGRA
+ PIXEL_FORMAT_RGBA_5551 = 6, // 16-bit ARGB
+ PIXEL_FORMAT_RGBA_4444 = 7, // 16-bit ARGB
+ PIXEL_FORMAT_RGBA_FP16 = HAL_PIXEL_FORMAT_RGBA_FP16, // 64-bit RGBA
+ PIXEL_FORMAT_RGBA_1010102 = HAL_PIXEL_FORMAT_RGBA_1010102, // 32-bit RGBA
+ PIXEL_FORMAT_R_8 = 0x38,
+ PIXEL_FORMAT_R_16_UINT = 0x39,
+ PIXEL_FORMAT_RG_1616_UINT = 0x3a,
+ PIXEL_FORMAT_RGBA_10101010 = 0x3b,
};
typedef int32_t PixelFormat;
diff --git a/libs/ui/include/ui/PublicFormat.h b/libs/ui/include/ui/PublicFormat.h
index aa58805..2248cca 100644
--- a/libs/ui/include/ui/PublicFormat.h
+++ b/libs/ui/include/ui/PublicFormat.h
@@ -57,6 +57,7 @@
YCBCR_P010 = 0x36,
DEPTH16 = 0x44363159,
DEPTH_JPEG = 0x69656963,
+ JPEG_R = 0x1005,
HEIC = 0x48454946,
};
diff --git a/libs/ui/include_types/ui/DataspaceUtils.h b/libs/ui/include_types/ui/DataspaceUtils.h
index a461cb4..cd31167 100644
--- a/libs/ui/include_types/ui/DataspaceUtils.h
+++ b/libs/ui/include_types/ui/DataspaceUtils.h
@@ -22,8 +22,10 @@
inline bool isHdrDataspace(ui::Dataspace dataspace) {
const auto transfer = dataspace & HAL_DATASPACE_TRANSFER_MASK;
+ const auto range = dataspace & HAL_DATASPACE_RANGE_MASK;
- return transfer == HAL_DATASPACE_TRANSFER_ST2084 || transfer == HAL_DATASPACE_TRANSFER_HLG;
+ return transfer == HAL_DATASPACE_TRANSFER_ST2084 || transfer == HAL_DATASPACE_TRANSFER_HLG ||
+ range == HAL_DATASPACE_RANGE_EXTENDED;
}
-} // namespace android
\ No newline at end of file
+} // namespace android
diff --git a/libs/ui/tests/DataspaceUtils_test.cpp b/libs/ui/tests/DataspaceUtils_test.cpp
index 3e09671..ffe6438 100644
--- a/libs/ui/tests/DataspaceUtils_test.cpp
+++ b/libs/ui/tests/DataspaceUtils_test.cpp
@@ -29,12 +29,13 @@
EXPECT_TRUE(isHdrDataspace(ui::Dataspace::BT2020_ITU_PQ));
EXPECT_TRUE(isHdrDataspace(ui::Dataspace::BT2020_PQ));
EXPECT_TRUE(isHdrDataspace(ui::Dataspace::BT2020_HLG));
+ // The original formulation of scRGB indicates the same white points as that
+ // of sRGB, however scRGB may be used to implement HDR.
+ EXPECT_TRUE(isHdrDataspace(ui::Dataspace::V0_SCRGB_LINEAR));
+ EXPECT_TRUE(isHdrDataspace(ui::Dataspace::V0_SCRGB));
EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_SRGB_LINEAR));
- // scRGB defines a very wide gamut but not an expanded luminance range
- EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_SCRGB_LINEAR));
EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_SRGB));
- EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_SCRGB));
EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_JFIF));
EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_BT601_625));
EXPECT_FALSE(isHdrDataspace(ui::Dataspace::V0_BT601_525));
diff --git a/opengl/TEST_MAPPING b/opengl/TEST_MAPPING
index d391dce..7c50a94 100644
--- a/opengl/TEST_MAPPING
+++ b/opengl/TEST_MAPPING
@@ -2,6 +2,9 @@
"presubmit": [
{
"name": "CtsGpuToolsHostTestCases"
+ },
+ {
+ "name": "EGL_test"
}
]
}
diff --git a/opengl/libs/EGL/egl_platform_entries.cpp b/opengl/libs/EGL/egl_platform_entries.cpp
index 7619a50..0527c8a 100644
--- a/opengl/libs/EGL/egl_platform_entries.cpp
+++ b/opengl/libs/EGL/egl_platform_entries.cpp
@@ -937,6 +937,8 @@
android::GraphicsEnv::getInstance().setTargetStats(
android::GpuStatsInfo::Stats::GLES_1_IN_USE);
}
+ android::GraphicsEnv::getInstance().setTargetStats(
+ android::GpuStatsInfo::Stats::CREATED_GLES_CONTEXT);
egl_context_t* c = new egl_context_t(dpy, context, config, cnx, version);
return c;
}
diff --git a/opengl/tests/EGLTest/Android.bp b/opengl/tests/EGLTest/Android.bp
index 51c9376..d96a895 100644
--- a/opengl/tests/EGLTest/Android.bp
+++ b/opengl/tests/EGLTest/Android.bp
@@ -1,4 +1,3 @@
-
package {
// See: http://go/android-license-faq
// A large-scale-change added 'default_applicable_licenses' to import
@@ -11,6 +10,7 @@
cc_test {
name: "EGL_test",
+ test_suites: ["general-tests"],
srcs: [
"egl_cache_test.cpp",
diff --git a/opengl/tests/EGLTest/EGL_test.cpp b/opengl/tests/EGLTest/EGL_test.cpp
index bbd786d..cbe4ef9 100644
--- a/opengl/tests/EGLTest/EGL_test.cpp
+++ b/opengl/tests/EGLTest/EGL_test.cpp
@@ -343,6 +343,11 @@
}
TEST_F(EGLTest, EGLDisplayP31010102) {
+ // This test has been failing since:
+ // libEGL: When driver doesn't understand P3, map sRGB-encoded P3 to sRGB
+ // https://android-review.git.corp.google.com/c/platform/frameworks/native/+/793504
+ GTEST_SKIP() << "Skipping broken test. See b/120714942 and b/117104367";
+
EGLint numConfigs;
EGLConfig config;
EGLBoolean success;
@@ -866,6 +871,12 @@
EGLConfig config;
EGLBoolean success;
+ if (!hasWideColorDisplay) {
+ // skip this test if device does not have wide-color display
+ RecordProperty("hasWideColorDisplay", false);
+ return;
+ }
+
const EGLint attrs[] = {
// clang-format off
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
@@ -951,6 +962,12 @@
TEST_F(EGLTest, EGLCreateWindowTwoColorspaces) {
EGLConfig config;
+ if (!hasWideColorDisplay) {
+ // skip this test if device does not have wide-color display
+ RecordProperty("hasWideColorDisplay", false);
+ return;
+ }
+
ASSERT_NO_FATAL_FAILURE(get8BitConfig(config));
struct MockConsumer : public BnConsumerListener {
diff --git a/services/gpuservice/GpuService.cpp b/services/gpuservice/GpuService.cpp
index 7b9782f..aaa8c18 100644
--- a/services/gpuservice/GpuService.cpp
+++ b/services/gpuservice/GpuService.cpp
@@ -82,6 +82,12 @@
mGpuStats->insertTargetStats(appPackageName, driverVersionCode, stats, value);
}
+void GpuService::setTargetStatsArray(const std::string& appPackageName,
+ const uint64_t driverVersionCode, const GpuStatsInfo::Stats stats,
+ const uint64_t* values, const uint32_t valueCount) {
+ mGpuStats->insertTargetStatsArray(appPackageName, driverVersionCode, stats, values, valueCount);
+}
+
void GpuService::setUpdatableDriverPath(const std::string& driverPath) {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
diff --git a/services/gpuservice/GpuService.h b/services/gpuservice/GpuService.h
index d7313d1..e7e0cba 100644
--- a/services/gpuservice/GpuService.h
+++ b/services/gpuservice/GpuService.h
@@ -56,6 +56,9 @@
int64_t driverLoadingTime) override;
void setTargetStats(const std::string& appPackageName, const uint64_t driverVersionCode,
const GpuStatsInfo::Stats stats, const uint64_t value) override;
+ void setTargetStatsArray(const std::string& appPackageName,
+ const uint64_t driverVersionCode, const GpuStatsInfo::Stats stats,
+ const uint64_t* values, const uint32_t valueCount) override;
void setUpdatableDriverPath(const std::string& driverPath) override;
std::string getUpdatableDriverPath() override;
diff --git a/services/gpuservice/gpustats/GpuStats.cpp b/services/gpuservice/gpustats/GpuStats.cpp
index d033453..f06a045 100644
--- a/services/gpuservice/gpustats/GpuStats.cpp
+++ b/services/gpuservice/gpustats/GpuStats.cpp
@@ -175,29 +175,83 @@
void GpuStats::insertTargetStats(const std::string& appPackageName,
const uint64_t driverVersionCode, const GpuStatsInfo::Stats stats,
- const uint64_t /*value*/) {
+ const uint64_t value) {
+ return insertTargetStatsArray(appPackageName, driverVersionCode, stats, &value, 1);
+}
+
+void GpuStats::insertTargetStatsArray(const std::string& appPackageName,
+ const uint64_t driverVersionCode, const GpuStatsInfo::Stats stats,
+ const uint64_t* values, const uint32_t valueCount) {
ATRACE_CALL();
const std::string appStatsKey = appPackageName + std::to_string(driverVersionCode);
std::lock_guard<std::mutex> lock(mLock);
registerStatsdCallbacksIfNeeded();
- if (!mAppStats.count(appStatsKey)) {
+
+ const auto foundApp = mAppStats.find(appStatsKey);
+ if (foundApp == mAppStats.end()) {
return;
}
- switch (stats) {
- case GpuStatsInfo::Stats::CPU_VULKAN_IN_USE:
- mAppStats[appStatsKey].cpuVulkanInUse = true;
- break;
- case GpuStatsInfo::Stats::FALSE_PREROTATION:
- mAppStats[appStatsKey].falsePrerotation = true;
- break;
- case GpuStatsInfo::Stats::GLES_1_IN_USE:
- mAppStats[appStatsKey].gles1InUse = true;
- break;
- default:
- break;
+ GpuStatsAppInfo& targetAppStats = foundApp->second;
+
+ if (stats == GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION
+ || stats == GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION) {
+ // Handle extension arrays separately as we need to store a unique set of them
+ // in the stats vector. Storing in std::set<> is not efficient for serialization tasks.
+ std::vector<int32_t>& targetVec =
+ (stats == GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION) ?
+ targetAppStats.vulkanInstanceExtensions :
+ targetAppStats.vulkanDeviceExtensions;
+ const bool addAll = (targetVec.size() == 0);
+ targetVec.reserve(valueCount);
+
+ // Add new extensions into the set
+ for(uint32_t i = 0;
+ (i < valueCount) && (targetVec.size() < GpuStatsAppInfo::MAX_NUM_EXTENSIONS);
+ i++) {
+ const int32_t extVal = int32_t(values[i] & 0xFFFFFFFF);
+ if (addAll
+ || std::find(targetVec.cbegin(), targetVec.cend(), extVal) == targetVec.cend()) {
+ targetVec.push_back(extVal);
+ }
+ }
+ }
+ else {
+ // Handle other type of stats info events
+ for(uint32_t i = 0; i < valueCount; i++) {
+ const uint64_t value = values[i];
+ switch (stats) {
+ case GpuStatsInfo::Stats::CPU_VULKAN_IN_USE:
+ targetAppStats.cpuVulkanInUse = true;
+ break;
+ case GpuStatsInfo::Stats::FALSE_PREROTATION:
+ targetAppStats.falsePrerotation = true;
+ break;
+ case GpuStatsInfo::Stats::GLES_1_IN_USE:
+ targetAppStats.gles1InUse = true;
+ break;
+ case GpuStatsInfo::Stats::CREATED_GLES_CONTEXT:
+ targetAppStats.createdGlesContext = true;
+ break;
+ case GpuStatsInfo::Stats::CREATED_VULKAN_DEVICE:
+ targetAppStats.createdVulkanDevice = true;
+ break;
+ case GpuStatsInfo::Stats::CREATED_VULKAN_API_VERSION:
+ targetAppStats.vulkanApiVersion = uint32_t(value & 0xffffffff);
+ break;
+ case GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN:
+ targetAppStats.createdVulkanSwapchain = true;
+ break;
+ case GpuStatsInfo::Stats::VULKAN_DEVICE_FEATURES_ENABLED:
+ // Merge all requested feature bits together for this app
+ targetAppStats.vulkanDeviceFeaturesEnabled |= value;
+ break;
+ default:
+ break;
+ }
+ }
}
}
@@ -347,7 +401,14 @@
ele.second.cpuVulkanInUse,
ele.second.falsePrerotation,
ele.second.gles1InUse,
- ele.second.angleInUse);
+ ele.second.angleInUse,
+ ele.second.createdGlesContext,
+ ele.second.createdVulkanDevice,
+ ele.second.createdVulkanSwapchain,
+ ele.second.vulkanApiVersion,
+ ele.second.vulkanDeviceFeaturesEnabled,
+ ele.second.vulkanInstanceExtensions,
+ ele.second.vulkanDeviceExtensions);
}
}
diff --git a/services/gpuservice/gpustats/include/gpustats/GpuStats.h b/services/gpuservice/gpustats/include/gpustats/GpuStats.h
index 2aba651..22c64db 100644
--- a/services/gpuservice/gpustats/include/gpustats/GpuStats.h
+++ b/services/gpuservice/gpustats/include/gpustats/GpuStats.h
@@ -41,11 +41,14 @@
// Insert target stats into app stats or potentially global stats as well.
void insertTargetStats(const std::string& appPackageName, const uint64_t driverVersionCode,
const GpuStatsInfo::Stats stats, const uint64_t value);
+ void insertTargetStatsArray(const std::string& appPackageName,
+ const uint64_t driverVersionCode, const GpuStatsInfo::Stats stats,
+ const uint64_t* values, const uint32_t valueCount);
// dumpsys interface
void dump(const Vector<String16>& args, std::string* result);
// This limits the worst case number of loading times tracked.
- static const size_t MAX_NUM_LOADING_TIMES = 50;
+ static const size_t MAX_NUM_LOADING_TIMES = 16;
// Below limits the memory usage of GpuStats to be less than 10KB. This is
// the preferred number for statsd while maintaining nice data quality.
static const size_t MAX_NUM_APP_RECORDS = 100;
diff --git a/services/gpuservice/tests/unittests/GpuStatsTest.cpp b/services/gpuservice/tests/unittests/GpuStatsTest.cpp
index 7ea2288..4ce533f 100644
--- a/services/gpuservice/tests/unittests/GpuStatsTest.cpp
+++ b/services/gpuservice/tests/unittests/GpuStatsTest.cpp
@@ -52,6 +52,13 @@
#define DRIVER_LOADING_TIME_2 789
#define DRIVER_LOADING_TIME_3 891
+constexpr uint64_t VULKAN_FEATURES_MASK = 0x600D;
+constexpr uint32_t VULKAN_API_VERSION = 0x400000;
+constexpr int32_t VULKAN_INSTANCE_EXTENSION_1 = 0x1234;
+constexpr int32_t VULKAN_INSTANCE_EXTENSION_2 = 0x8765;
+constexpr int32_t VULKAN_DEVICE_EXTENSION_1 = 0x9012;
+constexpr int32_t VULKAN_DEVICE_EXTENSION_2 = 0x3456;
+
enum InputCommand : int32_t {
DUMP_ALL = 0,
DUMP_GLOBAL = 1,
@@ -218,6 +225,24 @@
GpuStatsInfo::Stats::FALSE_PREROTATION, 0);
mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
GpuStatsInfo::Stats::GLES_1_IN_USE, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_GLES_CONTEXT, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_API_VERSION,
+ VULKAN_API_VERSION);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_DEVICE, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_FEATURES_ENABLED,
+ VULKAN_FEATURES_MASK);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ VULKAN_INSTANCE_EXTENSION_1);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ VULKAN_DEVICE_EXTENSION_1);
EXPECT_TRUE(inputCommand(InputCommand::DUMP_APP).empty());
}
@@ -233,10 +258,51 @@
GpuStatsInfo::Stats::FALSE_PREROTATION, 0);
mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
GpuStatsInfo::Stats::GLES_1_IN_USE, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_GLES_CONTEXT, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_API_VERSION,
+ VULKAN_API_VERSION);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_DEVICE, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN, 0);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_FEATURES_ENABLED,
+ VULKAN_FEATURES_MASK);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ VULKAN_INSTANCE_EXTENSION_1);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ VULKAN_INSTANCE_EXTENSION_2);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ VULKAN_DEVICE_EXTENSION_1);
+ mGpuStats->insertTargetStats(APP_PKG_NAME_1, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ VULKAN_DEVICE_EXTENSION_2);
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("cpuVulkanInUse = 1"));
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("falsePrerotation = 1"));
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("gles1InUse = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdGlesContext = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdVulkanDevice = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdVulkanSwapchain = 1"));
+ std::stringstream expectedResult;
+ expectedResult << "vulkanApiVersion = 0x" << std::hex << VULKAN_API_VERSION;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanDeviceFeaturesEnabled = 0x" << std::hex << VULKAN_FEATURES_MASK;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanInstanceExtensions: 0x" << std::hex << VULKAN_INSTANCE_EXTENSION_1
+ << " 0x" << std::hex << VULKAN_INSTANCE_EXTENSION_2;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanDeviceExtensions: 0x" << std::hex << VULKAN_DEVICE_EXTENSION_1
+ << " 0x" << std::hex << VULKAN_DEVICE_EXTENSION_2;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
}
// Verify we always have the most recently used apps in mAppStats, even when we fill it.
@@ -260,11 +326,52 @@
GpuStatsInfo::Stats::FALSE_PREROTATION, 0);
mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
GpuStatsInfo::Stats::GLES_1_IN_USE, 0);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_GLES_CONTEXT, 0);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_API_VERSION,
+ VULKAN_API_VERSION);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_DEVICE, 0);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN, 0);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_FEATURES_ENABLED,
+ VULKAN_FEATURES_MASK);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ VULKAN_INSTANCE_EXTENSION_1);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
+ VULKAN_INSTANCE_EXTENSION_2);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ VULKAN_DEVICE_EXTENSION_1);
+ mGpuStats->insertTargetStats(fullPkgName, BUILTIN_DRIVER_VER_CODE,
+ GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
+ VULKAN_DEVICE_EXTENSION_2);
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(fullPkgName.c_str()));
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("cpuVulkanInUse = 1"));
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("falsePrerotation = 1"));
EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("gles1InUse = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdGlesContext = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdVulkanDevice = 1"));
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr("createdVulkanSwapchain = 1"));
+ std::stringstream expectedResult;
+ expectedResult << "vulkanApiVersion = 0x" << std::hex << VULKAN_API_VERSION;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanDeviceFeaturesEnabled = 0x" << std::hex << VULKAN_FEATURES_MASK;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanInstanceExtensions: 0x" << std::hex << VULKAN_INSTANCE_EXTENSION_1
+ << " 0x" << std::hex << VULKAN_INSTANCE_EXTENSION_2;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
+ expectedResult.str("");
+ expectedResult << "vulkanDeviceExtensions: 0x" << std::hex << VULKAN_DEVICE_EXTENSION_1
+ << " 0x" << std::hex << VULKAN_DEVICE_EXTENSION_2;
+ EXPECT_THAT(inputCommand(InputCommand::DUMP_APP), HasSubstr(expectedResult.str()));
}
// mAppStats purges GpuStats::APP_RECORD_HEADROOM apps removed everytime it's filled up.
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 4aac377..906bb1b 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -2060,6 +2060,12 @@
if (touchedWindow.windowHandle->getInfo()->supportsSplitTouch()) {
continue;
}
+ if (touchedWindow.windowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::IS_WALLPAPER)) {
+ // Wallpaper window should not affect whether or not touch is split
+ continue;
+ }
+
// Eventually, touchedWindow will contain the deviceId of each pointer that's currently
// being sent there. For now, use deviceId from touch state.
if (entry.deviceId == touchState.deviceId && !touchedWindow.pointerIds.isEmpty()) {
@@ -2223,6 +2229,32 @@
tempTouchState.addOrUpdateWindow(windowHandle, targetFlags, pointerIds,
entry.eventTime);
+
+ // If this is the pointer going down and the touched window has a wallpaper
+ // then also add the touched wallpaper windows so they are locked in for the duration
+ // of the touch gesture.
+ // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
+ // engine only supports touch events. We would need to add a mechanism similar
+ // to View.onGenericMotionEvent to enable wallpapers to handle these events.
+ if (maskedAction == AMOTION_EVENT_ACTION_DOWN ||
+ maskedAction == AMOTION_EVENT_ACTION_POINTER_DOWN) {
+ if (targetFlags.test(InputTarget::Flags::FOREGROUND) &&
+ windowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
+ sp<WindowInfoHandle> wallpaper = findWallpaperWindowBelow(windowHandle);
+ if (wallpaper != nullptr) {
+ ftl::Flags<InputTarget::Flags> wallpaperFlags =
+ InputTarget::Flags::WINDOW_IS_OBSCURED |
+ InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED |
+ InputTarget::Flags::DISPATCH_AS_IS;
+ if (isSplit) {
+ wallpaperFlags |= InputTarget::Flags::SPLIT;
+ }
+ tempTouchState.addOrUpdateWindow(wallpaper, wallpaperFlags, pointerIds,
+ entry.eventTime);
+ }
+ }
+ }
}
// If any existing window is pilfering pointers from newly added window, remove it
@@ -2307,6 +2339,10 @@
pointerIds.markBit(entry.pointerProperties[0].id);
tempTouchState.addOrUpdateWindow(newTouchedWindowHandle, targetFlags, pointerIds,
entry.eventTime);
+
+ // Check if the wallpaper window should deliver the corresponding event.
+ slipWallpaperTouch(targetFlags, oldTouchedWindowHandle, newTouchedWindowHandle,
+ tempTouchState, pointerIds);
}
}
@@ -2413,38 +2449,6 @@
}
}
- // If this is the first pointer going down and the touched window has a wallpaper
- // then also add the touched wallpaper windows so they are locked in for the duration
- // of the touch gesture.
- // We do not collect wallpapers during HOVER_MOVE or SCROLL because the wallpaper
- // engine only supports touch events. We would need to add a mechanism similar
- // to View.onGenericMotionEvent to enable wallpapers to handle these events.
- if (maskedAction == AMOTION_EVENT_ACTION_DOWN) {
- sp<WindowInfoHandle> foregroundWindowHandle =
- tempTouchState.getFirstForegroundWindowHandle();
- if (foregroundWindowHandle &&
- foregroundWindowHandle->getInfo()->inputConfig.test(
- WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
- const std::vector<sp<WindowInfoHandle>>& windowHandles =
- getWindowHandlesLocked(displayId);
- for (const sp<WindowInfoHandle>& windowHandle : windowHandles) {
- const WindowInfo* info = windowHandle->getInfo();
- if (info->displayId == displayId &&
- windowHandle->getInfo()->inputConfig.test(
- WindowInfo::InputConfig::IS_WALLPAPER)) {
- BitSet32 pointerIds;
- pointerIds.markBit(entry.pointerProperties[0].id);
- tempTouchState.addOrUpdateWindow(windowHandle,
- InputTarget::Flags::WINDOW_IS_OBSCURED |
- InputTarget::Flags::
- WINDOW_IS_PARTIALLY_OBSCURED |
- InputTarget::Flags::DISPATCH_AS_IS,
- pointerIds, entry.eventTime);
- }
- }
- }
- }
-
// Success! Output targets.
touchedWindows = tempTouchState.windows;
outInjectionResult = InputEventInjectionResult::SUCCEEDED;
@@ -3726,7 +3730,8 @@
}
void InputDispatcher::synthesizePointerDownEventsForConnectionLocked(
- const nsecs_t downTime, const sp<Connection>& connection) {
+ const nsecs_t downTime, const sp<Connection>& connection,
+ ftl::Flags<InputTarget::Flags> targetFlags) {
if (connection->status == Connection::Status::BROKEN) {
return;
}
@@ -3752,7 +3757,7 @@
target.globalScaleFactor = windowInfo->globalScaleFactor;
}
target.inputChannel = connection->inputChannel;
- target.flags = InputTarget::Flags::DISPATCH_AS_IS;
+ target.flags = targetFlags;
const bool wasEmpty = connection->outboundQueue.empty();
for (std::unique_ptr<EventEntry>& downEventEntry : downEvents) {
@@ -3787,6 +3792,16 @@
}
}
+void InputDispatcher::synthesizeCancelationEventsForWindowLocked(
+ const sp<WindowInfoHandle>& windowHandle, const CancelationOptions& options) {
+ if (windowHandle != nullptr) {
+ sp<Connection> wallpaperConnection = getConnectionLocked(windowHandle->getToken());
+ if (wallpaperConnection != nullptr) {
+ synthesizeCancelationEventsForConnectionLocked(wallpaperConnection, options);
+ }
+ }
+}
+
std::unique_ptr<MotionEntry> InputDispatcher::splitMotionEvent(
const MotionEntry& originalMotionEntry, BitSet32 pointerIds, nsecs_t splitDownTime) {
ALOG_ASSERT(pointerIds.value != 0);
@@ -4847,14 +4862,7 @@
touchedWindow.windowHandle->getInfo()->inputConfig.test(
gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER)) {
sp<WindowInfoHandle> wallpaper = state.getWallpaperWindow();
- if (wallpaper != nullptr) {
- sp<Connection> wallpaperConnection =
- getConnectionLocked(wallpaper->getToken());
- if (wallpaperConnection != nullptr) {
- synthesizeCancelationEventsForConnectionLocked(wallpaperConnection,
- options);
- }
- }
+ synthesizeCancelationEventsForWindowLocked(wallpaper, options);
}
}
state.windows.erase(state.windows.begin() + i);
@@ -5155,6 +5163,7 @@
// Erase old window.
ftl::Flags<InputTarget::Flags> oldTargetFlags = touchedWindow->targetFlags;
BitSet32 pointerIds = touchedWindow->pointerIds;
+ sp<WindowInfoHandle> fromWindowHandle = touchedWindow->windowHandle;
state->removeWindowByToken(fromToken);
// Add new window.
@@ -5187,7 +5196,12 @@
options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
"transferring touch focus from this window to another window");
synthesizeCancelationEventsForConnectionLocked(fromConnection, options);
- synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection);
+ synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, toConnection,
+ newTargetFlags);
+
+ // Check if the wallpaper window should deliver the corresponding event.
+ transferWallpaperTouch(oldTargetFlags, newTargetFlags, fromWindowHandle, toWindowHandle,
+ *state, pointerIds);
}
} // release lock
@@ -6465,4 +6479,100 @@
mMonitorDispatchingTimeout = timeout;
}
+void InputDispatcher::slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
+ const sp<WindowInfoHandle>& oldWindowHandle,
+ const sp<WindowInfoHandle>& newWindowHandle,
+ TouchState& state, const BitSet32& pointerIds) {
+ const bool oldHasWallpaper = oldWindowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
+ const bool newHasWallpaper = targetFlags.test(InputTarget::Flags::FOREGROUND) &&
+ newWindowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
+ const sp<WindowInfoHandle> oldWallpaper =
+ oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
+ const sp<WindowInfoHandle> newWallpaper =
+ newHasWallpaper ? findWallpaperWindowBelow(newWindowHandle) : nullptr;
+ if (oldWallpaper == newWallpaper) {
+ return;
+ }
+
+ if (oldWallpaper != nullptr) {
+ state.addOrUpdateWindow(oldWallpaper, InputTarget::Flags::DISPATCH_AS_SLIPPERY_EXIT,
+ BitSet32(0));
+ }
+
+ if (newWallpaper != nullptr) {
+ state.addOrUpdateWindow(newWallpaper,
+ InputTarget::Flags::DISPATCH_AS_SLIPPERY_ENTER |
+ InputTarget::Flags::WINDOW_IS_OBSCURED |
+ InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED,
+ pointerIds);
+ }
+}
+
+void InputDispatcher::transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
+ ftl::Flags<InputTarget::Flags> newTargetFlags,
+ const sp<WindowInfoHandle> fromWindowHandle,
+ const sp<WindowInfoHandle> toWindowHandle,
+ TouchState& state, const BitSet32& pointerIds) {
+ const bool oldHasWallpaper = oldTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
+ fromWindowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
+ const bool newHasWallpaper = newTargetFlags.test(InputTarget::Flags::FOREGROUND) &&
+ toWindowHandle->getInfo()->inputConfig.test(
+ gui::WindowInfo::InputConfig::DUPLICATE_TOUCH_TO_WALLPAPER);
+
+ const sp<WindowInfoHandle> oldWallpaper =
+ oldHasWallpaper ? state.getWallpaperWindow() : nullptr;
+ const sp<WindowInfoHandle> newWallpaper =
+ newHasWallpaper ? findWallpaperWindowBelow(toWindowHandle) : nullptr;
+ if (oldWallpaper == newWallpaper) {
+ return;
+ }
+
+ if (oldWallpaper != nullptr) {
+ CancelationOptions options(CancelationOptions::Mode::CANCEL_POINTER_EVENTS,
+ "transferring touch focus to another window");
+ state.removeWindowByToken(oldWallpaper->getToken());
+ synthesizeCancelationEventsForWindowLocked(oldWallpaper, options);
+ }
+
+ if (newWallpaper != nullptr) {
+ nsecs_t downTimeInTarget = now();
+ ftl::Flags<InputTarget::Flags> wallpaperFlags =
+ oldTargetFlags & (InputTarget::Flags::SPLIT | InputTarget::Flags::DISPATCH_AS_IS);
+ wallpaperFlags |= InputTarget::Flags::WINDOW_IS_OBSCURED |
+ InputTarget::Flags::WINDOW_IS_PARTIALLY_OBSCURED;
+ state.addOrUpdateWindow(newWallpaper, wallpaperFlags, pointerIds, downTimeInTarget);
+ sp<Connection> wallpaperConnection = getConnectionLocked(newWallpaper->getToken());
+ if (wallpaperConnection != nullptr) {
+ sp<Connection> toConnection = getConnectionLocked(toWindowHandle->getToken());
+ toConnection->inputState.mergePointerStateTo(wallpaperConnection->inputState);
+ synthesizePointerDownEventsForConnectionLocked(downTimeInTarget, wallpaperConnection,
+ wallpaperFlags);
+ }
+ }
+}
+
+sp<WindowInfoHandle> InputDispatcher::findWallpaperWindowBelow(
+ const sp<WindowInfoHandle>& windowHandle) const {
+ const std::vector<sp<WindowInfoHandle>>& windowHandles =
+ getWindowHandlesLocked(windowHandle->getInfo()->displayId);
+ bool foundWindow = false;
+ for (const sp<WindowInfoHandle>& otherHandle : windowHandles) {
+ if (!foundWindow && otherHandle != windowHandle) {
+ continue;
+ }
+ if (windowHandle == otherHandle) {
+ foundWindow = true;
+ continue;
+ }
+
+ if (otherHandle->getInfo()->inputConfig.test(WindowInfo::InputConfig::IS_WALLPAPER)) {
+ return otherHandle;
+ }
+ }
+ return nullptr;
+}
+
} // namespace android::inputdispatcher
diff --git a/services/inputflinger/dispatcher/InputDispatcher.h b/services/inputflinger/dispatcher/InputDispatcher.h
index 5efb39e..a32ebd3 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.h
+++ b/services/inputflinger/dispatcher/InputDispatcher.h
@@ -628,9 +628,14 @@
REQUIRES(mLock);
void synthesizePointerDownEventsForConnectionLocked(const nsecs_t downTime,
- const sp<Connection>& connection)
+ const sp<Connection>& connection,
+ ftl::Flags<InputTarget::Flags> targetFlags)
REQUIRES(mLock);
+ void synthesizeCancelationEventsForWindowLocked(
+ const sp<android::gui::WindowInfoHandle>& windowHandle,
+ const CancelationOptions& options) REQUIRES(mLock);
+
// Splitting motion events across windows. When splitting motion event for a target,
// splitDownTime refers to the time of first 'down' event on that particular target
std::unique_ptr<MotionEntry> splitMotionEvent(const MotionEntry& originalMotionEntry,
@@ -691,6 +696,19 @@
bool recentWindowsAreOwnedByLocked(int32_t pid, int32_t uid) REQUIRES(mLock);
sp<InputReporterInterface> mReporter;
+
+ void slipWallpaperTouch(ftl::Flags<InputTarget::Flags> targetFlags,
+ const sp<android::gui::WindowInfoHandle>& oldWindowHandle,
+ const sp<android::gui::WindowInfoHandle>& newWindowHandle,
+ TouchState& state, const BitSet32& pointerIds) REQUIRES(mLock);
+ void transferWallpaperTouch(ftl::Flags<InputTarget::Flags> oldTargetFlags,
+ ftl::Flags<InputTarget::Flags> newTargetFlags,
+ const sp<android::gui::WindowInfoHandle> fromWindowHandle,
+ const sp<android::gui::WindowInfoHandle> toWindowHandle,
+ TouchState& state, const BitSet32& pointerIds) REQUIRES(mLock);
+
+ sp<android::gui::WindowInfoHandle> findWallpaperWindowBelow(
+ const sp<android::gui::WindowInfoHandle>& windowHandle) const REQUIRES(mLock);
};
} // namespace android::inputdispatcher
diff --git a/services/inputflinger/include/InputReaderBase.h b/services/inputflinger/include/InputReaderBase.h
index b8a6dad..d2c940f 100644
--- a/services/inputflinger/include/InputReaderBase.h
+++ b/services/inputflinger/include/InputReaderBase.h
@@ -191,6 +191,12 @@
// The set of disabled input devices (disabledDevices) has changed.
CHANGE_ENABLED_STATE = 1 << 9,
+ // The device type has been updated.
+ CHANGE_DEVICE_TYPE = 1 << 10,
+
+ // The keyboard layout association has changed.
+ CHANGE_KEYBOARD_LAYOUT_ASSOCIATION = 1 << 11,
+
// All devices must be reopened.
CHANGE_MUST_REOPEN = 1 << 31,
};
@@ -208,10 +214,18 @@
// Used to determine which DisplayViewport should be tied to which InputDevice.
std::unordered_map<std::string, uint8_t> portAssociations;
- // The associations between input device names and display unique ids.
+ // The associations between input device physical port locations and display unique ids.
// Used to determine which DisplayViewport should be tied to which InputDevice.
std::unordered_map<std::string, std::string> uniqueIdAssociations;
+ // The associations between input device ports device types.
+ // This is used to determine which device type and source should be tied to which InputDevice.
+ std::unordered_map<std::string, std::string> deviceTypeAssociations;
+
+ // The map from the input device physical port location to the input device layout info.
+ // Can be used to determine the layout of the keyboard device.
+ std::unordered_map<std::string, KeyboardLayoutInfo> keyboardLayoutAssociations;
+
// The suggested display ID to show the cursor.
int32_t defaultPointerDisplayId;
@@ -326,7 +340,6 @@
std::optional<DisplayViewport> getDisplayViewportById(int32_t displayId) const;
void setDisplayViewports(const std::vector<DisplayViewport>& viewports);
-
void dump(std::string& dump) const;
void dumpViewport(std::string& dump, const DisplayViewport& viewport) const;
diff --git a/services/inputflinger/reader/Android.bp b/services/inputflinger/reader/Android.bp
index f37f0fa..f3b680b 100644
--- a/services/inputflinger/reader/Android.bp
+++ b/services/inputflinger/reader/Android.bp
@@ -29,6 +29,7 @@
"include",
"mapper",
"mapper/accumulator",
+ "mapper/gestures",
],
}
@@ -60,7 +61,9 @@
"mapper/accumulator/MultiTouchMotionAccumulator.cpp",
"mapper/accumulator/SingleTouchMotionAccumulator.cpp",
"mapper/accumulator/TouchButtonAccumulator.cpp",
+ "mapper/gestures/GestureConverter.cpp",
"mapper/gestures/GesturesLogging.cpp",
+ "mapper/gestures/HardwareStateConverter.cpp",
],
}
diff --git a/services/inputflinger/reader/InputDevice.cpp b/services/inputflinger/reader/InputDevice.cpp
index 11b5209..13f40ee 100644
--- a/services/inputflinger/reader/InputDevice.cpp
+++ b/services/inputflinger/reader/InputDevice.cpp
@@ -291,6 +291,9 @@
context.getConfiguration(&configuration);
mConfiguration.addAll(&configuration);
});
+
+ mAssociatedDeviceType =
+ getValueByKey(config->deviceTypeAssociations, mIdentifier.location);
}
if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) {
diff --git a/services/inputflinger/reader/Macros.h b/services/inputflinger/reader/Macros.h
index e107d88..d2a7ced 100644
--- a/services/inputflinger/reader/Macros.h
+++ b/services/inputflinger/reader/Macros.h
@@ -22,6 +22,8 @@
#include <log/log.h>
#include <log/log_event_list.h>
+#include <unordered_map>
+
namespace android {
/**
* Log debug messages for each raw event received from the EventHub.
@@ -113,4 +115,14 @@
return (sources & sourceMask & ~AINPUT_SOURCE_CLASS_MASK) != 0;
}
+template <typename K, typename V>
+static inline std::optional<V> getValueByKey(const std::unordered_map<K, V>& map, K key) {
+ auto it = map.find(key);
+ std::optional<V> value = std::nullopt;
+ if (it != map.end()) {
+ value = it->second;
+ }
+ return value;
+}
+
} // namespace android
diff --git a/services/inputflinger/reader/include/InputDevice.h b/services/inputflinger/reader/include/InputDevice.h
index 6fa21e5..b173618 100644
--- a/services/inputflinger/reader/include/InputDevice.h
+++ b/services/inputflinger/reader/include/InputDevice.h
@@ -54,6 +54,7 @@
inline std::optional<std::string> getBluetoothAddress() const {
return mIdentifier.bluetoothAddress;
}
+ inline const std::string getLocation() const { return mIdentifier.location; }
inline ftl::Flags<InputDeviceClass> getClasses() const { return mClasses; }
inline uint32_t getSources() const { return mSources; }
inline bool hasEventHubDevices() const { return !mDevices.empty(); }
@@ -65,6 +66,9 @@
inline std::optional<std::string> getAssociatedDisplayUniqueId() const {
return mAssociatedDisplayUniqueId;
}
+ inline std::optional<std::string> getDeviceTypeAssociation() const {
+ return mAssociatedDeviceType;
+ }
inline std::optional<DisplayViewport> getAssociatedViewport() const {
return mAssociatedViewport;
}
@@ -180,6 +184,7 @@
bool mIsExternal;
std::optional<uint8_t> mAssociatedDisplayPort;
std::optional<std::string> mAssociatedDisplayUniqueId;
+ std::optional<std::string> mAssociatedDeviceType;
std::optional<DisplayViewport> mAssociatedViewport;
bool mHasMic;
bool mDropUntilNextSync;
@@ -399,8 +404,9 @@
inline status_t enableDevice() { return mEventHub->enableDevice(mId); }
inline status_t disableDevice() { return mEventHub->disableDevice(mId); }
- inline const std::string getName() { return mDevice.getName(); }
+ inline const std::string getName() const { return mDevice.getName(); }
inline const std::string getDescriptor() { return mDevice.getDescriptor(); }
+ inline const std::string getLocation() { return mDevice.getLocation(); }
inline bool isExternal() { return mDevice.isExternal(); }
inline std::optional<uint8_t> getAssociatedDisplayPort() const {
return mDevice.getAssociatedDisplayPort();
@@ -408,6 +414,9 @@
inline std::optional<std::string> getAssociatedDisplayUniqueId() const {
return mDevice.getAssociatedDisplayUniqueId();
}
+ inline std::optional<std::string> getDeviceTypeAssociation() const {
+ return mDevice.getDeviceTypeAssociation();
+ }
inline std::optional<DisplayViewport> getAssociatedViewport() const {
return mDevice.getAssociatedViewport();
}
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
index 44f0dfe..6f01449 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.cpp
@@ -120,6 +120,10 @@
info->setKeyboardType(mKeyboardType);
info->setKeyCharacterMap(getDeviceContext().getKeyCharacterMap());
+
+ if (mKeyboardLayoutInfo) {
+ info->setKeyboardLayoutInfo(*mKeyboardLayoutInfo);
+ }
}
void KeyboardInputMapper::dump(std::string& dump) {
@@ -129,6 +133,12 @@
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 += INDENT3 "KeyboardLayoutInfo: ";
+ if (mKeyboardLayoutInfo) {
+ dump += mKeyboardLayoutInfo->languageTag + ", " + mKeyboardLayoutInfo->layoutType + "\n";
+ } else {
+ dump += "<not set>\n";
+ }
}
std::optional<DisplayViewport> KeyboardInputMapper::findViewport(
@@ -158,6 +168,12 @@
if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) {
mViewport = findViewport(config);
}
+
+ if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUT_ASSOCIATION)) {
+ mKeyboardLayoutInfo =
+ getValueByKey(config->keyboardLayoutAssociations, getDeviceContext().getLocation());
+ }
+
return out;
}
diff --git a/services/inputflinger/reader/mapper/KeyboardInputMapper.h b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
index 0526fd8..da5b8ee 100644
--- a/services/inputflinger/reader/mapper/KeyboardInputMapper.h
+++ b/services/inputflinger/reader/mapper/KeyboardInputMapper.h
@@ -58,6 +58,7 @@
uint32_t mSource{};
int32_t mKeyboardType{};
+ std::optional<KeyboardLayoutInfo> mKeyboardLayoutInfo;
std::vector<KeyDown> mKeyDowns{}; // keys that are down
int32_t mMetaState{};
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.cpp b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
index cefc44e..9a7af40 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.cpp
@@ -51,9 +51,8 @@
return base::StringPrintf("%dx%d", size.width, size.height);
}
-static bool isPointInRect(const Rect& rect, int32_t x, int32_t y) {
- // Consider all four sides as "inclusive".
- return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
+static bool isPointInRect(const Rect& rect, vec2 p) {
+ return p.x >= rect.left && p.x < rect.right && p.y >= rect.top && p.y < rect.bottom;
}
template <typename T>
@@ -81,29 +80,12 @@
return value >= 8 ? value - 16 : value;
}
-static std::tuple<ui::Size /*displayBounds*/, Rect /*physicalFrame*/> getNaturalDisplayInfo(
- const DisplayViewport& viewport, ui::Rotation naturalOrientation) {
+static ui::Size getNaturalDisplaySize(const DisplayViewport& viewport) {
ui::Size rotatedDisplaySize{viewport.deviceWidth, viewport.deviceHeight};
- if (naturalOrientation == ui::ROTATION_90 || naturalOrientation == ui::ROTATION_270) {
+ if (viewport.orientation == ui::ROTATION_90 || viewport.orientation == ui::ROTATION_270) {
std::swap(rotatedDisplaySize.width, rotatedDisplaySize.height);
}
-
- ui::Transform rotate(ui::Transform::toRotationFlags(naturalOrientation),
- rotatedDisplaySize.width, rotatedDisplaySize.height);
-
- Rect physicalFrame{viewport.physicalLeft, viewport.physicalTop, viewport.physicalRight,
- viewport.physicalBottom};
- physicalFrame = rotate.transform(physicalFrame);
-
- LOG_ALWAYS_FATAL_IF(!physicalFrame.isValid());
- if (physicalFrame.isEmpty()) {
- ALOGE("Viewport is not set properly: %s", viewport.toString().c_str());
- physicalFrame.right =
- physicalFrame.left + (physicalFrame.width() == 0 ? 1 : physicalFrame.width());
- physicalFrame.bottom =
- physicalFrame.top + (physicalFrame.height() == 0 ? 1 : physicalFrame.height());
- }
- return {rotatedDisplaySize, physicalFrame};
+ return rotatedDisplaySize;
}
// --- RawPointerData ---
@@ -197,18 +179,6 @@
if (mCursorScrollAccumulator.haveRelativeHWheel()) {
info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f);
}
- if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
- const InputDeviceInfo::MotionRange& x = mOrientedRanges.x;
- const InputDeviceInfo::MotionRange& y = mOrientedRanges.y;
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz,
- x.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz,
- y.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz,
- x.resolution);
- info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz,
- y.resolution);
- }
info->setButtonUnderPad(mParameters.hasButtonUnderPad);
info->setSupportsUsi(mParameters.supportsUsi);
}
@@ -224,10 +194,10 @@
dumpDisplay(dump);
dump += StringPrintf(INDENT3 "Translation and Scaling Factors:\n");
- dump += StringPrintf(INDENT4 "XScale: %0.3f\n", mXScale);
- dump += StringPrintf(INDENT4 "YScale: %0.3f\n", mYScale);
- dump += StringPrintf(INDENT4 "XPrecision: %0.3f\n", mXPrecision);
- dump += StringPrintf(INDENT4 "YPrecision: %0.3f\n", mYPrecision);
+ mRawToDisplay.dump(dump, "RawToDisplay Transform:", INDENT4);
+ mRawRotation.dump(dump, "RawRotation Transform:", INDENT4);
+ dump += StringPrintf(INDENT4 "OrientedXPrecision: %0.3f\n", mOrientedXPrecision);
+ dump += StringPrintf(INDENT4 "OrientedYPrecision: %0.3f\n", mOrientedYPrecision);
dump += StringPrintf(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale);
dump += StringPrintf(INDENT4 "PressureScale: %0.3f\n", mPressureScale);
dump += StringPrintf(INDENT4 "SizeScale: %0.3f\n", mSizeScale);
@@ -392,33 +362,10 @@
}
}
- if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
- // The device is a touch screen.
- mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
- } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
- // The device is a pointing device like a track pad.
- mParameters.deviceType = Parameters::DeviceType::POINTER;
- } else {
- // The device is a touch pad of unknown purpose.
- mParameters.deviceType = Parameters::DeviceType::POINTER;
- }
+ configureDeviceType();
mParameters.hasButtonUnderPad = getDeviceContext().hasInputProperty(INPUT_PROP_BUTTONPAD);
- std::string deviceTypeString;
- if (getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType",
- deviceTypeString)) {
- if (deviceTypeString == "touchScreen") {
- mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
- } else if (deviceTypeString == "touchNavigation") {
- mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
- } else if (deviceTypeString == "pointer") {
- mParameters.deviceType = Parameters::DeviceType::POINTER;
- } else if (deviceTypeString != "default") {
- ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
- }
- }
-
mParameters.orientationAware = mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN;
getDeviceContext().getConfiguration().tryGetProperty("touch.orientationAware",
mParameters.orientationAware);
@@ -444,7 +391,9 @@
mParameters.associatedDisplayIsExternal = false;
if (mParameters.orientationAware ||
mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN ||
- mParameters.deviceType == Parameters::DeviceType::POINTER) {
+ mParameters.deviceType == Parameters::DeviceType::POINTER ||
+ (mParameters.deviceType == Parameters::DeviceType::TOUCH_NAVIGATION &&
+ getDeviceContext().getAssociatedViewport())) {
mParameters.hasAssociatedDisplay = true;
if (mParameters.deviceType == Parameters::DeviceType::TOUCH_SCREEN) {
mParameters.associatedDisplayIsExternal = getDeviceContext().isExternal();
@@ -473,6 +422,34 @@
mParameters.enableForInactiveViewport);
}
+void TouchInputMapper::configureDeviceType() {
+ if (getDeviceContext().hasInputProperty(INPUT_PROP_DIRECT)) {
+ // The device is a touch screen.
+ mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
+ } else if (getDeviceContext().hasInputProperty(INPUT_PROP_POINTER)) {
+ // The device is a pointing device like a track pad.
+ mParameters.deviceType = Parameters::DeviceType::POINTER;
+ } else {
+ // The device is a touch pad of unknown purpose.
+ mParameters.deviceType = Parameters::DeviceType::POINTER;
+ }
+
+ // Type association takes precedence over the device type found in the idc file.
+ std::string deviceTypeString = getDeviceContext().getDeviceTypeAssociation().value_or("");
+ if (deviceTypeString.empty()) {
+ getDeviceContext().getConfiguration().tryGetProperty("touch.deviceType", deviceTypeString);
+ }
+ if (deviceTypeString == "touchScreen") {
+ mParameters.deviceType = Parameters::DeviceType::TOUCH_SCREEN;
+ } else if (deviceTypeString == "touchNavigation") {
+ mParameters.deviceType = Parameters::DeviceType::TOUCH_NAVIGATION;
+ } else if (deviceTypeString == "pointer") {
+ mParameters.deviceType = Parameters::DeviceType::POINTER;
+ } else if (deviceTypeString != "default" && deviceTypeString != "") {
+ ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.c_str());
+ }
+}
+
void TouchInputMapper::dumpParameters(std::string& dump) {
dump += INDENT3 "Parameters:\n";
@@ -680,10 +657,10 @@
void TouchInputMapper::initializeOrientedRanges() {
// Configure X and Y factors.
- mXScale = float(mDisplayBounds.width) / mRawPointerAxes.getRawWidth();
- mYScale = float(mDisplayBounds.height) / mRawPointerAxes.getRawHeight();
- mXPrecision = 1.0f / mXScale;
- mYPrecision = 1.0f / mYScale;
+ const float orientedScaleX = mRawToDisplay.getScaleX();
+ const float orientedScaleY = mRawToDisplay.getScaleY();
+ mOrientedXPrecision = 1.0f / orientedScaleX;
+ mOrientedYPrecision = 1.0f / orientedScaleY;
mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X;
mOrientedRanges.x.source = mSource;
@@ -693,7 +670,7 @@
// Scale factor for terms that are not oriented in a particular axis.
// If the pixels are square then xScale == yScale otherwise we fake it
// by choosing an average.
- mGeometricScale = avg(mXScale, mYScale);
+ mGeometricScale = avg(orientedScaleX, orientedScaleY);
initializeSizeRanges();
@@ -810,44 +787,74 @@
// Compute oriented precision, scales and ranges.
// Note that the maximum value reported is an inclusive maximum value so it is one
// unit less than the total width or height of the display.
+ // TODO(b/20508709): Calculate the oriented ranges using the input device's raw frame.
switch (mInputDeviceOrientation) {
case ui::ROTATION_90:
case ui::ROTATION_270:
- mOrientedXPrecision = mYPrecision;
- mOrientedYPrecision = mXPrecision;
-
mOrientedRanges.x.min = 0;
mOrientedRanges.x.max = mDisplayBounds.height - 1;
mOrientedRanges.x.flat = 0;
mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale;
+ mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
mOrientedRanges.y.min = 0;
mOrientedRanges.y.max = mDisplayBounds.width - 1;
mOrientedRanges.y.flat = 0;
mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale;
+ mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
break;
default:
- mOrientedXPrecision = mXPrecision;
- mOrientedYPrecision = mYPrecision;
-
mOrientedRanges.x.min = 0;
mOrientedRanges.x.max = mDisplayBounds.width - 1;
mOrientedRanges.x.flat = 0;
mOrientedRanges.x.fuzz = 0;
- mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale;
+ mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mRawToDisplay.getScaleX();
mOrientedRanges.y.min = 0;
mOrientedRanges.y.max = mDisplayBounds.height - 1;
mOrientedRanges.y.flat = 0;
mOrientedRanges.y.fuzz = 0;
- mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale;
+ mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mRawToDisplay.getScaleY();
break;
}
}
+void TouchInputMapper::computeInputTransforms() {
+ const ui::Size rawSize{mRawPointerAxes.getRawWidth(), mRawPointerAxes.getRawHeight()};
+
+ ui::Size rotatedRawSize = rawSize;
+ if (mInputDeviceOrientation == ui::ROTATION_270 || mInputDeviceOrientation == ui::ROTATION_90) {
+ std::swap(rotatedRawSize.width, rotatedRawSize.height);
+ }
+ const auto rotationFlags = ui::Transform::toRotationFlags(-mInputDeviceOrientation);
+ mRawRotation = ui::Transform{rotationFlags};
+
+ // Step 1: Undo the raw offset so that the raw coordinate space now starts at (0, 0).
+ ui::Transform undoRawOffset;
+ undoRawOffset.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
+
+ // Step 2: Rotate the raw coordinates to the expected orientation.
+ ui::Transform rotate;
+ // When rotating raw coordinates, the raw size will be used as an offset.
+ // Account for the extra unit added to the raw range when the raw size was calculated.
+ rotate.set(rotationFlags, rotatedRawSize.width - 1, rotatedRawSize.height - 1);
+
+ // Step 3: Scale the raw coordinates to the display space.
+ ui::Transform scaleToDisplay;
+ const float xScale = static_cast<float>(mDisplayBounds.width) / rotatedRawSize.width;
+ const float yScale = static_cast<float>(mDisplayBounds.height) / rotatedRawSize.height;
+ scaleToDisplay.set(xScale, 0, 0, yScale);
+
+ mRawToDisplay = (scaleToDisplay * (rotate * undoRawOffset));
+
+ // Calculate the transform that takes raw coordinates to the rotated display space.
+ ui::Transform displayToRotatedDisplay;
+ displayToRotatedDisplay.set(ui::Transform::toRotationFlags(-mViewport.orientation),
+ mViewport.deviceWidth, mViewport.deviceHeight);
+ mRawToRotatedDisplay = displayToRotatedDisplay * mRawToDisplay;
+}
+
void TouchInputMapper::configureInputDevice(nsecs_t when, bool* outResetNeeded) {
const DeviceMode oldDeviceMode = mDeviceMode;
@@ -919,14 +926,9 @@
if (mDeviceMode == DeviceMode::DIRECT || mDeviceMode == DeviceMode::POINTER) {
const auto oldDisplayBounds = mDisplayBounds;
- // Apply the inverse of the input device orientation so that the input device is
- // configured in the same orientation as the viewport. The input device orientation will
- // be re-applied by mInputDeviceOrientation.
- const ui::Rotation naturalDeviceOrientation =
- mViewport.orientation - mParameters.orientation;
-
- std::tie(mDisplayBounds, mPhysicalFrameInDisplay) =
- getNaturalDisplayInfo(mViewport, naturalDeviceOrientation);
+ mDisplayBounds = getNaturalDisplaySize(mViewport);
+ mPhysicalFrameInRotatedDisplay = {mViewport.physicalLeft, mViewport.physicalTop,
+ mViewport.physicalRight, mViewport.physicalBottom};
// 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
@@ -943,10 +945,14 @@
// Apply the input device orientation for the device.
mInputDeviceOrientation = mInputDeviceOrientation + mParameters.orientation;
+ computeInputTransforms();
} else {
mDisplayBounds = rawSize;
- mPhysicalFrameInDisplay = Rect{mDisplayBounds};
+ mPhysicalFrameInRotatedDisplay = Rect{mDisplayBounds};
mInputDeviceOrientation = ui::ROTATION_0;
+ mRawToDisplay.reset();
+ mRawToDisplay.set(-mRawPointerAxes.x.minValue, -mRawPointerAxes.y.minValue);
+ mRawToRotatedDisplay = mRawToDisplay;
}
}
@@ -1029,7 +1035,8 @@
void TouchInputMapper::dumpDisplay(std::string& dump) {
dump += StringPrintf(INDENT3 "%s\n", mViewport.toString().c_str());
dump += StringPrintf(INDENT3 "DisplayBounds: %s\n", toString(mDisplayBounds).c_str());
- dump += StringPrintf(INDENT3 "PhysicalFrame: %s\n", toString(mPhysicalFrameInDisplay).c_str());
+ dump += StringPrintf(INDENT3 "PhysicalFrameInRotatedDisplay: %s\n",
+ toString(mPhysicalFrameInRotatedDisplay).c_str());
dump += StringPrintf(INDENT3 "InputDeviceOrientation: %d\n", mInputDeviceOrientation);
}
@@ -1190,19 +1197,6 @@
if (in.tryGetProperty("touch.distance.scale", distanceScale)) {
out.distanceScale = distanceScale;
}
-
- out.coverageCalibration = Calibration::CoverageCalibration::DEFAULT;
- std::string coverageCalibrationString;
- if (in.tryGetProperty("touch.coverage.calibration", coverageCalibrationString)) {
- if (coverageCalibrationString == "none") {
- out.coverageCalibration = Calibration::CoverageCalibration::NONE;
- } else if (coverageCalibrationString == "box") {
- out.coverageCalibration = Calibration::CoverageCalibration::BOX;
- } else if (coverageCalibrationString != "default") {
- ALOGW("Invalid value for touch.coverage.calibration: '%s'",
- coverageCalibrationString.c_str());
- }
- }
}
void TouchInputMapper::resolveCalibration() {
@@ -1241,11 +1235,6 @@
} else {
mCalibration.distanceCalibration = Calibration::DistanceCalibration::NONE;
}
-
- // Coverage
- if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::DEFAULT) {
- mCalibration.coverageCalibration = Calibration::CoverageCalibration::NONE;
- }
}
void TouchInputMapper::dumpCalibration(std::string& dump) {
@@ -1316,17 +1305,6 @@
if (mCalibration.distanceScale) {
dump += StringPrintf(INDENT4 "touch.distance.scale: %0.3f\n", *mCalibration.distanceScale);
}
-
- switch (mCalibration.coverageCalibration) {
- case Calibration::CoverageCalibration::NONE:
- dump += INDENT4 "touch.coverage.calibration: none\n";
- break;
- case Calibration::CoverageCalibration::BOX:
- dump += INDENT4 "touch.coverage.calibration: box\n";
- break;
- default:
- ALOG_ASSERT(false);
- }
}
void TouchInputMapper::dumpAffineTransformation(std::string& dump) {
@@ -2283,20 +2261,20 @@
if (mHaveTilt) {
float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale;
float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale;
- orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle));
+ orientation = transformAngle(mRawRotation, atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)));
tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle));
} else {
tilt = 0;
switch (mCalibration.orientationCalibration) {
case Calibration::OrientationCalibration::INTERPOLATED:
- orientation = in.orientation * mOrientationScale;
+ orientation = transformAngle(mRawRotation, in.orientation * mOrientationScale);
break;
case Calibration::OrientationCalibration::VECTOR: {
int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4);
int32_t c2 = signExtendNybble(in.orientation & 0x0f);
if (c1 != 0 || c2 != 0) {
- orientation = atan2f(c1, c2) * 0.5f;
+ orientation = transformAngle(mRawRotation, atan2f(c1, c2) * 0.5f);
float confidence = hypotf(c1, c2);
float scale = 1.0f + confidence / 16.0f;
touchMajor *= scale;
@@ -2323,76 +2301,16 @@
distance = 0;
}
- // Coverage
- int32_t rawLeft, rawTop, rawRight, rawBottom;
- switch (mCalibration.coverageCalibration) {
- case Calibration::CoverageCalibration::BOX:
- rawLeft = (in.toolMinor & 0xffff0000) >> 16;
- rawRight = in.toolMinor & 0x0000ffff;
- rawBottom = in.toolMajor & 0x0000ffff;
- rawTop = (in.toolMajor & 0xffff0000) >> 16;
- break;
- default:
- rawLeft = rawTop = rawRight = rawBottom = 0;
- break;
- }
-
- // Adjust X,Y coords for device calibration
- // TODO: Adjust coverage coords?
- float xTransformed = in.x, yTransformed = in.y;
- mAffineTransform.applyTo(xTransformed, yTransformed);
- rotateAndScale(xTransformed, yTransformed);
-
- // Adjust X, Y, and coverage coords for input device orientation.
- float left, top, right, bottom;
-
- switch (mInputDeviceOrientation) {
- case ui::ROTATION_90:
- left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
- right = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
- bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
- top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
- orientation -= M_PI_2;
- if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
- orientation +=
- (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
- }
- break;
- case ui::ROTATION_180:
- left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale;
- right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale;
- bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
- top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
- orientation -= M_PI;
- if (mOrientedRanges.orientation && orientation < mOrientedRanges.orientation->min) {
- orientation +=
- (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
- }
- break;
- case ui::ROTATION_270:
- left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale;
- right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale;
- bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
- top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
- orientation += M_PI_2;
- if (mOrientedRanges.orientation && orientation > mOrientedRanges.orientation->max) {
- orientation -=
- (mOrientedRanges.orientation->max - mOrientedRanges.orientation->min);
- }
- break;
- default:
- left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale;
- right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale;
- bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale;
- top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale;
- break;
- }
+ // Adjust X,Y coords for device calibration and convert to the natural display coordinates.
+ vec2 transformed = {in.x, in.y};
+ mAffineTransform.applyTo(transformed.x /*byRef*/, transformed.y /*byRef*/);
+ transformed = mRawToDisplay.transform(transformed);
// Write output coords.
PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i];
out.clear();
- out.setAxisValue(AMOTION_EVENT_AXIS_X, xTransformed);
- out.setAxisValue(AMOTION_EVENT_AXIS_Y, yTransformed);
+ out.setAxisValue(AMOTION_EVENT_AXIS_X, transformed.x);
+ out.setAxisValue(AMOTION_EVENT_AXIS_Y, transformed.y);
out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure);
out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size);
out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor);
@@ -2400,23 +2318,16 @@
out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation);
out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt);
out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance);
- if (mCalibration.coverageCalibration == Calibration::CoverageCalibration::BOX) {
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right);
- out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom);
- } else {
- out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
- out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
- }
+ out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor);
+ out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor);
// Write output relative fields if applicable.
uint32_t id = in.id;
if (mSource == AINPUT_SOURCE_TOUCHPAD &&
mLastCookedState.cookedPointerData.hasPointerCoordsForId(id)) {
const PointerCoords& p = mLastCookedState.cookedPointerData.pointerCoordsForId(id);
- float dx = xTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_X);
- float dy = yTransformed - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
+ float dx = transformed.x - p.getAxisValue(AMOTION_EVENT_AXIS_X);
+ float dy = transformed.y - p.getAxisValue(AMOTION_EVENT_AXIS_Y);
out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, dx);
out.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, dy);
}
@@ -3789,48 +3700,10 @@
return out;
}
-// Transform input device coordinates to display panel coordinates.
-void TouchInputMapper::rotateAndScale(float& x, float& y) const {
- const float xScaled = float(x - mRawPointerAxes.x.minValue) * mXScale;
- const float yScaled = float(y - mRawPointerAxes.y.minValue) * mYScale;
-
- const float xScaledMax = float(mRawPointerAxes.x.maxValue - x) * mXScale;
- const float yScaledMax = float(mRawPointerAxes.y.maxValue - y) * mYScale;
-
- // Rotate to display coordinate.
- // 0 - no swap and reverse.
- // 90 - swap x/y and reverse y.
- // 180 - reverse x, y.
- // 270 - swap x/y and reverse x.
- switch (mInputDeviceOrientation) {
- case ui::ROTATION_0:
- x = xScaled;
- y = yScaled;
- break;
- case ui::ROTATION_90:
- y = xScaledMax;
- x = yScaled;
- break;
- case ui::ROTATION_180:
- x = xScaledMax;
- y = yScaledMax;
- break;
- case ui::ROTATION_270:
- y = xScaled;
- x = yScaledMax;
- break;
- default:
- assert(false);
- }
-}
-
bool TouchInputMapper::isPointInsidePhysicalFrame(int32_t x, int32_t y) const {
- const float xScaled = (x - mRawPointerAxes.x.minValue) * mXScale;
- const float yScaled = (y - mRawPointerAxes.y.minValue) * mYScale;
-
return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue &&
y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue &&
- isPointInRect(mPhysicalFrameInDisplay, xScaled, yScaled);
+ isPointInRect(mPhysicalFrameInRotatedDisplay, mRawToRotatedDisplay.transform(x, y));
}
const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit(int32_t x, int32_t y) {
diff --git a/services/inputflinger/reader/mapper/TouchInputMapper.h b/services/inputflinger/reader/mapper/TouchInputMapper.h
index 34ba625..6e35b46 100644
--- a/services/inputflinger/reader/mapper/TouchInputMapper.h
+++ b/services/inputflinger/reader/mapper/TouchInputMapper.h
@@ -291,14 +291,6 @@
DistanceCalibration distanceCalibration;
std::optional<float> distanceScale;
- enum class CoverageCalibration {
- DEFAULT,
- NONE,
- BOX,
- };
-
- CoverageCalibration coverageCalibration;
-
inline void applySizeScaleAndBias(float& outSize) const {
if (sizeScale) {
outSize *= *sizeScale;
@@ -410,21 +402,26 @@
// Always starts at (0, 0).
ui::Size mDisplayBounds{ui::kInvalidSize};
- // The physical frame is the rectangle in the natural display's coordinate space that maps to
+ // The physical frame is the rectangle in the rotated display's coordinate space that maps to
// the logical display frame.
- Rect mPhysicalFrameInDisplay{Rect::INVALID_RECT};
+ Rect mPhysicalFrameInRotatedDisplay{Rect::INVALID_RECT};
// The orientation of the input device relative to that of the display panel. It specifies
// the rotation of the input device coordinates required to produce the display panel
// orientation, so it will depend on whether the device is orientation aware.
ui::Rotation mInputDeviceOrientation;
- // Translation and scaling factors, orientation-independent.
- float mXScale;
- float mXPrecision;
+ // The transform that maps the input device's raw coordinate space to the un-rotated display's
+ // coordinate space. InputReader generates events in the un-rotated display's coordinate space.
+ ui::Transform mRawToDisplay;
- float mYScale;
- float mYPrecision;
+ // The transform that maps the input device's raw coordinate space to the rotated display's
+ // coordinate space. This used to perform hit-testing of raw events with the physical frame in
+ // the rotated coordinate space. See mPhysicalFrameInRotatedDisplay.
+ ui::Transform mRawToRotatedDisplay;
+
+ // The transform used for non-planar raw axes, such as orientation and tilt.
+ ui::Transform mRawRotation;
float mGeometricScale;
@@ -813,7 +810,9 @@
static void assignPointerIds(const RawState& last, RawState& current);
- void rotateAndScale(float& x, float& y) const;
+ void computeInputTransforms();
+
+ void configureDeviceType();
};
} // namespace android
diff --git a/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp b/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
index de6e4b0..c563dba 100644
--- a/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
+++ b/services/inputflinger/reader/mapper/TouchpadInputMapper.cpp
@@ -16,9 +16,8 @@
#include "../Macros.h"
-#include <chrono>
-
#include <android/input.h>
+#include <linux/input-event-codes.h>
#include <log/log_main.h>
#include "TouchCursorInputMapperCommon.h"
#include "TouchpadInputMapper.h"
@@ -28,11 +27,11 @@
namespace {
short getMaxTouchCount(const InputDeviceContext& context) {
- if (context.hasKeyCode(BTN_TOOL_QUINTTAP)) return 5;
- if (context.hasKeyCode(BTN_TOOL_QUADTAP)) return 4;
- if (context.hasKeyCode(BTN_TOOL_TRIPLETAP)) return 3;
- if (context.hasKeyCode(BTN_TOOL_DOUBLETAP)) return 2;
- if (context.hasKeyCode(BTN_TOOL_FINGER)) return 1;
+ if (context.hasScanCode(BTN_TOOL_QUINTTAP)) return 5;
+ if (context.hasScanCode(BTN_TOOL_QUADTAP)) return 4;
+ if (context.hasScanCode(BTN_TOOL_TRIPLETAP)) return 3;
+ if (context.hasScanCode(BTN_TOOL_DOUBLETAP)) return 2;
+ if (context.hasScanCode(BTN_TOOL_FINGER)) return 1;
return 0;
}
@@ -83,30 +82,14 @@
mapper->consumeGesture(gesture);
}
-uint32_t gesturesButtonToMotionEventButton(uint32_t gesturesButton) {
- switch (gesturesButton) {
- case GESTURES_BUTTON_LEFT:
- return AMOTION_EVENT_BUTTON_PRIMARY;
- case GESTURES_BUTTON_MIDDLE:
- return AMOTION_EVENT_BUTTON_TERTIARY;
- case GESTURES_BUTTON_RIGHT:
- return AMOTION_EVENT_BUTTON_SECONDARY;
- case GESTURES_BUTTON_BACK:
- return AMOTION_EVENT_BUTTON_BACK;
- case GESTURES_BUTTON_FORWARD:
- return AMOTION_EVENT_BUTTON_FORWARD;
- default:
- return 0;
- }
-}
-
} // namespace
TouchpadInputMapper::TouchpadInputMapper(InputDeviceContext& deviceContext)
: InputMapper(deviceContext),
mGestureInterpreter(NewGestureInterpreter(), DeleteGestureInterpreter),
mPointerController(getContext()->getPointerController(getDeviceId())),
- mTouchButtonAccumulator(deviceContext) {
+ mStateConverter(deviceContext),
+ mGestureConverter(*getContext(), getDeviceId()) {
mGestureInterpreter->Initialize(GESTURES_DEVCLASS_TOUCHPAD);
mGestureInterpreter->SetHardwareProperties(createHardwareProperties(deviceContext));
// Even though we don't explicitly delete copy/move semantics, it's safe to
@@ -116,16 +99,6 @@
mGestureInterpreter->SetCallback(gestureInterpreterCallback, this);
// TODO(b/251196347): set a property provider, so we can change gesture properties.
// TODO(b/251196347): set a timer provider, so the library can use timers.
-
- RawAbsoluteAxisInfo slotAxisInfo;
- getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
- if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
- ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
- "properly.",
- getDeviceName().c_str());
- }
- mMotionAccumulator.configure(getDeviceContext(), slotAxisInfo.maxValue + 1, true);
- mTouchButtonAccumulator.configure();
}
TouchpadInputMapper::~TouchpadInputMapper() {
@@ -139,82 +112,27 @@
}
std::list<NotifyArgs> TouchpadInputMapper::reset(nsecs_t when) {
- mCursorButtonAccumulator.reset(getDeviceContext());
- mTouchButtonAccumulator.reset();
- mMscTimestamp = 0;
-
- mButtonState = 0;
+ mStateConverter.reset();
+ mGestureConverter.reset();
return InputMapper::reset(when);
}
std::list<NotifyArgs> TouchpadInputMapper::process(const RawEvent* rawEvent) {
- std::list<NotifyArgs> out = {};
- if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
- out = sync(rawEvent->when, rawEvent->readTime);
+ std::optional<SelfContainedHardwareState> state = mStateConverter.processRawEvent(rawEvent);
+ if (state) {
+ return sendHardwareState(rawEvent->when, rawEvent->readTime, *state);
+ } else {
+ return {};
}
- if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
- mMscTimestamp = rawEvent->value;
- }
- mCursorButtonAccumulator.process(rawEvent);
- mMotionAccumulator.process(rawEvent);
- mTouchButtonAccumulator.process(rawEvent);
- return out;
}
-std::list<NotifyArgs> TouchpadInputMapper::sync(nsecs_t when, nsecs_t readTime) {
- HardwareState hwState;
- // The gestures library uses doubles to represent timestamps in seconds.
- hwState.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
- hwState.msc_timestamp =
- std::chrono::duration<stime_t>(std::chrono::microseconds(mMscTimestamp)).count();
-
- hwState.buttons_down = 0;
- if (mCursorButtonAccumulator.isLeftPressed()) {
- hwState.buttons_down |= GESTURES_BUTTON_LEFT;
- }
- if (mCursorButtonAccumulator.isMiddlePressed()) {
- hwState.buttons_down |= GESTURES_BUTTON_MIDDLE;
- }
- if (mCursorButtonAccumulator.isRightPressed()) {
- hwState.buttons_down |= GESTURES_BUTTON_RIGHT;
- }
- if (mCursorButtonAccumulator.isBackPressed() || mCursorButtonAccumulator.isSidePressed()) {
- hwState.buttons_down |= GESTURES_BUTTON_BACK;
- }
- if (mCursorButtonAccumulator.isForwardPressed() || mCursorButtonAccumulator.isExtraPressed()) {
- hwState.buttons_down |= GESTURES_BUTTON_FORWARD;
- }
-
- std::vector<FingerState> fingers;
- for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
- MultiTouchMotionAccumulator::Slot slot = mMotionAccumulator.getSlot(i);
- if (slot.isInUse()) {
- FingerState& fingerState = fingers.emplace_back();
- fingerState = {};
- fingerState.touch_major = slot.getTouchMajor();
- fingerState.touch_minor = slot.getTouchMinor();
- fingerState.width_major = slot.getToolMajor();
- fingerState.width_minor = slot.getToolMinor();
- fingerState.pressure = slot.getPressure();
- fingerState.orientation = slot.getOrientation();
- fingerState.position_x = slot.getX();
- fingerState.position_y = slot.getY();
- fingerState.tracking_id = slot.getTrackingId();
- }
- }
- hwState.fingers = fingers.data();
- hwState.finger_cnt = fingers.size();
- hwState.touch_cnt = mTouchButtonAccumulator.getTouchCount();
-
+std::list<NotifyArgs> TouchpadInputMapper::sendHardwareState(nsecs_t when, nsecs_t readTime,
+ SelfContainedHardwareState schs) {
mProcessing = true;
- mGestureInterpreter->PushHardwareState(&hwState);
+ mGestureInterpreter->PushHardwareState(&schs.state);
mProcessing = false;
- std::list<NotifyArgs> out = processGestures(when, readTime);
-
- mMotionAccumulator.finishSync();
- mMscTimestamp = 0;
- return out;
+ return processGestures(when, readTime);
}
void TouchpadInputMapper::consumeGesture(const Gesture* gesture) {
@@ -229,137 +147,10 @@
std::list<NotifyArgs> TouchpadInputMapper::processGestures(nsecs_t when, nsecs_t readTime) {
std::list<NotifyArgs> out = {};
for (Gesture& gesture : mGesturesToProcess) {
- switch (gesture.type) {
- case kGestureTypeMove:
- out.push_back(handleMove(when, readTime, gesture));
- break;
- case kGestureTypeButtonsChange:
- out += handleButtonsChange(when, readTime, gesture);
- break;
- default:
- // TODO(b/251196347): handle more gesture types.
- break;
- }
+ out += mGestureConverter.handleGesture(when, readTime, gesture);
}
mGesturesToProcess.clear();
return out;
}
-NotifyArgs TouchpadInputMapper::handleMove(nsecs_t when, nsecs_t readTime, const Gesture& gesture) {
- PointerProperties props;
- props.clear();
- props.id = 0;
- props.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
-
- mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
- mPointerController->move(gesture.details.move.dx, gesture.details.move.dy);
- mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
- float xCursorPosition, yCursorPosition;
- mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
-
- PointerCoords coords;
- coords.clear();
- coords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
- coords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
- coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, gesture.details.move.dx);
- coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, gesture.details.move.dy);
- const bool down = isPointerDown(mButtonState);
- coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
-
- const int32_t action = down ? AMOTION_EVENT_ACTION_MOVE : AMOTION_EVENT_ACTION_HOVER_MOVE;
- return makeMotionArgs(when, readTime, action, /* actionButton= */ 0, mButtonState,
- /* pointerCount= */ 1, &props, &coords, xCursorPosition, yCursorPosition);
-}
-
-std::list<NotifyArgs> TouchpadInputMapper::handleButtonsChange(nsecs_t when, nsecs_t readTime,
- const Gesture& gesture) {
- std::list<NotifyArgs> out = {};
-
- mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
- mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
-
- PointerProperties props;
- props.clear();
- props.id = 0;
- props.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
-
- float xCursorPosition, yCursorPosition;
- mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
-
- PointerCoords coords;
- coords.clear();
- coords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
- coords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
- coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, 0);
- coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, 0);
- const uint32_t buttonsPressed = gesture.details.buttons.down;
- bool pointerDown = isPointerDown(mButtonState) ||
- buttonsPressed &
- (GESTURES_BUTTON_LEFT | GESTURES_BUTTON_MIDDLE | GESTURES_BUTTON_RIGHT);
- coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerDown ? 1.0f : 0.0f);
-
- uint32_t newButtonState = mButtonState;
- std::list<NotifyArgs> pressEvents = {};
- for (uint32_t button = 1; button <= GESTURES_BUTTON_FORWARD; button <<= 1) {
- if (buttonsPressed & button) {
- uint32_t actionButton = gesturesButtonToMotionEventButton(button);
- newButtonState |= actionButton;
- pressEvents.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_BUTTON_PRESS,
- actionButton, newButtonState,
- /* pointerCount= */ 1, &props, &coords,
- xCursorPosition, yCursorPosition));
- }
- }
- if (!isPointerDown(mButtonState) && isPointerDown(newButtonState)) {
- mDownTime = when;
- out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_DOWN,
- /* actionButton= */ 0, newButtonState, /* pointerCount= */ 1,
- &props, &coords, xCursorPosition, yCursorPosition));
- }
- out.splice(out.end(), pressEvents);
-
- // The same button may be in both down and up in the same gesture, in which case we should treat
- // it as having gone down and then up. So, we treat a single button change gesture as two state
- // changes: a set of buttons going down, followed by a set of buttons going up.
- mButtonState = newButtonState;
-
- const uint32_t buttonsReleased = gesture.details.buttons.up;
- for (uint32_t button = 1; button <= GESTURES_BUTTON_FORWARD; button <<= 1) {
- if (buttonsReleased & button) {
- uint32_t actionButton = gesturesButtonToMotionEventButton(button);
- newButtonState &= ~actionButton;
- out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
- actionButton, newButtonState, /* pointerCount= */ 1,
- &props, &coords, xCursorPosition, yCursorPosition));
- }
- }
- if (isPointerDown(mButtonState) && !isPointerDown(newButtonState)) {
- coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
- out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_UP, /* actionButton= */ 0,
- newButtonState, /* pointerCount= */ 1, &props, &coords,
- xCursorPosition, yCursorPosition));
- }
- mButtonState = newButtonState;
- return out;
-}
-
-NotifyMotionArgs TouchpadInputMapper::makeMotionArgs(nsecs_t when, nsecs_t readTime, int32_t action,
- int32_t actionButton, int32_t buttonState,
- uint32_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords,
- float xCursorPosition, float yCursorPosition) {
- // TODO(b/260226362): consider what the appropriate source for these events is.
- const uint32_t source = AINPUT_SOURCE_MOUSE;
-
- return NotifyMotionArgs(getContext()->getNextId(), when, readTime, getDeviceId(), source,
- mPointerController->getDisplayId(), /* policyFlags= */ 0, action,
- /* actionButton= */ actionButton, /* flags= */ 0,
- getContext()->getGlobalMetaState(), buttonState,
- MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount,
- pointerProperties, pointerCoords,
- /* xPrecision= */ 1.0f, /* yPrecision= */ 1.0f, xCursorPosition,
- yCursorPosition, /* downTime= */ mDownTime, /* videoFrames= */ {});
-}
-
} // namespace android
diff --git a/services/inputflinger/reader/mapper/TouchpadInputMapper.h b/services/inputflinger/reader/mapper/TouchpadInputMapper.h
index fe6b1fe..b3bc831 100644
--- a/services/inputflinger/reader/mapper/TouchpadInputMapper.h
+++ b/services/inputflinger/reader/mapper/TouchpadInputMapper.h
@@ -16,7 +16,9 @@
#pragma once
+#include <list>
#include <memory>
+#include <vector>
#include <PointerControllerInterface.h>
@@ -24,9 +26,8 @@
#include "InputDevice.h"
#include "InputMapper.h"
#include "NotifyArgs.h"
-#include "accumulator/CursorButtonAccumulator.h"
-#include "accumulator/MultiTouchMotionAccumulator.h"
-#include "accumulator/TouchButtonAccumulator.h"
+#include "gestures/GestureConverter.h"
+#include "gestures/HardwareStateConverter.h"
#include "include/gestures.h"
@@ -44,35 +45,19 @@
void consumeGesture(const Gesture* gesture);
private:
- [[nodiscard]] std::list<NotifyArgs> sync(nsecs_t when, nsecs_t readTime);
+ [[nodiscard]] std::list<NotifyArgs> sendHardwareState(nsecs_t when, nsecs_t readTime,
+ SelfContainedHardwareState schs);
[[nodiscard]] std::list<NotifyArgs> processGestures(nsecs_t when, nsecs_t readTime);
- NotifyArgs handleMove(nsecs_t when, nsecs_t readTime, const Gesture& gesture);
- [[nodiscard]] std::list<NotifyArgs> handleButtonsChange(nsecs_t when, nsecs_t readTime,
- const Gesture& gesture);
-
- NotifyMotionArgs makeMotionArgs(nsecs_t when, nsecs_t readTime, int32_t action,
- int32_t actionButton, int32_t buttonState,
- uint32_t pointerCount,
- const PointerProperties* pointerProperties,
- const PointerCoords* pointerCoords, float xCursorPosition,
- float yCursorPosition);
std::unique_ptr<gestures::GestureInterpreter, void (*)(gestures::GestureInterpreter*)>
mGestureInterpreter;
std::shared_ptr<PointerControllerInterface> mPointerController;
- CursorButtonAccumulator mCursorButtonAccumulator;
- MultiTouchMotionAccumulator mMotionAccumulator;
- TouchButtonAccumulator mTouchButtonAccumulator;
- int32_t mMscTimestamp = 0;
+ HardwareStateConverter mStateConverter;
+ GestureConverter mGestureConverter;
bool mProcessing = false;
std::vector<Gesture> mGesturesToProcess;
-
- // The current button state according to the gestures library, but converted into MotionEvent
- // button values (AMOTION_EVENT_BUTTON_...).
- uint32_t mButtonState = 0;
- nsecs_t mDownTime = 0;
};
} // namespace android
diff --git a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.cpp b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.cpp
index 2d7d73b..153236c 100644
--- a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.cpp
+++ b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.cpp
@@ -25,7 +25,7 @@
clearButtons();
}
-void CursorButtonAccumulator::reset(InputDeviceContext& deviceContext) {
+void CursorButtonAccumulator::reset(const InputDeviceContext& deviceContext) {
mBtnLeft = deviceContext.isKeyPressed(BTN_LEFT);
mBtnRight = deviceContext.isKeyPressed(BTN_RIGHT);
mBtnMiddle = deviceContext.isKeyPressed(BTN_MIDDLE);
diff --git a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
index 1380604..6960644 100644
--- a/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/CursorButtonAccumulator.h
@@ -27,7 +27,7 @@
class CursorButtonAccumulator {
public:
CursorButtonAccumulator();
- void reset(InputDeviceContext& deviceContext);
+ void reset(const InputDeviceContext& deviceContext);
void process(const RawEvent* rawEvent);
diff --git a/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.cpp b/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.cpp
index 8746729..f6a42bd 100644
--- a/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.cpp
+++ b/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.cpp
@@ -26,8 +26,8 @@
MultiTouchMotionAccumulator::MultiTouchMotionAccumulator()
: mCurrentSlot(-1), mUsingSlotsProtocol(false) {}
-void MultiTouchMotionAccumulator::configure(InputDeviceContext& deviceContext, size_t slotCount,
- bool usingSlotsProtocol) {
+void MultiTouchMotionAccumulator::configure(const InputDeviceContext& deviceContext,
+ size_t slotCount, bool usingSlotsProtocol) {
mUsingSlotsProtocol = usingSlotsProtocol;
mSlots = std::vector<Slot>(slotCount);
diff --git a/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.h b/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.h
index 62bc780..3c1a2a9 100644
--- a/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/MultiTouchMotionAccumulator.h
@@ -72,7 +72,8 @@
MultiTouchMotionAccumulator();
- void configure(InputDeviceContext& deviceContext, size_t slotCount, bool usingSlotsProtocol);
+ void configure(const InputDeviceContext& deviceContext, size_t slotCount,
+ bool usingSlotsProtocol);
void process(const RawEvent* rawEvent);
void finishSync();
diff --git a/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h b/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
index 2e70e2e..c2aa2ad 100644
--- a/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
+++ b/services/inputflinger/reader/mapper/accumulator/TouchButtonAccumulator.h
@@ -27,7 +27,7 @@
/* Keeps track of the state of touch, stylus and tool buttons. */
class TouchButtonAccumulator {
public:
- explicit TouchButtonAccumulator(InputDeviceContext& deviceContext)
+ explicit TouchButtonAccumulator(const InputDeviceContext& deviceContext)
: mDeviceContext(deviceContext){};
void configure();
@@ -65,7 +65,7 @@
HidUsageAccumulator mHidUsageAccumulator{};
- InputDeviceContext& mDeviceContext;
+ const InputDeviceContext& mDeviceContext;
void processMappedKey(int32_t scanCode, bool down);
};
diff --git a/services/inputflinger/reader/mapper/gestures/GestureConverter.cpp b/services/inputflinger/reader/mapper/gestures/GestureConverter.cpp
new file mode 100644
index 0000000..23216d3
--- /dev/null
+++ b/services/inputflinger/reader/mapper/gestures/GestureConverter.cpp
@@ -0,0 +1,186 @@
+/*
+ * 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 "gestures/GestureConverter.h"
+
+#include <android/input.h>
+
+#include "TouchCursorInputMapperCommon.h"
+#include "input/Input.h"
+
+namespace android {
+
+namespace {
+
+uint32_t gesturesButtonToMotionEventButton(uint32_t gesturesButton) {
+ switch (gesturesButton) {
+ case GESTURES_BUTTON_LEFT:
+ return AMOTION_EVENT_BUTTON_PRIMARY;
+ case GESTURES_BUTTON_MIDDLE:
+ return AMOTION_EVENT_BUTTON_TERTIARY;
+ case GESTURES_BUTTON_RIGHT:
+ return AMOTION_EVENT_BUTTON_SECONDARY;
+ case GESTURES_BUTTON_BACK:
+ return AMOTION_EVENT_BUTTON_BACK;
+ case GESTURES_BUTTON_FORWARD:
+ return AMOTION_EVENT_BUTTON_FORWARD;
+ default:
+ return 0;
+ }
+}
+
+} // namespace
+
+GestureConverter::GestureConverter(InputReaderContext& readerContext, int32_t deviceId)
+ : mDeviceId(deviceId),
+ mReaderContext(readerContext),
+ mPointerController(readerContext.getPointerController(deviceId)) {}
+
+void GestureConverter::reset() {
+ mButtonState = 0;
+}
+
+std::list<NotifyArgs> GestureConverter::handleGesture(nsecs_t when, nsecs_t readTime,
+ const Gesture& gesture) {
+ switch (gesture.type) {
+ case kGestureTypeMove:
+ return {handleMove(when, readTime, gesture)};
+ case kGestureTypeButtonsChange:
+ return handleButtonsChange(when, readTime, gesture);
+ default:
+ // TODO(b/251196347): handle more gesture types.
+ return {};
+ }
+}
+
+NotifyArgs GestureConverter::handleMove(nsecs_t when, nsecs_t readTime, const Gesture& gesture) {
+ PointerProperties props;
+ props.clear();
+ props.id = 0;
+ props.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
+
+ mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
+ mPointerController->move(gesture.details.move.dx, gesture.details.move.dy);
+ mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
+ float xCursorPosition, yCursorPosition;
+ mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
+
+ PointerCoords coords;
+ coords.clear();
+ coords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, gesture.details.move.dx);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, gesture.details.move.dy);
+ const bool down = isPointerDown(mButtonState);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f);
+
+ const int32_t action = down ? AMOTION_EVENT_ACTION_MOVE : AMOTION_EVENT_ACTION_HOVER_MOVE;
+ return makeMotionArgs(when, readTime, action, /* actionButton= */ 0, mButtonState,
+ /* pointerCount= */ 1, &props, &coords, xCursorPosition, yCursorPosition);
+}
+
+std::list<NotifyArgs> GestureConverter::handleButtonsChange(nsecs_t when, nsecs_t readTime,
+ const Gesture& gesture) {
+ std::list<NotifyArgs> out = {};
+
+ mPointerController->setPresentation(PointerControllerInterface::Presentation::POINTER);
+ mPointerController->unfade(PointerControllerInterface::Transition::IMMEDIATE);
+
+ PointerProperties props;
+ props.clear();
+ props.id = 0;
+ props.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER;
+
+ float xCursorPosition, yCursorPosition;
+ mPointerController->getPosition(&xCursorPosition, &yCursorPosition);
+
+ PointerCoords coords;
+ coords.clear();
+ coords.setAxisValue(AMOTION_EVENT_AXIS_X, xCursorPosition);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_Y, yCursorPosition);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, 0);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, 0);
+ const uint32_t buttonsPressed = gesture.details.buttons.down;
+ bool pointerDown = isPointerDown(mButtonState) ||
+ buttonsPressed &
+ (GESTURES_BUTTON_LEFT | GESTURES_BUTTON_MIDDLE | GESTURES_BUTTON_RIGHT);
+ coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pointerDown ? 1.0f : 0.0f);
+
+ uint32_t newButtonState = mButtonState;
+ std::list<NotifyArgs> pressEvents = {};
+ for (uint32_t button = 1; button <= GESTURES_BUTTON_FORWARD; button <<= 1) {
+ if (buttonsPressed & button) {
+ uint32_t actionButton = gesturesButtonToMotionEventButton(button);
+ newButtonState |= actionButton;
+ pressEvents.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_BUTTON_PRESS,
+ actionButton, newButtonState,
+ /* pointerCount= */ 1, &props, &coords,
+ xCursorPosition, yCursorPosition));
+ }
+ }
+ if (!isPointerDown(mButtonState) && isPointerDown(newButtonState)) {
+ mDownTime = when;
+ out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_DOWN,
+ /* actionButton= */ 0, newButtonState, /* pointerCount= */ 1,
+ &props, &coords, xCursorPosition, yCursorPosition));
+ }
+ out.splice(out.end(), pressEvents);
+
+ // The same button may be in both down and up in the same gesture, in which case we should treat
+ // it as having gone down and then up. So, we treat a single button change gesture as two state
+ // changes: a set of buttons going down, followed by a set of buttons going up.
+ mButtonState = newButtonState;
+
+ const uint32_t buttonsReleased = gesture.details.buttons.up;
+ for (uint32_t button = 1; button <= GESTURES_BUTTON_FORWARD; button <<= 1) {
+ if (buttonsReleased & button) {
+ uint32_t actionButton = gesturesButtonToMotionEventButton(button);
+ newButtonState &= ~actionButton;
+ out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_BUTTON_RELEASE,
+ actionButton, newButtonState, /* pointerCount= */ 1,
+ &props, &coords, xCursorPosition, yCursorPosition));
+ }
+ }
+ if (isPointerDown(mButtonState) && !isPointerDown(newButtonState)) {
+ coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 0.0f);
+ out.push_back(makeMotionArgs(when, readTime, AMOTION_EVENT_ACTION_UP, /* actionButton= */ 0,
+ newButtonState, /* pointerCount= */ 1, &props, &coords,
+ xCursorPosition, yCursorPosition));
+ }
+ mButtonState = newButtonState;
+ return out;
+}
+
+NotifyMotionArgs GestureConverter::makeMotionArgs(nsecs_t when, nsecs_t readTime, int32_t action,
+ int32_t actionButton, int32_t buttonState,
+ uint32_t pointerCount,
+ const PointerProperties* pointerProperties,
+ const PointerCoords* pointerCoords,
+ float xCursorPosition, float yCursorPosition) {
+ // TODO(b/260226362): consider what the appropriate source for these events is.
+ const uint32_t source = AINPUT_SOURCE_MOUSE;
+
+ return NotifyMotionArgs(mReaderContext.getNextId(), when, readTime, mDeviceId, source,
+ mPointerController->getDisplayId(), /* policyFlags= */ 0, action,
+ /* actionButton= */ actionButton, /* flags= */ 0,
+ mReaderContext.getGlobalMetaState(), buttonState,
+ MotionClassification::NONE, AMOTION_EVENT_EDGE_FLAG_NONE, pointerCount,
+ pointerProperties, pointerCoords,
+ /* xPrecision= */ 1.0f, /* yPrecision= */ 1.0f, xCursorPosition,
+ yCursorPosition, /* downTime= */ mDownTime, /* videoFrames= */ {});
+}
+
+} // namespace android
diff --git a/services/inputflinger/reader/mapper/gestures/GestureConverter.h b/services/inputflinger/reader/mapper/gestures/GestureConverter.h
new file mode 100644
index 0000000..dc11f24
--- /dev/null
+++ b/services/inputflinger/reader/mapper/gestures/GestureConverter.h
@@ -0,0 +1,65 @@
+/*
+ * 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 <list>
+#include <memory>
+
+#include <PointerControllerInterface.h>
+#include <utils/Timers.h>
+
+#include "InputReaderContext.h"
+#include "NotifyArgs.h"
+
+#include "include/gestures.h"
+
+namespace android {
+
+// Converts Gesture structs from the gestures library into NotifyArgs and the appropriate
+// PointerController calls.
+class GestureConverter {
+public:
+ GestureConverter(InputReaderContext& readerContext, int32_t deviceId);
+
+ void reset();
+
+ [[nodiscard]] std::list<NotifyArgs> handleGesture(nsecs_t when, nsecs_t readTime,
+ const Gesture& gesture);
+
+private:
+ NotifyArgs handleMove(nsecs_t when, nsecs_t readTime, const Gesture& gesture);
+ [[nodiscard]] std::list<NotifyArgs> handleButtonsChange(nsecs_t when, nsecs_t readTime,
+ const Gesture& gesture);
+
+ NotifyMotionArgs makeMotionArgs(nsecs_t when, nsecs_t readTime, int32_t action,
+ int32_t actionButton, int32_t buttonState,
+ uint32_t pointerCount,
+ const PointerProperties* pointerProperties,
+ const PointerCoords* pointerCoords, float xCursorPosition,
+ float yCursorPosition);
+
+ const int32_t mDeviceId;
+ InputReaderContext& mReaderContext;
+ std::shared_ptr<PointerControllerInterface> mPointerController;
+
+ // The current button state according to the gestures library, but converted into MotionEvent
+ // button values (AMOTION_EVENT_BUTTON_...).
+ uint32_t mButtonState = 0;
+ nsecs_t mDownTime = 0;
+};
+
+} // namespace android
diff --git a/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.cpp b/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.cpp
new file mode 100644
index 0000000..2e175b8
--- /dev/null
+++ b/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.cpp
@@ -0,0 +1,109 @@
+/*
+ * 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 "gestures/HardwareStateConverter.h"
+
+#include <chrono>
+#include <vector>
+
+#include <linux/input-event-codes.h>
+
+namespace android {
+
+HardwareStateConverter::HardwareStateConverter(const InputDeviceContext& deviceContext)
+ : mDeviceContext(deviceContext), mTouchButtonAccumulator(deviceContext) {
+ RawAbsoluteAxisInfo slotAxisInfo;
+ deviceContext.getAbsoluteAxisInfo(ABS_MT_SLOT, &slotAxisInfo);
+ if (!slotAxisInfo.valid || slotAxisInfo.maxValue <= 0) {
+ ALOGW("Touchpad \"%s\" doesn't have a valid ABS_MT_SLOT axis, and probably won't work "
+ "properly.",
+ deviceContext.getName().c_str());
+ }
+ mMotionAccumulator.configure(deviceContext, slotAxisInfo.maxValue + 1, true);
+ mTouchButtonAccumulator.configure();
+}
+
+std::optional<SelfContainedHardwareState> HardwareStateConverter::processRawEvent(
+ const RawEvent* rawEvent) {
+ std::optional<SelfContainedHardwareState> out;
+ if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {
+ out = produceHardwareState(rawEvent->when);
+ mMotionAccumulator.finishSync();
+ mMscTimestamp = 0;
+ }
+ if (rawEvent->type == EV_MSC && rawEvent->code == MSC_TIMESTAMP) {
+ mMscTimestamp = rawEvent->value;
+ }
+ mCursorButtonAccumulator.process(rawEvent);
+ mMotionAccumulator.process(rawEvent);
+ mTouchButtonAccumulator.process(rawEvent);
+ return out;
+}
+
+SelfContainedHardwareState HardwareStateConverter::produceHardwareState(nsecs_t when) {
+ SelfContainedHardwareState schs;
+ // The gestures library uses doubles to represent timestamps in seconds.
+ schs.state.timestamp = std::chrono::duration<stime_t>(std::chrono::nanoseconds(when)).count();
+ schs.state.msc_timestamp =
+ std::chrono::duration<stime_t>(std::chrono::microseconds(mMscTimestamp)).count();
+
+ schs.state.buttons_down = 0;
+ if (mCursorButtonAccumulator.isLeftPressed()) {
+ schs.state.buttons_down |= GESTURES_BUTTON_LEFT;
+ }
+ if (mCursorButtonAccumulator.isMiddlePressed()) {
+ schs.state.buttons_down |= GESTURES_BUTTON_MIDDLE;
+ }
+ if (mCursorButtonAccumulator.isRightPressed()) {
+ schs.state.buttons_down |= GESTURES_BUTTON_RIGHT;
+ }
+ if (mCursorButtonAccumulator.isBackPressed() || mCursorButtonAccumulator.isSidePressed()) {
+ schs.state.buttons_down |= GESTURES_BUTTON_BACK;
+ }
+ if (mCursorButtonAccumulator.isForwardPressed() || mCursorButtonAccumulator.isExtraPressed()) {
+ schs.state.buttons_down |= GESTURES_BUTTON_FORWARD;
+ }
+
+ schs.fingers.clear();
+ for (size_t i = 0; i < mMotionAccumulator.getSlotCount(); i++) {
+ MultiTouchMotionAccumulator::Slot slot = mMotionAccumulator.getSlot(i);
+ if (slot.isInUse()) {
+ FingerState& fingerState = schs.fingers.emplace_back();
+ fingerState = {};
+ fingerState.touch_major = slot.getTouchMajor();
+ fingerState.touch_minor = slot.getTouchMinor();
+ fingerState.width_major = slot.getToolMajor();
+ fingerState.width_minor = slot.getToolMinor();
+ fingerState.pressure = slot.getPressure();
+ fingerState.orientation = slot.getOrientation();
+ fingerState.position_x = slot.getX();
+ fingerState.position_y = slot.getY();
+ fingerState.tracking_id = slot.getTrackingId();
+ }
+ }
+ schs.state.fingers = schs.fingers.data();
+ schs.state.finger_cnt = schs.fingers.size();
+ schs.state.touch_cnt = mTouchButtonAccumulator.getTouchCount();
+ return schs;
+}
+
+void HardwareStateConverter::reset() {
+ mCursorButtonAccumulator.reset(mDeviceContext);
+ mTouchButtonAccumulator.reset();
+ mMscTimestamp = 0;
+}
+
+} // namespace android
diff --git a/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.h b/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.h
new file mode 100644
index 0000000..8831299
--- /dev/null
+++ b/services/inputflinger/reader/mapper/gestures/HardwareStateConverter.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 <optional>
+
+#include <utils/Timers.h>
+
+#include "EventHub.h"
+#include "InputDevice.h"
+#include "accumulator/CursorButtonAccumulator.h"
+#include "accumulator/MultiTouchMotionAccumulator.h"
+#include "accumulator/TouchButtonAccumulator.h"
+
+#include "include/gestures.h"
+
+namespace android {
+
+// A HardwareState struct, but bundled with a vector to contain its FingerStates, so you don't have
+// to worry about where that memory is allocated.
+struct SelfContainedHardwareState {
+ HardwareState state;
+ std::vector<FingerState> fingers;
+};
+
+// Converts RawEvents into the HardwareState structs used by the gestures library.
+class HardwareStateConverter {
+public:
+ HardwareStateConverter(const InputDeviceContext& deviceContext);
+
+ std::optional<SelfContainedHardwareState> processRawEvent(const RawEvent* event);
+ void reset();
+
+private:
+ SelfContainedHardwareState produceHardwareState(nsecs_t when);
+
+ const InputDeviceContext& mDeviceContext;
+ CursorButtonAccumulator mCursorButtonAccumulator;
+ MultiTouchMotionAccumulator mMotionAccumulator;
+ TouchButtonAccumulator mTouchButtonAccumulator;
+ int32_t mMscTimestamp = 0;
+};
+
+} // namespace android
diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp
index 53d821f..58a5c31 100644
--- a/services/inputflinger/tests/Android.bp
+++ b/services/inputflinger/tests/Android.bp
@@ -44,6 +44,8 @@
"FakeInputReaderPolicy.cpp",
"FakePointerController.cpp",
"FocusResolver_test.cpp",
+ "GestureConverter_test.cpp",
+ "HardwareStateConverter_test.cpp",
"InputMapperTest.cpp",
"InputProcessor_test.cpp",
"InputProcessorConverter_test.cpp",
diff --git a/services/inputflinger/tests/FakeInputReaderPolicy.cpp b/services/inputflinger/tests/FakeInputReaderPolicy.cpp
index 3af4298..f755356 100644
--- a/services/inputflinger/tests/FakeInputReaderPolicy.cpp
+++ b/services/inputflinger/tests/FakeInputReaderPolicy.cpp
@@ -126,11 +126,21 @@
mConfig.portAssociations.insert({inputPort, displayPort});
}
+void FakeInputReaderPolicy::addDeviceTypeAssociation(const std::string& inputPort,
+ const std::string& type) {
+ mConfig.deviceTypeAssociations.insert({inputPort, type});
+}
+
void FakeInputReaderPolicy::addInputUniqueIdAssociation(const std::string& inputUniqueId,
const std::string& displayUniqueId) {
mConfig.uniqueIdAssociations.insert({inputUniqueId, displayUniqueId});
}
+void FakeInputReaderPolicy::addKeyboardLayoutAssociation(const std::string& inputUniqueId,
+ const KeyboardLayoutInfo& layoutInfo) {
+ mConfig.keyboardLayoutAssociations.insert({inputUniqueId, layoutInfo});
+}
+
void FakeInputReaderPolicy::addDisabledDevice(int32_t deviceId) {
mConfig.disabledDevices.insert(deviceId);
}
diff --git a/services/inputflinger/tests/FakeInputReaderPolicy.h b/services/inputflinger/tests/FakeInputReaderPolicy.h
index c16cda4..862ff0b 100644
--- a/services/inputflinger/tests/FakeInputReaderPolicy.h
+++ b/services/inputflinger/tests/FakeInputReaderPolicy.h
@@ -55,8 +55,11 @@
bool updateViewport(const DisplayViewport& viewport);
void addExcludedDeviceName(const std::string& deviceName);
void addInputPortAssociation(const std::string& inputPort, uint8_t displayPort);
+ void addDeviceTypeAssociation(const std::string& inputPort, const std::string& type);
void addInputUniqueIdAssociation(const std::string& inputUniqueId,
const std::string& displayUniqueId);
+ void addKeyboardLayoutAssociation(const std::string& inputUniqueId,
+ const KeyboardLayoutInfo& layoutInfo);
void addDisabledDevice(int32_t deviceId);
void removeDisabledDevice(int32_t deviceId);
void setPointerController(std::shared_ptr<FakePointerController> controller);
diff --git a/services/inputflinger/tests/FakePointerController.cpp b/services/inputflinger/tests/FakePointerController.cpp
index 635366b..ab7879f 100644
--- a/services/inputflinger/tests/FakePointerController.cpp
+++ b/services/inputflinger/tests/FakePointerController.cpp
@@ -16,6 +16,8 @@
#include "FakePointerController.h"
+#include <gtest/gtest.h>
+
namespace android {
void FakePointerController::setBounds(float minX, float minY, float maxX, float maxY) {
@@ -56,6 +58,13 @@
mDisplayId = viewport.displayId;
}
+void FakePointerController::assertPosition(float x, float y) {
+ float actualX, actualY;
+ getPosition(&actualX, &actualY);
+ ASSERT_NEAR(x, actualX, 1);
+ ASSERT_NEAR(y, actualY, 1);
+}
+
bool FakePointerController::getBounds(float* outMinX, float* outMinY, float* outMaxX,
float* outMaxY) const {
*outMinX = mMinX;
diff --git a/services/inputflinger/tests/FakePointerController.h b/services/inputflinger/tests/FakePointerController.h
index f00870f..d10cbcd 100644
--- a/services/inputflinger/tests/FakePointerController.h
+++ b/services/inputflinger/tests/FakePointerController.h
@@ -38,6 +38,8 @@
int32_t getDisplayId() const override;
void setDisplayViewport(const DisplayViewport& viewport) override;
+ void assertPosition(float x, float y);
+
private:
bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const override;
void move(float deltaX, float deltaY) override;
diff --git a/services/inputflinger/tests/GestureConverter_test.cpp b/services/inputflinger/tests/GestureConverter_test.cpp
new file mode 100644
index 0000000..91efd1a
--- /dev/null
+++ b/services/inputflinger/tests/GestureConverter_test.cpp
@@ -0,0 +1,200 @@
+/*
+ * 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 <memory>
+
+#include <EventHub.h>
+#include <gestures/GestureConverter.h>
+#include <gtest/gtest.h>
+
+#include "FakeEventHub.h"
+#include "FakeInputReaderPolicy.h"
+#include "FakePointerController.h"
+#include "InstrumentedInputReader.h"
+#include "NotifyArgs.h"
+#include "TestConstants.h"
+#include "TestInputListener.h"
+#include "TestInputListenerMatchers.h"
+#include "include/gestures.h"
+
+namespace android {
+
+using testing::AllOf;
+
+class GestureConverterTest : public testing::Test {
+protected:
+ static constexpr int32_t DEVICE_ID = END_RESERVED_ID + 1000;
+ static constexpr stime_t ARBITRARY_GESTURE_TIME = 1.2;
+ static constexpr float POINTER_X = 100;
+ static constexpr float POINTER_Y = 200;
+
+ void SetUp() {
+ mFakeEventHub = std::make_unique<FakeEventHub>();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
+ mFakeListener = std::make_unique<TestInputListener>();
+ mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
+ *mFakeListener);
+
+ mFakePointerController = std::make_shared<FakePointerController>();
+ mFakePointerController->setBounds(0, 0, 800 - 1, 480 - 1);
+ mFakePointerController->setPosition(POINTER_X, POINTER_Y);
+ mFakePolicy->setPointerController(mFakePointerController);
+ }
+
+ std::shared_ptr<FakeEventHub> mFakeEventHub;
+ sp<FakeInputReaderPolicy> mFakePolicy;
+ std::unique_ptr<TestInputListener> mFakeListener;
+ std::unique_ptr<InstrumentedInputReader> mReader;
+ std::shared_ptr<FakePointerController> mFakePointerController;
+};
+
+TEST_F(GestureConverterTest, Move) {
+ GestureConverter converter(*mReader->getContext(), DEVICE_ID);
+
+ Gesture moveGesture(kGestureMove, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME, -5, 10);
+ std::list<NotifyArgs> args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, moveGesture);
+ ASSERT_EQ(1u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_HOVER_MOVE),
+ WithCoords(POINTER_X - 5, POINTER_Y + 10), WithRelativeMotion(-5, 10),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER), WithButtonState(0),
+ WithPressure(0.0f)));
+
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(95, 210));
+}
+
+TEST_F(GestureConverterTest, ButtonsChange) {
+ GestureConverter converter(*mReader->getContext(), DEVICE_ID);
+
+ // Press left and right buttons at once
+ Gesture downGesture(kGestureButtonsChange, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME,
+ /* down= */ GESTURES_BUTTON_LEFT | GESTURES_BUTTON_RIGHT,
+ /* up= */ GESTURES_BUTTON_NONE, /* is_tap= */ false);
+ std::list<NotifyArgs> args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, downGesture);
+ ASSERT_EQ(3u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY |
+ AMOTION_EVENT_BUTTON_SECONDARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+ args.pop_front();
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
+ WithActionButton(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+ args.pop_front();
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
+ WithActionButton(AMOTION_EVENT_BUTTON_SECONDARY),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY |
+ AMOTION_EVENT_BUTTON_SECONDARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+
+ // Then release the left button
+ Gesture leftUpGesture(kGestureButtonsChange, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME,
+ /* down= */ GESTURES_BUTTON_NONE, /* up= */ GESTURES_BUTTON_LEFT,
+ /* is_tap= */ false);
+ args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, leftUpGesture);
+ ASSERT_EQ(1u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
+ WithActionButton(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithButtonState(AMOTION_EVENT_BUTTON_SECONDARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+
+ // Finally release the right button
+ Gesture rightUpGesture(kGestureButtonsChange, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME,
+ /* down= */ GESTURES_BUTTON_NONE, /* up= */ GESTURES_BUTTON_RIGHT,
+ /* is_tap= */ false);
+ args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, rightUpGesture);
+ ASSERT_EQ(2u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
+ WithActionButton(AMOTION_EVENT_BUTTON_SECONDARY), WithButtonState(0),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+ args.pop_front();
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+}
+
+TEST_F(GestureConverterTest, DragWithButton) {
+ GestureConverter converter(*mReader->getContext(), DEVICE_ID);
+
+ // Press the button
+ Gesture downGesture(kGestureButtonsChange, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME,
+ /* down= */ GESTURES_BUTTON_LEFT, /* up= */ GESTURES_BUTTON_NONE,
+ /* is_tap= */ false);
+ std::list<NotifyArgs> args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, downGesture);
+ ASSERT_EQ(2u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_DOWN),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+ args.pop_front();
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_PRESS),
+ WithActionButton(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY),
+ WithCoords(POINTER_X, POINTER_Y),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+
+ // Move
+ Gesture moveGesture(kGestureMove, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME, -5, 10);
+ args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, moveGesture);
+ ASSERT_EQ(1u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_MOVE),
+ WithCoords(POINTER_X - 5, POINTER_Y + 10), WithRelativeMotion(-5, 10),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER),
+ WithButtonState(AMOTION_EVENT_BUTTON_PRIMARY), WithPressure(1.0f)));
+
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(95, 210));
+
+ // Release the button
+ Gesture upGesture(kGestureButtonsChange, ARBITRARY_GESTURE_TIME, ARBITRARY_GESTURE_TIME,
+ /* down= */ GESTURES_BUTTON_NONE, /* up= */ GESTURES_BUTTON_LEFT,
+ /* is_tap= */ false);
+ args = converter.handleGesture(ARBITRARY_TIME, READ_TIME, upGesture);
+ ASSERT_EQ(2u, args.size());
+
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_BUTTON_RELEASE),
+ WithActionButton(AMOTION_EVENT_BUTTON_PRIMARY), WithButtonState(0),
+ WithCoords(POINTER_X - 5, POINTER_Y + 10),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+ args.pop_front();
+ ASSERT_THAT(std::get<NotifyMotionArgs>(args.front()),
+ AllOf(WithMotionAction(AMOTION_EVENT_ACTION_UP), WithButtonState(0),
+ WithCoords(POINTER_X - 5, POINTER_Y + 10),
+ WithToolType(AMOTION_EVENT_TOOL_TYPE_FINGER)));
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/HardwareStateConverter_test.cpp b/services/inputflinger/tests/HardwareStateConverter_test.cpp
new file mode 100644
index 0000000..7921881
--- /dev/null
+++ b/services/inputflinger/tests/HardwareStateConverter_test.cpp
@@ -0,0 +1,219 @@
+/*
+ * 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 <EventHub.h>
+#include <gestures/HardwareStateConverter.h>
+#include <gtest/gtest.h>
+#include <linux/input-event-codes.h>
+
+#include "FakeEventHub.h"
+#include "FakeInputReaderPolicy.h"
+#include "InstrumentedInputReader.h"
+#include "TestConstants.h"
+#include "TestInputListener.h"
+
+namespace android {
+
+class HardwareStateConverterTest : public testing::Test {
+protected:
+ static constexpr int32_t DEVICE_ID = END_RESERVED_ID + 1000;
+ static constexpr int32_t EVENTHUB_ID = 1;
+
+ void SetUp() {
+ mFakeEventHub = std::make_unique<FakeEventHub>();
+ mFakePolicy = sp<FakeInputReaderPolicy>::make();
+ mFakeListener = std::make_unique<TestInputListener>();
+ mReader = std::make_unique<InstrumentedInputReader>(mFakeEventHub, mFakePolicy,
+ *mFakeListener);
+ mDevice = newDevice();
+
+ mFakeEventHub->addAbsoluteAxis(EVENTHUB_ID, ABS_MT_SLOT, 0, 7, 0, 0, 0);
+ }
+
+ std::shared_ptr<InputDevice> newDevice() {
+ InputDeviceIdentifier identifier;
+ identifier.name = "device";
+ identifier.location = "USB1";
+ identifier.bus = 0;
+ std::shared_ptr<InputDevice> device =
+ std::make_shared<InputDevice>(mReader->getContext(), DEVICE_ID, /* generation= */ 2,
+ identifier);
+ mReader->pushNextDevice(device);
+ mFakeEventHub->addDevice(EVENTHUB_ID, identifier.name, InputDeviceClass::TOUCHPAD,
+ identifier.bus);
+ mReader->loopOnce();
+ return device;
+ }
+
+ void processAxis(HardwareStateConverter& conv, nsecs_t when, int32_t type, int32_t code,
+ int32_t value) {
+ RawEvent event;
+ event.when = when;
+ event.readTime = READ_TIME;
+ event.deviceId = EVENTHUB_ID;
+ event.type = type;
+ event.code = code;
+ event.value = value;
+ std::optional<SelfContainedHardwareState> schs = conv.processRawEvent(&event);
+ EXPECT_FALSE(schs.has_value());
+ }
+
+ std::optional<SelfContainedHardwareState> processSync(HardwareStateConverter& conv,
+ nsecs_t when) {
+ RawEvent event;
+ event.when = when;
+ event.readTime = READ_TIME;
+ event.deviceId = EVENTHUB_ID;
+ event.type = EV_SYN;
+ event.code = SYN_REPORT;
+ event.value = 0;
+ return conv.processRawEvent(&event);
+ }
+
+ std::shared_ptr<FakeEventHub> mFakeEventHub;
+ sp<FakeInputReaderPolicy> mFakePolicy;
+ std::unique_ptr<TestInputListener> mFakeListener;
+ std::unique_ptr<InstrumentedInputReader> mReader;
+ std::shared_ptr<InputDevice> mDevice;
+};
+
+TEST_F(HardwareStateConverterTest, OneFinger) {
+ const nsecs_t time = 1500000000;
+ InputDeviceContext deviceContext(*mDevice, EVENTHUB_ID);
+ HardwareStateConverter conv(deviceContext);
+
+ processAxis(conv, time, EV_ABS, ABS_MT_SLOT, 0);
+ processAxis(conv, time, EV_ABS, ABS_MT_TRACKING_ID, 123);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_X, 50);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_Y, 100);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MAJOR, 5);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MINOR, 4);
+ processAxis(conv, time, EV_ABS, ABS_MT_PRESSURE, 42);
+ processAxis(conv, time, EV_ABS, ABS_MT_ORIENTATION, 2);
+
+ processAxis(conv, time, EV_ABS, ABS_X, 50);
+ processAxis(conv, time, EV_ABS, ABS_Y, 100);
+ processAxis(conv, time, EV_ABS, ABS_PRESSURE, 42);
+
+ processAxis(conv, time, EV_KEY, BTN_TOUCH, 1);
+ processAxis(conv, time, EV_KEY, BTN_TOOL_FINGER, 1);
+ std::optional<SelfContainedHardwareState> schs = processSync(conv, time);
+
+ ASSERT_TRUE(schs.has_value());
+ const HardwareState& state = schs->state;
+ EXPECT_NEAR(1.5, state.timestamp, EPSILON);
+ EXPECT_EQ(0, state.buttons_down);
+ EXPECT_EQ(1, state.touch_cnt);
+
+ ASSERT_EQ(1, state.finger_cnt);
+ const FingerState& finger = state.fingers[0];
+ EXPECT_EQ(123, finger.tracking_id);
+ EXPECT_NEAR(50, finger.position_x, EPSILON);
+ EXPECT_NEAR(100, finger.position_y, EPSILON);
+ EXPECT_NEAR(5, finger.touch_major, EPSILON);
+ EXPECT_NEAR(4, finger.touch_minor, EPSILON);
+ EXPECT_NEAR(42, finger.pressure, EPSILON);
+ EXPECT_NEAR(2, finger.orientation, EPSILON);
+ EXPECT_EQ(0u, finger.flags);
+
+ EXPECT_EQ(0, state.rel_x);
+ EXPECT_EQ(0, state.rel_y);
+ EXPECT_EQ(0, state.rel_wheel);
+ EXPECT_EQ(0, state.rel_wheel_hi_res);
+ EXPECT_EQ(0, state.rel_hwheel);
+ EXPECT_NEAR(0.0, state.msc_timestamp, EPSILON);
+}
+
+TEST_F(HardwareStateConverterTest, TwoFingers) {
+ const nsecs_t time = ARBITRARY_TIME;
+ InputDeviceContext deviceContext(*mDevice, EVENTHUB_ID);
+ HardwareStateConverter conv(deviceContext);
+
+ processAxis(conv, time, EV_ABS, ABS_MT_SLOT, 0);
+ processAxis(conv, time, EV_ABS, ABS_MT_TRACKING_ID, 123);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_X, 50);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_Y, 100);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MAJOR, 5);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MINOR, 4);
+ processAxis(conv, time, EV_ABS, ABS_MT_PRESSURE, 42);
+ processAxis(conv, time, EV_ABS, ABS_MT_ORIENTATION, 2);
+
+ processAxis(conv, time, EV_ABS, ABS_MT_SLOT, 1);
+ processAxis(conv, time, EV_ABS, ABS_MT_TRACKING_ID, 456);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_X, -20);
+ processAxis(conv, time, EV_ABS, ABS_MT_POSITION_Y, 40);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MAJOR, 8);
+ processAxis(conv, time, EV_ABS, ABS_MT_TOUCH_MINOR, 7);
+ processAxis(conv, time, EV_ABS, ABS_MT_PRESSURE, 21);
+ processAxis(conv, time, EV_ABS, ABS_MT_ORIENTATION, 1);
+
+ processAxis(conv, time, EV_ABS, ABS_X, 50);
+ processAxis(conv, time, EV_ABS, ABS_Y, 100);
+ processAxis(conv, time, EV_ABS, ABS_PRESSURE, 42);
+
+ processAxis(conv, time, EV_KEY, BTN_TOUCH, 1);
+ processAxis(conv, time, EV_KEY, BTN_TOOL_DOUBLETAP, 1);
+ std::optional<SelfContainedHardwareState> schs = processSync(conv, time);
+
+ ASSERT_TRUE(schs.has_value());
+ ASSERT_EQ(2, schs->state.finger_cnt);
+ const FingerState& finger1 = schs->state.fingers[0];
+ EXPECT_EQ(123, finger1.tracking_id);
+ EXPECT_NEAR(50, finger1.position_x, EPSILON);
+ EXPECT_NEAR(100, finger1.position_y, EPSILON);
+ EXPECT_NEAR(5, finger1.touch_major, EPSILON);
+ EXPECT_NEAR(4, finger1.touch_minor, EPSILON);
+ EXPECT_NEAR(42, finger1.pressure, EPSILON);
+ EXPECT_NEAR(2, finger1.orientation, EPSILON);
+ EXPECT_EQ(0u, finger1.flags);
+
+ const FingerState& finger2 = schs->state.fingers[1];
+ EXPECT_EQ(456, finger2.tracking_id);
+ EXPECT_NEAR(-20, finger2.position_x, EPSILON);
+ EXPECT_NEAR(40, finger2.position_y, EPSILON);
+ EXPECT_NEAR(8, finger2.touch_major, EPSILON);
+ EXPECT_NEAR(7, finger2.touch_minor, EPSILON);
+ EXPECT_NEAR(21, finger2.pressure, EPSILON);
+ EXPECT_NEAR(1, finger2.orientation, EPSILON);
+ EXPECT_EQ(0u, finger2.flags);
+}
+
+TEST_F(HardwareStateConverterTest, ButtonPressed) {
+ const nsecs_t time = ARBITRARY_TIME;
+ InputDeviceContext deviceContext(*mDevice, EVENTHUB_ID);
+ HardwareStateConverter conv(deviceContext);
+
+ processAxis(conv, time, EV_KEY, BTN_LEFT, 1);
+ std::optional<SelfContainedHardwareState> schs = processSync(conv, time);
+
+ ASSERT_TRUE(schs.has_value());
+ EXPECT_EQ(GESTURES_BUTTON_LEFT, schs->state.buttons_down);
+}
+
+TEST_F(HardwareStateConverterTest, MscTimestamp) {
+ const nsecs_t time = ARBITRARY_TIME;
+ mFakeEventHub->setMscEvent(EVENTHUB_ID, MSC_TIMESTAMP);
+ InputDeviceContext deviceContext(*mDevice, EVENTHUB_ID);
+ HardwareStateConverter conv(deviceContext);
+
+ processAxis(conv, time, EV_MSC, MSC_TIMESTAMP, 1200000);
+ std::optional<SelfContainedHardwareState> schs = processSync(conv, time);
+
+ ASSERT_TRUE(schs.has_value());
+ EXPECT_NEAR(1.2, schs->state.msc_timestamp, EPSILON);
+}
+
+} // namespace android
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 41c174a..864aaea 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -29,6 +29,7 @@
#include <sys/epoll.h>
#include <cinttypes>
+#include <compare>
#include <thread>
#include <unordered_set>
#include <vector>
@@ -56,12 +57,15 @@
static constexpr int32_t DISPLAY_ID = ADISPLAY_ID_DEFAULT;
static constexpr int32_t SECOND_DISPLAY_ID = 1;
+static constexpr int32_t ACTION_OUTSIDE = AMOTION_EVENT_ACTION_OUTSIDE;
static constexpr int32_t POINTER_1_DOWN =
AMOTION_EVENT_ACTION_POINTER_DOWN | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
static constexpr int32_t POINTER_2_DOWN =
AMOTION_EVENT_ACTION_POINTER_DOWN | (2 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
static constexpr int32_t POINTER_3_DOWN =
AMOTION_EVENT_ACTION_POINTER_DOWN | (3 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
+static constexpr int32_t POINTER_0_UP =
+ AMOTION_EVENT_ACTION_POINTER_UP | (0 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
static constexpr int32_t POINTER_1_UP =
AMOTION_EVENT_ACTION_POINTER_UP | (1 << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT);
@@ -81,9 +85,13 @@
static constexpr std::chrono::duration STALE_EVENT_TIMEOUT = 1000ms;
+static constexpr int expectedWallpaperFlags =
+ AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
+
struct PointF {
float x;
float y;
+ auto operator<=>(const PointF&) const = default;
};
/**
@@ -137,6 +145,24 @@
return arg.getSource() == source;
}
+MATCHER_P2(WithCoords, x, y, "MotionEvent with specified coordinates") {
+ if (arg.getPointerCount() != 1) {
+ *result_listener << "Expected 1 pointer, got " << arg.getPointerCount();
+ return false;
+ }
+ return arg.getX(0 /*pointerIndex*/) == x && arg.getY(0 /*pointerIndex*/) == y;
+}
+
+MATCHER_P(WithPointers, pointers, "MotionEvent with specified pointers") {
+ // Build a map for the received pointers, by pointer id
+ std::map<int32_t /*pointerId*/, PointF> actualPointers;
+ for (size_t pointerIndex = 0; pointerIndex < arg.getPointerCount(); pointerIndex++) {
+ const int32_t pointerId = arg.getPointerId(pointerIndex);
+ actualPointers[pointerId] = {arg.getX(pointerIndex), arg.getY(pointerIndex)};
+ }
+ return pointers == actualPointers;
+}
+
// --- FakeInputDispatcherPolicy ---
class FakeInputDispatcherPolicy : public InputDispatcherPolicyInterface {
@@ -1717,8 +1743,6 @@
sp<FakeWindowHandle> wallpaperWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
- constexpr int expectedWallpaperFlags =
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -1761,8 +1785,6 @@
sp<FakeWindowHandle> wallpaperWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
- constexpr int expectedWallpaperFlags =
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -1792,24 +1814,27 @@
foregroundWindow->consumeMotionCancel();
}
+class ShouldSplitTouchFixture : public InputDispatcherTest,
+ public ::testing::WithParamInterface<bool> {};
+INSTANTIATE_TEST_SUITE_P(InputDispatcherTest, ShouldSplitTouchFixture,
+ ::testing::Values(true, false));
/**
* A single window that receives touch (on top), and a wallpaper window underneath it.
* The top window gets a multitouch gesture.
* Ensure that wallpaper gets the same gesture.
*/
-TEST_F(InputDispatcherTest, WallpaperWindow_ReceivesMultiTouch) {
+TEST_P(ShouldSplitTouchFixture, WallpaperWindowReceivesMultiTouch) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
- window->setDupTouchToWallpaper(true);
+ sp<FakeWindowHandle> foregroundWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Foreground", ADISPLAY_ID_DEFAULT);
+ foregroundWindow->setDupTouchToWallpaper(true);
+ foregroundWindow->setPreventSplitting(GetParam());
sp<FakeWindowHandle> wallpaperWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
- constexpr int expectedWallpaperFlags =
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
- mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {foregroundWindow, wallpaperWindow}}});
// Touch down on top window
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
@@ -1818,7 +1843,7 @@
<< "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
// Both top window and its wallpaper should receive the touch down
- window->consumeMotionDown();
+ foregroundWindow->consumeMotionDown();
wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
// Second finger down on the top window
@@ -1837,11 +1862,34 @@
InputEventInjectionSync::WAIT_FOR_RESULT))
<< "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
- window->consumeMotionPointerDown(1 /* pointerIndex */);
+ foregroundWindow->consumeMotionPointerDown(1 /* pointerIndex */);
wallpaperWindow->consumeMotionPointerDown(1 /* pointerIndex */, ADISPLAY_ID_DEFAULT,
expectedWallpaperFlags);
- window->assertNoEvents();
- wallpaperWindow->assertNoEvents();
+
+ const MotionEvent secondFingerUpEvent =
+ MotionEventBuilder(POINTER_0_UP, AINPUT_SOURCE_TOUCHSCREEN)
+ .displayId(ADISPLAY_ID_DEFAULT)
+ .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
+ .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER)
+ .x(100)
+ .y(100))
+ .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER)
+ .x(150)
+ .y(150))
+ .build();
+ ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
+ injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
+ InputEventInjectionSync::WAIT_FOR_RESULT))
+ << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
+ foregroundWindow->consumeMotionPointerUp(0);
+ wallpaperWindow->consumeMotionPointerUp(0, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+
+ ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
+ injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
+ {100, 100}))
+ << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
+ foregroundWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT);
+ wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
}
/**
@@ -1868,8 +1916,6 @@
sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setFrame(Rect(0, 0, 400, 200));
wallpaperWindow->setIsWallpaper(true);
- constexpr int expectedWallpaperFlags =
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
mDispatcher->setInputWindows(
{{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
@@ -1934,62 +1980,49 @@
wallpaperWindow->assertNoEvents();
}
-TEST_F(InputDispatcherTest, WallpaperWindowReceivesMultiTouch) {
+/**
+ * Two windows: a window on the left with dup touch to wallpaper and window on the right without it.
+ * The touch slips to the right window. so left window and wallpaper should receive ACTION_CANCEL
+ * The right window should receive ACTION_DOWN.
+ */
+TEST_F(InputDispatcherTest, WallpaperWindowWhenSlippery) {
std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
- sp<FakeWindowHandle> window =
- sp<FakeWindowHandle>::make(application, mDispatcher, "Top", ADISPLAY_ID_DEFAULT);
- window->setDupTouchToWallpaper(true);
+ sp<FakeWindowHandle> leftWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Left", ADISPLAY_ID_DEFAULT);
+ leftWindow->setFrame(Rect(0, 0, 200, 200));
+ leftWindow->setDupTouchToWallpaper(true);
+ leftWindow->setSlippery(true);
+
+ sp<FakeWindowHandle> rightWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Right", ADISPLAY_ID_DEFAULT);
+ rightWindow->setFrame(Rect(200, 0, 400, 200));
sp<FakeWindowHandle> wallpaperWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
wallpaperWindow->setIsWallpaper(true);
- constexpr int expectedWallpaperFlags =
- AMOTION_EVENT_FLAG_WINDOW_IS_OBSCURED | AMOTION_EVENT_FLAG_WINDOW_IS_PARTIALLY_OBSCURED;
- wallpaperWindow->setPreventSplitting(true);
- mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window, wallpaperWindow}}});
+ mDispatcher->setInputWindows(
+ {{ADISPLAY_ID_DEFAULT, {leftWindow, rightWindow, wallpaperWindow}}});
+ // Touch down on left window
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
injectMotionDown(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
- {50, 50}))
+ {100, 100}))
<< "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
- window->consumeMotionDown(ADISPLAY_ID_DEFAULT);
+
+ // Both foreground window and its wallpaper should receive the touch down
+ leftWindow->consumeMotionDown();
wallpaperWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
- const MotionEvent secondFingerDownEvent =
- MotionEventBuilder(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN)
- .displayId(ADISPLAY_ID_DEFAULT)
- .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
- .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
- .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
- .build();
+ // Move to right window, the left window should receive cancel.
ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
- injectMotionEvent(mDispatcher, secondFingerDownEvent, INJECT_EVENT_TIMEOUT,
- InputEventInjectionSync::WAIT_FOR_RESULT))
+ injectMotionEvent(mDispatcher, AMOTION_EVENT_ACTION_MOVE, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {201, 100}))
<< "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
- window->consumeMotionPointerDown(1);
- wallpaperWindow->consumeMotionPointerDown(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
-
- const MotionEvent secondFingerUpEvent =
- MotionEventBuilder(POINTER_1_UP, AINPUT_SOURCE_TOUCHSCREEN)
- .displayId(ADISPLAY_ID_DEFAULT)
- .eventTime(systemTime(SYSTEM_TIME_MONOTONIC))
- .pointer(PointerBuilder(/* id */ 0, AMOTION_EVENT_TOOL_TYPE_FINGER).x(50).y(50))
- .pointer(PointerBuilder(/* id */ 1, AMOTION_EVENT_TOOL_TYPE_FINGER).x(10).y(10))
- .build();
- ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
- injectMotionEvent(mDispatcher, secondFingerUpEvent, INJECT_EVENT_TIMEOUT,
- InputEventInjectionSync::WAIT_FOR_RESULT))
- << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
- window->consumeMotionPointerUp(1);
- wallpaperWindow->consumeMotionPointerUp(1, ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
-
- ASSERT_EQ(InputEventInjectionResult::SUCCEEDED,
- injectMotionUp(mDispatcher, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT, {50, 50}))
- << "Inject motion event should return InputEventInjectionResult::SUCCEEDED";
- window->consumeMotionUp(ADISPLAY_ID_DEFAULT);
- wallpaperWindow->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+ leftWindow->consumeMotionCancel();
+ rightWindow->consumeMotionDown(ADISPLAY_ID_DEFAULT);
+ wallpaperWindow->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
}
/**
@@ -2536,6 +2569,39 @@
}
/**
+ * Two windows. First is a regular window. Second does not overlap with the first, and has
+ * WATCH_OUTSIDE_TOUCH.
+ * Both windows are owned by the same UID.
+ * Tap first window. Make sure that the second window receives ACTION_OUTSIDE with correct, non-zero
+ * coordinates. The coordinates are not zeroed out because both windows are owned by the same UID.
+ */
+TEST_F(InputDispatcherTest, ActionOutsideForOwnedWindowHasValidCoordinates) {
+ std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
+ sp<FakeWindowHandle> window = sp<FakeWindowHandle>::make(application, mDispatcher,
+ "First Window", ADISPLAY_ID_DEFAULT);
+ window->setFrame(Rect{0, 0, 100, 100});
+
+ sp<FakeWindowHandle> outsideWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
+ outsideWindow->setFrame(Rect{100, 100, 200, 200});
+ outsideWindow->setWatchOutsideTouch(true);
+ // outsideWindow must be above 'window' to receive ACTION_OUTSIDE events when 'window' is tapped
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {outsideWindow, window}}});
+
+ // Tap on first window.
+ NotifyMotionArgs motionArgs =
+ generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT, {PointF{50, 50}});
+ mDispatcher->notifyMotion(&motionArgs);
+ window->consumeMotionDown();
+ // The coordinates of the tap in 'outsideWindow' are relative to its top left corner.
+ // Therefore, we should offset them by (100, 100) relative to the screen's top left corner.
+ outsideWindow->consumeMotionEvent(
+ AllOf(WithMotionAction(ACTION_OUTSIDE), WithCoords(-50, -50)));
+}
+
+/**
* This test documents the behavior of WATCH_OUTSIDE_TOUCH. The window will get ACTION_OUTSIDE when
* a another pointer causes ACTION_DOWN to be sent to another window for the first time. Only one
* ACTION_OUTSIDE event is sent per gesture.
@@ -2570,7 +2636,9 @@
motionArgs = generateMotionArgs(POINTER_1_DOWN, AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT,
{PointF{-10, -10}, PointF{105, 105}});
mDispatcher->notifyMotion(&motionArgs);
- window->consumeMotionOutside();
+ const std::map<int32_t, PointF> expectedPointers{{0, PointF{-10, -10}}, {1, PointF{105, 105}}};
+ window->consumeMotionEvent(
+ AllOf(WithMotionAction(ACTION_OUTSIDE), WithPointers(expectedPointers)));
secondWindow->consumeMotionDown();
thirdWindow->assertNoEvents();
@@ -2802,21 +2870,26 @@
sp<FakeWindowHandle> firstWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
ADISPLAY_ID_DEFAULT);
+ firstWindow->setDupTouchToWallpaper(true);
sp<FakeWindowHandle> secondWindow =
sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
ADISPLAY_ID_DEFAULT);
-
+ sp<FakeWindowHandle> wallpaper =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper", ADISPLAY_ID_DEFAULT);
+ wallpaper->setIsWallpaper(true);
// Add the windows to the dispatcher
- mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow, wallpaper}}});
// Send down to the first window
NotifyMotionArgs downMotionArgs =
generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
ADISPLAY_ID_DEFAULT);
mDispatcher->notifyMotion(&downMotionArgs);
+
// Only the first window should get the down event
firstWindow->consumeMotionDown();
secondWindow->assertNoEvents();
+ wallpaper->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
// Transfer touch to the second window
TransferFunction f = GetParam();
@@ -2825,6 +2898,7 @@
// The first window gets cancel and the second gets down
firstWindow->consumeMotionCancel();
secondWindow->consumeMotionDown();
+ wallpaper->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
// Send up event to the second window
NotifyMotionArgs upMotionArgs =
@@ -2834,6 +2908,7 @@
// The first window gets no events and the second gets up
firstWindow->assertNoEvents();
secondWindow->consumeMotionUp();
+ wallpaper->assertNoEvents();
}
/**
@@ -2957,6 +3032,65 @@
secondWindow->consumeMotionUp();
}
+TEST_P(TransferTouchFixture, TransferTouch_MultipleWallpapers) {
+ std::shared_ptr<FakeApplicationHandle> application = std::make_shared<FakeApplicationHandle>();
+
+ // Create a couple of windows
+ sp<FakeWindowHandle> firstWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "First Window",
+ ADISPLAY_ID_DEFAULT);
+ firstWindow->setDupTouchToWallpaper(true);
+ sp<FakeWindowHandle> secondWindow =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Second Window",
+ ADISPLAY_ID_DEFAULT);
+ secondWindow->setDupTouchToWallpaper(true);
+
+ sp<FakeWindowHandle> wallpaper1 =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper1", ADISPLAY_ID_DEFAULT);
+ wallpaper1->setIsWallpaper(true);
+
+ sp<FakeWindowHandle> wallpaper2 =
+ sp<FakeWindowHandle>::make(application, mDispatcher, "Wallpaper2", ADISPLAY_ID_DEFAULT);
+ wallpaper2->setIsWallpaper(true);
+ // Add the windows to the dispatcher
+ mDispatcher->setInputWindows(
+ {{ADISPLAY_ID_DEFAULT, {firstWindow, wallpaper1, secondWindow, wallpaper2}}});
+
+ // Send down to the first window
+ NotifyMotionArgs downMotionArgs =
+ generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT);
+ mDispatcher->notifyMotion(&downMotionArgs);
+
+ // Only the first window should get the down event
+ firstWindow->consumeMotionDown();
+ secondWindow->assertNoEvents();
+ wallpaper1->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+ wallpaper2->assertNoEvents();
+
+ // Transfer touch focus to the second window
+ TransferFunction f = GetParam();
+ bool success = f(mDispatcher, firstWindow->getToken(), secondWindow->getToken());
+ ASSERT_TRUE(success);
+
+ // The first window gets cancel and the second gets down
+ firstWindow->consumeMotionCancel();
+ secondWindow->consumeMotionDown();
+ wallpaper1->consumeMotionCancel(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+ wallpaper2->consumeMotionDown(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+
+ // Send up event to the second window
+ NotifyMotionArgs upMotionArgs =
+ generateMotionArgs(AMOTION_EVENT_ACTION_UP, AINPUT_SOURCE_TOUCHSCREEN,
+ ADISPLAY_ID_DEFAULT);
+ mDispatcher->notifyMotion(&upMotionArgs);
+ // The first window gets no events and the second gets up
+ firstWindow->assertNoEvents();
+ secondWindow->consumeMotionUp();
+ wallpaper1->assertNoEvents();
+ wallpaper2->consumeMotionUp(ADISPLAY_ID_DEFAULT, expectedWallpaperFlags);
+}
+
// For the cases of single pointer touch and two pointers non-split touch, the api's
// 'transferTouch' and 'transferTouchFocus' are equivalent in behaviour. They only differ
// for the case where there are multiple pointers split across several windows.
diff --git a/services/inputflinger/tests/InputMapperTest.cpp b/services/inputflinger/tests/InputMapperTest.cpp
index 3cd7c1b..a02ef05 100644
--- a/services/inputflinger/tests/InputMapperTest.cpp
+++ b/services/inputflinger/tests/InputMapperTest.cpp
@@ -166,11 +166,4 @@
ASSERT_NEAR(distance, coords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE), EPSILON);
}
-void InputMapperTest::assertPosition(const FakePointerController& controller, float x, float y) {
- float actualX, actualY;
- controller.getPosition(&actualX, &actualY);
- ASSERT_NEAR(x, actualX, 1);
- ASSERT_NEAR(y, actualY, 1);
-}
-
} // namespace android
diff --git a/services/inputflinger/tests/InputMapperTest.h b/services/inputflinger/tests/InputMapperTest.h
index b3401c3..63ca44c 100644
--- a/services/inputflinger/tests/InputMapperTest.h
+++ b/services/inputflinger/tests/InputMapperTest.h
@@ -89,7 +89,6 @@
float size, float touchMajor, float touchMinor, float toolMajor,
float toolMinor, float orientation, float distance,
float scaledAxisEpsilon = 1.f);
- static void assertPosition(const FakePointerController& controller, float x, float y);
};
} // namespace android
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index 4cc48f6..96d27b8 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -2763,7 +2763,7 @@
class KeyboardInputMapperTest : public InputMapperTest {
protected:
const std::string UNIQUE_ID = "local:0";
-
+ const KeyboardLayoutInfo DEVICE_KEYBOARD_LAYOUT_INFO = KeyboardLayoutInfo("en-US", "qwerty");
void prepareDisplay(ui::Rotation orientation);
void testDPadKeyRotation(KeyboardInputMapper& mapper, int32_t originalScanCode,
@@ -3582,6 +3582,24 @@
ASSERT_EQ(AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_CANCELED, args.flags);
}
+TEST_F(KeyboardInputMapperTest, Configure_AssignKeyboardLayoutInfo) {
+ mDevice->addMapper<KeyboardInputMapper>(EVENTHUB_ID, AINPUT_SOURCE_KEYBOARD,
+ AINPUT_KEYBOARD_TYPE_ALPHABETIC);
+ std::list<NotifyArgs> unused =
+ mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(), 0);
+
+ mFakePolicy->addKeyboardLayoutAssociation(DEVICE_LOCATION, DEVICE_KEYBOARD_LAYOUT_INFO);
+
+ unused += mDevice->configure(ARBITRARY_TIME, mFakePolicy->getReaderConfiguration(),
+ InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUT_ASSOCIATION);
+
+ InputDeviceInfo deviceInfo = mDevice->getDeviceInfo();
+ ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.languageTag,
+ deviceInfo.getKeyboardLayoutInfo()->languageTag);
+ ASSERT_EQ(DEVICE_KEYBOARD_LAYOUT_INFO.layoutType,
+ deviceInfo.getKeyboardLayoutInfo()->layoutType);
+}
+
// --- KeyboardInputMapperTest_ExternalDevice ---
class KeyboardInputMapperTest_ExternalDevice : public InputMapperTest {
@@ -4344,7 +4362,7 @@
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(assertPosition(*mFakePointerController, 110.0f, 220.0f));
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
}
TEST_F(CursorInputMapperTest, Process_PointerCapture) {
@@ -4372,7 +4390,7 @@
ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
10.0f, 20.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
- ASSERT_NO_FATAL_FAILURE(assertPosition(*mFakePointerController, 100.0f, 200.0f));
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(100.0f, 200.0f));
// Button press.
process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_MOUSE, 1);
@@ -4411,7 +4429,7 @@
ASSERT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
ASSERT_NO_FATAL_FAILURE(assertPointerCoords(args.pointerCoords[0],
30.0f, 40.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f));
- ASSERT_NO_FATAL_FAILURE(assertPosition(*mFakePointerController, 100.0f, 200.0f));
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(100.0f, 200.0f));
// Disable pointer capture and check that the device generation got bumped
// and events are generated the usual way.
@@ -4431,7 +4449,7 @@
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(assertPosition(*mFakePointerController, 110.0f, 220.0f));
+ ASSERT_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
}
/**
@@ -4548,7 +4566,7 @@
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_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
}
TEST_F(CursorInputMapperTest, ConfigureDisplayId_WithAssociatedViewport) {
@@ -4575,7 +4593,7 @@
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_NO_FATAL_FAILURE(mFakePointerController->assertPosition(110.0f, 220.0f));
}
TEST_F(CursorInputMapperTest, ConfigureDisplayId_IgnoresEventsForMismatchedPointerDisplay) {
@@ -5535,7 +5553,7 @@
// Rotation 90.
clearViewports();
prepareDisplay(ui::ROTATION_90);
- processDown(mapper, toRawX(75), RAW_Y_MAX - toRawY(50) + RAW_Y_MIN);
+ processDown(mapper, toRotatedRawX(75), RAW_Y_MAX - toRotatedRawY(50) + RAW_Y_MIN);
processSync(mapper);
ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
@@ -5563,7 +5581,7 @@
// Rotation 270.
clearViewports();
prepareDisplay(ui::ROTATION_270);
- processDown(mapper, RAW_X_MAX - toRawX(75) + RAW_X_MIN, toRawY(50));
+ processDown(mapper, RAW_X_MAX - toRotatedRawX(75) + RAW_X_MIN, toRotatedRawY(50));
processSync(mapper);
ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
@@ -5700,7 +5718,7 @@
// Orientation 90, Rotation 90.
clearViewports();
prepareDisplay(ui::ROTATION_90);
- processDown(mapper, toRotatedRawX(50), toRotatedRawY(75));
+ processDown(mapper, toRawX(50), toRawY(75));
processSync(mapper);
EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
@@ -5728,8 +5746,7 @@
// Orientation 90, Rotation 270.
clearViewports();
prepareDisplay(ui::ROTATION_270);
- processDown(mapper, RAW_X_MAX - toRotatedRawX(50) + RAW_X_MIN,
- RAW_Y_MAX - toRotatedRawY(75) + RAW_Y_MIN);
+ processDown(mapper, RAW_X_MAX - toRawX(50) + RAW_X_MIN, RAW_Y_MAX - toRawY(75) + RAW_Y_MIN);
processSync(mapper);
EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
@@ -5741,6 +5758,61 @@
EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled());
}
+TEST_F(SingleTouchInputMapperTest, Process_IgnoresTouchesOutsidePhysicalFrame) {
+ addConfigurationProperty("touch.deviceType", "touchScreen");
+ prepareButtons();
+ prepareAxes(POSITION);
+ addConfigurationProperty("touch.orientationAware", "1");
+ prepareDisplay(ui::ROTATION_0);
+ auto& mapper = addMapperAndConfigure<SingleTouchInputMapper>();
+
+ // Set a physical frame in the display viewport.
+ auto viewport = mFakePolicy->getDisplayViewportByType(ViewportType::INTERNAL);
+ viewport->physicalLeft = 20;
+ viewport->physicalTop = 600;
+ viewport->physicalRight = 30;
+ viewport->physicalBottom = 610;
+ mFakePolicy->updateViewport(*viewport);
+ configureDevice(InputReaderConfiguration::CHANGE_DISPLAY_INFO);
+
+ // Start the touch.
+ process(mapper, ARBITRARY_TIME, READ_TIME, EV_KEY, BTN_TOUCH, 1);
+ processSync(mapper);
+
+ // Expect all input starting outside the physical frame to be ignored.
+ const std::array<Point, 6> outsidePoints = {
+ {{0, 0}, {19, 605}, {31, 605}, {25, 599}, {25, 611}, {DISPLAY_WIDTH, DISPLAY_HEIGHT}}};
+ for (const auto& p : outsidePoints) {
+ processMove(mapper, toRawX(p.x), toRawY(p.y));
+ processSync(mapper);
+ EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasNotCalled());
+ }
+
+ // Move the touch into the physical frame.
+ processMove(mapper, toRawX(25), toRawY(605));
+ processSync(mapper);
+ NotifyMotionArgs args;
+ EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
+ EXPECT_EQ(AMOTION_EVENT_ACTION_DOWN, args.action);
+ EXPECT_NEAR(25, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
+ EXPECT_NEAR(605, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
+
+ // Once the touch down is reported, continue reporting input, even if it is outside the frame.
+ for (const auto& p : outsidePoints) {
+ processMove(mapper, toRawX(p.x), toRawY(p.y));
+ processSync(mapper);
+ EXPECT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&args));
+ EXPECT_EQ(AMOTION_EVENT_ACTION_MOVE, args.action);
+ EXPECT_NEAR(p.x, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), 1);
+ EXPECT_NEAR(p.y, args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y), 1);
+ }
+
+ processUp(mapper);
+ processSync(mapper);
+ EXPECT_NO_FATAL_FAILURE(
+ mFakeListener->assertNotifyMotionWasCalled(WithMotionAction(AMOTION_EVENT_ACTION_UP)));
+}
+
TEST_F(SingleTouchInputMapperTest, Process_AllAxes_DefaultCalibration) {
addConfigurationProperty("touch.deviceType", "touchScreen");
prepareDisplay(ui::ROTATION_0);
@@ -6505,6 +6577,17 @@
WithCoords(toDisplayX(100), toDisplayY(200)), WithButtonState(0))));
}
+TEST_F(SingleTouchInputMapperTest, WhenDeviceTypeIsSetToTouchNavigation_setsCorrectType) {
+ mFakePolicy->addDeviceTypeAssociation(DEVICE_LOCATION, "touchNavigation");
+ prepareDisplay(ui::ROTATION_0);
+ prepareButtons();
+ prepareAxes(POSITION);
+ SingleTouchInputMapper& mapper = addMapperAndConfigure<SingleTouchInputMapper>();
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled());
+
+ ASSERT_EQ(AINPUT_SOURCE_TOUCH_NAVIGATION, mapper.getSources());
+}
+
// --- TouchDisplayProjectionTest ---
class TouchDisplayProjectionTest : public SingleTouchInputMapperTest {
diff --git a/services/inputflinger/tests/TestInputListenerMatchers.h b/services/inputflinger/tests/TestInputListenerMatchers.h
index 9db3422..e5a4b14 100644
--- a/services/inputflinger/tests/TestInputListenerMatchers.h
+++ b/services/inputflinger/tests/TestInputListenerMatchers.h
@@ -74,6 +74,14 @@
return argX == x && argY == y;
}
+MATCHER_P2(WithRelativeMotion, x, y, "InputEvent with specified relative motion") {
+ const auto argX = arg.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X);
+ const auto argY = arg.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y);
+ *result_listener << "expected relative motion (" << x << ", " << y << "), but got (" << argX
+ << ", " << argY << ")";
+ return argX == x && argY == y;
+}
+
MATCHER_P(WithPressure, pressure, "InputEvent with specified pressure") {
const auto argPressure = arg.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE);
*result_listener << "expected pressure " << pressure << ", but got " << argPressure;
@@ -97,6 +105,12 @@
return arg.buttonState == buttons;
}
+MATCHER_P(WithActionButton, actionButton, "InputEvent with specified action button") {
+ *result_listener << "expected action button " << actionButton << ", but got "
+ << arg.actionButton;
+ return arg.actionButton == actionButton;
+}
+
MATCHER_P(WithEventTime, eventTime, "InputEvent with specified eventTime") {
*result_listener << "expected event time " << eventTime << ", but got " << arg.eventTime;
return arg.eventTime == eventTime;
diff --git a/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp
index cc523e1..be85026 100644
--- a/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/CursorInputFuzzer.cpp
@@ -16,11 +16,10 @@
#include <CursorInputMapper.h>
#include <FuzzContainer.h>
-#include <fuzzer/FuzzedDataProvider.h>
namespace android {
-static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<FuzzedDataProvider> fdp) {
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) {
// Pick a random property to set for the mapper to have set.
fdp->PickValueInArray<std::function<void()>>(
{[&]() -> void { fuzzer.addProperty("cursor.mode", "pointer"); },
@@ -35,7 +34,8 @@
}
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
- std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp =
+ std::make_shared<ThreadSafeFuzzedDataProvider>(data, size);
FuzzContainer fuzzer(fdp);
CursorInputMapper& mapper = fuzzer.getMapper<CursorInputMapper>();
diff --git a/services/inputflinger/tests/fuzzers/FuzzContainer.h b/services/inputflinger/tests/fuzzers/FuzzContainer.h
index 1e0764f..76d2bcd 100644
--- a/services/inputflinger/tests/fuzzers/FuzzContainer.h
+++ b/services/inputflinger/tests/fuzzers/FuzzContainer.h
@@ -20,7 +20,6 @@
#include <InputMapper.h>
#include <InputReader.h>
#include <MapperHelpers.h>
-#include <fuzzer/FuzzedDataProvider.h>
namespace android {
@@ -31,10 +30,10 @@
std::unique_ptr<FuzzInputReaderContext> mFuzzContext;
std::unique_ptr<InputDevice> mFuzzDevice;
InputReaderConfiguration mPolicyConfig;
- std::shared_ptr<FuzzedDataProvider> mFdp;
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
public:
- FuzzContainer(std::shared_ptr<FuzzedDataProvider> fdp) : mFdp(fdp) {
+ FuzzContainer(std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) : mFdp(fdp) {
// Setup parameters.
std::string deviceName = mFdp->ConsumeRandomLengthString(16);
std::string deviceLocation = mFdp->ConsumeRandomLengthString(12);
diff --git a/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp b/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp
index 057c15d..a80839c 100644
--- a/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/InputReaderFuzzer.cpp
@@ -170,7 +170,8 @@
};
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
- std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp =
+ std::make_shared<ThreadSafeFuzzedDataProvider>(data, size);
FuzzInputListener fuzzListener;
sp<FuzzInputReaderPolicy> fuzzPolicy = sp<FuzzInputReaderPolicy>::make(fdp);
diff --git a/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp
index e880f55..8e2d677 100644
--- a/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/KeyboardInputFuzzer.cpp
@@ -16,13 +16,12 @@
#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) {
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) {
// Pick a random property to set for the mapper to have set.
fdp->PickValueInArray<std::function<void()>>(
{[&]() -> void { fuzzer.addProperty("keyboard.orientationAware", "1"); },
@@ -41,7 +40,8 @@
}
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
- std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp =
+ std::make_shared<ThreadSafeFuzzedDataProvider>(data, size);
FuzzContainer fuzzer(fdp);
KeyboardInputMapper& mapper =
diff --git a/services/inputflinger/tests/fuzzers/MapperHelpers.h b/services/inputflinger/tests/fuzzers/MapperHelpers.h
index cd852d6..a0910ea 100644
--- a/services/inputflinger/tests/fuzzers/MapperHelpers.h
+++ b/services/inputflinger/tests/fuzzers/MapperHelpers.h
@@ -13,13 +13,12 @@
* 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 <ThreadSafeFuzzedDataProvider.h>
#include "android/hardware/input/InputDeviceCountryCode.h"
using android::hardware::input::InputDeviceCountryCode;
@@ -114,10 +113,10 @@
InputDeviceIdentifier mIdentifier;
std::vector<TouchVideoFrame> mVideoFrames;
PropertyMap mFuzzConfig;
- std::shared_ptr<FuzzedDataProvider> mFdp;
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
public:
- FuzzEventHub(std::shared_ptr<FuzzedDataProvider> fdp) : mFdp(std::move(fdp)) {}
+ FuzzEventHub(std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) : mFdp(std::move(fdp)) {}
~FuzzEventHub() {}
void addProperty(std::string key, std::string value) { mFuzzConfig.addProperty(key, value); }
@@ -264,10 +263,10 @@
};
class FuzzPointerController : public PointerControllerInterface {
- std::shared_ptr<FuzzedDataProvider> mFdp;
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
public:
- FuzzPointerController(std::shared_ptr<FuzzedDataProvider> mFdp) : mFdp(mFdp) {}
+ FuzzPointerController(std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp) : mFdp(mFdp) {}
~FuzzPointerController() {}
bool getBounds(float* outMinX, float* outMinY, float* outMaxX, float* outMaxY) const override {
return mFdp->ConsumeBool();
@@ -290,13 +289,13 @@
class FuzzInputReaderPolicy : public InputReaderPolicyInterface {
TouchAffineTransformation mTransform;
std::shared_ptr<FuzzPointerController> mPointerController;
- std::shared_ptr<FuzzedDataProvider> mFdp;
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
protected:
~FuzzInputReaderPolicy() {}
public:
- FuzzInputReaderPolicy(std::shared_ptr<FuzzedDataProvider> mFdp) : mFdp(mFdp) {
+ FuzzInputReaderPolicy(std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp) : mFdp(mFdp) {
mPointerController = std::make_shared<FuzzPointerController>(mFdp);
}
void getReaderConfiguration(InputReaderConfiguration* outConfig) override {}
@@ -334,13 +333,13 @@
class FuzzInputReaderContext : public InputReaderContext {
std::shared_ptr<EventHubInterface> mEventHub;
sp<InputReaderPolicyInterface> mPolicy;
- std::shared_ptr<FuzzedDataProvider> mFdp;
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp;
public:
FuzzInputReaderContext(std::shared_ptr<EventHubInterface> eventHub,
const sp<InputReaderPolicyInterface>& policy,
InputListenerInterface& listener,
- std::shared_ptr<FuzzedDataProvider> mFdp)
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> mFdp)
: mEventHub(eventHub), mPolicy(policy), mFdp(mFdp) {}
~FuzzInputReaderContext() {}
void updateGlobalMetaState() override {}
diff --git a/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp
index 99fd083..011455b 100644
--- a/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/MultiTouchInputFuzzer.cpp
@@ -16,13 +16,12 @@
#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) {
+static void addProperty(FuzzContainer& fuzzer, std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp) {
// Pick a random property to set for the mapper to have set.
fdp->PickValueInArray<std::function<void()>>(
{[&]() -> void { fuzzer.addProperty("touch.deviceType", "touchScreen"); },
@@ -58,7 +57,8 @@
}
extern "C" int LLVMFuzzerTestOneInput(uint8_t* data, size_t size) {
- std::shared_ptr<FuzzedDataProvider> fdp = std::make_shared<FuzzedDataProvider>(data, size);
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp =
+ std::make_shared<ThreadSafeFuzzedDataProvider>(data, size);
FuzzContainer fuzzer(fdp);
MultiTouchInputMapper& mapper = fuzzer.getMapper<MultiTouchInputMapper>();
diff --git a/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp b/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp
index 7416ce9..c4938f2 100644
--- a/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp
+++ b/services/inputflinger/tests/fuzzers/SwitchInputFuzzer.cpp
@@ -16,12 +16,12 @@
#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);
+ std::shared_ptr<ThreadSafeFuzzedDataProvider> fdp =
+ std::make_shared<ThreadSafeFuzzedDataProvider>(data, size);
FuzzContainer fuzzer(fdp);
SwitchInputMapper& mapper = fuzzer.getMapper<SwitchInputMapper>();
diff --git a/services/inputflinger/tests/fuzzers/ThreadSafeFuzzedDataProvider.h b/services/inputflinger/tests/fuzzers/ThreadSafeFuzzedDataProvider.h
new file mode 100644
index 0000000..2f76f18
--- /dev/null
+++ b/services/inputflinger/tests/fuzzers/ThreadSafeFuzzedDataProvider.h
@@ -0,0 +1,136 @@
+/*
+ * 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>
+
+/**
+ * A thread-safe interface to the FuzzedDataProvider
+ */
+class ThreadSafeFuzzedDataProvider : FuzzedDataProvider {
+private:
+ std::mutex mLock;
+
+public:
+ ThreadSafeFuzzedDataProvider(const uint8_t* data, size_t size)
+ : FuzzedDataProvider(data, size) {}
+
+ template <typename T>
+ std::vector<T> ConsumeBytes(size_t num_bytes) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeBytes<T>(num_bytes);
+ }
+
+ template <typename T>
+ std::vector<T> ConsumeBytesWithTerminator(size_t num_bytes, T terminator) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeBytesWithTerminator<T>(num_bytes, terminator);
+ }
+
+ template <typename T>
+ std::vector<T> ConsumeRemainingBytes() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeRemainingBytes<T>();
+ }
+
+ std::string ConsumeBytesAsString(size_t num_bytes) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeBytesAsString(num_bytes);
+ }
+
+ std::string ConsumeRandomLengthString(size_t max_length) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeRandomLengthString(max_length);
+ }
+
+ std::string ConsumeRandomLengthString() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeRandomLengthString();
+ }
+
+ std::string ConsumeRemainingBytesAsString() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeRemainingBytesAsString();
+ }
+
+ template <typename T>
+ T ConsumeIntegral() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeIntegral<T>();
+ }
+
+ template <typename T>
+ T ConsumeIntegralInRange(T min, T max) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeIntegralInRange<T>(min, max);
+ }
+
+ template <typename T>
+ T ConsumeFloatingPoint() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeFloatingPoint<T>();
+ }
+
+ template <typename T>
+ T ConsumeFloatingPointInRange(T min, T max) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeFloatingPointInRange<T>(min, max);
+ }
+
+ template <typename T>
+ T ConsumeProbability() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeProbability<T>();
+ }
+
+ bool ConsumeBool() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeBool();
+ }
+
+ template <typename T>
+ T ConsumeEnum() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeEnum<T>();
+ }
+
+ template <typename T, size_t size>
+ T PickValueInArray(const T (&array)[size]) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::PickValueInArray(array);
+ }
+
+ template <typename T, size_t size>
+ T PickValueInArray(const std::array<T, size>& array) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::PickValueInArray(array);
+ }
+
+ template <typename T>
+ T PickValueInArray(std::initializer_list<const T> list) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::PickValueInArray(list);
+ }
+
+ size_t ConsumeData(void* destination, size_t num_bytes) {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::ConsumeData(destination, num_bytes);
+ }
+
+ size_t remaining_bytes() {
+ std::scoped_lock _l(mLock);
+ return FuzzedDataProvider::remaining_bytes();
+ }
+};
diff --git a/services/sensorservice/Android.bp b/services/sensorservice/Android.bp
index 0eeb820..11c56a8 100644
--- a/services/sensorservice/Android.bp
+++ b/services/sensorservice/Android.bp
@@ -76,7 +76,7 @@
"libaidlcommonsupport",
"android.hardware.sensors@1.0-convert",
"android.hardware.sensors-V1-convert",
- "android.hardware.sensors-V1-ndk",
+ "android.hardware.sensors-V2-ndk",
],
generated_headers: ["framework-cppstream-protos"],
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 7124d35..6504b79 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -13,6 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+#include <aidl/android/hardware/sensors/ISensors.h>
#include <android-base/strings.h>
#include <android/content/pm/IPackageManagerNative.h>
#include <android/util/ProtoOutputStream.h>
@@ -104,12 +105,10 @@
namespace {
-// TODO(b/259227294): Move the sensor ranges to the HAL.
int32_t nextRuntimeSensorHandle() {
- static constexpr int32_t kRuntimeHandleBase = 0x5F000000;
- static constexpr int32_t kRuntimeHandleEnd = 0x5FFFFFFF;
- static int32_t nextHandle = kRuntimeHandleBase;
- if (nextHandle == kRuntimeHandleEnd) {
+ using ::aidl::android::hardware::sensors::ISensors;
+ static int32_t nextHandle = ISensors::RUNTIME_SENSORS_HANDLE_BASE;
+ if (nextHandle == ISensors::RUNTIME_SENSORS_HANDLE_END) {
return -1;
}
return nextHandle++;
diff --git a/services/sensorservice/aidl/Android.bp b/services/sensorservice/aidl/Android.bp
index 34d1de7..542fcae 100644
--- a/services/sensorservice/aidl/Android.bp
+++ b/services/sensorservice/aidl/Android.bp
@@ -28,7 +28,7 @@
"libbinder_ndk",
"libsensor",
"android.frameworks.sensorservice-V1-ndk",
- "android.hardware.sensors-V1-ndk",
+ "android.hardware.sensors-V2-ndk",
],
export_include_dirs: [
"include/",
diff --git a/services/sensorservice/aidl/fuzzer/Android.bp b/services/sensorservice/aidl/fuzzer/Android.bp
index 0d6e476..5301fe9 100644
--- a/services/sensorservice/aidl/fuzzer/Android.bp
+++ b/services/sensorservice/aidl/fuzzer/Android.bp
@@ -18,7 +18,7 @@
"libpermission",
"android.frameworks.sensorservice-V1-ndk",
"android.hardware.sensors-V1-convert",
- "android.hardware.sensors-V1-ndk",
+ "android.hardware.sensors-V2-ndk",
"android.hardware.common-V2-ndk",
"libsensor",
"libfakeservicemanager",
diff --git a/services/stats/StatsHal.cpp b/services/stats/StatsHal.cpp
index ae0a984..d27d989 100644
--- a/services/stats/StatsHal.cpp
+++ b/services/stats/StatsHal.cpp
@@ -112,13 +112,13 @@
}
hardware::Return<void> StatsHal::reportVendorAtom(const VendorAtom& vendorAtom) {
- std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
return hardware::Void();
}
- if (reverseDomainName.length() > 50) {
- ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
+ if (vendorAtom.reverseDomainName.size() > 50) {
+ ALOGE("Vendor atom reverse domain name %s is too long.",
+ vendorAtom.reverseDomainName.c_str());
return hardware::Void();
}
AStatsEvent* event = AStatsEvent_obtain();
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index 0a192c5..e0dcab5 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -26,8 +26,8 @@
name: "libsurfaceflinger_defaults",
defaults: [
"android.hardware.graphics.composer3-ndk_shared",
+ "librenderengine_deps",
"surfaceflinger_defaults",
- "skia_renderengine_deps",
],
cflags: [
"-DLOG_TAG=\"SurfaceFlinger\"",
diff --git a/services/surfaceflinger/CompositionEngine/Android.bp b/services/surfaceflinger/CompositionEngine/Android.bp
index 30d34a5..f3a0186 100644
--- a/services/surfaceflinger/CompositionEngine/Android.bp
+++ b/services/surfaceflinger/CompositionEngine/Android.bp
@@ -11,6 +11,7 @@
name: "libcompositionengine_defaults",
defaults: [
"android.hardware.graphics.composer3-ndk_shared",
+ "librenderengine_deps",
"surfaceflinger_defaults",
],
cflags: [
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/CompositionRefreshArgs.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/CompositionRefreshArgs.h
index 415a041..4777f13 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/CompositionRefreshArgs.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/CompositionRefreshArgs.h
@@ -67,9 +67,6 @@
// Used to correctly apply an inverse-display buffer transform if applicable
ui::Transform::RotationFlags internalDisplayRotationFlags{ui::Transform::ROT_0};
- // If true, GPU clocks will be increased when rendering blurs
- bool blursAreExpensive{false};
-
// If true, the complete output geometry needs to be recomputed this frame
bool updatingOutputGeometryThisFrame{false};
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
index bd43c89..52ebd9e 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Output.h
@@ -290,12 +290,11 @@
using GpuCompositionResult = compositionengine::impl::GpuCompositionResult;
// Runs prepare frame in another thread while running client composition using
// the previous frame's composition strategy.
- virtual GpuCompositionResult prepareFrameAsync(const CompositionRefreshArgs&) = 0;
+ virtual GpuCompositionResult prepareFrameAsync() = 0;
virtual void devOptRepaintFlash(const CompositionRefreshArgs&) = 0;
- virtual void finishFrame(const CompositionRefreshArgs&, GpuCompositionResult&&) = 0;
+ virtual void finishFrame(GpuCompositionResult&&) = 0;
virtual std::optional<base::unique_fd> composeSurfaces(
- const Region&, const compositionengine::CompositionRefreshArgs&,
- std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&) = 0;
+ const Region&, std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&) = 0;
virtual void postFramebuffer() = 0;
virtual void renderCachedSets(const CompositionRefreshArgs&) = 0;
virtual bool chooseCompositionStrategy(
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
index 33a10a3..6cf1d68 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
@@ -61,7 +61,7 @@
bool getSkipColorTransform() const override;
compositionengine::Output::FrameFences presentAndGetFrameFences() override;
void setExpensiveRenderingExpected(bool) override;
- void finishFrame(const CompositionRefreshArgs&, GpuCompositionResult&&) override;
+ void finishFrame(GpuCompositionResult&&) override;
// compositionengine::Display overrides
DisplayId getId() const override;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/HwcBufferCache.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/HwcBufferCache.h
index 6e9ea6f..b6a4240 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/HwcBufferCache.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/HwcBufferCache.h
@@ -83,7 +83,7 @@
// If the buffer is already in the cache, the buffer is null to optimize away sending HWC the
// buffer handle.
//
- HwcSlotAndBuffer getHwcSlotAndBufferForOverride(const sp<GraphicBuffer>& buffer);
+ HwcSlotAndBuffer getOverrideHwcSlotAndBuffer(const sp<GraphicBuffer>& buffer);
//
// When a client process discards a buffer, it needs to be purged from the HWC cache.
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
index 1393e29..8ec77c0 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Output.h
@@ -96,11 +96,10 @@
void updateColorProfile(const compositionengine::CompositionRefreshArgs&) override;
void beginFrame() override;
void prepareFrame() override;
- GpuCompositionResult prepareFrameAsync(const CompositionRefreshArgs&) override;
+ GpuCompositionResult prepareFrameAsync() override;
void devOptRepaintFlash(const CompositionRefreshArgs&) override;
- void finishFrame(const CompositionRefreshArgs&, GpuCompositionResult&&) override;
+ void finishFrame(GpuCompositionResult&&) override;
std::optional<base::unique_fd> composeSurfaces(const Region&,
- const compositionengine::CompositionRefreshArgs&,
std::shared_ptr<renderengine::ExternalTexture>,
base::unique_fd&) override;
void postFramebuffer() override;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
index 2b383c1..2a5bfae 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputLayerCompositionState.h
@@ -136,6 +136,9 @@
// cost of sending reused buffers to the HWC.
HwcBufferCache hwcBufferCache;
+ // The previously-active buffer for this layer.
+ uint32_t activeBufferSlot;
+
// Set to true when overridden info has been sent to HW composer
bool stateOverridden = false;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
index 14922a4..12e063b 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/LayerFE.h
@@ -36,6 +36,7 @@
// sp<StrictMock<LayerFE>>::make()
friend class sp<LayerFE>;
friend class testing::StrictMock<LayerFE>;
+ friend class testing::NiceMock<LayerFE>;
public:
virtual ~LayerFE();
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
index 18e6879..a56fc79 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Output.h
@@ -100,7 +100,7 @@
MOCK_METHOD0(beginFrame, void());
MOCK_METHOD0(prepareFrame, void());
- MOCK_METHOD1(prepareFrameAsync, GpuCompositionResult(const CompositionRefreshArgs&));
+ MOCK_METHOD0(prepareFrameAsync, GpuCompositionResult());
MOCK_METHOD1(chooseCompositionStrategy,
bool(std::optional<android::HWComposer::DeviceRequestedChanges>*));
MOCK_METHOD1(chooseCompositionStrategyAsync,
@@ -110,14 +110,12 @@
MOCK_METHOD1(devOptRepaintFlash, void(const compositionengine::CompositionRefreshArgs&));
- MOCK_METHOD2(finishFrame,
- void(const compositionengine::CompositionRefreshArgs&, GpuCompositionResult&&));
+ MOCK_METHOD1(finishFrame, void(GpuCompositionResult&&));
- MOCK_METHOD4(composeSurfaces,
- std::optional<base::unique_fd>(
- const Region&,
- const compositionengine::CompositionRefreshArgs& refreshArgs,
- std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&));
+ MOCK_METHOD3(composeSurfaces,
+ std::optional<base::unique_fd>(const Region&,
+ std::shared_ptr<renderengine::ExternalTexture>,
+ base::unique_fd&));
MOCK_CONST_METHOD0(getSkipColorTransform, bool());
MOCK_METHOD0(postFramebuffer, void());
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index 24669c2..d50a768 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -428,8 +428,7 @@
mPowerAdvisor->setGpuFenceTime(mId, std::move(gpuFence));
}
-void Display::finishFrame(const compositionengine::CompositionRefreshArgs& refreshArgs,
- GpuCompositionResult&& result) {
+void Display::finishFrame(GpuCompositionResult&& result) {
// We only need to actually compose the display if:
// 1) It is being handled by hardware composer, which may need this to
// keep its virtual display state machine in sync, or
@@ -439,7 +438,7 @@
return;
}
- impl::Output::finishFrame(refreshArgs, std::move(result));
+ impl::Output::finishFrame(std::move(result));
}
} // namespace android::compositionengine::impl
diff --git a/services/surfaceflinger/CompositionEngine/src/HwcBufferCache.cpp b/services/surfaceflinger/CompositionEngine/src/HwcBufferCache.cpp
index d64fd57..34ed214 100644
--- a/services/surfaceflinger/CompositionEngine/src/HwcBufferCache.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/HwcBufferCache.cpp
@@ -22,7 +22,7 @@
namespace android::compositionengine::impl {
HwcBufferCache::HwcBufferCache() {
- for (uint32_t i = 0; i < kMaxLayerBufferCount; i++) {
+ for (uint32_t i = kMaxLayerBufferCount; i-- > 0;) {
mFreeSlots.push(i);
}
}
@@ -42,7 +42,7 @@
return {cache(buffer), buffer};
}
-HwcSlotAndBuffer HwcBufferCache::getHwcSlotAndBufferForOverride(const sp<GraphicBuffer>& buffer) {
+HwcSlotAndBuffer HwcBufferCache::getOverrideHwcSlotAndBuffer(const sp<GraphicBuffer>& buffer) {
if (buffer == mLastOverrideBuffer) {
return {kOverrideBufferSlot, nullptr};
}
diff --git a/services/surfaceflinger/CompositionEngine/src/Output.cpp b/services/surfaceflinger/CompositionEngine/src/Output.cpp
index 16ef812..d513731 100644
--- a/services/surfaceflinger/CompositionEngine/src/Output.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Output.cpp
@@ -445,13 +445,13 @@
GpuCompositionResult result;
const bool predictCompositionStrategy = canPredictCompositionStrategy(refreshArgs);
if (predictCompositionStrategy) {
- result = prepareFrameAsync(refreshArgs);
+ result = prepareFrameAsync();
} else {
prepareFrame();
}
devOptRepaintFlash(refreshArgs);
- finishFrame(refreshArgs, std::move(result));
+ finishFrame(std::move(result));
postFramebuffer();
renderCachedSets(refreshArgs);
}
@@ -1069,7 +1069,7 @@
[&, changes]() { return chooseCompositionStrategy(changes); });
}
-GpuCompositionResult Output::prepareFrameAsync(const CompositionRefreshArgs& refreshArgs) {
+GpuCompositionResult Output::prepareFrameAsync() {
ATRACE_CALL();
ALOGV(__FUNCTION__);
auto& state = editState();
@@ -1089,7 +1089,7 @@
GpuCompositionResult compositionResult;
if (dequeueSucceeded) {
std::optional<base::unique_fd> optFd =
- composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
+ composeSurfaces(Region::INVALID_REGION, buffer, bufferFence);
if (optFd) {
compositionResult.fence = std::move(*optFd);
}
@@ -1127,7 +1127,7 @@
std::shared_ptr<renderengine::ExternalTexture> buffer;
updateProtectedContentState();
dequeueRenderBuffer(&bufferFence, &buffer);
- static_cast<void>(composeSurfaces(dirtyRegion, refreshArgs, buffer, bufferFence));
+ static_cast<void>(composeSurfaces(dirtyRegion, buffer, bufferFence));
mRenderSurface->queueBuffer(base::unique_fd());
}
}
@@ -1139,7 +1139,7 @@
prepareFrame();
}
-void Output::finishFrame(const CompositionRefreshArgs& refreshArgs, GpuCompositionResult&& result) {
+void Output::finishFrame(GpuCompositionResult&& result) {
ATRACE_CALL();
ALOGV(__FUNCTION__);
const auto& outputState = getState();
@@ -1164,7 +1164,7 @@
}
// Repaint the framebuffer (if needed), getting the optional fence for when
// the composition completes.
- optReadyFence = composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
+ optReadyFence = composeSurfaces(Region::INVALID_REGION, buffer, bufferFence);
}
if (!optReadyFence) {
return;
@@ -1218,8 +1218,8 @@
}
std::optional<base::unique_fd> Output::composeSurfaces(
- const Region& debugRegion, const compositionengine::CompositionRefreshArgs& refreshArgs,
- std::shared_ptr<renderengine::ExternalTexture> tex, base::unique_fd& fd) {
+ const Region& debugRegion, std::shared_ptr<renderengine::ExternalTexture> tex,
+ base::unique_fd& fd) {
ATRACE_CALL();
ALOGV(__FUNCTION__);
@@ -1275,9 +1275,7 @@
// or complex GPU shaders and it's expensive. We boost the GPU frequency so that
// GPU composition can finish in time. We must reset GPU frequency afterwards,
// because high frequency consumes extra battery.
- const bool expensiveBlurs =
- refreshArgs.blursAreExpensive && mLayerRequestingBackgroundBlur != nullptr;
- const bool expensiveRenderingExpected = expensiveBlurs ||
+ const bool expensiveRenderingExpected =
std::any_of(clientCompositionLayers.begin(), clientCompositionLayers.end(),
[outputDataspace =
clientCompositionDisplay.outputDataspace](const auto& layer) {
diff --git a/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp b/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
index a7c24b6..766d7ea 100644
--- a/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/OutputLayer.cpp
@@ -610,16 +610,26 @@
}
}
-void OutputLayer::uncacheBuffers(std::vector<uint64_t> const& bufferIdsToUncache) {
+void OutputLayer::uncacheBuffers(const std::vector<uint64_t>& bufferIdsToUncache) {
auto& state = editState();
// Skip doing this if there is no HWC interface
if (!state.hwc) {
return;
}
- for (auto bufferId : bufferIdsToUncache) {
- state.hwc->hwcBufferCache.uncache(bufferId);
- // TODO(b/258196272): send uncache requests to Composer HAL
+ std::vector<uint32_t> slotsToClear;
+ for (uint64_t bufferId : bufferIdsToUncache) {
+ uint32_t slot = state.hwc->hwcBufferCache.uncache(bufferId);
+ if (slot != UINT32_MAX) {
+ slotsToClear.push_back(slot);
+ }
+ }
+
+ hal::Error error =
+ state.hwc->hwcLayer->setBufferSlotsToClear(slotsToClear, state.hwc->activeBufferSlot);
+ if (error != hal::Error::NONE) {
+ ALOGE("[%s] Failed to clear buffer slots: %s (%d)", getLayerFE().getDebugName(),
+ to_string(error).c_str(), static_cast<int32_t>(error));
}
}
@@ -637,15 +647,25 @@
HwcSlotAndBuffer hwcSlotAndBuffer;
sp<Fence> hwcFence;
- // Override buffers use a special cache slot so that they don't evict client buffers.
- if (getState().overrideInfo.buffer != nullptr && !skipLayer) {
- hwcSlotAndBuffer = editState().hwc->hwcBufferCache.getHwcSlotAndBufferForOverride(
- getState().overrideInfo.buffer->getBuffer());
- hwcFence = getState().overrideInfo.acquireFence;
- } else {
- hwcSlotAndBuffer =
- editState().hwc->hwcBufferCache.getHwcSlotAndBuffer(outputIndependentState.buffer);
- hwcFence = outputIndependentState.acquireFence;
+ {
+ // Editing the state only because we update the HWC buffer cache and active buffer.
+ auto& state = editState();
+ // Override buffers use a special cache slot so that they don't evict client buffers.
+ if (state.overrideInfo.buffer != nullptr && !skipLayer) {
+ hwcSlotAndBuffer = state.hwc->hwcBufferCache.getOverrideHwcSlotAndBuffer(
+ state.overrideInfo.buffer->getBuffer());
+ hwcFence = state.overrideInfo.acquireFence;
+ } else {
+ hwcSlotAndBuffer =
+ state.hwc->hwcBufferCache.getHwcSlotAndBuffer(outputIndependentState.buffer);
+ hwcFence = outputIndependentState.acquireFence;
+ }
+
+ // Keep track of the active buffer slot, so we can restore it after clearing other buffer
+ // slots.
+ if (hwcSlotAndBuffer.buffer) {
+ state.hwc->activeBufferSlot = hwcSlotAndBuffer.slot;
+ }
}
if (auto error = hwcLayer->setBuffer(hwcSlotAndBuffer.slot, hwcSlotAndBuffer.buffer, hwcFence);
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index 95459c0..0756c1b 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -959,7 +959,7 @@
mDisplay->editState().layerStackSpace.setContent(Rect(0, 0, 1, 1));
mDisplay->editState().dirtyRegion = Region::INVALID_REGION;
- mDisplay->finishFrame({}, std::move(mResultWithBuffer));
+ mDisplay->finishFrame(std::move(mResultWithBuffer));
}
TEST_F(DisplayFinishFrameTest, skipsCompositionIfNotDirty) {
@@ -980,7 +980,7 @@
gpuDisplay->editState().lastCompositionHadVisibleLayers = true;
gpuDisplay->beginFrame();
- gpuDisplay->finishFrame({}, std::move(mResultWithoutBuffer));
+ gpuDisplay->finishFrame(std::move(mResultWithoutBuffer));
}
TEST_F(DisplayFinishFrameTest, skipsCompositionIfEmpty) {
@@ -1001,7 +1001,7 @@
gpuDisplay->editState().lastCompositionHadVisibleLayers = false;
gpuDisplay->beginFrame();
- gpuDisplay->finishFrame({}, std::move(mResultWithoutBuffer));
+ gpuDisplay->finishFrame(std::move(mResultWithoutBuffer));
}
TEST_F(DisplayFinishFrameTest, performsCompositionIfDirtyAndNotEmpty) {
@@ -1022,7 +1022,7 @@
gpuDisplay->editState().lastCompositionHadVisibleLayers = true;
gpuDisplay->beginFrame();
- gpuDisplay->finishFrame({}, std::move(mResultWithBuffer));
+ gpuDisplay->finishFrame(std::move(mResultWithBuffer));
}
/*
diff --git a/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp b/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
index cf72e8f..c5fb594 100644
--- a/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/HwcBufferCacheTest.cpp
@@ -115,20 +115,20 @@
EXPECT_EQ(cache.uncache(mBuffer2->getId()), UINT32_MAX);
}
-TEST_F(HwcBufferCacheTest, getHwcSlotAndBufferForOverride_whenCached_returnsSameSlotAndNullBuffer) {
+TEST_F(HwcBufferCacheTest, getOverrideHwcSlotAndBuffer_whenCached_returnsSameSlotAndNullBuffer) {
HwcBufferCache cache;
sp<GraphicBuffer> outBuffer;
- HwcSlotAndBuffer originalSlotAndBuffer = cache.getHwcSlotAndBufferForOverride(mBuffer1);
+ HwcSlotAndBuffer originalSlotAndBuffer = cache.getOverrideHwcSlotAndBuffer(mBuffer1);
EXPECT_NE(originalSlotAndBuffer.slot, UINT32_MAX);
EXPECT_EQ(originalSlotAndBuffer.buffer, mBuffer1);
- HwcSlotAndBuffer finalSlotAndBuffer = cache.getHwcSlotAndBufferForOverride(mBuffer1);
+ HwcSlotAndBuffer finalSlotAndBuffer = cache.getOverrideHwcSlotAndBuffer(mBuffer1);
EXPECT_EQ(finalSlotAndBuffer.slot, originalSlotAndBuffer.slot);
EXPECT_EQ(finalSlotAndBuffer.buffer, nullptr);
}
-TEST_F(HwcBufferCacheTest, getHwcSlotAndBufferForOverride_whenSlotsFull_returnsIndependentSlot) {
+TEST_F(HwcBufferCacheTest, getOverrideHwcSlotAndBuffer_whenSlotsFull_returnsIndependentSlot) {
HwcBufferCache cache;
sp<GraphicBuffer> outBuffer;
@@ -149,7 +149,7 @@
sp<GraphicBuffer> overrideBuffer =
sp<GraphicBuffer>::make(1u, 1u, HAL_PIXEL_FORMAT_RGBA_8888, 1u, 0u);
- HwcSlotAndBuffer overrideSlotAndBuffer = cache.getHwcSlotAndBufferForOverride(overrideBuffer);
+ HwcSlotAndBuffer overrideSlotAndBuffer = cache.getOverrideHwcSlotAndBuffer(overrideBuffer);
// expect us to have a slot number
EXPECT_NE(overrideSlotAndBuffer.slot, UINT32_MAX);
// expect this to be the first time we cached the buffer
@@ -173,7 +173,7 @@
HwcBufferCache cache;
sp<GraphicBuffer> outBuffer;
- HwcSlotAndBuffer hwcSlotAndBuffer = cache.getHwcSlotAndBufferForOverride(mBuffer1);
+ HwcSlotAndBuffer hwcSlotAndBuffer = cache.getOverrideHwcSlotAndBuffer(mBuffer1);
ASSERT_NE(hwcSlotAndBuffer.slot, UINT32_MAX);
EXPECT_EQ(cache.uncache(mBuffer1->getId()), hwcSlotAndBuffer.slot);
@@ -184,7 +184,7 @@
HwcBufferCache cache;
sp<GraphicBuffer> outBuffer;
- HwcSlotAndBuffer hwcSlotAndBuffer = cache.getHwcSlotAndBufferForOverride(mBuffer1);
+ HwcSlotAndBuffer hwcSlotAndBuffer = cache.getOverrideHwcSlotAndBuffer(mBuffer1);
ASSERT_NE(hwcSlotAndBuffer.slot, UINT32_MAX);
EXPECT_EQ(cache.uncache(mBuffer2->getId()), UINT32_MAX);
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
index d933b94..b0b1a02 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWC2.h
@@ -56,6 +56,7 @@
MOCK_METHOD3(setBuffer,
Error(uint32_t, const android::sp<android::GraphicBuffer>&,
const android::sp<android::Fence>&));
+ MOCK_METHOD2(setBufferSlotsToClear, Error(const std::vector<uint32_t>&, uint32_t));
MOCK_METHOD1(setSurfaceDamage, Error(const android::Region&));
MOCK_METHOD1(setBlendMode, Error(hal::BlendMode));
MOCK_METHOD1(setColor, Error(aidl::android::hardware::graphics::composer3::Color));
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
index 03cf292..0edc226 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputLayerTest.cpp
@@ -42,6 +42,8 @@
using testing::_;
using testing::InSequence;
+using testing::Mock;
+using testing::NiceMock;
using testing::Return;
using testing::ReturnRef;
using testing::StrictMock;
@@ -82,13 +84,13 @@
struct OutputLayerTest : public testing::Test {
struct OutputLayer final : public impl::OutputLayer {
- OutputLayer(const compositionengine::Output& output, sp<compositionengine::LayerFE> layerFE)
+ OutputLayer(const compositionengine::Output& output, compositionengine::LayerFE& layerFE)
: mOutput(output), mLayerFE(layerFE) {}
~OutputLayer() override = default;
// compositionengine::OutputLayer overrides
const compositionengine::Output& getOutput() const override { return mOutput; }
- compositionengine::LayerFE& getLayerFE() const override { return *mLayerFE; }
+ compositionengine::LayerFE& getLayerFE() const override { return mLayerFE; }
const impl::OutputLayerCompositionState& getState() const override { return mState; }
impl::OutputLayerCompositionState& editState() override { return mState; }
@@ -96,21 +98,22 @@
void dumpState(std::string& out) const override { mState.dump(out); }
const compositionengine::Output& mOutput;
- sp<compositionengine::LayerFE> mLayerFE;
+ compositionengine::LayerFE& mLayerFE;
impl::OutputLayerCompositionState mState;
};
OutputLayerTest() {
- EXPECT_CALL(*mLayerFE, getDebugName()).WillRepeatedly(Return("Test LayerFE"));
- EXPECT_CALL(mOutput, getName()).WillRepeatedly(ReturnRef(kOutputName));
+ ON_CALL(mLayerFE, getDebugName()).WillByDefault(Return("Test LayerFE"));
+ ON_CALL(mOutput, getName()).WillByDefault(ReturnRef(kOutputName));
- EXPECT_CALL(*mLayerFE, getCompositionState()).WillRepeatedly(Return(&mLayerFEState));
- EXPECT_CALL(mOutput, getState()).WillRepeatedly(ReturnRef(mOutputState));
+ ON_CALL(mLayerFE, getCompositionState()).WillByDefault(Return(&mLayerFEState));
+ ON_CALL(mOutput, getState()).WillByDefault(ReturnRef(mOutputState));
}
- compositionengine::mock::Output mOutput;
- sp<StrictMock<compositionengine::mock::LayerFE>> mLayerFE =
- sp<StrictMock<compositionengine::mock::LayerFE>>::make();
+ NiceMock<compositionengine::mock::Output> mOutput;
+ sp<NiceMock<compositionengine::mock::LayerFE>> mLayerFE_ =
+ sp<NiceMock<compositionengine::mock::LayerFE>>::make();
+ NiceMock<compositionengine::mock::LayerFE>& mLayerFE = *mLayerFE_;
OutputLayer mOutputLayer{mOutput, mLayerFE};
LayerFECompositionState mLayerFEState;
@@ -530,7 +533,7 @@
struct OutputLayerPartialMockForUpdateCompositionState : public impl::OutputLayer {
OutputLayerPartialMockForUpdateCompositionState(const compositionengine::Output& output,
- sp<compositionengine::LayerFE> layerFE)
+ compositionengine::LayerFE& layerFE)
: mOutput(output), mLayerFE(layerFE) {}
// Mock everything called by updateCompositionState to simplify testing it.
MOCK_CONST_METHOD1(calculateOutputSourceCrop, FloatRect(uint32_t));
@@ -539,7 +542,7 @@
// compositionengine::OutputLayer overrides
const compositionengine::Output& getOutput() const override { return mOutput; }
- compositionengine::LayerFE& getLayerFE() const override { return *mLayerFE; }
+ compositionengine::LayerFE& getLayerFE() const override { return mLayerFE; }
const impl::OutputLayerCompositionState& getState() const override { return mState; }
impl::OutputLayerCompositionState& editState() override { return mState; }
@@ -547,7 +550,7 @@
MOCK_CONST_METHOD1(dumpState, void(std::string&));
const compositionengine::Output& mOutput;
- sp<compositionengine::LayerFE> mLayerFE;
+ compositionengine::LayerFE& mLayerFE;
impl::OutputLayerCompositionState mState;
};
@@ -588,7 +591,7 @@
};
TEST_F(OutputLayerUpdateCompositionStateTest, doesNothingIfNoFECompositionState) {
- EXPECT_CALL(*mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
+ EXPECT_CALL(mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
mOutputLayer.updateCompositionState(true, false, ui::Transform::RotationFlags::ROT_90);
}
@@ -833,7 +836,6 @@
EXPECT_CALL(mDisplayColorProfile, getSupportedPerFrameMetadata())
.WillRepeatedly(Return(kSupportedPerFrameMetadata));
}
-
// Some tests may need to simulate unsupported HWC calls
enum class SimulateUnsupported { None, ColorTransform };
@@ -952,7 +954,10 @@
const HdrMetadata OutputLayerWriteStateToHWCTest::kHdrMetadata{{/* LightFlattenable */}, 1029};
native_handle_t* OutputLayerWriteStateToHWCTest::kSidebandStreamHandle =
reinterpret_cast<native_handle_t*>(1031);
-const sp<GraphicBuffer> OutputLayerWriteStateToHWCTest::kBuffer;
+const sp<GraphicBuffer> OutputLayerWriteStateToHWCTest::kBuffer =
+ sp<GraphicBuffer>::make(1, 2, PIXEL_FORMAT_RGBA_8888,
+ AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
+ AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
const sp<GraphicBuffer> OutputLayerWriteStateToHWCTest::kOverrideBuffer =
sp<GraphicBuffer>::make(4, 5, PIXEL_FORMAT_RGBA_8888,
AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
@@ -968,7 +973,7 @@
{4, 5, 6, 7}};
TEST_F(OutputLayerWriteStateToHWCTest, doesNothingIfNoFECompositionState) {
- EXPECT_CALL(*mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
+ EXPECT_CALL(mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -993,7 +998,7 @@
expectPerFrameCommonCalls();
expectNoSetCompositionTypeCall();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
+ EXPECT_CALL(mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1018,7 +1023,6 @@
mLayerFEState.compositionType = Composition::SOLID_COLOR;
expectPerFrameCommonCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
// Setting the composition type should happen before setting the color. We
// check this in this test only by setting up an testing::InSeqeuence
@@ -1038,8 +1042,6 @@
expectSetSidebandHandleCall();
expectSetCompositionTypeCall(Composition::SIDEBAND);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1051,8 +1053,6 @@
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::CURSOR);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1064,8 +1064,6 @@
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1079,8 +1077,6 @@
expectSetColorCall();
expectNoSetCompositionTypeCall();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1119,8 +1115,6 @@
expectGenericLayerMetadataCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1133,8 +1127,6 @@
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
-
mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
@@ -1149,7 +1141,6 @@
kOverrideSurfaceDamage, kOverrideLayerBrightness);
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ true, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1165,7 +1156,6 @@
kOverrideSurfaceDamage, kOverrideLayerBrightness);
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ true, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1181,7 +1171,6 @@
kOverrideSurfaceDamage, kOverrideLayerBrightness);
expectSetHdrMetadataAndBufferCalls(kOverrideHwcSlot, kOverrideBuffer, kOverrideFence);
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1197,7 +1186,6 @@
kOverrideSurfaceDamage, kOverrideLayerBrightness);
expectSetHdrMetadataAndBufferCalls(kOverrideHwcSlot, kOverrideBuffer, kOverrideFence);
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1212,7 +1200,6 @@
Region::INVALID_REGION);
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1229,7 +1216,6 @@
Region::INVALID_REGION);
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::DEVICE);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1247,22 +1233,20 @@
Region::INVALID_REGION);
expectSetHdrMetadataAndBufferCalls();
expectSetCompositionTypeCall(Composition::CLIENT);
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
}
TEST_F(OutputLayerWriteStateToHWCTest, peekThroughChangesBlendMode) {
- auto peekThroughLayerFE = sp<compositionengine::mock::LayerFE>::make();
- OutputLayer peekThroughLayer{mOutput, peekThroughLayerFE};
+ auto peekThroughLayerFE = sp<NiceMock<compositionengine::mock::LayerFE>>::make();
+ OutputLayer peekThroughLayer{mOutput, *peekThroughLayerFE};
mOutputLayer.mState.overrideInfo.peekThroughLayer = &peekThroughLayer;
expectGeometryCommonCalls(kDisplayFrame, kSourceCrop, kBufferTransform,
Hwc2::IComposerClient::BlendMode::PREMULTIPLIED);
expectPerFrameCommonCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false);
@@ -1280,7 +1264,6 @@
TEST_F(OutputLayerWriteStateToHWCTest, zIsOverriddenSetsOverride) {
expectGeometryCommonCalls();
expectPerFrameCommonCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(false));
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
/*zIsOverridden*/ true, /*isPeekingThrough*/
@@ -1291,7 +1274,7 @@
TEST_F(OutputLayerWriteStateToHWCTest, roundedCornersForceClientComposition) {
expectGeometryCommonCalls();
expectPerFrameCommonCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillOnce(Return(true));
+ EXPECT_CALL(mLayerFE, hasRoundedCorners()).WillOnce(Return(true));
expectSetCompositionTypeCall(Composition::CLIENT);
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
@@ -1303,7 +1286,7 @@
expectGeometryCommonCalls();
expectPerFrameCommonCalls();
expectSetHdrMetadataAndBufferCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(true));
+ EXPECT_CALL(mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(true));
expectSetCompositionTypeCall(Composition::DEVICE);
mLayerFEState.compositionType = Composition::DEVICE;
@@ -1322,7 +1305,6 @@
expectPerFrameCommonCalls(SimulateUnsupported::None, kDataspace, kOutputSpaceVisibleRegion,
kSurfaceDamage, kLayerBrightness, blockingRegion);
expectSetHdrMetadataAndBufferCalls();
- EXPECT_CALL(*mLayerFE, hasRoundedCorners()).WillRepeatedly(Return(false));
expectSetCompositionTypeCall(Composition::DISPLAY_DECORATION);
mOutputLayer.writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, 0,
@@ -1331,6 +1313,76 @@
}
/*
+ * OutputLayer::uncacheBuffers
+ */
+struct OutputLayerUncacheBufferTest : public OutputLayerTest {
+ static const sp<GraphicBuffer> kBuffer1;
+ static const sp<GraphicBuffer> kBuffer2;
+ static const sp<Fence> kFence;
+
+ OutputLayerUncacheBufferTest() {
+ auto& outputLayerState = mOutputLayer.editState();
+ outputLayerState.hwc = impl::OutputLayerCompositionState::Hwc(mHwcLayer_);
+
+ mLayerFEState.compositionType = Composition::DEVICE;
+ mLayerFEState.acquireFence = kFence;
+
+ ON_CALL(mOutput, getDisplayColorProfile()).WillByDefault(Return(&mDisplayColorProfile));
+ }
+
+ std::shared_ptr<HWC2::mock::Layer> mHwcLayer_{std::make_shared<NiceMock<HWC2::mock::Layer>>()};
+ HWC2::mock::Layer& mHwcLayer = *mHwcLayer_;
+ NiceMock<mock::DisplayColorProfile> mDisplayColorProfile;
+};
+
+const sp<GraphicBuffer> OutputLayerUncacheBufferTest::kBuffer1 =
+ sp<GraphicBuffer>::make(1, 2, PIXEL_FORMAT_RGBA_8888,
+ AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
+ AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
+const sp<GraphicBuffer> OutputLayerUncacheBufferTest::kBuffer2 =
+ sp<GraphicBuffer>::make(2, 3, PIXEL_FORMAT_RGBA_8888,
+ AHARDWAREBUFFER_USAGE_CPU_WRITE_OFTEN |
+ AHARDWAREBUFFER_USAGE_CPU_READ_OFTEN);
+const sp<Fence> OutputLayerUncacheBufferTest::kFence = sp<Fence>::make();
+
+TEST_F(OutputLayerUncacheBufferTest, canUncacheAndReuseSlot) {
+ // Buffer1 is stored in slot 0
+ mLayerFEState.buffer = kBuffer1;
+ EXPECT_CALL(mHwcLayer, setBuffer(/*slot*/ 0, kBuffer1, kFence));
+ mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false);
+ Mock::VerifyAndClearExpectations(&mHwcLayer);
+
+ // Buffer2 is stored in slot 1
+ mLayerFEState.buffer = kBuffer2;
+ EXPECT_CALL(mHwcLayer, setBuffer(/*slot*/ 1, kBuffer2, kFence));
+ mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false);
+ Mock::VerifyAndClearExpectations(&mHwcLayer);
+
+ // buffer slots are cleared in HWC
+ std::vector<uint32_t> slotsToClear = {0, 1};
+ EXPECT_CALL(mHwcLayer,
+ setBufferSlotsToClear(/*slotsToClear*/ slotsToClear, /*activeBufferSlot*/ 1));
+ mOutputLayer.uncacheBuffers({kBuffer1->getId(), kBuffer2->getId()});
+ Mock::VerifyAndClearExpectations(&mHwcLayer);
+
+ // rather than allocating a new slot, the active buffer slot (slot 1) is reused first to free
+ // the memory as soon as possible
+ mLayerFEState.buffer = kBuffer1;
+ EXPECT_CALL(mHwcLayer, setBuffer(/*slot*/ 1, kBuffer1, kFence));
+ mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false);
+ Mock::VerifyAndClearExpectations(&mHwcLayer);
+
+ // rather than allocating a new slot, slot 0 is reused
+ mLayerFEState.buffer = kBuffer2;
+ EXPECT_CALL(mHwcLayer, setBuffer(/*slot*/ 0, kBuffer2, kFence));
+ mOutputLayer.writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
+ /*zIsOverridden*/ false, /*isPeekingThrough*/ false);
+}
+
+/*
* OutputLayer::writeCursorPositionToHWC()
*/
@@ -1358,7 +1410,7 @@
const Rect OutputLayerWriteCursorPositionToHWCTest::kDefaultCursorFrame{1, 2, 3, 4};
TEST_F(OutputLayerWriteCursorPositionToHWCTest, doesNothingIfNoFECompositionState) {
- EXPECT_CALL(*mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
+ EXPECT_CALL(mLayerFE, getCompositionState()).WillOnce(Return(nullptr));
mOutputLayer.writeCursorPositionToHWC();
}
diff --git a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
index bfd863b..aaf0f06 100644
--- a/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/OutputTest.cpp
@@ -799,20 +799,17 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_180));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_180));
EXPECT_CALL(*layer3.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
injectOutputLayer(layer1);
injectOutputLayer(layer2);
@@ -839,20 +836,17 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer3.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
injectOutputLayer(layer1);
injectOutputLayer(layer2);
@@ -878,20 +872,17 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
EXPECT_CALL(*layer3.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
injectOutputLayer(layer1);
injectOutputLayer(layer2);
@@ -917,8 +908,7 @@
InSequence seq;
EXPECT_CALL(*layer0.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer1.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(true, false, ui::Transform::ROT_0));
@@ -926,9 +916,7 @@
EXPECT_CALL(*layer0.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer0.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
-
+ EXPECT_CALL(*layer0.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
// After calling planComposition (which clears overrideInfo), this test sets
// layer3 to be the peekThroughLayer for layer1 and layer2. As a result, it
@@ -938,18 +926,15 @@
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ true, /*isPeekingThrough*/
true));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ false, z++,
/*zIsOverridden*/ true, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ true, /*skipLayer*/ true, z++,
/*zIsOverridden*/ true, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
injectOutputLayer(layer0);
injectOutputLayer(layer1);
@@ -1050,10 +1035,10 @@
MOCK_METHOD1(
chooseCompositionStrategyAsync,
std::future<bool>(std::optional<android::HWComposer::DeviceRequestedChanges>*));
- MOCK_METHOD4(composeSurfaces,
- std::optional<base::unique_fd>(
- const Region&, const compositionengine::CompositionRefreshArgs&,
- std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&));
+ MOCK_METHOD3(composeSurfaces,
+ std::optional<base::unique_fd>(const Region&,
+ std::shared_ptr<renderengine::ExternalTexture>,
+ base::unique_fd&));
MOCK_METHOD0(resetCompositionStrategy, void());
};
@@ -1087,9 +1072,9 @@
EXPECT_CALL(mOutput, chooseCompositionStrategyAsync(_))
.WillOnce(DoAll(SetArgPointee<0>(mOutput.editState().previousDeviceRequestedChanges),
Return(ByMove(p.get_future()))));
- EXPECT_CALL(mOutput, composeSurfaces(_, Ref(mRefreshArgs), _, _));
+ EXPECT_CALL(mOutput, composeSurfaces(_, _, _));
- impl::GpuCompositionResult result = mOutput.prepareFrameAsync(mRefreshArgs);
+ impl::GpuCompositionResult result = mOutput.prepareFrameAsync();
EXPECT_EQ(mOutput.getState().strategyPrediction, CompositionStrategyPredictionState::SUCCESS);
EXPECT_FALSE(result.bufferAvailable());
}
@@ -1112,7 +1097,7 @@
.WillOnce(DoAll(SetArgPointee<0>(mOutput.editState().previousDeviceRequestedChanges),
Return(ByMove(p.get_future()))));
- impl::GpuCompositionResult result = mOutput.prepareFrameAsync(mRefreshArgs);
+ impl::GpuCompositionResult result = mOutput.prepareFrameAsync();
EXPECT_EQ(mOutput.getState().strategyPrediction, CompositionStrategyPredictionState::FAIL);
EXPECT_FALSE(result.bufferAvailable());
}
@@ -1140,9 +1125,9 @@
EXPECT_CALL(mOutput, chooseCompositionStrategyAsync(_)).WillOnce([&] {
return p.get_future();
});
- EXPECT_CALL(mOutput, composeSurfaces(_, Ref(mRefreshArgs), _, _));
+ EXPECT_CALL(mOutput, composeSurfaces(_, _, _));
- impl::GpuCompositionResult result = mOutput.prepareFrameAsync(mRefreshArgs);
+ impl::GpuCompositionResult result = mOutput.prepareFrameAsync();
EXPECT_EQ(mOutput.getState().strategyPrediction, CompositionStrategyPredictionState::FAIL);
EXPECT_TRUE(result.bufferAvailable());
}
@@ -1172,9 +1157,9 @@
EXPECT_CALL(mOutput, chooseCompositionStrategyAsync(_)).WillOnce([&] {
return p.get_future();
});
- EXPECT_CALL(mOutput, composeSurfaces(_, Ref(mRefreshArgs), _, _));
+ EXPECT_CALL(mOutput, composeSurfaces(_, _, _));
- impl::GpuCompositionResult result = mOutput.prepareFrameAsync(mRefreshArgs);
+ impl::GpuCompositionResult result = mOutput.prepareFrameAsync();
EXPECT_EQ(mOutput.getState().strategyPrediction, CompositionStrategyPredictionState::FAIL);
EXPECT_TRUE(result.bufferAvailable());
}
@@ -2035,11 +2020,9 @@
MOCK_METHOD1(setColorTransform, void(const compositionengine::CompositionRefreshArgs&));
MOCK_METHOD0(beginFrame, void());
MOCK_METHOD0(prepareFrame, void());
- MOCK_METHOD1(prepareFrameAsync, GpuCompositionResult(const CompositionRefreshArgs&));
+ MOCK_METHOD0(prepareFrameAsync, GpuCompositionResult());
MOCK_METHOD1(devOptRepaintFlash, void(const compositionengine::CompositionRefreshArgs&));
- MOCK_METHOD2(finishFrame,
- void(const compositionengine::CompositionRefreshArgs&,
- GpuCompositionResult&&));
+ MOCK_METHOD1(finishFrame, void(GpuCompositionResult&&));
MOCK_METHOD0(postFramebuffer, void());
MOCK_METHOD1(renderCachedSets, void(const compositionengine::CompositionRefreshArgs&));
MOCK_METHOD1(canPredictCompositionStrategy, bool(const CompositionRefreshArgs&));
@@ -2061,7 +2044,7 @@
EXPECT_CALL(mOutput, canPredictCompositionStrategy(Ref(args))).WillOnce(Return(false));
EXPECT_CALL(mOutput, prepareFrame());
EXPECT_CALL(mOutput, devOptRepaintFlash(Ref(args)));
- EXPECT_CALL(mOutput, finishFrame(Ref(args), _));
+ EXPECT_CALL(mOutput, finishFrame(_));
EXPECT_CALL(mOutput, postFramebuffer());
EXPECT_CALL(mOutput, renderCachedSets(Ref(args)));
@@ -2079,9 +2062,9 @@
EXPECT_CALL(mOutput, setColorTransform(Ref(args)));
EXPECT_CALL(mOutput, beginFrame());
EXPECT_CALL(mOutput, canPredictCompositionStrategy(Ref(args))).WillOnce(Return(true));
- EXPECT_CALL(mOutput, prepareFrameAsync(Ref(args)));
+ EXPECT_CALL(mOutput, prepareFrameAsync());
EXPECT_CALL(mOutput, devOptRepaintFlash(Ref(args)));
- EXPECT_CALL(mOutput, finishFrame(Ref(args), _));
+ EXPECT_CALL(mOutput, finishFrame(_));
EXPECT_CALL(mOutput, postFramebuffer());
EXPECT_CALL(mOutput, renderCachedSets(Ref(args)));
@@ -2980,10 +2963,10 @@
// Sets up the helper functions called by the function under test to use
// mock implementations.
MOCK_METHOD(Region, getDirtyRegion, (), (const));
- MOCK_METHOD4(composeSurfaces,
- std::optional<base::unique_fd>(
- const Region&, const compositionengine::CompositionRefreshArgs&,
- std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&));
+ MOCK_METHOD3(composeSurfaces,
+ std::optional<base::unique_fd>(const Region&,
+ std::shared_ptr<renderengine::ExternalTexture>,
+ base::unique_fd&));
MOCK_METHOD0(postFramebuffer, void());
MOCK_METHOD0(prepareFrame, void());
MOCK_METHOD0(updateProtectedContentState, void());
@@ -3047,7 +3030,7 @@
EXPECT_CALL(mOutput, getDirtyRegion()).WillOnce(Return(kNotEmptyRegion));
EXPECT_CALL(mOutput, updateProtectedContentState());
EXPECT_CALL(mOutput, dequeueRenderBuffer(_, _));
- EXPECT_CALL(mOutput, composeSurfaces(RegionEq(kNotEmptyRegion), Ref(mRefreshArgs), _, _));
+ EXPECT_CALL(mOutput, composeSurfaces(RegionEq(kNotEmptyRegion), _, _));
EXPECT_CALL(*mRenderSurface, queueBuffer(_));
EXPECT_CALL(mOutput, postFramebuffer());
EXPECT_CALL(mOutput, prepareFrame());
@@ -3063,10 +3046,10 @@
struct OutputPartialMock : public OutputPartialMockBase {
// Sets up the helper functions called by the function under test to use
// mock implementations.
- MOCK_METHOD4(composeSurfaces,
- std::optional<base::unique_fd>(
- const Region&, const compositionengine::CompositionRefreshArgs&,
- std::shared_ptr<renderengine::ExternalTexture>, base::unique_fd&));
+ MOCK_METHOD3(composeSurfaces,
+ std::optional<base::unique_fd>(const Region&,
+ std::shared_ptr<renderengine::ExternalTexture>,
+ base::unique_fd&));
MOCK_METHOD0(postFramebuffer, void());
MOCK_METHOD0(updateProtectedContentState, void());
MOCK_METHOD2(dequeueRenderBuffer,
@@ -3082,24 +3065,23 @@
StrictMock<OutputPartialMock> mOutput;
mock::DisplayColorProfile* mDisplayColorProfile = new StrictMock<mock::DisplayColorProfile>();
mock::RenderSurface* mRenderSurface = new StrictMock<mock::RenderSurface>();
- CompositionRefreshArgs mRefreshArgs;
};
TEST_F(OutputFinishFrameTest, ifNotEnabledDoesNothing) {
mOutput.mState.isEnabled = false;
impl::GpuCompositionResult result;
- mOutput.finishFrame(mRefreshArgs, std::move(result));
+ mOutput.finishFrame(std::move(result));
}
TEST_F(OutputFinishFrameTest, takesEarlyOutifComposeSurfacesReturnsNoFence) {
mOutput.mState.isEnabled = true;
EXPECT_CALL(mOutput, updateProtectedContentState());
EXPECT_CALL(mOutput, dequeueRenderBuffer(_, _)).WillOnce(Return(true));
- EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _, _, _));
+ EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _, _));
impl::GpuCompositionResult result;
- mOutput.finishFrame(mRefreshArgs, std::move(result));
+ mOutput.finishFrame(std::move(result));
}
TEST_F(OutputFinishFrameTest, queuesBufferIfComposeSurfacesReturnsAFence) {
@@ -3108,12 +3090,12 @@
InSequence seq;
EXPECT_CALL(mOutput, updateProtectedContentState());
EXPECT_CALL(mOutput, dequeueRenderBuffer(_, _)).WillOnce(Return(true));
- EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _, _, _))
+ EXPECT_CALL(mOutput, composeSurfaces(RegionEq(Region::INVALID_REGION), _, _))
.WillOnce(Return(ByMove(base::unique_fd())));
EXPECT_CALL(*mRenderSurface, queueBuffer(_));
impl::GpuCompositionResult result;
- mOutput.finishFrame(mRefreshArgs, std::move(result));
+ mOutput.finishFrame(std::move(result));
}
TEST_F(OutputFinishFrameTest, predictionSucceeded) {
@@ -3123,7 +3105,7 @@
EXPECT_CALL(*mRenderSurface, queueBuffer(_));
impl::GpuCompositionResult result;
- mOutput.finishFrame(mRefreshArgs, std::move(result));
+ mOutput.finishFrame(std::move(result));
}
TEST_F(OutputFinishFrameTest, predictionFailedAndBufferIsReused) {
@@ -3139,11 +3121,11 @@
2);
EXPECT_CALL(mOutput,
- composeSurfaces(RegionEq(Region::INVALID_REGION), _, result.buffer,
+ composeSurfaces(RegionEq(Region::INVALID_REGION), result.buffer,
Eq(ByRef(result.fence))))
.WillOnce(Return(ByMove(base::unique_fd())));
EXPECT_CALL(*mRenderSurface, queueBuffer(_));
- mOutput.finishFrame(mRefreshArgs, std::move(result));
+ mOutput.finishFrame(std::move(result));
}
/*
@@ -3334,7 +3316,8 @@
// mock implementations.
MOCK_CONST_METHOD0(getSkipColorTransform, bool());
MOCK_METHOD3(generateClientCompositionRequests,
- std::vector<LayerFE::LayerSettings>(bool, ui::Dataspace, std::vector<LayerFE*>&));
+ std::vector<LayerFE::LayerSettings>(bool, ui::Dataspace,
+ std::vector<LayerFE*>&));
MOCK_METHOD2(appendRegionFlashRequests,
void(const Region&, std::vector<LayerFE::LayerSettings>&));
MOCK_METHOD1(setExpensiveRenderingExpected, void(bool));
@@ -3380,8 +3363,8 @@
getInstance()->mOutput.dequeueRenderBuffer(&fence, &externalTexture);
if (success) {
getInstance()->mReadyFence =
- getInstance()->mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs,
- externalTexture, fence);
+ getInstance()->mOutput.composeSurfaces(kDebugRegion, externalTexture,
+ fence);
}
return nextState<FenceCheckState>();
}
@@ -4055,7 +4038,7 @@
std::shared_ptr<renderengine::ExternalTexture> tex;
mOutput.updateProtectedContentState();
mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs, tex, fd);
+ mOutput.composeSurfaces(kDebugRegion, tex, fd);
}
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifNotEnabled) {
@@ -4077,7 +4060,7 @@
std::shared_ptr<renderengine::ExternalTexture> tex;
mOutput.updateProtectedContentState();
mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs, tex, fd);
+ mOutput.composeSurfaces(kDebugRegion, tex, fd);
}
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifAlreadyEnabledEverywhere) {
@@ -4090,7 +4073,7 @@
std::shared_ptr<renderengine::ExternalTexture> tex;
mOutput.updateProtectedContentState();
mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs, tex, fd);
+ mOutput.composeSurfaces(kDebugRegion, tex, fd);
}
TEST_F(OutputComposeSurfacesTest_HandlesProtectedContent, ifAlreadyEnabledInRenderSurface) {
@@ -4103,7 +4086,7 @@
std::shared_ptr<renderengine::ExternalTexture> tex;
mOutput.updateProtectedContentState();
mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs, tex, fd);
+ mOutput.composeSurfaces(kDebugRegion, tex, fd);
}
struct OutputComposeSurfacesTest_SetsExpensiveRendering : public OutputComposeSurfacesTest {
@@ -4136,61 +4119,7 @@
std::shared_ptr<renderengine::ExternalTexture> tex;
mOutput.updateProtectedContentState();
mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, kDefaultRefreshArgs, tex, fd);
-}
-
-struct OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur
- : public OutputComposeSurfacesTest_SetsExpensiveRendering {
- OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur() {
- mLayer.layerFEState.backgroundBlurRadius = 10;
- mLayer.layerFEState.isOpaque = false;
- mOutput.editState().isEnabled = true;
-
- EXPECT_CALL(mLayer.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
- EXPECT_CALL(mLayer.outputLayer,
- writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, 0,
- /*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(mOutput, generateClientCompositionRequests(_, kDefaultOutputDataspace, _))
- .WillOnce(Return(std::vector<LayerFE::LayerSettings>{}));
- EXPECT_CALL(mRenderEngine, drawLayers(_, _, _, false, _))
- .WillOnce(Return(ByMove(ftl::yield<FenceResult>(Fence::NO_FENCE))));
- EXPECT_CALL(mOutput, getOutputLayerCount()).WillRepeatedly(Return(1u));
- EXPECT_CALL(mOutput, getOutputLayerOrderedByZByIndex(0u))
- .WillRepeatedly(Return(&mLayer.outputLayer));
- }
-
- NonInjectedLayer mLayer;
- compositionengine::CompositionRefreshArgs mRefreshArgs;
-};
-
-TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur, IfBlursAreExpensive) {
- mRefreshArgs.blursAreExpensive = true;
- mOutput.updateCompositionState(mRefreshArgs);
- mOutput.planComposition();
- mOutput.writeCompositionState(mRefreshArgs);
-
- EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true));
-
- base::unique_fd fd;
- std::shared_ptr<renderengine::ExternalTexture> tex;
- mOutput.updateProtectedContentState();
- mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, mRefreshArgs, tex, fd);
-}
-
-TEST_F(OutputComposeSurfacesTest_SetsExpensiveRendering_ForBlur, IfBlursAreNotExpensive) {
- mRefreshArgs.blursAreExpensive = false;
- mOutput.updateCompositionState(mRefreshArgs);
- mOutput.planComposition();
- mOutput.writeCompositionState(mRefreshArgs);
-
- EXPECT_CALL(mOutput, setExpensiveRenderingExpected(true)).Times(0);
-
- base::unique_fd fd;
- std::shared_ptr<renderengine::ExternalTexture> tex;
- mOutput.updateProtectedContentState();
- mOutput.dequeueRenderBuffer(&fd, &tex);
- mOutput.composeSurfaces(kDebugRegion, mRefreshArgs, tex, fd);
+ mOutput.composeSurfaces(kDebugRegion, tex, fd);
}
/*
@@ -4201,7 +4130,7 @@
struct OutputPartialMock : public OutputPartialMockBase {
// compositionengine::Output overrides
std::vector<LayerFE::LayerSettings> generateClientCompositionRequestsHelper(
- bool supportsProtectedContent, ui::Dataspace dataspace) {
+ bool supportsProtectedContent, ui::Dataspace dataspace) {
std::vector<LayerFE*> ignore;
return impl::Output::generateClientCompositionRequests(supportsProtectedContent,
dataspace, ignore);
@@ -4293,8 +4222,9 @@
EXPECT_CALL(mLayers[1].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
EXPECT_CALL(mLayers[2].mOutputLayer, requiresClientComposition()).WillOnce(Return(false));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
EXPECT_EQ(0u, requests.size());
}
@@ -4303,8 +4233,9 @@
mLayers[1].mOutputLayerState.visibleRegion = Region(Rect(4000, 0, 4010, 10));
mLayers[2].mOutputLayerState.visibleRegion = Region(Rect(-10, -10, 0, 0));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
EXPECT_EQ(0u, requests.size());
}
@@ -4316,8 +4247,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(_))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(2u, requests.size());
EXPECT_EQ(mLayers[1].mLayerSettings, requests[0]);
EXPECT_EQ(mLayers[2].mLayerSettings, requests[1]);
@@ -4347,8 +4279,9 @@
prepareClientComposition(ClientCompositionTargetSettingsBlurSettingsEq(
LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly)))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(2u, requests.size());
EXPECT_EQ(mLayers[1].mLayerSettings, requests[0]);
EXPECT_EQ(mLayers[2].mLayerSettings, requests[1]);
@@ -4376,8 +4309,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(_))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(1u, requests.size());
EXPECT_EQ(mLayers[2].mLayerSettings, requests[0]);
}
@@ -4399,8 +4333,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(_))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(1u, requests.size());
EXPECT_EQ(mLayers[2].mLayerSettings, requests[0]);
}
@@ -4462,8 +4397,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(Eq(ByRef(layer2TargetSettings))))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(2u, requests.size());
// The second layer is expected to be rendered as alpha=0 black with no blending
@@ -4527,7 +4463,7 @@
static_cast<void>(
mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace));
+ kDisplayDataspace));
}
TEST_F(GenerateClientCompositionRequestsTest_ThreeLayers,
@@ -4749,8 +4685,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(Eq(ByRef(layer2TargetSettings))))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>()));
- static_cast<void>(mOutput.generateClientCompositionRequestsHelper(true /* supportsProtectedContent */,
- kDisplayDataspace));
+ static_cast<void>(
+ mOutput.generateClientCompositionRequestsHelper(true /* supportsProtectedContent */,
+ kDisplayDataspace));
}
TEST_F(OutputUpdateAndWriteCompositionStateTest, noBackgroundBlurWhenOpaque) {
@@ -4763,14 +4700,12 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
layer2.layerFEState.backgroundBlurRadius = 10;
layer2.layerFEState.isOpaque = true;
@@ -4799,20 +4734,17 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer3.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
layer2.layerFEState.backgroundBlurRadius = 10;
layer2.layerFEState.isOpaque = false;
@@ -4842,20 +4774,17 @@
EXPECT_CALL(*layer1.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer1.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer1.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer2.outputLayer, updateCompositionState(false, true, ui::Transform::ROT_0));
EXPECT_CALL(*layer2.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer2.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer2.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
EXPECT_CALL(*layer3.outputLayer, updateCompositionState(false, false, ui::Transform::ROT_0));
EXPECT_CALL(*layer3.outputLayer,
writeStateToHWC(/*includeGeometry*/ false, /*skipLayer*/ false, z++,
/*zIsOverridden*/ false, /*isPeekingThrough*/ false));
- EXPECT_CALL(*layer3.outputLayer, requiresClientComposition())
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*layer3.outputLayer, requiresClientComposition()).WillRepeatedly(Return(false));
BlurRegion region;
layer2.layerFEState.blurRegions.push_back(region);
@@ -4952,8 +4881,8 @@
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(rightLayer.mLayerSettings)));
constexpr bool supportsProtectedContent = true;
- auto requests =
- mOutput.generateClientCompositionRequestsHelper(supportsProtectedContent, kOutputDataspace);
+ auto requests = mOutput.generateClientCompositionRequestsHelper(supportsProtectedContent,
+ kOutputDataspace);
ASSERT_EQ(2u, requests.size());
EXPECT_EQ(leftLayer.mLayerSettings, requests[0]);
EXPECT_EQ(rightLayer.mLayerSettings, requests[1]);
@@ -4991,8 +4920,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(Eq(ByRef(layer2Settings))))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mShadowSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(1u, requests.size());
EXPECT_EQ(mShadowSettings, requests[0]);
@@ -5028,8 +4958,9 @@
EXPECT_CALL(*mLayers[2].mLayerFE, prepareClientComposition(Eq(ByRef(layer2Settings))))
.WillOnce(Return(std::optional<LayerFE::LayerSettings>(mLayers[2].mLayerSettings)));
- auto requests = mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
- kDisplayDataspace);
+ auto requests =
+ mOutput.generateClientCompositionRequestsHelper(false /* supportsProtectedContent */,
+ kDisplayDataspace);
ASSERT_EQ(1u, requests.size());
EXPECT_EQ(mLayers[2].mLayerSettings, requests[0]);
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 46b857b..96ae77f 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -452,7 +452,8 @@
}
}
-auto DisplayDevice::setDesiredActiveMode(const ActiveModeInfo& info) -> DesiredActiveModeAction {
+auto DisplayDevice::setDesiredActiveMode(const ActiveModeInfo& info, bool force)
+ -> DesiredActiveModeAction {
ATRACE_CALL();
LOG_ALWAYS_FATAL_IF(!info.modeOpt, "desired mode not provided");
@@ -473,7 +474,7 @@
const auto& desiredMode = *info.modeOpt->modePtr;
// Check if we are already at the desired mode
- if (refreshRateSelector().getActiveMode().modePtr->getId() == desiredMode.getId()) {
+ if (!force && refreshRateSelector().getActiveMode().modePtr->getId() == desiredMode.getId()) {
if (refreshRateSelector().getActiveMode() == info.modeOpt) {
return DesiredActiveModeAction::None;
}
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index 8f9b2a1..d757673 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -210,7 +210,8 @@
InitiateDisplayModeSwitch,
InitiateRenderRateSwitch
};
- DesiredActiveModeAction setDesiredActiveMode(const ActiveModeInfo&) EXCLUDES(mActiveModeLock);
+ DesiredActiveModeAction setDesiredActiveMode(const ActiveModeInfo&, bool force = false)
+ EXCLUDES(mActiveModeLock);
std::optional<ActiveModeInfo> getDesiredActiveMode() const EXCLUDES(mActiveModeLock);
void clearDesiredActiveModeState() EXCLUDES(mActiveModeLock);
ActiveModeInfo getUpcomingActiveMode() const REQUIRES(kMainThreadContext) {
diff --git a/services/surfaceflinger/DisplayHardware/AidlComposerHal.cpp b/services/surfaceflinger/DisplayHardware/AidlComposerHal.cpp
index 800e36d..e372b72 100644
--- a/services/surfaceflinger/DisplayHardware/AidlComposerHal.cpp
+++ b/services/surfaceflinger/DisplayHardware/AidlComposerHal.cpp
@@ -23,6 +23,7 @@
#include <android-base/file.h>
#include <android/binder_ibinder_platform.h>
#include <android/binder_manager.h>
+#include <gui/TraceUtils.h>
#include <log/log.h>
#include <utils/Trace.h>
@@ -232,6 +233,25 @@
addReader(translate<Display>(kSingleReaderKey));
+ // If unable to read interface version, then become backwards compatible.
+ int32_t version = 1;
+ const auto status = mAidlComposerClient->getInterfaceVersion(&version);
+ if (!status.isOk()) {
+ ALOGE("getInterfaceVersion for AidlComposer constructor failed %s",
+ status.getDescription().c_str());
+ }
+ if (version == 1) {
+ mClearSlotBuffer = sp<GraphicBuffer>::make(1, 1, PIXEL_FORMAT_RGBX_8888,
+ GraphicBuffer::USAGE_HW_COMPOSER |
+ GraphicBuffer::USAGE_SW_READ_OFTEN |
+ GraphicBuffer::USAGE_SW_WRITE_OFTEN,
+ "AidlComposer");
+ if (!mClearSlotBuffer || mClearSlotBuffer->initCheck() != ::android::OK) {
+ LOG_ALWAYS_FATAL("Failed to allocate a buffer for clearing layer buffer slots");
+ return;
+ }
+ }
+
ALOGI("Loaded AIDL composer3 HAL service");
}
@@ -578,13 +598,15 @@
}
Error AidlComposer::presentDisplay(Display display, int* outPresentFence) {
- ATRACE_NAME("HwcPresentDisplay");
+ const auto displayId = translate<int64_t>(display);
+ ATRACE_FORMAT("HwcPresentDisplay %" PRId64, displayId);
+
Error error = Error::NONE;
mMutex.lock_shared();
auto writer = getWriter(display);
auto reader = getReader(display);
if (writer && reader) {
- writer->get().presentDisplay(translate<int64_t>(display));
+ writer->get().presentDisplay(displayId);
error = execute(display);
} else {
error = Error::BAD_DISPLAY;
@@ -595,7 +617,7 @@
return error;
}
- auto fence = reader->get().takePresentFence(translate<int64_t>(display));
+ auto fence = reader->get().takePresentFence(displayId);
mMutex.unlock_shared();
// take ownership
*outPresentFence = fence.get();
@@ -707,8 +729,9 @@
Error AidlComposer::validateDisplay(Display display, nsecs_t expectedPresentTime,
uint32_t* outNumTypes, uint32_t* outNumRequests) {
- ATRACE_NAME("HwcValidateDisplay");
const auto displayId = translate<int64_t>(display);
+ ATRACE_FORMAT("HwcValidateDisplay %" PRId64, displayId);
+
Error error = Error::NONE;
mMutex.lock_shared();
auto writer = getWriter(display);
@@ -734,8 +757,9 @@
Error AidlComposer::presentOrValidateDisplay(Display display, nsecs_t expectedPresentTime,
uint32_t* outNumTypes, uint32_t* outNumRequests,
int* outPresentFence, uint32_t* state) {
- ATRACE_NAME("HwcPresentOrValidateDisplay");
const auto displayId = translate<int64_t>(display);
+ ATRACE_FORMAT("HwcPresentOrValidateDisplay %" PRId64, displayId);
+
Error error = Error::NONE;
mMutex.lock_shared();
auto writer = getWriter(display);
@@ -809,6 +833,49 @@
return error;
}
+Error AidlComposer::setLayerBufferSlotsToClear(Display display, Layer layer,
+ const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) {
+ if (slotsToClear.empty()) {
+ return Error::NONE;
+ }
+
+ Error error = Error::NONE;
+ mMutex.lock_shared();
+ if (auto writer = getWriter(display)) {
+ // Backwards compatible way of clearing buffer is to set the layer buffer with a placeholder
+ // buffer, using the slot that needs to cleared... tricky.
+ if (mClearSlotBuffer == nullptr) {
+ writer->get().setLayerBufferSlotsToClear(translate<int64_t>(display),
+ translate<int64_t>(layer), slotsToClear);
+ } else {
+ for (uint32_t slot : slotsToClear) {
+ // Don't clear the active buffer slot because we need to restore the active buffer
+ // after clearing the requested buffer slots with a placeholder buffer.
+ if (slot != activeBufferSlot) {
+ writer->get().setLayerBufferWithNewCommand(translate<int64_t>(display),
+ translate<int64_t>(layer), slot,
+ mClearSlotBuffer->handle,
+ /*fence*/ -1);
+ }
+ }
+ // Since we clear buffers by setting them to a placeholder buffer, we want to make
+ // sure that the last setLayerBuffer command is sent with the currently active
+ // buffer, not the placeholder buffer, so that there is no perceptual change when
+ // buffers are discarded.
+ writer->get().setLayerBufferWithNewCommand(translate<int64_t>(display),
+ translate<int64_t>(layer), activeBufferSlot,
+ // The active buffer is still cached in
+ // its slot and doesn't need a fence.
+ /*buffer*/ nullptr, /*fence*/ -1);
+ }
+ } else {
+ error = Error::BAD_DISPLAY;
+ }
+ mMutex.unlock_shared();
+ return error;
+}
+
Error AidlComposer::setLayerSurfaceDamage(Display display, Layer layer,
const std::vector<IComposerClient::Rect>& damage) {
Error error = Error::NONE;
diff --git a/services/surfaceflinger/DisplayHardware/AidlComposerHal.h b/services/surfaceflinger/DisplayHardware/AidlComposerHal.h
index 2a043fd..9a7ade7 100644
--- a/services/surfaceflinger/DisplayHardware/AidlComposerHal.h
+++ b/services/surfaceflinger/DisplayHardware/AidlComposerHal.h
@@ -143,6 +143,9 @@
/* see setClientTarget for the purpose of slot */
Error setLayerBuffer(Display display, Layer layer, uint32_t slot,
const sp<GraphicBuffer>& buffer, int acquireFence) override;
+ Error setLayerBufferSlotsToClear(Display display, Layer layer,
+ const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) override;
Error setLayerSurfaceDamage(Display display, Layer layer,
const std::vector<IComposerClient::Rect>& damage) override;
Error setLayerBlendMode(Display display, Layer layer, IComposerClient::BlendMode mode) override;
@@ -280,6 +283,9 @@
// threading annotations.
ftl::SharedMutex mMutex;
+ // Buffer slots for layers are cleared by setting the slot buffer to this buffer.
+ sp<GraphicBuffer> mClearSlotBuffer;
+
// Aidl interface
using AidlIComposer = aidl::android::hardware::graphics::composer3::IComposer;
using AidlIComposerClient = aidl::android::hardware::graphics::composer3::IComposerClient;
diff --git a/services/surfaceflinger/DisplayHardware/ComposerHal.h b/services/surfaceflinger/DisplayHardware/ComposerHal.h
index ec23935..1c2b8b5 100644
--- a/services/surfaceflinger/DisplayHardware/ComposerHal.h
+++ b/services/surfaceflinger/DisplayHardware/ComposerHal.h
@@ -179,6 +179,9 @@
/* see setClientTarget for the purpose of slot */
virtual Error setLayerBuffer(Display display, Layer layer, uint32_t slot,
const sp<GraphicBuffer>& buffer, int acquireFence) = 0;
+ virtual Error setLayerBufferSlotsToClear(Display display, Layer layer,
+ const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) = 0;
virtual Error setLayerSurfaceDamage(Display display, Layer layer,
const std::vector<IComposerClient::Rect>& damage) = 0;
virtual Error setLayerBlendMode(Display display, Layer layer,
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index d0126d0..6738f00 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -717,6 +717,16 @@
return static_cast<Error>(intError);
}
+Error Layer::setBufferSlotsToClear(const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) {
+ if (CC_UNLIKELY(!mDisplay)) {
+ return Error::BAD_DISPLAY;
+ }
+ auto intError = mComposer.setLayerBufferSlotsToClear(mDisplay->getId(), mId, slotsToClear,
+ activeBufferSlot);
+ return static_cast<Error>(intError);
+}
+
Error Layer::setSurfaceDamage(const Region& damage)
{
if (CC_UNLIKELY(!mDisplay)) {
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.h b/services/surfaceflinger/DisplayHardware/HWC2.h
index 4971d19..c1c7070 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.h
+++ b/services/surfaceflinger/DisplayHardware/HWC2.h
@@ -310,6 +310,8 @@
[[nodiscard]] virtual hal::Error setBuffer(uint32_t slot,
const android::sp<android::GraphicBuffer>& buffer,
const android::sp<android::Fence>& acquireFence) = 0;
+ [[nodiscard]] virtual hal::Error setBufferSlotsToClear(
+ const std::vector<uint32_t>& slotsToClear, uint32_t activeBufferSlot) = 0;
[[nodiscard]] virtual hal::Error setSurfaceDamage(const android::Region& damage) = 0;
[[nodiscard]] virtual hal::Error setBlendMode(hal::BlendMode mode) = 0;
@@ -360,6 +362,8 @@
hal::Error setCursorPosition(int32_t x, int32_t y) override;
hal::Error setBuffer(uint32_t slot, const android::sp<android::GraphicBuffer>& buffer,
const android::sp<android::Fence>& acquireFence) override;
+ hal::Error setBufferSlotsToClear(const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) override;
hal::Error setSurfaceDamage(const android::Region& damage) override;
hal::Error setBlendMode(hal::BlendMode mode) override;
diff --git a/services/surfaceflinger/DisplayHardware/HidlComposerHal.cpp b/services/surfaceflinger/DisplayHardware/HidlComposerHal.cpp
index b607df0..c9e1e79 100644
--- a/services/surfaceflinger/DisplayHardware/HidlComposerHal.cpp
+++ b/services/surfaceflinger/DisplayHardware/HidlComposerHal.cpp
@@ -186,9 +186,22 @@
return out;
}
+sp<GraphicBuffer> allocateClearSlotBuffer() {
+ sp<GraphicBuffer> buffer = sp<GraphicBuffer>::make(1, 1, PIXEL_FORMAT_RGBX_8888,
+ GraphicBuffer::USAGE_HW_COMPOSER |
+ GraphicBuffer::USAGE_SW_READ_OFTEN |
+ GraphicBuffer::USAGE_SW_WRITE_OFTEN,
+ "HidlComposer");
+ if (!buffer || buffer->initCheck() != ::android::OK) {
+ return nullptr;
+ }
+ return std::move(buffer);
+}
+
} // anonymous namespace
-HidlComposer::HidlComposer(const std::string& serviceName) : mWriter(kWriterInitialSize) {
+HidlComposer::HidlComposer(const std::string& serviceName)
+ : mClearSlotBuffer(allocateClearSlotBuffer()), mWriter(kWriterInitialSize) {
mComposer = V2_1::IComposer::getService(serviceName);
if (mComposer == nullptr) {
@@ -230,6 +243,11 @@
if (mClient == nullptr) {
LOG_ALWAYS_FATAL("failed to create composer client");
}
+
+ if (!mClearSlotBuffer) {
+ LOG_ALWAYS_FATAL("Failed to allocate a buffer for clearing layer buffer slots");
+ return;
+ }
}
bool HidlComposer::isSupported(OptionalFeature feature) const {
@@ -694,6 +712,32 @@
return Error::NONE;
}
+Error HidlComposer::setLayerBufferSlotsToClear(Display display, Layer layer,
+ const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) {
+ if (slotsToClear.empty()) {
+ return Error::NONE;
+ }
+ // Backwards compatible way of clearing buffer is to set the layer buffer with a placeholder
+ // buffer, using the slot that needs to cleared... tricky.
+ for (uint32_t slot : slotsToClear) {
+ // Don't clear the active buffer slot because we need to restore the active buffer after
+ // setting the requested buffer slots with a placeholder buffer.
+ if (slot != activeBufferSlot) {
+ mWriter.selectDisplay(display);
+ mWriter.selectLayer(layer);
+ mWriter.setLayerBuffer(slot, mClearSlotBuffer->handle, /*fence*/ -1);
+ }
+ }
+ // Since we clear buffers by setting them to a placeholder buffer, we want to make sure that the
+ // last setLayerBuffer command is sent with the currently active buffer, not the placeholder
+ // buffer, so that there is no perceptual change.
+ mWriter.selectDisplay(display);
+ mWriter.selectLayer(layer);
+ mWriter.setLayerBuffer(activeBufferSlot, /*buffer*/ nullptr, /*fence*/ -1);
+ return Error::NONE;
+}
+
Error HidlComposer::setLayerSurfaceDamage(Display display, Layer layer,
const std::vector<IComposerClient::Rect>& damage) {
mWriter.selectDisplay(display);
diff --git a/services/surfaceflinger/DisplayHardware/HidlComposerHal.h b/services/surfaceflinger/DisplayHardware/HidlComposerHal.h
index 3602bbb..921add5 100644
--- a/services/surfaceflinger/DisplayHardware/HidlComposerHal.h
+++ b/services/surfaceflinger/DisplayHardware/HidlComposerHal.h
@@ -248,6 +248,9 @@
/* see setClientTarget for the purpose of slot */
Error setLayerBuffer(Display display, Layer layer, uint32_t slot,
const sp<GraphicBuffer>& buffer, int acquireFence) override;
+ Error setLayerBufferSlotsToClear(Display display, Layer layer,
+ const std::vector<uint32_t>& slotsToClear,
+ uint32_t activeBufferSlot) override;
Error setLayerSurfaceDamage(Display display, Layer layer,
const std::vector<IComposerClient::Rect>& damage) override;
Error setLayerBlendMode(Display display, Layer layer, IComposerClient::BlendMode mode) override;
@@ -362,6 +365,9 @@
sp<V2_3::IComposerClient> mClient_2_3;
sp<IComposerClient> mClient_2_4;
+ // Buffer slots for layers are cleared by setting the slot buffer to this buffer.
+ sp<GraphicBuffer> mClearSlotBuffer;
+
// 64KiB minus a small space for metadata such as read/write pointers
static constexpr size_t kWriterInitialSize = 64 * 1024 / sizeof(uint32_t) - 16;
// Max number of buffers that may be cached for a given layer
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index b7abd95..1f159ae 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -216,6 +216,9 @@
}
Layer::~Layer() {
+ LOG_ALWAYS_FATAL_IF(std::this_thread::get_id() != mFlinger->mMainThreadId,
+ "Layer destructor called off the main thread.");
+
// 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
diff --git a/services/surfaceflinger/Scheduler/RefreshRateSelector.h b/services/surfaceflinger/Scheduler/RefreshRateSelector.h
index 4f5842a..14d08f8 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateSelector.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateSelector.h
@@ -61,7 +61,7 @@
std::chrono::nanoseconds(800us).count();
// The lowest Render Frame Rate that will ever be selected
- static constexpr Fps kMinSupportedFrameRate = 20_Hz;
+ static constexpr Fps kMinSupportedFrameRate = 1_Hz;
class Policy {
static constexpr int kAllowGroupSwitchingDefault = false;
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 34f8df2..856fda0 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -815,18 +815,18 @@
.powerOnImminent = powerOnImminent};
}
-ftl::Optional<FrameRateMode> Scheduler::getPreferredDisplayMode() {
+FrameRateMode Scheduler::getPreferredDisplayMode() {
std::lock_guard<std::mutex> lock(mPolicyLock);
- // Make sure the stored mode is up to date.
- if (mPolicy.modeOpt) {
- const auto ranking =
- leaderSelectorPtr()
- ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
- .ranking;
+ const auto frameRateMode =
+ leaderSelectorPtr()
+ ->getRankedFrameRates(mPolicy.contentRequirements, makeGlobalSignals())
+ .ranking.front()
+ .frameRateMode;
- mPolicy.modeOpt = ranking.front().frameRateMode;
- }
- return mPolicy.modeOpt;
+ // Make sure the stored mode is up to date.
+ mPolicy.modeOpt = frameRateMode;
+
+ return frameRateMode;
}
void Scheduler::onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline) {
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index cf2ffb8..f189426 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -209,8 +209,8 @@
void dump(ConnectionHandle, std::string&) const;
void dumpVsync(std::string&) const;
- // Get the appropriate refresh for current conditions.
- ftl::Optional<FrameRateMode> getPreferredDisplayMode();
+ // Returns the preferred refresh rate and frame rate for the leader display.
+ FrameRateMode getPreferredDisplayMode();
// Notifies the scheduler about a refresh rate timeline change.
void onNewVsyncPeriodChangeTimeline(const hal::VsyncPeriodChangeTimeline& timeline);
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index cdd6044..3dd86aa 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -299,6 +299,7 @@
const String16 sDump("android.permission.DUMP");
const String16 sCaptureBlackoutContent("android.permission.CAPTURE_BLACKOUT_CONTENT");
const String16 sInternalSystemWindow("android.permission.INTERNAL_SYSTEM_WINDOW");
+const String16 sWakeupSurfaceFlinger("android.permission.WAKEUP_SURFACE_FLINGER");
const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled";
@@ -332,20 +333,12 @@
}
}
-bool callingThreadHasRotateSurfaceFlingerAccess() {
+bool callingThreadHasPermission(const String16& permission) {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
- PermissionCache::checkPermission(sRotateSurfaceFlinger, pid, uid);
-}
-
-bool callingThreadHasInternalSystemWindowAccess() {
- IPCThreadState* ipc = IPCThreadState::self();
- const int pid = ipc->getCallingPid();
- const int uid = ipc->getCallingUid();
- return uid == AID_GRAPHICS || uid == AID_SYSTEM ||
- PermissionCache::checkPermission(sInternalSystemWindow, pid, uid);
+ PermissionCache::checkPermission(permission, pid, uid);
}
SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
@@ -426,8 +419,6 @@
bool supportsBlurs = atoi(value);
mSupportsBlur = supportsBlurs;
ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
- property_get("ro.sf.blurs_are_expensive", value, "0");
- mBlursAreExpensive = atoi(value);
const size_t defaultListSize = MAX_LAYERS;
auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
@@ -449,6 +440,9 @@
property_get("debug.sf.treat_170m_as_sRGB", value, "0");
mTreat170mAsSrgb = atoi(value);
+ mIgnoreHwcPhysicalDisplayOrientation =
+ base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, false);
+
// We should be reading 'persist.sys.sf.color_saturation' here
// but since /data may be encrypted, we need to wait until after vold
// comes online to attempt to read the property. The property is
@@ -1141,7 +1135,7 @@
return NO_ERROR;
}
-void SurfaceFlinger::setDesiredActiveMode(display::DisplayModeRequest&& request) {
+void SurfaceFlinger::setDesiredActiveMode(display::DisplayModeRequest&& request, bool force) {
ATRACE_CALL();
auto display = getDisplayDeviceLocked(request.mode.modePtr->getPhysicalDisplayId());
@@ -1153,7 +1147,8 @@
const auto mode = request.mode;
const bool emitEvent = request.emitEvent;
- switch (display->setDesiredActiveMode(DisplayDevice::ActiveModeInfo(std::move(request)))) {
+ switch (display->setDesiredActiveMode(DisplayDevice::ActiveModeInfo(std::move(request)),
+ force)) {
case DisplayDevice::DesiredActiveModeAction::InitiateDisplayModeSwitch:
scheduleComposite(FrameHint::kNone);
@@ -2305,7 +2300,6 @@
layers.push_back(layer);
}
});
- refreshArgs.blursAreExpensive = mBlursAreExpensive;
refreshArgs.internalDisplayRotationFlags = DisplayDevice::getPrimaryDisplayRotationFlags();
if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
@@ -2451,7 +2445,8 @@
if (!id) {
return ui::ROTATION_0;
}
- if (getHwComposer().getComposer()->isSupported(
+ if (!mIgnoreHwcPhysicalDisplayOrientation &&
+ getHwComposer().getComposer()->isSupported(
Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) {
switch (getHwComposer().getPhysicalDisplayOrientation(*id)) {
case Hwc2::AidlTransform::ROT_90:
@@ -3467,10 +3462,21 @@
for (auto& request : modeRequests) {
const auto& modePtr = request.mode.modePtr;
- const auto display = getDisplayDeviceLocked(modePtr->getPhysicalDisplayId());
+
+ const auto displayId = modePtr->getPhysicalDisplayId();
+ const auto display = getDisplayDeviceLocked(displayId);
if (!display) continue;
+ const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
+ .transform(&PhysicalDisplay::isInternal)
+ .value_or(false);
+
+ if (isInternalDisplay && displayId != mActiveDisplayId) {
+ ALOGV("%s(%s): Inactive display", __func__, to_string(displayId).c_str());
+ continue;
+ }
+
if (display->refreshRateSelector().isModeAllowed(request.mode)) {
setDesiredActiveMode(std::move(request));
} else {
@@ -3992,18 +3998,23 @@
// Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER
// permissions.
if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
- callingThreadHasRotateSurfaceFlingerAccess()) {
+ callingThreadHasPermission(sRotateSurfaceFlinger)) {
permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER;
}
- if (callingThreadHasInternalSystemWindowAccess()) {
+ if (callingThreadHasPermission(sInternalSystemWindow)) {
permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW;
}
- if (!(permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) &&
- (flags & (eEarlyWakeupStart | eEarlyWakeupEnd))) {
- ALOGE("Only WindowManager is allowed to use eEarlyWakeup[Start|End] flags");
- flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
+ if (flags & (eEarlyWakeupStart | eEarlyWakeupEnd)) {
+ const bool hasPermission =
+ (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) ||
+ callingThreadHasPermission(sWakeupSurfaceFlinger);
+ if (!hasPermission) {
+ ALOGE("Caller needs permission android.permission.WAKEUP_SURFACE_FLINGER to use "
+ "eEarlyWakeup[Start|End] flags");
+ flags &= ~(eEarlyWakeupStart | eEarlyWakeupEnd);
+ }
}
const int64_t postTime = systemTime();
@@ -6730,7 +6741,7 @@
ftl::Optional<scheduler::FrameRateMode> SurfaceFlinger::getPreferredDisplayMode(
PhysicalDisplayId displayId, DisplayModeId defaultModeId) const {
if (const auto schedulerMode = mScheduler->getPreferredDisplayMode();
- schedulerMode && schedulerMode->modePtr->getPhysicalDisplayId() == displayId) {
+ schedulerMode.modePtr->getPhysicalDisplayId() == displayId) {
return schedulerMode;
}
@@ -6765,12 +6776,24 @@
case SetPolicyResult::Unchanged:
return NO_ERROR;
case SetPolicyResult::Changed:
- return applyRefreshRateSelectorPolicy(displayId, selector);
+ break;
}
+
+ const bool isInternalDisplay = mPhysicalDisplays.get(displayId)
+ .transform(&PhysicalDisplay::isInternal)
+ .value_or(false);
+
+ if (isInternalDisplay && displayId != mActiveDisplayId) {
+ // The policy will be be applied when the display becomes active.
+ ALOGV("%s(%s): Inactive display", __func__, to_string(displayId).c_str());
+ return NO_ERROR;
+ }
+
+ return applyRefreshRateSelectorPolicy(displayId, selector);
}
status_t SurfaceFlinger::applyRefreshRateSelectorPolicy(
- PhysicalDisplayId displayId, const scheduler::RefreshRateSelector& selector) {
+ PhysicalDisplayId displayId, const scheduler::RefreshRateSelector& selector, bool force) {
const scheduler::RefreshRateSelector::Policy currentPolicy = selector.getCurrentPolicy();
ALOGV("Setting desired display mode specs: %s", currentPolicy.toString().c_str());
@@ -6800,7 +6823,7 @@
return INVALID_OPERATION;
}
- setDesiredActiveMode({std::move(preferredMode), .emitEvent = true});
+ setDesiredActiveMode({std::move(preferredMode), .emitEvent = true}, force);
return NO_ERROR;
}
@@ -7104,7 +7127,8 @@
// case, its preferred mode has not been propagated to HWC (via setDesiredActiveMode). In either
// case, the Scheduler's cachedModeChangedParams must be initialized to the newly active mode,
// and the kernel idle timer of the newly active display must be toggled.
- applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay->refreshRateSelector());
+ constexpr bool kForce = true;
+ applyRefreshRateSelectorPolicy(mActiveDisplayId, activeDisplay->refreshRateSelector(), kForce);
}
status_t SurfaceFlinger::addWindowInfosListener(
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index c957b67..23ac19e 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -311,6 +311,11 @@
// on this behavior to increase contrast for some media sources.
bool mTreat170mAsSrgb = false;
+ // Allows to ignore physical orientation provided through hwc API in favour of
+ // 'ro.surface_flinger.primary_display_orientation'.
+ // TODO(b/246793311): Clean up a temporary property
+ bool mIgnoreHwcPhysicalDisplayOrientation = false;
+
protected:
// We're reference counted, never destroy SurfaceFlinger directly
virtual ~SurfaceFlinger();
@@ -649,7 +654,8 @@
// Show render rate with refresh rate overlay
bool mRefreshRateOverlayRenderRate = false;
- void setDesiredActiveMode(display::DisplayModeRequest&&) REQUIRES(mStateLock);
+ void setDesiredActiveMode(display::DisplayModeRequest&&, bool force = false)
+ REQUIRES(mStateLock);
status_t setActiveModeFromBackdoor(const sp<display::DisplayToken>&, DisplayModeId);
// Sets the active mode and a new refresh rate in SF.
@@ -678,7 +684,8 @@
// TODO(b/241285191): Look up RefreshRateSelector on Scheduler to remove redundant parameter.
status_t applyRefreshRateSelectorPolicy(PhysicalDisplayId,
- const scheduler::RefreshRateSelector&)
+ const scheduler::RefreshRateSelector&,
+ bool force = false)
REQUIRES(mStateLock, kMainThreadContext);
void commitTransactions() EXCLUDES(mStateLock) REQUIRES(kMainThreadContext);
@@ -1187,7 +1194,9 @@
display::PhysicalDisplays mPhysicalDisplays GUARDED_BY(mStateLock);
// The inner or outer display for foldables, assuming they have mutually exclusive power states.
- PhysicalDisplayId mActiveDisplayId GUARDED_BY(mStateLock);
+ // Atomic because writes from onActiveDisplayChangedLocked are not always under mStateLock, but
+ // reads from ISchedulerCallback::requestDisplayModes may happen concurrently.
+ std::atomic<PhysicalDisplayId> mActiveDisplayId GUARDED_BY(mStateLock);
struct {
DisplayIdGenerator<GpuVirtualDisplayId> gpu;
@@ -1217,8 +1226,6 @@
// If blurs should be enabled on this device.
bool mSupportsBlur = false;
- // If blurs are considered expensive and should require high GPU frequency.
- bool mBlursAreExpensive = false;
std::atomic<uint32_t> mFrameMissedCount = 0;
std::atomic<uint32_t> mHwcFrameMissedCount = 0;
std::atomic<uint32_t> mGpuFrameMissedCount = 0;
diff --git a/services/surfaceflinger/Tracing/tools/Android.bp b/services/surfaceflinger/Tracing/tools/Android.bp
index e8fe734..b6435a8 100644
--- a/services/surfaceflinger/Tracing/tools/Android.bp
+++ b/services/surfaceflinger/Tracing/tools/Android.bp
@@ -25,8 +25,8 @@
name: "layertracegenerator",
defaults: [
"libsurfaceflinger_mocks_defaults",
+ "librenderengine_deps",
"surfaceflinger_defaults",
- "skia_renderengine_deps",
],
srcs: [
":libsurfaceflinger_sources",
diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp
index bf22521..6d1b3fe 100644
--- a/services/surfaceflinger/tests/unittests/Android.bp
+++ b/services/surfaceflinger/tests/unittests/Android.bp
@@ -140,6 +140,7 @@
defaults: [
"android.hardware.graphics.common-ndk_static",
"android.hardware.graphics.composer3-ndk_static",
+ "librenderengine_deps",
],
static_libs: [
"android.hardware.common-V2-ndk",
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
index a3b3c4c..79d02dd 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateSelectorTest.cpp
@@ -141,6 +141,12 @@
RefreshRateSelectorTest();
~RefreshRateSelectorTest();
+ // Represents the number of refresh rates possible
+ // from 1_Hz to 90_hz, including fractional rates.
+ static constexpr size_t kTotalRefreshRates120 = 120;
+ // Represents the number of refresh rates possible
+ // from 1_Hz to 120_hz, including fractional rates.
+ static constexpr size_t kTotalRefreshRates216 = 216;
static constexpr DisplayModeId kModeId60{0};
static constexpr DisplayModeId kModeId90{1};
static constexpr DisplayModeId kModeId72{2};
@@ -1129,7 +1135,12 @@
return {{90_Hz, kMode90}, {60_Hz, kMode60}, {45_Hz, kMode90}, {30_Hz, kMode30}};
}
}();
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1155,10 +1166,18 @@
case Config::FrameRateOverride::AppOverride:
return {{30_Hz, kMode30}, {60_Hz, kMode60}, {90_Hz, kMode90}};
case Config::FrameRateOverride::Enabled:
- return {{30_Hz, kMode30}, {45_Hz, kMode90}, {60_Hz, kMode60}, {90_Hz, kMode90}};
+ return {{1_Hz, kMode30},
+ {1.011_Hz, kMode90},
+ {1.016_Hz, kMode60},
+ {1.022_Hz, kMode90}};
}
}();
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1250,7 +1269,12 @@
{30_Hz, kMode60}, {22.5_Hz, kMode90}, {20_Hz, kMode60}};
}
}();
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1264,7 +1288,11 @@
selector.getRankedRefreshRatesAsPair({}, {.powerOnImminent = true});
EXPECT_TRUE(signals.powerOnImminent);
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1284,7 +1312,11 @@
selector.getRankedRefreshRatesAsPair(layers, {.powerOnImminent = true});
EXPECT_TRUE(signals.powerOnImminent);
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1309,7 +1341,12 @@
{30_Hz, kMode60}, {22.5_Hz, kMode90}, {20_Hz, kMode60}};
}
}();
- ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates120, refreshRates.size());
+ } else {
+ ASSERT_EQ(expectedRefreshRates.size(), refreshRates.size());
+ }
for (size_t i = 0; i < expectedRefreshRates.size(); ++i) {
EXPECT_EQ(expectedRefreshRates[i], refreshRates[i].frameRateMode)
@@ -1562,7 +1599,11 @@
}();
auto actualRanking = selector.getRankedFrameRates(layers, {}).ranking;
- ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates216, actualRanking.size());
+ } else {
+ ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ }
for (size_t i = 0; i < expectedRanking.size(); ++i) {
EXPECT_EQ(expectedRanking[i], actualRanking[i].frameRateMode)
@@ -1604,7 +1645,11 @@
}();
actualRanking = selector.getRankedFrameRates(layers, {}).ranking;
- ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates216, actualRanking.size());
+ } else {
+ ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ }
for (size_t i = 0; i < expectedRanking.size(); ++i) {
EXPECT_EQ(expectedRanking[i], actualRanking[i].frameRateMode)
@@ -1644,7 +1689,11 @@
}();
actualRanking = selector.getRankedFrameRates(layers, {}).ranking;
- ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates216, actualRanking.size());
+ } else {
+ ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ }
for (size_t i = 0; i < expectedRanking.size(); ++i) {
EXPECT_EQ(expectedRanking[i], actualRanking[i].frameRateMode)
@@ -1687,7 +1736,11 @@
}();
actualRanking = selector.getRankedFrameRates(layers, {}).ranking;
- ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates216, actualRanking.size());
+ } else {
+ ASSERT_EQ(expectedRanking.size(), actualRanking.size());
+ }
for (size_t i = 0; i < expectedRanking.size(); ++i) {
EXPECT_EQ(expectedRanking[i], actualRanking[i].frameRateMode)
@@ -2317,7 +2370,8 @@
}
// b/190578904
-TEST_P(RefreshRateSelectorTest, getBestFrameRateMode_withCloseRefreshRates) {
+TEST_P(RefreshRateSelectorTest,
+ getBestFrameRateMode_withCloseRefreshRates_LayerVoteType_Heuristic) {
if (g_noSlowTests) {
GTEST_SKIP();
}
@@ -2346,8 +2400,101 @@
for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
const auto refreshRate = Fps::fromValue(static_cast<float>(fps));
testRefreshRate(refreshRate, LayerVoteType::Heuristic);
+ }
+}
+TEST_P(RefreshRateSelectorTest,
+ getBestFrameRateMode_withCloseRefreshRates_LayerVoteType_ExplicitDefault) {
+ if (g_noSlowTests) {
+ GTEST_SKIP();
+ }
+
+ const int kMinRefreshRate = RefreshRateSelector::kMinSupportedFrameRate.getIntValue();
+ constexpr int kMaxRefreshRate = 240;
+
+ DisplayModes displayModes;
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const DisplayModeId modeId(fps);
+ displayModes.try_emplace(modeId,
+ createDisplayMode(modeId,
+ Fps::fromValue(static_cast<float>(fps))));
+ }
+
+ const auto selector = createSelector(std::move(displayModes), DisplayModeId(kMinRefreshRate));
+
+ std::vector<LayerRequirement> layers = {{.weight = 1.f}};
+ const auto testRefreshRate = [&](Fps fps, LayerVoteType vote) {
+ layers[0].desiredRefreshRate = fps;
+ layers[0].vote = vote;
+ EXPECT_EQ(fps.getIntValue(), selector.getBestFrameRateMode(layers)->getFps().getIntValue())
+ << "Failed for " << ftl::enum_string(vote);
+ };
+
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const auto refreshRate = Fps::fromValue(static_cast<float>(fps));
testRefreshRate(refreshRate, LayerVoteType::ExplicitDefault);
+ }
+}
+TEST_P(RefreshRateSelectorTest,
+ getBestFrameRateMode_withCloseRefreshRates_LayerVoteType_ExplicitExactOrMultiple) {
+ if (g_noSlowTests) {
+ GTEST_SKIP();
+ }
+
+ const int kMinRefreshRate = RefreshRateSelector::kMinSupportedFrameRate.getIntValue();
+ constexpr int kMaxRefreshRate = 240;
+
+ DisplayModes displayModes;
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const DisplayModeId modeId(fps);
+ displayModes.try_emplace(modeId,
+ createDisplayMode(modeId,
+ Fps::fromValue(static_cast<float>(fps))));
+ }
+
+ const auto selector = createSelector(std::move(displayModes), DisplayModeId(kMinRefreshRate));
+
+ std::vector<LayerRequirement> layers = {{.weight = 1.f}};
+ const auto testRefreshRate = [&](Fps fps, LayerVoteType vote) {
+ layers[0].desiredRefreshRate = fps;
+ layers[0].vote = vote;
+ EXPECT_EQ(fps.getIntValue(), selector.getBestFrameRateMode(layers)->getFps().getIntValue())
+ << "Failed for " << ftl::enum_string(vote);
+ };
+
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const auto refreshRate = Fps::fromValue(static_cast<float>(fps));
testRefreshRate(refreshRate, LayerVoteType::ExplicitExactOrMultiple);
+ }
+}
+TEST_P(RefreshRateSelectorTest,
+ getBestFrameRateMode_withCloseRefreshRates_LayerVoteType_ExplicitExact) {
+ if (g_noSlowTests) {
+ GTEST_SKIP();
+ }
+
+ const int kMinRefreshRate = RefreshRateSelector::kMinSupportedFrameRate.getIntValue();
+ constexpr int kMaxRefreshRate = 240;
+
+ DisplayModes displayModes;
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const DisplayModeId modeId(fps);
+ displayModes.try_emplace(modeId,
+ createDisplayMode(modeId,
+ Fps::fromValue(static_cast<float>(fps))));
+ }
+
+ const auto selector = createSelector(std::move(displayModes), DisplayModeId(kMinRefreshRate));
+
+ std::vector<LayerRequirement> layers = {{.weight = 1.f}};
+ const auto testRefreshRate = [&](Fps fps, LayerVoteType vote) {
+ layers[0].desiredRefreshRate = fps;
+ layers[0].vote = vote;
+ EXPECT_EQ(fps.getIntValue(), selector.getBestFrameRateMode(layers)->getFps().getIntValue())
+ << "Failed for " << ftl::enum_string(vote);
+ };
+
+ for (int fps = kMinRefreshRate; fps < kMaxRefreshRate; fps++) {
+ const auto refreshRate = Fps::fromValue(static_cast<float>(fps));
testRefreshRate(refreshRate, LayerVoteType::ExplicitExact);
}
}
@@ -2807,13 +2954,18 @@
{90_Hz, 90_Hz},
{120_Hz, 120_Hz}};
case Config::FrameRateOverride::Enabled:
- return {{30_Hz, 30_Hz}, {36_Hz, 72_Hz}, {40_Hz, 120_Hz}, {45_Hz, 90_Hz},
- {60_Hz, 60_Hz}, {72_Hz, 72_Hz}, {90_Hz, 90_Hz}, {120_Hz, 120_Hz}};
+ return {{1_Hz, 30_Hz}, {1.008_Hz, 120_Hz}, {1.011_Hz, 90_Hz},
+ {1.014_Hz, 72_Hz}, {1.016_Hz, 60_Hz}, {1.022_Hz, 90_Hz},
+ {1.0256_Hz, 120_Hz}, {1.028_Hz, 72_Hz}};
}
}();
const auto& primaryRefreshRates = selector.getPrimaryFrameRates();
- ASSERT_EQ(expected.size(), primaryRefreshRates.size());
+ if (GetParam() == Config::FrameRateOverride::Enabled) {
+ ASSERT_EQ(kTotalRefreshRates216, primaryRefreshRates.size());
+ } else {
+ ASSERT_EQ(expected.size(), primaryRefreshRates.size());
+ }
for (size_t i = 0; i < expected.size(); i++) {
const auto [expectedRenderRate, expectedRefreshRate] = expected[i];
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
index 074bf8c..ad3bd35 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayModeSwitching.cpp
@@ -14,12 +14,12 @@
* limitations under the License.
*/
-#include "mock/MockDisplayModeSpecs.h"
-#include "mock/MockEventThread.h"
#undef LOG_TAG
#define LOG_TAG "LibSurfaceFlingerUnittests"
#include "DisplayTransactionTestHelpers.h"
+#include "mock/DisplayHardware/MockDisplayMode.h"
+#include "mock/MockDisplayModeSpecs.h"
#include <ftl/fake_guard.h>
#include <scheduler/Fps.h>
@@ -42,8 +42,7 @@
PrimaryDisplayVariant::setupNativeWindowSurfaceCreationCallExpectations(this);
PrimaryDisplayVariant::setupHwcGetActiveConfigCallExpectations(this);
- DisplayModes modes = makeModes(kMode60, kMode90, kMode120, kMode90_4K);
- auto selectorPtr = std::make_shared<scheduler::RefreshRateSelector>(modes, kModeId60);
+ auto selectorPtr = std::make_shared<scheduler::RefreshRateSelector>(kModes, kModeId60);
setupScheduler(selectorPtr);
@@ -51,7 +50,7 @@
mFlinger.configureAndCommit();
mDisplay = PrimaryDisplayVariant::makeFakeExistingDisplayInjector(this)
- .setDisplayModes(std::move(modes), kModeId60, std::move(selectorPtr))
+ .setDisplayModes(kModes, kModeId60, std::move(selectorPtr))
.inject();
// isVsyncPeriodSwitchSupported should return true, otherwise the SF's HWC proxy
@@ -78,6 +77,8 @@
static constexpr ui::Size kResolution4K{3840, 2160};
static inline const DisplayModePtr kMode90_4K =
createDisplayMode(kModeId90_4K, 90_Hz, 3, kResolution4K);
+
+ static inline const DisplayModes kModes = makeModes(kMode60, kMode90, kMode120, kMode90_4K);
};
void DisplayModeSwitchingTest::setupScheduler(
@@ -283,5 +284,114 @@
ASSERT_EQ(mDisplay->getActiveMode().modePtr->getId(), kModeId90_4K);
}
+TEST_F(DisplayModeSwitchingTest, multiDisplay) {
+ ftl::FakeGuard guard(kMainThreadContext);
+
+ constexpr HWDisplayId kInnerDisplayHwcId = PrimaryDisplayVariant::HWC_DISPLAY_ID;
+ constexpr HWDisplayId kOuterDisplayHwcId = kInnerDisplayHwcId + 1;
+
+ constexpr PhysicalDisplayId kOuterDisplayId = PhysicalDisplayId::fromPort(254u);
+
+ constexpr bool kIsPrimary = false;
+ TestableSurfaceFlinger::FakeHwcDisplayInjector(kOuterDisplayId, hal::DisplayType::PHYSICAL,
+ kIsPrimary)
+ .setHwcDisplayId(kOuterDisplayHwcId)
+ .inject(&mFlinger, mComposer);
+
+ const auto outerDisplay = mFakeDisplayInjector.injectInternalDisplay(
+ [&](FakeDisplayDeviceInjector& injector) {
+ injector.setDisplayModes(mock::cloneForDisplay(kOuterDisplayId, kModes),
+ kModeId120);
+ },
+ {.displayId = kOuterDisplayId,
+ .hwcDisplayId = kOuterDisplayHwcId,
+ .isPrimary = kIsPrimary});
+
+ const auto& innerDisplay = mDisplay;
+
+ EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
+ EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+
+ EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId60);
+ EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId120);
+
+ mFlinger.onActiveDisplayChanged(innerDisplay);
+
+ EXPECT_EQ(NO_ERROR,
+ mFlinger.setDesiredDisplayModeSpecs(innerDisplay->getDisplayToken().promote(),
+ mock::createDisplayModeSpecs(kModeId90.value(),
+ false, 0.f, 120.f)));
+
+ EXPECT_EQ(NO_ERROR,
+ mFlinger.setDesiredDisplayModeSpecs(outerDisplay->getDisplayToken().promote(),
+ mock::createDisplayModeSpecs(kModeId60.value(),
+ false, 0.f, 120.f)));
+
+ // Transition on the inner display.
+ ASSERT_TRUE(innerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(innerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
+
+ // No transition on the outer display.
+ EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+
+ const VsyncPeriodChangeTimeline timeline{.refreshRequired = true};
+ EXPECT_CALL(*mComposer,
+ setActiveConfigWithConstraints(kInnerDisplayHwcId,
+ hal::HWConfigId(kModeId90.value()), _, _))
+ .WillOnce(DoAll(SetArgPointee<3>(timeline), Return(Error::NONE)));
+
+ mFlinger.commit();
+
+ // Transition on the inner display.
+ ASSERT_TRUE(innerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(innerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId90);
+
+ // No transition on the outer display.
+ EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+
+ mFlinger.commit();
+
+ // Transition on the inner display.
+ EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId90);
+
+ // No transition on the outer display.
+ EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId120);
+
+ mFlinger.onActiveDisplayChanged(outerDisplay);
+
+ // No transition on the inner display.
+ EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
+
+ // Transition on the outer display.
+ ASSERT_TRUE(outerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(outerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId60);
+
+ EXPECT_CALL(*mComposer,
+ setActiveConfigWithConstraints(kOuterDisplayHwcId,
+ hal::HWConfigId(kModeId60.value()), _, _))
+ .WillOnce(DoAll(SetArgPointee<3>(timeline), Return(Error::NONE)));
+
+ mFlinger.commit();
+
+ // No transition on the inner display.
+ EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
+
+ // Transition on the outer display.
+ ASSERT_TRUE(outerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(outerDisplay->getDesiredActiveMode()->modeOpt->modePtr->getId(), kModeId60);
+
+ mFlinger.commit();
+
+ // No transition on the inner display.
+ EXPECT_FALSE(innerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(innerDisplay->getActiveMode().modePtr->getId(), kModeId90);
+
+ // Transition on the outer display.
+ EXPECT_FALSE(outerDisplay->getDesiredActiveMode());
+ EXPECT_EQ(outerDisplay->getActiveMode().modePtr->getId(), kModeId60);
+}
+
} // namespace
} // namespace android
diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
index 0fb8e2b..6e50059 100644
--- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp
@@ -484,7 +484,8 @@
transitionDisplayCommon<ExternalDisplayPowerCase<TransitionOnToUnknownVariant>>();
}
-TEST_F(SetPowerModeInternalTest, designatesLeaderDisplay) {
+// TODO(b/262417075)
+TEST_F(SetPowerModeInternalTest, DISABLED_designatesLeaderDisplay) {
using Case = SimplePrimaryDisplayCase;
// --------------------------------------------------------------------
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
index 836e3a4..2f16b7b 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
@@ -98,6 +98,8 @@
Error(Display, nsecs_t, uint32_t*, uint32_t*, int*, uint32_t*));
MOCK_METHOD4(setCursorPosition, Error(Display, Layer, int32_t, int32_t));
MOCK_METHOD5(setLayerBuffer, Error(Display, Layer, uint32_t, const sp<GraphicBuffer>&, int));
+ MOCK_METHOD4(setLayerBufferSlotsToClear,
+ Error(Display, Layer, const std::vector<uint32_t>&, uint32_t));
MOCK_METHOD3(setLayerSurfaceDamage,
Error(Display, Layer, const std::vector<IComposerClient::Rect>&));
MOCK_METHOD3(setLayerBlendMode, Error(Display, Layer, IComposerClient::BlendMode));
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplayMode.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplayMode.h
index c78b6bd..3b36361 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplayMode.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockDisplayMode.h
@@ -38,4 +38,24 @@
return createDisplayMode(modeId, refreshRate, {}, {}, displayId);
}
+inline DisplayModePtr cloneForDisplay(PhysicalDisplayId displayId, const DisplayModePtr& modePtr) {
+ return DisplayMode::Builder(modePtr->getHwcId())
+ .setId(modePtr->getId())
+ .setPhysicalDisplayId(displayId)
+ .setVsyncPeriod(modePtr->getVsyncPeriod())
+ .setGroup(modePtr->getGroup())
+ .setResolution(modePtr->getResolution())
+ .build();
+}
+
+inline DisplayModes cloneForDisplay(PhysicalDisplayId displayId, const DisplayModes& modes) {
+ DisplayModes clones;
+
+ for (const auto& [id, modePtr] : modes) {
+ clones.try_emplace(id, cloneForDisplay(displayId, modePtr));
+ }
+
+ return clones;
+}
+
} // namespace android::mock
diff --git a/vulkan/libvulkan/driver.cpp b/vulkan/libvulkan/driver.cpp
index a99355f..273cdd5 100644
--- a/vulkan/libvulkan/driver.cpp
+++ b/vulkan/libvulkan/driver.cpp
@@ -636,6 +636,7 @@
case ProcHook::EXT_swapchain_colorspace:
case ProcHook::KHR_get_surface_capabilities2:
case ProcHook::GOOGLE_surfaceless_query:
+ case ProcHook::EXT_surface_maintenance1:
hook_extensions_.set(ext_bit);
// return now as these extensions do not require HAL support
return;
@@ -657,9 +658,11 @@
case ProcHook::KHR_shared_presentable_image:
case ProcHook::KHR_swapchain:
case ProcHook::EXT_hdr_metadata:
+ case ProcHook::EXT_swapchain_maintenance1:
case ProcHook::ANDROID_external_memory_android_hardware_buffer:
case ProcHook::ANDROID_native_buffer:
case ProcHook::GOOGLE_display_timing:
+ case ProcHook::KHR_external_fence_fd:
case ProcHook::EXTENSION_CORE_1_0:
case ProcHook::EXTENSION_CORE_1_1:
case ProcHook::EXTENSION_CORE_1_2:
@@ -690,16 +693,22 @@
ext_bit = ProcHook::ANDROID_native_buffer;
break;
case ProcHook::KHR_incremental_present:
- case ProcHook::GOOGLE_display_timing:
case ProcHook::KHR_shared_presentable_image:
+ case ProcHook::GOOGLE_display_timing:
hook_extensions_.set(ext_bit);
// return now as these extensions do not require HAL support
return;
+ case ProcHook::EXT_swapchain_maintenance1:
+ // map VK_KHR_swapchain_maintenance1 to KHR_external_fence_fd
+ name = VK_KHR_EXTERNAL_FENCE_FD_EXTENSION_NAME;
+ ext_bit = ProcHook::KHR_external_fence_fd;
+ break;
case ProcHook::EXT_hdr_metadata:
case ProcHook::KHR_bind_memory2:
hook_extensions_.set(ext_bit);
break;
case ProcHook::ANDROID_external_memory_android_hardware_buffer:
+ case ProcHook::KHR_external_fence_fd:
case ProcHook::EXTENSION_UNKNOWN:
// Extensions we don't need to do anything about at this level
break;
@@ -715,6 +724,7 @@
case ProcHook::KHR_surface_protected_capabilities:
case ProcHook::EXT_debug_report:
case ProcHook::EXT_swapchain_colorspace:
+ case ProcHook::EXT_surface_maintenance1:
case ProcHook::GOOGLE_surfaceless_query:
case ProcHook::ANDROID_native_buffer:
case ProcHook::EXTENSION_CORE_1_0:
@@ -747,10 +757,18 @@
if (strcmp(name, props.extensionName) != 0)
continue;
+ if (ext_bit != ProcHook::EXTENSION_UNKNOWN &&
+ hal_extensions_.test(ext_bit)) {
+ ALOGI("CreateInfoWrapper::FilterExtension: already have '%s'.", name);
+ continue;
+ }
+
filter.names[filter.name_count++] = name;
if (ext_bit != ProcHook::EXTENSION_UNKNOWN) {
if (ext_bit == ProcHook::ANDROID_native_buffer)
hook_extensions_.set(ProcHook::KHR_swapchain);
+ if (ext_bit == ProcHook::KHR_external_fence_fd)
+ hook_extensions_.set(ProcHook::EXT_swapchain_maintenance1);
hal_extensions_.set(ext_bit);
}
@@ -940,6 +958,9 @@
VK_KHR_GET_SURFACE_CAPABILITIES_2_SPEC_VERSION});
loader_extensions.push_back({VK_GOOGLE_SURFACELESS_QUERY_EXTENSION_NAME,
VK_GOOGLE_SURFACELESS_QUERY_SPEC_VERSION});
+ loader_extensions.push_back({
+ VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME,
+ VK_EXT_SURFACE_MAINTENANCE_1_SPEC_VERSION});
static const VkExtensionProperties loader_debug_report_extension = {
VK_EXT_DEBUG_REPORT_EXTENSION_NAME, VK_EXT_DEBUG_REPORT_SPEC_VERSION,
@@ -1072,6 +1093,33 @@
return result;
}
+bool CanSupportSwapchainMaintenance1Extension(VkPhysicalDevice physicalDevice) {
+ const auto& driver = GetData(physicalDevice).driver;
+ if (!driver.GetPhysicalDeviceExternalFenceProperties)
+ return false;
+
+ // Requires support for external fences imported from sync fds.
+ // This is _almost_ universal on Android, but may be missing on
+ // some extremely old drivers, or on strange implementations like
+ // cuttlefish.
+ VkPhysicalDeviceExternalFenceInfo fenceInfo = {
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_FENCE_INFO,
+ nullptr,
+ VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT
+ };
+ VkExternalFenceProperties fenceProperties = {
+ VK_STRUCTURE_TYPE_EXTERNAL_FENCE_PROPERTIES,
+ nullptr,
+ 0, 0, 0
+ };
+
+ GetPhysicalDeviceExternalFenceProperties(physicalDevice, &fenceInfo, &fenceProperties);
+ if (fenceProperties.externalFenceFeatures & VK_EXTERNAL_FENCE_FEATURE_IMPORTABLE_BIT)
+ return true;
+
+ return false;
+}
+
VkResult EnumerateDeviceExtensionProperties(
VkPhysicalDevice physicalDevice,
const char* pLayerName,
@@ -1149,6 +1197,12 @@
VK_EXT_IMAGE_COMPRESSION_CONTROL_SWAPCHAIN_SPEC_VERSION});
}
+ if (CanSupportSwapchainMaintenance1Extension(physicalDevice)) {
+ loader_extensions.push_back({
+ VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME,
+ VK_EXT_SWAPCHAIN_MAINTENANCE_1_SPEC_VERSION});
+ }
+
// enumerate our extensions first
if (!pLayerName && pProperties) {
uint32_t count = std::min(
@@ -1266,6 +1320,27 @@
return VK_ERROR_INCOMPATIBLE_DRIVER;
}
+ // TODO(b/259516419) avoid getting stats from hwui
+ // const bool reportStats = (pCreateInfo->pApplicationInfo == nullptr )
+ // || (strcmp("android framework",
+ // pCreateInfo->pApplicationInfo->pEngineName) != 0);
+ const bool reportStats = true;
+ if (reportStats) {
+ // Set stats for Vulkan api version requested with application info
+ if (pCreateInfo->pApplicationInfo) {
+ const uint32_t vulkanApiVersion =
+ pCreateInfo->pApplicationInfo->apiVersion;
+ android::GraphicsEnv::getInstance().setTargetStats(
+ android::GpuStatsInfo::Stats::CREATED_VULKAN_API_VERSION,
+ vulkanApiVersion);
+ }
+
+ // Update stats for the extensions requested
+ android::GraphicsEnv::getInstance().setVulkanInstanceExtensions(
+ pCreateInfo->enabledExtensionCount,
+ pCreateInfo->ppEnabledExtensionNames);
+ }
+
*pInstance = instance;
return VK_SUCCESS;
@@ -1371,6 +1446,65 @@
*pDevice = dev;
+ // TODO(b/259516419) avoid getting stats from hwui
+ const bool reportStats = true;
+ if (reportStats) {
+ android::GraphicsEnv::getInstance().setTargetStats(
+ android::GpuStatsInfo::Stats::CREATED_VULKAN_DEVICE);
+
+ // Set stats for creating a Vulkan device and report features in use
+ const VkPhysicalDeviceFeatures* pEnabledFeatures =
+ pCreateInfo->pEnabledFeatures;
+ if (!pEnabledFeatures) {
+ // Use features from the chained VkPhysicalDeviceFeatures2
+ // structure, if given
+ const VkPhysicalDeviceFeatures2* features2 =
+ reinterpret_cast<const VkPhysicalDeviceFeatures2*>(
+ pCreateInfo->pNext);
+ while (features2 &&
+ features2->sType !=
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2) {
+ features2 = reinterpret_cast<const VkPhysicalDeviceFeatures2*>(
+ features2->pNext);
+ }
+ if (features2) {
+ pEnabledFeatures = &features2->features;
+ }
+ }
+ const VkBool32* pFeatures =
+ reinterpret_cast<const VkBool32*>(pEnabledFeatures);
+ if (pFeatures) {
+ // VkPhysicalDeviceFeatures consists of VkBool32 values, go over all
+ // of them using pointer arithmetic here and save the features in a
+ // 64-bit bitfield
+ static_assert(
+ (sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32)) <= 64,
+ "VkPhysicalDeviceFeatures has too many elements for bitfield "
+ "packing");
+ static_assert(
+ (sizeof(VkPhysicalDeviceFeatures) % sizeof(VkBool32)) == 0,
+ "VkPhysicalDeviceFeatures has invalid size for bitfield "
+ "packing");
+ const int numFeatures =
+ sizeof(VkPhysicalDeviceFeatures) / sizeof(VkBool32);
+
+ uint64_t enableFeatureBits = 0;
+ for (int i = 0; i < numFeatures; i++) {
+ if (pFeatures[i] != VK_FALSE) {
+ enableFeatureBits |= (uint64_t(1) << i);
+ }
+ }
+ android::GraphicsEnv::getInstance().setTargetStats(
+ android::GpuStatsInfo::Stats::VULKAN_DEVICE_FEATURES_ENABLED,
+ enableFeatureBits);
+ }
+
+ // Update stats for the extensions requested
+ android::GraphicsEnv::getInstance().setVulkanDeviceExtensions(
+ pCreateInfo->enabledExtensionCount,
+ pCreateInfo->ppEnabledExtensionNames);
+ }
+
return VK_SUCCESS;
}
@@ -1564,6 +1698,12 @@
imageCompressionControlSwapchainInChain = true;
} break;
+ case VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SWAPCHAIN_MAINTENANCE_1_FEATURES_EXT: {
+ auto smf = reinterpret_cast<VkPhysicalDeviceSwapchainMaintenance1FeaturesEXT *>(
+ pFeats);
+ smf->swapchainMaintenance1 = true;
+ } break;
+
default:
break;
}
diff --git a/vulkan/libvulkan/driver_gen.cpp b/vulkan/libvulkan/driver_gen.cpp
index de98aa7..798af5c 100644
--- a/vulkan/libvulkan/driver_gen.cpp
+++ b/vulkan/libvulkan/driver_gen.cpp
@@ -162,6 +162,15 @@
}
}
+VKAPI_ATTR VkResult checkedReleaseSwapchainImagesEXT(VkDevice device, const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
+ if (GetData(device).hook_extensions[ProcHook::EXT_swapchain_maintenance1]) {
+ return ReleaseSwapchainImagesEXT(device, pReleaseInfo);
+ } else {
+ Logger(device).Err(device, "VK_EXT_swapchain_maintenance1 not enabled. vkReleaseSwapchainImagesEXT not executed.");
+ return VK_SUCCESS;
+ }
+}
+
// clang-format on
const ProcHook g_proc_hooks[] = {
@@ -545,6 +554,13 @@
nullptr,
},
{
+ "vkReleaseSwapchainImagesEXT",
+ ProcHook::DEVICE,
+ ProcHook::EXT_swapchain_maintenance1,
+ reinterpret_cast<PFN_vkVoidFunction>(ReleaseSwapchainImagesEXT),
+ reinterpret_cast<PFN_vkVoidFunction>(checkedReleaseSwapchainImagesEXT),
+ },
+ {
"vkSetHdrMetadataEXT",
ProcHook::DEVICE,
ProcHook::EXT_hdr_metadata,
@@ -580,6 +596,8 @@
if (strcmp(name, "VK_KHR_surface") == 0) return ProcHook::KHR_surface;
if (strcmp(name, "VK_KHR_surface_protected_capabilities") == 0) return ProcHook::KHR_surface_protected_capabilities;
if (strcmp(name, "VK_KHR_swapchain") == 0) return ProcHook::KHR_swapchain;
+ if (strcmp(name, "VK_EXT_swapchain_maintenance1") == 0) return ProcHook::EXT_swapchain_maintenance1;
+ if (strcmp(name, "VK_EXT_surface_maintenance1") == 0) return ProcHook::EXT_surface_maintenance1;
if (strcmp(name, "VK_ANDROID_external_memory_android_hardware_buffer") == 0) return ProcHook::ANDROID_external_memory_android_hardware_buffer;
if (strcmp(name, "VK_KHR_bind_memory2") == 0) return ProcHook::KHR_bind_memory2;
if (strcmp(name, "VK_KHR_get_physical_device_properties2") == 0) return ProcHook::KHR_get_physical_device_properties2;
@@ -587,6 +605,7 @@
if (strcmp(name, "VK_KHR_external_memory_capabilities") == 0) return ProcHook::KHR_external_memory_capabilities;
if (strcmp(name, "VK_KHR_external_semaphore_capabilities") == 0) return ProcHook::KHR_external_semaphore_capabilities;
if (strcmp(name, "VK_KHR_external_fence_capabilities") == 0) return ProcHook::KHR_external_fence_capabilities;
+ if (strcmp(name, "VK_KHR_external_fence_fd") == 0) return ProcHook::KHR_external_fence_fd;
// clang-format on
return ProcHook::EXTENSION_UNKNOWN;
}
@@ -666,6 +685,7 @@
INIT_PROC(true, dev, CreateImage);
INIT_PROC(true, dev, DestroyImage);
INIT_PROC(true, dev, AllocateCommandBuffers);
+ INIT_PROC_EXT(KHR_external_fence_fd, true, dev, ImportFenceFdKHR);
INIT_PROC(false, dev, BindImageMemory2);
INIT_PROC_EXT(KHR_bind_memory2, true, dev, BindImageMemory2KHR);
INIT_PROC(false, dev, GetDeviceQueue2);
diff --git a/vulkan/libvulkan/driver_gen.h b/vulkan/libvulkan/driver_gen.h
index 2f60086..31ba04b 100644
--- a/vulkan/libvulkan/driver_gen.h
+++ b/vulkan/libvulkan/driver_gen.h
@@ -49,6 +49,8 @@
KHR_surface,
KHR_surface_protected_capabilities,
KHR_swapchain,
+ EXT_swapchain_maintenance1,
+ EXT_surface_maintenance1,
ANDROID_external_memory_android_hardware_buffer,
KHR_bind_memory2,
KHR_get_physical_device_properties2,
@@ -56,6 +58,7 @@
KHR_external_memory_capabilities,
KHR_external_semaphore_capabilities,
KHR_external_fence_capabilities,
+ KHR_external_fence_fd,
EXTENSION_CORE_1_0,
EXTENSION_CORE_1_1,
@@ -118,6 +121,7 @@
PFN_vkCreateImage CreateImage;
PFN_vkDestroyImage DestroyImage;
PFN_vkAllocateCommandBuffers AllocateCommandBuffers;
+ PFN_vkImportFenceFdKHR ImportFenceFdKHR;
PFN_vkBindImageMemory2 BindImageMemory2;
PFN_vkBindImageMemory2KHR BindImageMemory2KHR;
PFN_vkGetDeviceQueue2 GetDeviceQueue2;
diff --git a/vulkan/libvulkan/swapchain.cpp b/vulkan/libvulkan/swapchain.cpp
index c7284ce..1bff50d 100644
--- a/vulkan/libvulkan/swapchain.cpp
+++ b/vulkan/libvulkan/swapchain.cpp
@@ -291,6 +291,9 @@
release_fence(-1),
dequeued(false) {}
VkImage image;
+ // If the image is bound to memory, an sp to the underlying gralloc buffer.
+ // Otherwise, nullptr; the image will be bound to memory as part of
+ // AcquireNextImage.
android::sp<ANativeWindowBuffer> buffer;
// The fence is only valid when the buffer is dequeued, and should be
// -1 any other time. When valid, we own the fd, and must ensure it is
@@ -511,6 +514,10 @@
case VK_FORMAT_R8_UNORM:
native_format = android::PIXEL_FORMAT_R_8;
break;
+ // TODO: Do we need to query for VK_EXT_rgba10x6_formats here?
+ case VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16:
+ native_format = android::PIXEL_FORMAT_RGBA_10101010;
+ break;
default:
ALOGV("unsupported swapchain format %d", format);
break;
@@ -652,100 +659,40 @@
VkSurfaceCapabilitiesKHR* capabilities) {
ATRACE_CALL();
- int err;
- int width, height;
- int transform_hint;
- int max_buffer_count;
- if (surface == VK_NULL_HANDLE) {
- const InstanceData& instance_data = GetData(pdev);
- ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
- bool surfaceless_enabled =
- instance_data.hook_extensions.test(surfaceless);
- if (!surfaceless_enabled) {
- // It is an error to pass a surface==VK_NULL_HANDLE unless the
- // VK_GOOGLE_surfaceless_query extension is enabled
- return VK_ERROR_SURFACE_LOST_KHR;
- }
- // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
- // extension for this function is for
- // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
- // four values cannot be known without a surface. Default values will
- // be supplied anyway, but cannot be relied upon.
- width = 0xFFFFFFFF;
- height = 0xFFFFFFFF;
- transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
- capabilities->minImageCount = 0xFFFFFFFF;
- capabilities->maxImageCount = 0xFFFFFFFF;
+ // Implement in terms of GetPhysicalDeviceSurfaceCapabilities2KHR
+
+ VkPhysicalDeviceSurfaceInfo2KHR info2 = {
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SURFACE_INFO_2_KHR,
+ nullptr,
+ surface
+ };
+
+ VkSurfaceCapabilities2KHR caps2 = {
+ VK_STRUCTURE_TYPE_SURFACE_CAPABILITIES_2_KHR,
+ nullptr,
+ {},
+ };
+
+ VkResult result = GetPhysicalDeviceSurfaceCapabilities2KHR(pdev, &info2, &caps2);
+ *capabilities = caps2.surfaceCapabilities;
+ return result;
+}
+
+// Does the call-twice and VK_INCOMPLETE handling for querying lists
+// of things, where we already have the full set built in a vector.
+template <typename T>
+VkResult CopyWithIncomplete(std::vector<T> const& things,
+ T* callerPtr, uint32_t* callerCount) {
+ VkResult result = VK_SUCCESS;
+ if (callerPtr) {
+ if (things.size() > *callerCount)
+ result = VK_INCOMPLETE;
+ *callerCount = std::min(uint32_t(things.size()), *callerCount);
+ std::copy(things.begin(), things.begin() + *callerCount, callerPtr);
} else {
- ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
-
- err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
- if (err != android::OK) {
- ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
- strerror(-err), err);
- return VK_ERROR_SURFACE_LOST_KHR;
- }
- err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
- if (err != android::OK) {
- ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
- strerror(-err), err);
- return VK_ERROR_SURFACE_LOST_KHR;
- }
-
- err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
- &transform_hint);
- if (err != android::OK) {
- ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
- strerror(-err), err);
- return VK_ERROR_SURFACE_LOST_KHR;
- }
-
- err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
- &max_buffer_count);
- if (err != android::OK) {
- ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
- strerror(-err), err);
- return VK_ERROR_SURFACE_LOST_KHR;
- }
- capabilities->minImageCount = std::min(max_buffer_count, 3);
- capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
+ *callerCount = things.size();
}
-
- capabilities->currentExtent =
- VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
-
- // TODO(http://b/134182502): Figure out what the max extent should be.
- capabilities->minImageExtent = VkExtent2D{1, 1};
- capabilities->maxImageExtent = VkExtent2D{4096, 4096};
-
- if (capabilities->maxImageExtent.height <
- capabilities->currentExtent.height) {
- capabilities->maxImageExtent.height =
- capabilities->currentExtent.height;
- }
-
- if (capabilities->maxImageExtent.width <
- capabilities->currentExtent.width) {
- capabilities->maxImageExtent.width = capabilities->currentExtent.width;
- }
-
- capabilities->maxImageArrayLayers = 1;
-
- capabilities->supportedTransforms = kSupportedTransforms;
- capabilities->currentTransform =
- TranslateNativeToVulkanTransform(transform_hint);
-
- // On Android, window composition is a WindowManager property, not something
- // associated with the bufferqueue. It can't be changed from here.
- capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
-
- capabilities->supportedUsageFlags =
- VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
- VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
- VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
- VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
-
- return VK_SUCCESS;
+ return result;
}
VKAPI_ATTR
@@ -858,25 +805,27 @@
}
}
+ // TODO query VK_EXT_rgba10x6_formats support
+ desc.format = AHARDWAREBUFFER_FORMAT_R10G10B10A10_UNORM;
+ if (AHardwareBuffer_isSupported(&desc)) {
+ all_formats.emplace_back(
+ VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
+ VK_COLOR_SPACE_SRGB_NONLINEAR_KHR});
+ if (colorspace_ext) {
+ all_formats.emplace_back(
+ VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
+ VK_COLOR_SPACE_PASS_THROUGH_EXT});
+ all_formats.emplace_back(
+ VkSurfaceFormatKHR{VK_FORMAT_R10X6G10X6B10X6A10X6_UNORM_4PACK16,
+ VK_COLOR_SPACE_DISPLAY_P3_NONLINEAR_EXT});
+ }
+ }
+
// NOTE: Any new formats that are added must be coordinated across different
// Android users. This includes the ANGLE team (a layered implementation of
// OpenGL-ES).
- VkResult result = VK_SUCCESS;
- if (formats) {
- uint32_t transfer_count = all_formats.size();
- if (transfer_count > *count) {
- transfer_count = *count;
- result = VK_INCOMPLETE;
- }
- std::copy(all_formats.begin(), all_formats.begin() + transfer_count,
- formats);
- *count = transfer_count;
- } else {
- *count = all_formats.size();
- }
-
- return result;
+ return CopyWithIncomplete(all_formats, formats, count);
}
VKAPI_ATTR
@@ -886,19 +835,134 @@
VkSurfaceCapabilities2KHR* pSurfaceCapabilities) {
ATRACE_CALL();
- VkResult result = GetPhysicalDeviceSurfaceCapabilitiesKHR(
- physicalDevice, pSurfaceInfo->surface,
- &pSurfaceCapabilities->surfaceCapabilities);
+ auto surface = pSurfaceInfo->surface;
+ auto capabilities = &pSurfaceCapabilities->surfaceCapabilities;
- VkSurfaceCapabilities2KHR* caps = pSurfaceCapabilities;
- while (caps->pNext) {
- caps = reinterpret_cast<VkSurfaceCapabilities2KHR*>(caps->pNext);
+ VkSurfacePresentModeEXT const *pPresentMode = nullptr;
+ for (auto pNext = reinterpret_cast<VkBaseInStructure const *>(pSurfaceInfo->pNext);
+ pNext; pNext = reinterpret_cast<VkBaseInStructure const *>(pNext->pNext)) {
+ switch (pNext->sType) {
+ case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_EXT:
+ pPresentMode = reinterpret_cast<VkSurfacePresentModeEXT const *>(pNext);
+ break;
- switch (caps->sType) {
+ default:
+ break;
+ }
+ }
+
+ int err;
+ int width, height;
+ int transform_hint;
+ int max_buffer_count;
+ if (surface == VK_NULL_HANDLE) {
+ const InstanceData& instance_data = GetData(physicalDevice);
+ ProcHook::Extension surfaceless = ProcHook::GOOGLE_surfaceless_query;
+ bool surfaceless_enabled =
+ instance_data.hook_extensions.test(surfaceless);
+ if (!surfaceless_enabled) {
+ // It is an error to pass a surface==VK_NULL_HANDLE unless the
+ // VK_GOOGLE_surfaceless_query extension is enabled
+ return VK_ERROR_SURFACE_LOST_KHR;
+ }
+ // Support for VK_GOOGLE_surfaceless_query. The primary purpose of this
+ // extension for this function is for
+ // VkSurfaceProtectedCapabilitiesKHR::supportsProtected. The following
+ // four values cannot be known without a surface. Default values will
+ // be supplied anyway, but cannot be relied upon.
+ width = 0xFFFFFFFF;
+ height = 0xFFFFFFFF;
+ transform_hint = VK_SURFACE_TRANSFORM_INHERIT_BIT_KHR;
+ capabilities->minImageCount = 0xFFFFFFFF;
+ capabilities->maxImageCount = 0xFFFFFFFF;
+ } else {
+ ANativeWindow* window = SurfaceFromHandle(surface)->window.get();
+
+ err = window->query(window, NATIVE_WINDOW_DEFAULT_WIDTH, &width);
+ if (err != android::OK) {
+ ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
+ strerror(-err), err);
+ return VK_ERROR_SURFACE_LOST_KHR;
+ }
+ err = window->query(window, NATIVE_WINDOW_DEFAULT_HEIGHT, &height);
+ if (err != android::OK) {
+ ALOGE("NATIVE_WINDOW_DEFAULT_WIDTH query failed: %s (%d)",
+ strerror(-err), err);
+ return VK_ERROR_SURFACE_LOST_KHR;
+ }
+
+ err = window->query(window, NATIVE_WINDOW_TRANSFORM_HINT,
+ &transform_hint);
+ if (err != android::OK) {
+ ALOGE("NATIVE_WINDOW_TRANSFORM_HINT query failed: %s (%d)",
+ strerror(-err), err);
+ return VK_ERROR_SURFACE_LOST_KHR;
+ }
+
+ err = window->query(window, NATIVE_WINDOW_MAX_BUFFER_COUNT,
+ &max_buffer_count);
+ if (err != android::OK) {
+ ALOGE("NATIVE_WINDOW_MAX_BUFFER_COUNT query failed: %s (%d)",
+ strerror(-err), err);
+ return VK_ERROR_SURFACE_LOST_KHR;
+ }
+
+ if (pPresentMode && IsSharedPresentMode(pPresentMode->presentMode)) {
+ capabilities->minImageCount = 1;
+ capabilities->maxImageCount = 1;
+ } else if (pPresentMode && pPresentMode->presentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
+ // TODO: use undequeued buffer requirement for more precise bound
+ capabilities->minImageCount = std::min(max_buffer_count, 4);
+ capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
+ } else {
+ // TODO: if we're able to, provide better bounds on the number of buffers
+ // for other modes as well.
+ capabilities->minImageCount = std::min(max_buffer_count, 3);
+ capabilities->maxImageCount = static_cast<uint32_t>(max_buffer_count);
+ }
+ }
+
+ capabilities->currentExtent =
+ VkExtent2D{static_cast<uint32_t>(width), static_cast<uint32_t>(height)};
+
+ // TODO(http://b/134182502): Figure out what the max extent should be.
+ capabilities->minImageExtent = VkExtent2D{1, 1};
+ capabilities->maxImageExtent = VkExtent2D{4096, 4096};
+
+ if (capabilities->maxImageExtent.height <
+ capabilities->currentExtent.height) {
+ capabilities->maxImageExtent.height =
+ capabilities->currentExtent.height;
+ }
+
+ if (capabilities->maxImageExtent.width <
+ capabilities->currentExtent.width) {
+ capabilities->maxImageExtent.width = capabilities->currentExtent.width;
+ }
+
+ capabilities->maxImageArrayLayers = 1;
+
+ capabilities->supportedTransforms = kSupportedTransforms;
+ capabilities->currentTransform =
+ TranslateNativeToVulkanTransform(transform_hint);
+
+ // On Android, window composition is a WindowManager property, not something
+ // associated with the bufferqueue. It can't be changed from here.
+ capabilities->supportedCompositeAlpha = VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
+
+ capabilities->supportedUsageFlags =
+ VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT |
+ VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT |
+ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT |
+ VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT;
+
+ for (auto pNext = reinterpret_cast<VkBaseOutStructure*>(pSurfaceCapabilities->pNext);
+ pNext; pNext = reinterpret_cast<VkBaseOutStructure*>(pNext->pNext)) {
+
+ switch (pNext->sType) {
case VK_STRUCTURE_TYPE_SHARED_PRESENT_SURFACE_CAPABILITIES_KHR: {
VkSharedPresentSurfaceCapabilitiesKHR* shared_caps =
- reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(
- caps);
+ reinterpret_cast<VkSharedPresentSurfaceCapabilitiesKHR*>(pNext);
// Claim same set of usage flags are supported for
// shared present modes as for other modes.
shared_caps->sharedPresentSupportedUsageFlags =
@@ -908,17 +972,64 @@
case VK_STRUCTURE_TYPE_SURFACE_PROTECTED_CAPABILITIES_KHR: {
VkSurfaceProtectedCapabilitiesKHR* protected_caps =
- reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(caps);
+ reinterpret_cast<VkSurfaceProtectedCapabilitiesKHR*>(pNext);
protected_caps->supportsProtected = VK_TRUE;
} break;
+ case VK_STRUCTURE_TYPE_SURFACE_PRESENT_SCALING_CAPABILITIES_EXT: {
+ VkSurfacePresentScalingCapabilitiesEXT* scaling_caps =
+ reinterpret_cast<VkSurfacePresentScalingCapabilitiesEXT*>(pNext);
+ // By default, Android stretches the buffer to fit the window,
+ // without preserving aspect ratio. Other modes are technically possible
+ // but consult with CoGS team before exposing them here!
+ scaling_caps->supportedPresentScaling = VK_PRESENT_SCALING_STRETCH_BIT_EXT;
+
+ // Since we always scale, we don't support any gravity.
+ scaling_caps->supportedPresentGravityX = 0;
+ scaling_caps->supportedPresentGravityY = 0;
+
+ // Scaled image limits are just the basic image limits
+ scaling_caps->minScaledImageExtent = capabilities->minImageExtent;
+ scaling_caps->maxScaledImageExtent = capabilities->maxImageExtent;
+ } break;
+
+ case VK_STRUCTURE_TYPE_SURFACE_PRESENT_MODE_COMPATIBILITY_EXT: {
+ VkSurfacePresentModeCompatibilityEXT* mode_caps =
+ reinterpret_cast<VkSurfacePresentModeCompatibilityEXT*>(pNext);
+
+ ALOG_ASSERT(pPresentMode,
+ "querying VkSurfacePresentModeCompatibilityEXT "
+ "requires VkSurfacePresentModeEXT to be provided");
+ std::vector<VkPresentModeKHR> compatibleModes;
+ compatibleModes.push_back(pPresentMode->presentMode);
+
+ switch (pPresentMode->presentMode) {
+ // Shared modes are both compatible with each other.
+ case VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR:
+ compatibleModes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
+ break;
+ case VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR:
+ compatibleModes.push_back(VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR);
+ break;
+ default:
+ // Other modes are only compatible with themselves.
+ // TODO: consider whether switching between FIFO and MAILBOX is reasonable
+ break;
+ }
+
+ // Note: this does not generate VK_INCOMPLETE since we're nested inside
+ // a larger query and there would be no way to determine exactly where it came from.
+ CopyWithIncomplete(compatibleModes, mode_caps->pPresentModes,
+ &mode_caps->presentModeCount);
+ } break;
+
default:
// Ignore all other extension structs
break;
}
}
- return result;
+ return VK_SUCCESS;
}
VKAPI_ATTR
@@ -1077,18 +1188,7 @@
present_modes.push_back(VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
}
- uint32_t num_modes = uint32_t(present_modes.size());
-
- VkResult result = VK_SUCCESS;
- if (modes) {
- if (*count < num_modes)
- result = VK_INCOMPLETE;
- *count = std::min(*count, num_modes);
- std::copy_n(present_modes.data(), *count, modes);
- } else {
- *count = num_modes;
- }
- return result;
+ return CopyWithIncomplete(present_modes, modes, count);
}
VKAPI_ATTR
@@ -1374,8 +1474,7 @@
}
VkSwapchainImageUsageFlagsANDROID swapchain_image_usage = 0;
- if (create_info->presentMode == VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR ||
- create_info->presentMode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR) {
+ if (IsSharedPresentMode(create_info->presentMode)) {
swapchain_image_usage |= VK_SWAPCHAIN_IMAGE_USAGE_SHARED_BIT_ANDROID;
err = native_window_set_shared_buffer_mode(window, true);
if (err != android::OK) {
@@ -1525,8 +1624,6 @@
Swapchain* swapchain = new (mem)
Swapchain(surface, num_images, create_info->presentMode,
TranslateVulkanToNativeTransform(create_info->preTransform));
- // -- Dequeue all buffers and create a VkImage for each --
- // Any failures during or after this must cancel the dequeued buffers.
VkSwapchainImageCreateInfoANDROID swapchain_image_create = {
#pragma clang diagnostic push
@@ -1543,13 +1640,18 @@
#pragma clang diagnostic pop
.pNext = &swapchain_image_create,
};
+
VkImageCreateInfo image_create = {
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
- .pNext = &image_native_buffer,
+ .pNext = nullptr,
.flags = createProtectedSwapchain ? VK_IMAGE_CREATE_PROTECTED_BIT : 0u,
.imageType = VK_IMAGE_TYPE_2D,
.format = create_info->imageFormat,
- .extent = {0, 0, 1},
+ .extent = {
+ create_info->imageExtent.width,
+ create_info->imageExtent.height,
+ 1
+ },
.mipLevels = 1,
.arrayLayers = 1,
.samples = VK_SAMPLE_COUNT_1_BIT,
@@ -1560,60 +1662,87 @@
.pQueueFamilyIndices = create_info->pQueueFamilyIndices,
};
- for (uint32_t i = 0; i < num_images; i++) {
- Swapchain::Image& img = swapchain->images[i];
+ // Note: don't do deferred allocation for shared present modes. There's only one buffer
+ // involved so very little benefit.
+ if ((create_info->flags & VK_SWAPCHAIN_CREATE_DEFERRED_MEMORY_ALLOCATION_BIT_EXT) &&
+ !IsSharedPresentMode(create_info->presentMode)) {
+ // Don't want to touch the underlying gralloc buffers yet;
+ // instead just create unbound VkImages which will later be bound to memory inside
+ // AcquireNextImage.
+ VkImageSwapchainCreateInfoKHR image_swapchain_create = {
+ .sType = VK_STRUCTURE_TYPE_IMAGE_SWAPCHAIN_CREATE_INFO_KHR,
+ .pNext = nullptr,
+ .swapchain = HandleFromSwapchain(swapchain),
+ };
+ image_create.pNext = &image_swapchain_create;
- ANativeWindowBuffer* buffer;
- err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
- if (err != android::OK) {
- ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
- switch (-err) {
- case ENOMEM:
- result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
- break;
- default:
- result = VK_ERROR_SURFACE_LOST_KHR;
- break;
+ for (uint32_t i = 0; i < num_images; i++) {
+ Swapchain::Image& img = swapchain->images[i];
+ img.buffer = nullptr;
+ img.dequeued = false;
+
+ result = dispatch.CreateImage(device, &image_create, nullptr, &img.image);
+ if (result != VK_SUCCESS) {
+ ALOGD("vkCreateImage w/ for deferred swapchain image failed: %u", result);
+ break;
}
- break;
}
- img.buffer = buffer;
- img.dequeued = true;
+ } else {
+ // -- Dequeue all buffers and create a VkImage for each --
+ // Any failures during or after this must cancel the dequeued buffers.
- image_create.extent =
- VkExtent3D{static_cast<uint32_t>(img.buffer->width),
- static_cast<uint32_t>(img.buffer->height),
- 1};
- image_native_buffer.handle = img.buffer->handle;
- image_native_buffer.stride = img.buffer->stride;
- image_native_buffer.format = img.buffer->format;
- image_native_buffer.usage = int(img.buffer->usage);
- android_convertGralloc0To1Usage(int(img.buffer->usage),
- &image_native_buffer.usage2.producer,
- &image_native_buffer.usage2.consumer);
- image_native_buffer.usage3 = img.buffer->usage;
+ for (uint32_t i = 0; i < num_images; i++) {
+ Swapchain::Image& img = swapchain->images[i];
- ATRACE_BEGIN("CreateImage");
- result =
- dispatch.CreateImage(device, &image_create, nullptr, &img.image);
- ATRACE_END();
- if (result != VK_SUCCESS) {
- ALOGD("vkCreateImage w/ native buffer failed: %u", result);
- break;
+ ANativeWindowBuffer* buffer;
+ err = window->dequeueBuffer(window, &buffer, &img.dequeue_fence);
+ if (err != android::OK) {
+ ALOGE("dequeueBuffer[%u] failed: %s (%d)", i, strerror(-err), err);
+ switch (-err) {
+ case ENOMEM:
+ result = VK_ERROR_OUT_OF_DEVICE_MEMORY;
+ break;
+ default:
+ result = VK_ERROR_SURFACE_LOST_KHR;
+ break;
+ }
+ break;
+ }
+ img.buffer = buffer;
+ img.dequeued = true;
+
+ image_native_buffer.handle = img.buffer->handle;
+ image_native_buffer.stride = img.buffer->stride;
+ image_native_buffer.format = img.buffer->format;
+ image_native_buffer.usage = int(img.buffer->usage);
+ android_convertGralloc0To1Usage(int(img.buffer->usage),
+ &image_native_buffer.usage2.producer,
+ &image_native_buffer.usage2.consumer);
+ image_native_buffer.usage3 = img.buffer->usage;
+ image_create.pNext = &image_native_buffer;
+
+ ATRACE_BEGIN("CreateImage");
+ result =
+ dispatch.CreateImage(device, &image_create, nullptr, &img.image);
+ ATRACE_END();
+ if (result != VK_SUCCESS) {
+ ALOGD("vkCreateImage w/ native buffer failed: %u", result);
+ break;
+ }
}
- }
- // -- Cancel all buffers, returning them to the queue --
- // If an error occurred before, also destroy the VkImage and release the
- // buffer reference. Otherwise, we retain a strong reference to the buffer.
- for (uint32_t i = 0; i < num_images; i++) {
- Swapchain::Image& img = swapchain->images[i];
- if (img.dequeued) {
- if (!swapchain->shared) {
- window->cancelBuffer(window, img.buffer.get(),
- img.dequeue_fence);
- img.dequeue_fence = -1;
- img.dequeued = false;
+ // -- Cancel all buffers, returning them to the queue --
+ // If an error occurred before, also destroy the VkImage and release the
+ // buffer reference. Otherwise, we retain a strong reference to the buffer.
+ for (uint32_t i = 0; i < num_images; i++) {
+ Swapchain::Image& img = swapchain->images[i];
+ if (img.dequeued) {
+ if (!swapchain->shared) {
+ window->cancelBuffer(window, img.buffer.get(),
+ img.dequeue_fence);
+ img.dequeue_fence = -1;
+ img.dequeued = false;
+ }
}
}
}
@@ -1630,6 +1759,10 @@
android::GpuStatsInfo::Stats::FALSE_PREROTATION);
}
+ // Set stats for creating a Vulkan swapchain
+ android::GraphicsEnv::getInstance().setTargetStats(
+ android::GpuStatsInfo::Stats::CREATED_VULKAN_SWAPCHAIN);
+
surface.swapchain_handle = HandleFromSwapchain(swapchain);
*swapchain_handle = surface.swapchain_handle;
return VK_SUCCESS;
@@ -1732,6 +1865,64 @@
break;
}
}
+
+ // If this is a deferred alloc swapchain, this may be the first time we've
+ // seen a particular buffer. If so, there should be an empty slot. Find it,
+ // and bind the gralloc buffer to the VkImage for that slot. If there is no
+ // empty slot, then we dequeued an unexpected buffer. Non-deferred swapchains
+ // will also take this path, but will never have an empty slot since we
+ // populated them all upfront.
+ if (idx == swapchain.num_images) {
+ for (idx = 0; idx < swapchain.num_images; idx++) {
+ if (!swapchain.images[idx].buffer) {
+ // Note: this structure is technically required for
+ // Vulkan correctness, even though the driver is probably going
+ // to use everything from the VkNativeBufferANDROID below.
+ // This is kindof silly, but it's how we did the ANB
+ // side of VK_KHR_swapchain v69, so we're stuck with it unless
+ // we want to go tinkering with the ANB spec some more.
+ VkBindImageMemorySwapchainInfoKHR bimsi = {
+ .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_SWAPCHAIN_INFO_KHR,
+ .pNext = nullptr,
+ .swapchain = swapchain_handle,
+ .imageIndex = idx,
+ };
+ VkNativeBufferANDROID nb = {
+ .sType = VK_STRUCTURE_TYPE_NATIVE_BUFFER_ANDROID,
+ .pNext = &bimsi,
+ .handle = buffer->handle,
+ .stride = buffer->stride,
+ .format = buffer->format,
+ .usage = int(buffer->usage),
+ };
+ VkBindImageMemoryInfo bimi = {
+ .sType = VK_STRUCTURE_TYPE_BIND_IMAGE_MEMORY_INFO,
+ .pNext = &nb,
+ .image = swapchain.images[idx].image,
+ .memory = VK_NULL_HANDLE,
+ .memoryOffset = 0,
+ };
+ result = GetData(device).driver.BindImageMemory2(device, 1, &bimi);
+ if (result != VK_SUCCESS) {
+ // This shouldn't really happen. If it does, something is probably
+ // unrecoverably wrong with the swapchain and its images. Cancel
+ // the buffer and declare the swapchain broken.
+ ALOGE("failed to do deferred gralloc buffer bind");
+ window->cancelBuffer(window, buffer, fence_fd);
+ return VK_ERROR_OUT_OF_DATE_KHR;
+ }
+
+ swapchain.images[idx].dequeued = true;
+ swapchain.images[idx].dequeue_fence = fence_fd;
+ swapchain.images[idx].buffer = buffer;
+ break;
+ }
+ }
+ }
+
+ // The buffer doesn't match any slot. This shouldn't normally happen, but is
+ // possible if the bufferqueue is reconfigured behind libvulkan's back. If this
+ // happens, just declare the swapchain to be broken and the app will recreate it.
if (idx == swapchain.num_images) {
ALOGE("dequeueBuffer returned unrecognized buffer");
window->cancelBuffer(window, buffer, fence_fd);
@@ -1857,12 +2048,32 @@
}
}
+// EXT_swapchain_maintenance1 present mode change
+static bool SetSwapchainPresentMode(ANativeWindow *window, VkPresentModeKHR mode) {
+ // There is no dynamic switching between non-shared present modes.
+ // All we support is switching between demand and continuous refresh.
+ if (!IsSharedPresentMode(mode))
+ return true;
+
+ int err = native_window_set_auto_refresh(window,
+ mode == VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR);
+ if (err != android::OK) {
+ ALOGE("native_window_set_auto_refresh() failed: %s (%d)",
+ strerror(-err), err);
+ return false;
+ }
+
+ return true;
+}
+
static VkResult PresentOneSwapchain(
VkQueue queue,
Swapchain& swapchain,
uint32_t imageIndex,
const VkPresentRegionKHR *pRegion,
const VkPresentTimeGOOGLE *pTime,
+ VkFence presentFence,
+ const VkPresentModeKHR *pPresentMode,
uint32_t waitSemaphoreCount,
const VkSemaphore *pWaitSemaphores) {
@@ -1893,12 +2104,33 @@
ANativeWindow* window = swapchain.surface.window.get();
if (swapchain_result == VK_SUCCESS) {
+ if (presentFence != VK_NULL_HANDLE) {
+ int fence_copy = fence < 0 ? -1 : dup(fence);
+ VkImportFenceFdInfoKHR iffi = {
+ VK_STRUCTURE_TYPE_IMPORT_FENCE_FD_INFO_KHR,
+ nullptr,
+ presentFence,
+ VK_FENCE_IMPORT_TEMPORARY_BIT,
+ VK_EXTERNAL_FENCE_HANDLE_TYPE_SYNC_FD_BIT,
+ fence_copy,
+ };
+ if (VK_SUCCESS != dispatch.ImportFenceFdKHR(device, &iffi) && fence_copy >= 0) {
+ // ImportFenceFdKHR takes ownership only if it succeeds
+ close(fence_copy);
+ }
+ }
+
if (pRegion) {
SetSwapchainSurfaceDamage(window, pRegion);
}
if (pTime) {
SetSwapchainFrameTimestamp(swapchain, pTime);
}
+ if (pPresentMode) {
+ if (!SetSwapchainPresentMode(window, *pPresentMode))
+ swapchain_result = WorstPresentResult(swapchain_result,
+ VK_ERROR_SURFACE_LOST_KHR);
+ }
err = window->queueBuffer(window, img.buffer.get(), fence);
// queueBuffer always closes fence, even on error
@@ -1979,6 +2211,9 @@
// Look at the pNext chain for supported extension structs:
const VkPresentRegionsKHR* present_regions = nullptr;
const VkPresentTimesInfoGOOGLE* present_times = nullptr;
+ const VkSwapchainPresentFenceInfoEXT* present_fences = nullptr;
+ const VkSwapchainPresentModeInfoEXT* present_modes = nullptr;
+
const VkPresentRegionsKHR* next =
reinterpret_cast<const VkPresentRegionsKHR*>(present_info->pNext);
while (next) {
@@ -1990,6 +2225,14 @@
present_times =
reinterpret_cast<const VkPresentTimesInfoGOOGLE*>(next);
break;
+ case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_FENCE_INFO_EXT:
+ present_fences =
+ reinterpret_cast<const VkSwapchainPresentFenceInfoEXT*>(next);
+ break;
+ case VK_STRUCTURE_TYPE_SWAPCHAIN_PRESENT_MODE_INFO_EXT:
+ present_modes =
+ reinterpret_cast<const VkSwapchainPresentModeInfoEXT*>(next);
+ break;
default:
ALOGV("QueuePresentKHR ignoring unrecognized pNext->sType = %x",
next->sType);
@@ -2005,6 +2248,15 @@
present_times->swapchainCount != present_info->swapchainCount,
"VkPresentTimesInfoGOOGLE::swapchainCount != "
"VkPresentInfo::swapchainCount");
+ ALOGV_IF(present_fences &&
+ present_fences->swapchainCount != present_info->swapchainCount,
+ "VkSwapchainPresentFenceInfoEXT::swapchainCount != "
+ "VkPresentInfo::swapchainCount");
+ ALOGV_IF(present_modes &&
+ present_modes->swapchainCount != present_info->swapchainCount,
+ "VkSwapchainPresentModeInfoEXT::swapchainCount != "
+ "VkPresentInfo::swapchainCount");
+
const VkPresentRegionKHR* regions =
(present_regions) ? present_regions->pRegions : nullptr;
const VkPresentTimeGOOGLE* times =
@@ -2020,6 +2272,8 @@
present_info->pImageIndices[sc],
(regions && !swapchain.mailbox_mode) ? ®ions[sc] : nullptr,
times ? ×[sc] : nullptr,
+ present_fences ? present_fences->pFences[sc] : VK_NULL_HANDLE,
+ present_modes ? &present_modes->pPresentModes[sc] : nullptr,
present_info->waitSemaphoreCount,
present_info->pWaitSemaphores);
@@ -2244,5 +2498,35 @@
out_bind_infos.empty() ? pBindInfos : out_bind_infos.data());
}
+VKAPI_ATTR
+VkResult ReleaseSwapchainImagesEXT(VkDevice /*device*/,
+ const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo) {
+ ATRACE_CALL();
+
+ Swapchain& swapchain = *SwapchainFromHandle(pReleaseInfo->swapchain);
+ ANativeWindow* window = swapchain.surface.window.get();
+
+ // If in shared present mode, don't actually release the image back to the BQ.
+ // Both sides share it forever.
+ if (swapchain.shared)
+ return VK_SUCCESS;
+
+ for (uint32_t i = 0; i < pReleaseInfo->imageIndexCount; i++) {
+ Swapchain::Image& img = swapchain.images[pReleaseInfo->pImageIndices[i]];
+ window->cancelBuffer(window, img.buffer.get(), img.dequeue_fence);
+
+ // cancelBuffer has taken ownership of the dequeue fence
+ img.dequeue_fence = -1;
+ // if we're still holding a release fence, get rid of it now
+ if (img.release_fence >= 0) {
+ close(img.release_fence);
+ img.release_fence = -1;
+ }
+ img.dequeued = false;
+ }
+
+ return VK_SUCCESS;
+}
+
} // namespace driver
} // namespace vulkan
diff --git a/vulkan/libvulkan/swapchain.h b/vulkan/libvulkan/swapchain.h
index 4912ef1..280fe9b 100644
--- a/vulkan/libvulkan/swapchain.h
+++ b/vulkan/libvulkan/swapchain.h
@@ -46,6 +46,7 @@
VKAPI_ATTR VkResult GetPhysicalDeviceSurfaceFormats2KHR(VkPhysicalDevice physicalDevice, const VkPhysicalDeviceSurfaceInfo2KHR* pSurfaceInfo, uint32_t* pSurfaceFormatCount, VkSurfaceFormat2KHR* pSurfaceFormats);
VKAPI_ATTR VkResult BindImageMemory2(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
VKAPI_ATTR VkResult BindImageMemory2KHR(VkDevice device, uint32_t bindInfoCount, const VkBindImageMemoryInfo* pBindInfos);
+VKAPI_ATTR VkResult ReleaseSwapchainImagesEXT(VkDevice device, const VkReleaseSwapchainImagesInfoEXT* pReleaseInfo);
// clang-format on
} // namespace driver
diff --git a/vulkan/scripts/driver_generator.py b/vulkan/scripts/driver_generator.py
index af56764..78b550c 100644
--- a/vulkan/scripts/driver_generator.py
+++ b/vulkan/scripts/driver_generator.py
@@ -35,6 +35,8 @@
'VK_KHR_surface',
'VK_KHR_surface_protected_capabilities',
'VK_KHR_swapchain',
+ 'VK_EXT_swapchain_maintenance1',
+ 'VK_EXT_surface_maintenance1',
]
# Extensions known to vulkan::driver level.
@@ -46,6 +48,7 @@
'VK_KHR_external_memory_capabilities',
'VK_KHR_external_semaphore_capabilities',
'VK_KHR_external_fence_capabilities',
+ 'VK_KHR_external_fence_fd',
]
# Functions needed at vulkan::driver level.
@@ -112,6 +115,9 @@
# For promoted VK_KHR_external_fence_capabilities
'vkGetPhysicalDeviceExternalFenceProperties',
'vkGetPhysicalDeviceExternalFencePropertiesKHR',
+
+ # VK_KHR_swapchain_maintenance1 requirement
+ 'vkImportFenceFdKHR',
]
# Functions intercepted at vulkan::driver level.
diff --git a/vulkan/vkjson/vkjson.cc b/vulkan/vkjson/vkjson.cc
index da6b00a..0284192 100644
--- a/vulkan/vkjson/vkjson.cc
+++ b/vulkan/vkjson/vkjson.cc
@@ -731,7 +731,7 @@
visitor->Visit("vulkanMemoryModelAvailabilityVisibilityChains", &features->vulkanMemoryModelAvailabilityVisibilityChains) &&
visitor->Visit("shaderOutputViewportIndex", &features->shaderOutputViewportIndex) &&
visitor->Visit("shaderOutputLayer", &features->shaderOutputLayer) &&
- visitor->Visit("shaderOutputLayer", &features->shaderOutputLayer);
+ visitor->Visit("subgroupBroadcastDynamicId", &features->subgroupBroadcastDynamicId);
}
template <typename Visitor>