Merge "hdr10+: adding OMX config index and profiles"
diff --git a/PREUPLOAD.cfg b/PREUPLOAD.cfg
index 08218b8..1a932c3 100644
--- a/PREUPLOAD.cfg
+++ b/PREUPLOAD.cfg
@@ -4,6 +4,7 @@
[Builtin Hooks Options]
# Only turn on clang-format check for the following subfolders.
clang_format = --commit ${PREUPLOAD_COMMIT} --style file --extensions c,h,cc,cpp
+ libs/binder/ndk/
libs/graphicsenv/
libs/gui/
libs/renderengine/
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 19c2830..53b3a00 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -228,6 +228,10 @@
{ OPT, "events/kmem/rss_stat/enable" },
{ OPT, "events/kmem/ion_heap_grow/enable" },
{ OPT, "events/kmem/ion_heap_shrink/enable" },
+ { OPT, "events/oom/oom_score_adj_update/enable" },
+ { OPT, "events/sched/sched_process_exit/enable" },
+ { OPT, "events/task/task_rename/enable" },
+ { OPT, "events/task/task_newtask/enable" },
} },
};
@@ -435,14 +439,10 @@
const char* path = category.sysfiles[i].path;
bool req = category.sysfiles[i].required == REQ;
if (path != nullptr) {
- if (req) {
- if (!fileIsWritable(path)) {
- return false;
- } else {
- ok = true;
- }
- } else {
+ if (fileIsWritable(path)) {
ok = true;
+ } else if (req) {
+ return false;
}
}
}
diff --git a/cmds/atrace/atrace_userdebug.rc b/cmds/atrace/atrace_userdebug.rc
index f4e5b98..5c28c9d 100644
--- a/cmds/atrace/atrace_userdebug.rc
+++ b/cmds/atrace/atrace_userdebug.rc
@@ -9,8 +9,8 @@
chmod 0666 /sys/kernel/debug/tracing/events/workqueue/enable
chmod 0666 /sys/kernel/tracing/events/regulator/enable
chmod 0666 /sys/kernel/debug/tracing/events/regulator/enable
- chmod 0666 /sys/kernel/tracing/events/pagecache/enable
- chmod 0666 /sys/kernel/debug/tracing/events/pagecache/enable
+ chmod 0666 /sys/kernel/tracing/events/filemap/enable
+ chmod 0666 /sys/kernel/debug/tracing/events/filemap/enable
# irq
chmod 0666 /sys/kernel/tracing/events/irq/enable
diff --git a/cmds/dumpstate/DumpstateService.cpp b/cmds/dumpstate/DumpstateService.cpp
index 0ee6c3a..849eb44 100644
--- a/cmds/dumpstate/DumpstateService.cpp
+++ b/cmds/dumpstate/DumpstateService.cpp
@@ -108,7 +108,8 @@
bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_REMOTE &&
bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_WEAR &&
bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_TELEPHONY &&
- bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_WIFI) {
+ bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_WIFI &&
+ bugreport_mode != Dumpstate::BugreportMode::BUGREPORT_DEFAULT) {
return exception(binder::Status::EX_ILLEGAL_ARGUMENT,
StringPrintf("Invalid bugreport mode: %d", bugreport_mode));
}
@@ -137,6 +138,7 @@
dprintf(fd, "extra_options: %s\n", ds_.options_->extra_options.c_str());
dprintf(fd, "version: %s\n", ds_.version_.c_str());
dprintf(fd, "bugreport_dir: %s\n", ds_.bugreport_dir_.c_str());
+ dprintf(fd, "bugreport_internal_dir_: %s\n", ds_.bugreport_internal_dir_.c_str());
dprintf(fd, "screenshot_path: %s\n", ds_.screenshot_path_.c_str());
dprintf(fd, "log_path: %s\n", ds_.log_path_.c_str());
dprintf(fd, "tmp_path: %s\n", ds_.tmp_path_.c_str());
diff --git a/cmds/dumpstate/binder/android/os/IDumpstate.aidl b/cmds/dumpstate/binder/android/os/IDumpstate.aidl
index 9e59f58..617eab3 100644
--- a/cmds/dumpstate/binder/android/os/IDumpstate.aidl
+++ b/cmds/dumpstate/binder/android/os/IDumpstate.aidl
@@ -40,7 +40,7 @@
boolean getSectionDetails);
// These modes encapsulate a set of run time options for generating bugreports.
- // A zipped bugreport; default mode.
+ // Takes a bugreport without user interference.
const int BUGREPORT_MODE_FULL = 0;
// Interactive bugreport, i.e. triggered by the user.
@@ -58,6 +58,9 @@
// Bugreport limited to only wifi info.
const int BUGREPORT_MODE_WIFI = 5;
+ // Default mode.
+ const int BUGREPORT_MODE_DEFAULT = 6;
+
/*
* Starts a bugreport in the background.
*/
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index df80651..516e3d8 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -82,6 +82,7 @@
using android::TIMED_OUT;
using android::UNKNOWN_ERROR;
using android::Vector;
+using android::base::StringPrintf;
using android::os::dumpstate::CommandOptions;
using android::os::dumpstate::DumpFileToFd;
using android::os::dumpstate::DumpstateSectionReporter;
@@ -121,6 +122,69 @@
// TODO: temporary variables and functions used during C++ refactoring
static Dumpstate& ds = Dumpstate::GetInstance();
+
+namespace android {
+namespace os {
+namespace {
+
+static int Open(std::string path, int flags, mode_t mode = 0) {
+ int fd = TEMP_FAILURE_RETRY(open(path.c_str(), flags, mode));
+ if (fd == -1) {
+ MYLOGE("open(%s, %s)\n", path.c_str(), strerror(errno));
+ }
+ return fd;
+}
+
+static int OpenForWrite(std::string path) {
+ return Open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC | O_NOFOLLOW,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
+}
+
+static int OpenForRead(std::string path) {
+ return Open(path, O_RDONLY | O_CLOEXEC | O_NOFOLLOW);
+}
+
+bool CopyFile(int in_fd, int out_fd) {
+ char buf[4096];
+ ssize_t byte_count;
+ while ((byte_count = TEMP_FAILURE_RETRY(read(in_fd, buf, sizeof(buf)))) > 0) {
+ if (!android::base::WriteFully(out_fd, buf, byte_count)) {
+ return false;
+ }
+ }
+ return (byte_count != -1);
+}
+
+static bool CopyFileToFd(const std::string& input_file, int out_fd) {
+ MYLOGD("Going to copy bugreport file (%s) to %d\n", ds.path_.c_str(), out_fd);
+
+ // Obtain a handle to the source file.
+ android::base::unique_fd in_fd(OpenForRead(input_file));
+ if (out_fd != -1 && in_fd.get() != -1) {
+ if (CopyFile(in_fd.get(), out_fd)) {
+ return true;
+ }
+ MYLOGE("Failed to copy zip file: %s\n", strerror(errno));
+ }
+ return false;
+}
+
+static bool CopyFileToFile(const std::string& input_file, const std::string& output_file) {
+ if (input_file == output_file) {
+ MYLOGD("Skipping copying bugreport file since the destination is the same (%s)\n",
+ output_file.c_str());
+ return false;
+ }
+
+ MYLOGD("Going to copy bugreport file (%s) to %s\n", input_file.c_str(), output_file.c_str());
+ android::base::unique_fd out_fd(OpenForWrite(output_file));
+ return CopyFileToFd(input_file, out_fd.get());
+}
+
+} // namespace
+} // namespace os
+} // namespace android
+
static int RunCommand(const std::string& title, const std::vector<std::string>& fullCommand,
const CommandOptions& options = CommandOptions::DEFAULT) {
return ds.RunCommand(title, fullCommand, options);
@@ -137,8 +201,6 @@
// Relative directory (inside the zip) for all files copied as-is into the bugreport.
static const std::string ZIP_ROOT_DIR = "FS";
-// Must be hardcoded because dumpstate HAL implementation need SELinux access to it
-static const std::string kDumpstateBoardPath = "/bugreports/";
static const std::string kProtoPath = "proto/";
static const std::string kProtoExt = ".proto";
static const std::string kDumpstateBoardFiles[] = {
@@ -1145,7 +1207,7 @@
return !isalnum(c) &&
std::string("@-_:.").find(c) == std::string::npos;
}, '_');
- const std::string path = kDumpstateBoardPath + "lshal_debug_" + cleanName;
+ const std::string path = ds.bugreport_internal_dir_ + "/lshal_debug_" + cleanName;
{
auto fd = android::base::unique_fd(
@@ -1529,7 +1591,8 @@
std::vector<std::string> paths;
std::vector<android::base::ScopeGuard<std::function<void()>>> remover;
for (int i = 0; i < NUM_OF_DUMPS; i++) {
- paths.emplace_back(kDumpstateBoardPath + kDumpstateBoardFiles[i]);
+ paths.emplace_back(StringPrintf("%s/%s", ds.bugreport_internal_dir_.c_str(),
+ kDumpstateBoardFiles[i].c_str()));
remover.emplace_back(android::base::make_scope_guard(std::bind(
[](std::string path) {
if (remove(path.c_str()) != 0 && errno != ENOENT) {
@@ -1687,7 +1750,8 @@
MYLOGE("Failed to add dumpstate log to .zip file\n");
return false;
}
- // ... and re-opens it for further logging.
+ // TODO: Should truncate the existing file.
+ // ... and re-open it for further logging.
redirect_to_existing_file(stderr, const_cast<char*>(ds.log_path_.c_str()));
fprintf(stderr, "\n");
@@ -1770,17 +1834,30 @@
// clang-format on
}
+static void MaybeResolveSymlink(std::string* path) {
+ std::string resolved_path;
+ if (android::base::Readlink(*path, &resolved_path)) {
+ *path = resolved_path;
+ }
+}
+
/*
* Prepares state like filename, screenshot path, etc in Dumpstate. Also initializes ZipWriter
* if we are writing zip files and adds the version file.
*/
static void PrepareToWriteToFile() {
- ds.bugreport_dir_ = dirname(ds.options_->use_outfile.c_str());
+ MaybeResolveSymlink(&ds.bugreport_internal_dir_);
+
+ std::string base_name_part1 = "bugreport";
+ if (!ds.options_->use_outfile.empty()) {
+ ds.bugreport_dir_ = dirname(ds.options_->use_outfile.c_str());
+ base_name_part1 = basename(ds.options_->use_outfile.c_str());
+ }
+
std::string build_id = android::base::GetProperty("ro.build.id", "UNKNOWN_BUILD");
std::string device_name = android::base::GetProperty("ro.product.name", "UNKNOWN_DEVICE");
ds.base_name_ =
- android::base::StringPrintf("%s-%s-%s", basename(ds.options_->use_outfile.c_str()),
- device_name.c_str(), build_id.c_str());
+ StringPrintf("%s-%s-%s", base_name_part1.c_str(), device_name.c_str(), build_id.c_str());
if (ds.options_->do_add_date) {
char date[80];
strftime(date, sizeof(date), "%Y-%m-%d-%H-%M-%S", localtime(&ds.now_));
@@ -1801,15 +1878,18 @@
ds.tmp_path_ = ds.GetPath(".tmp");
ds.log_path_ = ds.GetPath("-dumpstate_log-" + std::to_string(ds.pid_) + ".txt");
+ std::string destination = ds.options_->fd != -1 ? StringPrintf("[fd:%d]", ds.options_->fd)
+ : ds.bugreport_dir_.c_str();
MYLOGD(
"Bugreport dir: %s\n"
+ "Internal Bugreport dir: %s\n"
"Base name: %s\n"
"Suffix: %s\n"
"Log path: %s\n"
"Temporary path: %s\n"
"Screenshot path: %s\n",
- ds.bugreport_dir_.c_str(), ds.base_name_.c_str(), ds.name_.c_str(), ds.log_path_.c_str(),
- ds.tmp_path_.c_str(), ds.screenshot_path_.c_str());
+ destination.c_str(), ds.bugreport_internal_dir_.c_str(), ds.base_name_.c_str(),
+ ds.name_.c_str(), ds.log_path_.c_str(), ds.tmp_path_.c_str(), ds.screenshot_path_.c_str());
if (ds.options_->do_zip_file) {
ds.path_ = ds.GetPath(".zip");
@@ -1875,6 +1955,19 @@
ds.path_ = new_path;
}
}
+ // The zip file lives in an internal directory. Copy it over to output.
+ bool copy_succeeded = false;
+ if (ds.options_->fd != -1) {
+ copy_succeeded = android::os::CopyFileToFd(ds.path_, ds.options_->fd);
+ } else {
+ ds.final_path_ = ds.GetPath(ds.bugreport_dir_, ".zip");
+ copy_succeeded = android::os::CopyFileToFile(ds.path_, ds.final_path_);
+ }
+ if (copy_succeeded) {
+ if (remove(ds.path_.c_str())) {
+ MYLOGE("remove(%s): %s", ds.path_.c_str(), strerror(errno));
+ }
+ }
}
}
if (do_text_file) {
@@ -1899,8 +1992,9 @@
/* Broadcasts that we are done with the bugreport */
static void SendBugreportFinishedBroadcast() {
- if (!ds.path_.empty()) {
- MYLOGI("Final bugreport path: %s\n", ds.path_.c_str());
+ // TODO(b/111441001): use callback instead of broadcast.
+ if (!ds.final_path_.empty()) {
+ MYLOGI("Final bugreport path: %s\n", ds.final_path_.c_str());
// clang-format off
std::vector<std::string> am_args = {
@@ -1908,7 +2002,7 @@
"--ei", "android.intent.extra.ID", std::to_string(ds.id_),
"--ei", "android.intent.extra.PID", std::to_string(ds.pid_),
"--ei", "android.intent.extra.MAX", std::to_string(ds.progress_->GetMax()),
- "--es", "android.intent.extra.BUGREPORT", ds.path_,
+ "--es", "android.intent.extra.BUGREPORT", ds.final_path_,
"--es", "android.intent.extra.DUMPSTATE_LOG", ds.log_path_
};
// clang-format on
@@ -1930,7 +2024,7 @@
if (ds.options_->is_remote_mode) {
am_args.push_back("--es");
am_args.push_back("android.intent.extra.REMOTE_BUGREPORT_HASH");
- am_args.push_back(SHA256_file_hash(ds.path_));
+ am_args.push_back(SHA256_file_hash(ds.final_path_));
SendBroadcast("com.android.internal.intent.action.REMOTE_BUGREPORT_FINISHED", am_args);
} else {
SendBroadcast("com.android.internal.intent.action.BUGREPORT_FINISHED", am_args);
@@ -1954,10 +2048,13 @@
return "BUGREPORT_TELEPHONY";
case Dumpstate::BugreportMode::BUGREPORT_WIFI:
return "BUGREPORT_WIFI";
+ case Dumpstate::BugreportMode::BUGREPORT_DEFAULT:
+ return "BUGREPORT_DEFAULT";
}
}
static void SetOptionsFromMode(Dumpstate::BugreportMode mode, Dumpstate::DumpOptions* options) {
+ options->extra_options = ModeToString(mode);
switch (mode) {
case Dumpstate::BugreportMode::BUGREPORT_FULL:
options->do_broadcast = true;
@@ -1994,12 +2091,14 @@
options->do_fb = true;
options->do_broadcast = true;
break;
+ case Dumpstate::BugreportMode::BUGREPORT_DEFAULT:
+ break;
}
}
static Dumpstate::BugreportMode getBugreportModeFromProperty() {
- // If the system property is not set, it's assumed to be a full bugreport.
- Dumpstate::BugreportMode mode = Dumpstate::BugreportMode::BUGREPORT_FULL;
+ // If the system property is not set, it's assumed to be a default bugreport.
+ Dumpstate::BugreportMode mode = Dumpstate::BugreportMode::BUGREPORT_DEFAULT;
std::string extra_options = android::base::GetProperty(PROPERTY_EXTRA_OPTIONS, "");
if (!extra_options.empty()) {
@@ -2007,6 +2106,8 @@
// Currently, it contains the type of the requested bugreport.
if (extra_options == "bugreportplus") {
mode = Dumpstate::BugreportMode::BUGREPORT_INTERACTIVE;
+ } else if (extra_options == "bugreportfull") {
+ mode = Dumpstate::BugreportMode::BUGREPORT_FULL;
} else if (extra_options == "bugreportremote") {
mode = Dumpstate::BugreportMode::BUGREPORT_REMOTE;
} else if (extra_options == "bugreportwear") {
@@ -2060,6 +2161,7 @@
MYLOGI("telephony_only: %d\n", options.telephony_only);
MYLOGI("wifi_only: %d\n", options.wifi_only);
MYLOGI("do_progress_updates: %d\n", options.do_progress_updates);
+ MYLOGI("fd: %d\n", options.fd);
MYLOGI("use_outfile: %s\n", options.use_outfile.c_str());
MYLOGI("extra_options: %s\n", options.extra_options.c_str());
MYLOGI("args: %s\n", options.args.c_str());
@@ -2125,8 +2227,13 @@
}
bool Dumpstate::DumpOptions::ValidateOptions() const {
- if ((do_zip_file || do_add_date || do_progress_updates || do_broadcast)
- && use_outfile.empty()) {
+ if (fd != -1 && !do_zip_file) {
+ return false;
+ }
+
+ bool has_out_file_options = !use_outfile.empty() || fd != -1;
+ if ((do_zip_file || do_add_date || do_progress_updates || do_broadcast) &&
+ !has_out_file_options) {
return false;
}
@@ -2148,10 +2255,31 @@
options_ = std::move(options);
}
+/*
+ * Dumps relevant information to a bugreport based on the given options.
+ *
+ * The bugreport can be dumped to a file or streamed to a socket.
+ *
+ * How dumping to file works:
+ * stdout is redirected to a temporary file. This will later become the main bugreport entry.
+ * stderr is redirected a log file.
+ *
+ * The temporary bugreport is then populated via printfs, dumping contents of files and
+ * output of commands to stdout.
+ *
+ * If zipping, the temporary bugreport file is added to the zip archive. Else it's renamed to final
+ * text file.
+ *
+ * If zipping, a bunch of other files and dumps also get added to the zip archive. The log file also
+ * gets added to the archive.
+ *
+ * Bugreports are first generated in a local directory and later copied to the caller's fd or
+ * directory.
+ */
Dumpstate::RunStatus Dumpstate::Run() {
+ LogDumpOptions(*options_);
if (!options_->ValidateOptions()) {
MYLOGE("Invalid options specified\n");
- LogDumpOptions(*options_);
return RunStatus::INVALID_INPUT;
}
/* set as high priority, and protect from OOM killer */
@@ -2191,9 +2319,9 @@
// TODO: temporarily set progress until it's part of the Dumpstate constructor
std::string stats_path =
- is_redirecting ? android::base::StringPrintf("%s/dumpstate-stats.txt",
- dirname(options_->use_outfile.c_str()))
- : "";
+ is_redirecting
+ ? android::base::StringPrintf("%s/dumpstate-stats.txt", bugreport_internal_dir_.c_str())
+ : "";
progress_.reset(new Progress(stats_path));
/* gets the sequential id */
@@ -2289,13 +2417,18 @@
int dup_stdout_fd;
int dup_stderr_fd;
if (is_redirecting) {
+ // Redirect stderr to log_path_ for debugging.
TEMP_FAILURE_RETRY(dup_stderr_fd = dup(fileno(stderr)));
redirect_to_file(stderr, const_cast<char*>(log_path_.c_str()));
if (chown(log_path_.c_str(), AID_SHELL, AID_SHELL)) {
MYLOGE("Unable to change ownership of dumpstate log file %s: %s\n", log_path_.c_str(),
strerror(errno));
}
+
+ // Redirect stdout to tmp_path_. This is the main bugreport entry and will be
+ // moved into zip file later, if zipping.
TEMP_FAILURE_RETRY(dup_stdout_fd = dup(fileno(stdout)));
+ // TODO: why not write to a file instead of stdout to overcome this problem?
/* TODO: rather than generating a text file now and zipping it later,
it would be more efficient to redirect stdout to the zip entry
directly, but the libziparchive doesn't support that option yet. */
@@ -2370,7 +2503,7 @@
return RunStatus::OK;
}
-/* Main entry point for dumpstate. */
+/* Main entry point for dumpstate binary. */
int run_main(int argc, char* argv[]) {
std::unique_ptr<Dumpstate::DumpOptions> options = std::make_unique<Dumpstate::DumpOptions>();
Dumpstate::RunStatus status = options->Initialize(argc, argv);
@@ -2382,7 +2515,7 @@
switch (status) {
case Dumpstate::RunStatus::OK:
return 0;
- break;
+ // TODO(b/111441001): Exit directly in the following cases.
case Dumpstate::RunStatus::HELP:
ShowUsageAndExit(0 /* exit code */);
break;
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index 35cbdb1..ee952d9 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -142,7 +142,7 @@
float growth_factor_;
int32_t n_runs_;
int32_t average_max_;
- const std::string& path_;
+ std::string path_;
};
/*
@@ -164,6 +164,11 @@
static std::string VERSION_DEFAULT = "default";
/*
+ * Directory used by Dumpstate binary to keep its local files.
+ */
+static const std::string DUMPSTATE_DIRECTORY = "/bugreports";
+
+/*
* Structure that contains the information of an open dump file.
*/
struct DumpData {
@@ -196,7 +201,8 @@
BUGREPORT_REMOTE = android::os::IDumpstate::BUGREPORT_MODE_REMOTE,
BUGREPORT_WEAR = android::os::IDumpstate::BUGREPORT_MODE_WEAR,
BUGREPORT_TELEPHONY = android::os::IDumpstate::BUGREPORT_MODE_TELEPHONY,
- BUGREPORT_WIFI = android::os::IDumpstate::BUGREPORT_MODE_WIFI
+ BUGREPORT_WIFI = android::os::IDumpstate::BUGREPORT_MODE_WIFI,
+ BUGREPORT_DEFAULT = android::os::IDumpstate::BUGREPORT_MODE_DEFAULT
};
static android::os::dumpstate::CommandOptions DEFAULT_DUMPSYS;
@@ -300,7 +306,11 @@
*/
bool FinishZipFile();
- /* Gets the path of a bugreport file with the given suffix. */
+ /* Constructs a full path inside directory with file name formatted using the given suffix. */
+ std::string GetPath(const std::string& directory, const std::string& suffix) const;
+
+ /* Constructs a full path inside bugreport_internal_dir_ with file name formatted using the
+ * given suffix. */
std::string GetPath(const std::string& suffix) const;
/* Returns true if the current version supports priority dump feature. */
@@ -314,7 +324,6 @@
/* Sets runtime options. */
void SetOptions(std::unique_ptr<DumpOptions> options);
- // TODO: add other options from DumpState.
/*
* Structure to hold options that determine the behavior of dumpstate.
*/
@@ -333,6 +342,10 @@
bool wifi_only = false;
// Whether progress updates should be published.
bool do_progress_updates = false;
+ // File descriptor to output zip file. -1 indicates not set. Takes precedence over
+ // use_outfile.
+ int fd = -1;
+ // Partial path to output file.
std::string use_outfile;
// TODO: rename to MODE.
// Extra options passed as system property.
@@ -381,12 +394,6 @@
// Bugreport format version;
std::string version_ = VERSION_CURRENT;
- // Full path of the directory where the bugreport files will be written.
- std::string bugreport_dir_;
-
- // Full path of the temporary file containing the screenshot (when requested).
- std::string screenshot_path_;
-
time_t now_;
// Base name (without suffix or extensions) of the bugreport files, typically
@@ -397,15 +404,30 @@
// `-d`), but it could be changed by the user..
std::string name_;
- // Full path of the temporary file containing the bugreport.
+ std::string bugreport_internal_dir_ = DUMPSTATE_DIRECTORY;
+
+ // Full path of the temporary file containing the bugreport, inside bugreport_internal_dir_.
+ // At the very end this file is pulled into the zip file.
std::string tmp_path_;
- // Full path of the file containing the dumpstate logs.
+ // Full path of the file containing the dumpstate logs, inside bugreport_internal_dir_.
+ // This is useful for debugging.
std::string log_path_;
- // Pointer to the actual path, be it zip or text.
+ // Full path of the bugreport file, be it zip or text, inside bugreport_internal_dir_.
std::string path_;
+ // TODO: If temporary this should be removed at the end.
+ // Full path of the temporary file containing the screenshot (when requested).
+ std::string screenshot_path_;
+
+ // TODO(b/111441001): remove when obsolete.
+ // Full path of the final zip file inside the caller-specified directory, if available.
+ std::string final_path_;
+
+ // The caller-specified directory, if available.
+ std::string bugreport_dir_;
+
// Pointer to the zipped file.
std::unique_ptr<FILE, int (*)(FILE*)> zip_file{nullptr, fclose};
diff --git a/cmds/dumpstate/tests/dumpstate_test.cpp b/cmds/dumpstate/tests/dumpstate_test.cpp
index 9ca894d..fcf9371 100644
--- a/cmds/dumpstate/tests/dumpstate_test.cpp
+++ b/cmds/dumpstate/tests/dumpstate_test.cpp
@@ -36,6 +36,7 @@
#include <android-base/properties.h>
#include <android-base/stringprintf.h>
#include <android-base/strings.h>
+#include <cutils/properties.h>
namespace android {
namespace os {
@@ -148,7 +149,10 @@
virtual void SetUp() {
options_ = Dumpstate::DumpOptions();
}
-
+ void TearDown() {
+ // Reset the property
+ property_set("dumpstate.options", "");
+ }
Dumpstate::DumpOptions options_;
};
@@ -163,7 +167,6 @@
EXPECT_EQ(status, Dumpstate::RunStatus::OK);
- // These correspond to bugreport_mode = full, because that's the default.
EXPECT_FALSE(options_.do_add_date);
EXPECT_FALSE(options_.do_zip_file);
EXPECT_EQ("", options_.use_outfile);
@@ -171,10 +174,295 @@
EXPECT_FALSE(options_.use_control_socket);
EXPECT_FALSE(options_.show_header_only);
EXPECT_TRUE(options_.do_vibrate);
- EXPECT_TRUE(options_.do_fb);
+ EXPECT_FALSE(options_.do_fb);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.do_broadcast);
+}
+
+TEST_F(DumpOptionsTest, InitializeAdbBugreport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("dumpstatez"),
+ const_cast<char*>("-S"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.use_control_socket);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_fb);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.do_broadcast);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeAdbShellBugreport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("dumpstate"),
+ const_cast<char*>("-s"),
+ };
+ // clang-format on
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.use_socket);
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_EQ("", options_.use_outfile);
+ EXPECT_FALSE(options_.do_add_date);
+ EXPECT_FALSE(options_.do_zip_file);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_fb);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.do_broadcast);
+}
+
+TEST_F(DumpOptionsTest, InitializeFullBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+ property_set("dumpstate.options", "bugreportfull");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_fb);
+ EXPECT_TRUE(options_.do_zip_file);
EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+ EXPECT_FALSE(options_.do_start_service);
+}
+
+TEST_F(DumpOptionsTest, InitializeInteractiveBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "bugreportplus");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.do_progress_updates);
+ EXPECT_TRUE(options_.do_start_service);
+ EXPECT_FALSE(options_.do_fb);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeRemoteBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "bugreportremote");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.do_vibrate);
+ EXPECT_FALSE(options_.do_fb);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeWearBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "bugreportwear");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_fb);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.do_progress_updates);
+ EXPECT_TRUE(options_.do_start_service);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeTelephonyBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "bugreporttelephony");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_fb);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.telephony_only);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeWifiBugReport) {
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "bugreportwifi");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_fb);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.wifi_only);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+}
+
+TEST_F(DumpOptionsTest, InitializeDefaultBugReport) {
+ // default: commandline options are not overridden
+ // clang-format off
+ char* argv[] = {
+ const_cast<char*>("bugreport"),
+ const_cast<char*>("-d"),
+ const_cast<char*>("-p"),
+ const_cast<char*>("-B"),
+ const_cast<char*>("-z"),
+ const_cast<char*>("-o abc"),
+ };
+ // clang-format on
+
+ property_set("dumpstate.options", "");
+
+ Dumpstate::RunStatus status = options_.Initialize(ARRAY_SIZE(argv), argv);
+
+ EXPECT_EQ(status, Dumpstate::RunStatus::OK);
+ EXPECT_TRUE(options_.do_add_date);
+ EXPECT_TRUE(options_.do_fb);
+ EXPECT_TRUE(options_.do_zip_file);
+ EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_EQ(" abc", std::string(options_.use_outfile));
+
+ // Other options retain default values
+ EXPECT_TRUE(options_.do_vibrate);
+ EXPECT_FALSE(options_.use_control_socket);
+ EXPECT_FALSE(options_.show_header_only);
+ EXPECT_FALSE(options_.do_progress_updates);
+ EXPECT_FALSE(options_.is_remote_mode);
+ EXPECT_FALSE(options_.use_socket);
+ EXPECT_FALSE(options_.wifi_only);
}
TEST_F(DumpOptionsTest, InitializePartial1) {
@@ -203,10 +491,10 @@
// Other options retain default values
EXPECT_FALSE(options_.show_header_only);
EXPECT_TRUE(options_.do_vibrate);
- EXPECT_TRUE(options_.do_fb);
+ EXPECT_FALSE(options_.do_fb);
EXPECT_FALSE(options_.do_progress_updates);
EXPECT_FALSE(options_.is_remote_mode);
- EXPECT_TRUE(options_.do_broadcast);
+ EXPECT_FALSE(options_.do_broadcast);
}
TEST_F(DumpOptionsTest, InitializePartial2) {
diff --git a/cmds/dumpstate/utils.cpp b/cmds/dumpstate/utils.cpp
index 6cbb691..d97ffbf 100644
--- a/cmds/dumpstate/utils.cpp
+++ b/cmds/dumpstate/utils.cpp
@@ -229,7 +229,11 @@
}
std::string Dumpstate::GetPath(const std::string& suffix) const {
- return android::base::StringPrintf("%s/%s-%s%s", bugreport_dir_.c_str(), base_name_.c_str(),
+ return GetPath(bugreport_internal_dir_, suffix);
+}
+
+std::string Dumpstate::GetPath(const std::string& directory, const std::string& suffix) const {
+ return android::base::StringPrintf("%s/%s-%s%s", directory.c_str(), base_name_.c_str(),
name_.c_str(), suffix.c_str());
}
diff --git a/cmds/dumpsys/dumpsys.cpp b/cmds/dumpsys/dumpsys.cpp
index 9bfd710..4811927 100644
--- a/cmds/dumpsys/dumpsys.cpp
+++ b/cmds/dumpsys/dumpsys.cpp
@@ -389,7 +389,7 @@
auto time_left_ms = [end]() {
auto now = std::chrono::steady_clock::now();
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - now);
- return std::max(diff.count(), 0ll);
+ return std::max(diff.count(), 0LL);
};
int rc = TEMP_FAILURE_RETRY(poll(&pfd, 1, time_left_ms()));
diff --git a/cmds/lshal/ListCommand.cpp b/cmds/lshal/ListCommand.cpp
index a6d7a78..c706d91 100644
--- a/cmds/lshal/ListCommand.cpp
+++ b/cmds/lshal/ListCommand.cpp
@@ -376,23 +376,23 @@
}
mServicesTable.setDescription(
- "All binderized services (registered services through hwservicemanager)");
+ "| All binderized services (registered with hwservicemanager)");
mPassthroughRefTable.setDescription(
- "All interfaces that getService() has ever return as a passthrough interface;\n"
- "PIDs / processes shown below might be inaccurate because the process\n"
- "might have relinquished the interface or might have died.\n"
- "The Server / Server CMD column can be ignored.\n"
- "The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
- "the library and successfully fetched the passthrough implementation.");
+ "| All interfaces that getService() has ever returned as a passthrough interface;\n"
+ "| PIDs / processes shown below might be inaccurate because the process\n"
+ "| might have relinquished the interface or might have died.\n"
+ "| The Server / Server CMD column can be ignored.\n"
+ "| The Clients / Clients CMD column shows all process that have ever dlopen'ed \n"
+ "| the library and successfully fetched the passthrough implementation.");
mImplementationsTable.setDescription(
- "All available passthrough implementations (all -impl.so files).\n"
- "These may return subclasses through their respective HIDL_FETCH_I* functions.");
+ "| All available passthrough implementations (all -impl.so files).\n"
+ "| These may return subclasses through their respective HIDL_FETCH_I* functions.");
mManifestHalsTable.setDescription(
- "All HALs that are in VINTF manifest.");
+ "| All HALs that are in VINTF manifest.");
mLazyHalsTable.setDescription(
- "All HALs that are declared in VINTF manifest:\n"
- " - as hwbinder HALs but are not registered to hwservicemanager, and\n"
- " - as hwbinder/passthrough HALs with no implementation.");
+ "| All HALs that are declared in VINTF manifest:\n"
+ "| - as hwbinder HALs but are not registered to hwservicemanager, and\n"
+ "| - as hwbinder/passthrough HALs with no implementation.");
}
bool ListCommand::addEntryWithInstance(const TableEntry& entry,
@@ -972,10 +972,10 @@
thiz->mSelectedColumns.push_back(TableColumnType::VINTF);
return OK;
}, "print VINTF info. This column contains a comma-separated list of:\n"
- " - DM: device manifest\n"
- " - DC: device compatibility matrix\n"
- " - FM: framework manifest\n"
- " - FC: framework compatibility matrix"});
+ " - DM: if the HAL is in the device manifest\n"
+ " - DC: if the HAL is in the device compatibility matrix\n"
+ " - FM: if the HAL is in the framework manifest\n"
+ " - FC: if the HAL is in the framework compatibility matrix"});
mOptions.push_back({'S', "service-status", no_argument, v++, [](ListCommand* thiz, const char*) {
thiz->mSelectedColumns.push_back(TableColumnType::SERVICE_STATUS);
return OK;
@@ -1054,7 +1054,7 @@
return OK;
}, "comma-separated list of one or more sections.\nThe output is restricted to the selected "
"section(s). Valid options\nare: (b|binderized), (c|passthrough_clients), (l|"
- "passthrough_libs), and (v|vintf).\nDefault is `bcl`."});
+ "passthrough_libs), (v|vintf), and (z|lazy).\nDefault is `bcl`."});
}
// Create 'longopts' argument to getopt_long. Caller is responsible for maintaining
@@ -1150,7 +1150,7 @@
}
if (mSelectedColumns.empty()) {
- mSelectedColumns = {TableColumnType::RELEASED,
+ mSelectedColumns = {TableColumnType::VINTF, TableColumnType::RELEASED,
TableColumnType::INTERFACE_NAME, TableColumnType::THREADS,
TableColumnType::SERVER_PID, TableColumnType::CLIENT_PIDS};
}
@@ -1210,7 +1210,7 @@
err() << "list:" << std::endl
<< " lshal" << std::endl
<< " lshal list" << std::endl
- << " List all hals with default ordering and columns (`lshal list -liepc`)" << std::endl
+ << " List all hals with default ordering and columns (`lshal list -Vliepc`)" << std::endl
<< " lshal list [-h|--help]" << std::endl
<< " -h, --help: Print help message for list (`lshal help list`)" << std::endl
<< " lshal [list] [OPTIONS...]" << std::endl;
diff --git a/cmds/rss_hwm_reset/Android.bp b/cmds/rss_hwm_reset/Android.bp
new file mode 100644
index 0000000..15f10ef
--- /dev/null
+++ b/cmds/rss_hwm_reset/Android.bp
@@ -0,0 +1,28 @@
+// Copyright (C) 2018 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
+//
+// https://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.
+
+cc_binary {
+ name: "rss_hwm_reset",
+
+ srcs: [
+ "rss_hwm_reset.cc",
+ ],
+
+ shared_libs: [
+ "libbase",
+ "liblog",
+ ],
+
+ init_rc: ["rss_hwm_reset.rc"],
+}
diff --git a/cmds/rss_hwm_reset/rss_hwm_reset.cc b/cmds/rss_hwm_reset/rss_hwm_reset.cc
new file mode 100644
index 0000000..1626e7e
--- /dev/null
+++ b/cmds/rss_hwm_reset/rss_hwm_reset.cc
@@ -0,0 +1,72 @@
+/*
+ * Copyright (C) 2018 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
+ *
+ * https://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.
+ */
+
+ /*
+ * rss_hwm_reset clears the RSS high-water mark counters for all currently
+ * running processes. It writes "5" to /proc/PID/clear_refs for every PID.
+ *
+ * It runs in its own process becuase dac_override capability is required
+ * in order to write to other processes' clear_refs.
+ *
+ * It is invoked from a system service by flipping sys.rss_hwm_reset.on
+ * property to "1".
+ */
+
+#define LOG_TAG "rss_hwm_reset"
+
+#include <dirent.h>
+
+#include <string>
+
+#include <android-base/file.h>
+#include <android-base/stringprintf.h>
+#include <log/log.h>
+
+namespace {
+// Resets RSS HWM counter for the selected process by writing 5 to
+// /proc/PID/clear_refs.
+void reset_rss_hwm(const char* pid) {
+ std::string clear_refs_path =
+ ::android::base::StringPrintf("/proc/%s/clear_refs", pid);
+ ::android::base::WriteStringToFile("5", clear_refs_path);
+}
+}
+
+// Clears RSS HWM counters for all currently running processes.
+int main(int /* argc */, char** /* argv[] */) {
+ DIR* dirp = opendir("/proc");
+ if (dirp == nullptr) {
+ ALOGE("unable to read /proc");
+ return 1;
+ }
+ struct dirent* entry;
+ while ((entry = readdir(dirp)) != nullptr) {
+ // Skip entries that are not directories.
+ if (entry->d_type != DT_DIR) continue;
+ // Skip entries that do not contain only numbers.
+ const char* pid = entry->d_name;
+ while (*pid) {
+ if (*pid < '0' || *pid > '9') break;
+ pid++;
+ }
+ if (*pid != 0) continue;
+
+ pid = entry->d_name;
+ reset_rss_hwm(pid);
+ }
+ closedir(dirp);
+ return 0;
+}
diff --git a/cmds/rss_hwm_reset/rss_hwm_reset.rc b/cmds/rss_hwm_reset/rss_hwm_reset.rc
new file mode 100644
index 0000000..fbbc820
--- /dev/null
+++ b/cmds/rss_hwm_reset/rss_hwm_reset.rc
@@ -0,0 +1,26 @@
+# Copyright (C) 2018 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
+#
+# https://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.
+
+service rss_hwm_reset /system/bin/rss_hwm_reset
+ class late_start
+ disabled
+ oneshot
+ user nobody
+ group nobody readproc
+ writepid /dev/cpuset/system-background/tasks
+ capabilities DAC_OVERRIDE
+
+on property:sys.rss_hwm_reset.on=1
+ start rss_hwm_reset
+ setprop sys.rss_hwm_reset.on 0
diff --git a/data/etc/android.hardware.face.xml b/data/etc/android.hardware.biometrics.face.xml
similarity index 93%
rename from data/etc/android.hardware.face.xml
rename to data/etc/android.hardware.biometrics.face.xml
index abd23fb..7fa0bf9 100644
--- a/data/etc/android.hardware.face.xml
+++ b/data/etc/android.hardware.biometrics.face.xml
@@ -16,5 +16,5 @@
<!-- This is the standard set of features for a biometric face authentication sensor. -->
<permissions>
- <feature name="android.hardware.face" />
+ <feature name="android.hardware.biometrics.face" />
</permissions>
diff --git a/data/etc/android.hardware.biometrics.fingerprint.xml b/data/etc/android.hardware.biometrics.fingerprint.xml
new file mode 100644
index 0000000..e5af541
--- /dev/null
+++ b/data/etc/android.hardware.biometrics.fingerprint.xml
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+ ~ Copyright (C) 2018 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.
+ -->
+
+<!-- This is the standard set of features for a biometric fingerprint sensor. -->
+<permissions>
+ <feature name="android.hardware.biometrics.fingerprint" />
+</permissions>
diff --git a/data/etc/android.hardware.face.xml b/data/etc/android.software.ipsec_tunnels.xml
similarity index 79%
copy from data/etc/android.hardware.face.xml
copy to data/etc/android.software.ipsec_tunnels.xml
index abd23fb..f7ffc02 100644
--- a/data/etc/android.hardware.face.xml
+++ b/data/etc/android.software.ipsec_tunnels.xml
@@ -14,7 +14,11 @@
limitations under the License.
-->
-<!-- This is the standard set of features for a biometric face authentication sensor. -->
+<!--
+ This is the feature indicating that the device has support for multinetworking-capable IPsec
+ tunnels
+-->
+
<permissions>
- <feature name="android.hardware.face" />
+ <feature name="android.software.ipsec_tunnels" />
</permissions>
diff --git a/headers/media_plugin/media/cas/DescramblerAPI.h b/headers/media_plugin/media/cas/DescramblerAPI.h
index 033c8ce..c57f606 100644
--- a/headers/media_plugin/media/cas/DescramblerAPI.h
+++ b/headers/media_plugin/media/cas/DescramblerAPI.h
@@ -72,12 +72,12 @@
// associated MediaCas session is used to load decryption keys
// into the crypto/cas plugin. The keys are then referenced by key-id
// in the 'key' parameter to the decrypt() method.
- // Should return NO_ERROR on success, ERROR_DRM_SESSION_NOT_OPENED if
+ // Should return NO_ERROR on success, ERROR_CAS_SESSION_NOT_OPENED if
// the session is not opened and a code from MediaErrors.h otherwise.
virtual status_t setMediaCasSession(const CasSessionId& sessionId) = 0;
// If the error returned falls into the range
- // ERROR_DRM_VENDOR_MIN..ERROR_DRM_VENDOR_MAX, errorDetailMsg should be
+ // ERROR_CAS_VENDOR_MIN..ERROR_CAS_VENDOR_MAX, errorDetailMsg should be
// filled in with an appropriate string.
// At the java level these special errors will then trigger a
// MediaCodec.CryptoException that gives clients access to both
diff --git a/headers/media_plugin/media/openmax/OMX_AsString.h b/headers/media_plugin/media/openmax/OMX_AsString.h
index dc25ded..152015b 100644
--- a/headers/media_plugin/media/openmax/OMX_AsString.h
+++ b/headers/media_plugin/media/openmax/OMX_AsString.h
@@ -188,7 +188,9 @@
inline static const char *asString(OMX_AUDIO_CODINGEXTTYPE i, const char *def = "??") {
switch (i) {
case OMX_AUDIO_CodingAndroidAC3: return "AndroidAC3";
+ case OMX_AUDIO_CodingAndroidEAC3: return "AndroidEAC3";
case OMX_AUDIO_CodingAndroidOPUS: return "AndroidOPUS";
+ case OMX_AUDIO_CodingAndroidAC4: return "AndroidAC4";
default: return asString((OMX_AUDIO_CODINGTYPE)i, def);
}
}
@@ -533,9 +535,11 @@
// case OMX_IndexConfigCommit: return "ConfigCommit";
case OMX_IndexConfigAndroidVendorExtension: return "ConfigAndroidVendorExtension";
case OMX_IndexParamAudioAndroidAc3: return "ParamAudioAndroidAc3";
+ case OMX_IndexConfigAudioPresentation: return "ConfigAudioPresentation";
case OMX_IndexParamAudioAndroidOpus: return "ParamAudioAndroidOpus";
case OMX_IndexParamAudioAndroidAacPresentation: return "ParamAudioAndroidAacPresentation";
case OMX_IndexParamAudioAndroidEac3: return "ParamAudioAndroidEac3";
+ case OMX_IndexParamAudioAndroidAc4: return "ParamAudioAndroidAc4";
case OMX_IndexParamAudioProfileQuerySupported: return "ParamAudioProfileQuerySupported";
// case OMX_IndexParamNalStreamFormatSupported: return "ParamNalStreamFormatSupported";
// case OMX_IndexParamNalStreamFormat: return "ParamNalStreamFormat";
diff --git a/headers/media_plugin/media/openmax/OMX_AudioExt.h b/headers/media_plugin/media/openmax/OMX_AudioExt.h
index 8409553..477faed 100644
--- a/headers/media_plugin/media/openmax/OMX_AudioExt.h
+++ b/headers/media_plugin/media/openmax/OMX_AudioExt.h
@@ -48,6 +48,7 @@
OMX_AUDIO_CodingAndroidAC3, /**< AC3 encoded data */
OMX_AUDIO_CodingAndroidOPUS, /**< OPUS encoded data */
OMX_AUDIO_CodingAndroidEAC3, /**< EAC3 encoded data */
+ OMX_AUDIO_CodingAndroidAC4, /**< AC4 encoded data */
} OMX_AUDIO_CODINGEXTTYPE;
typedef struct OMX_AUDIO_PARAM_ANDROID_AC3TYPE {
@@ -68,6 +69,15 @@
variable or unknown sampling rate. */
} OMX_AUDIO_PARAM_ANDROID_EAC3TYPE;
+typedef struct OMX_AUDIO_PARAM_ANDROID_AC4TYPE {
+ OMX_U32 nSize; /**< size of the structure in bytes */
+ OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
+ OMX_U32 nPortIndex; /**< port that this structure applies to */
+ OMX_U32 nChannels; /**< Number of channels */
+ OMX_U32 nSampleRate; /**< Sampling rate of the source data. Use 0 for
+ variable or unknown sampling rate. */
+} OMX_AUDIO_PARAM_ANDROID_AC4TYPE;
+
typedef struct OMX_AUDIO_PARAM_ANDROID_OPUSTYPE {
OMX_U32 nSize; /**< size of the structure in bytes */
OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
@@ -117,6 +127,13 @@
OMX_U32 nProfileIndex; /**< Used to query for individual profile support information */
} OMX_AUDIO_PARAM_ANDROID_PROFILETYPE;
+typedef struct OMX_AUDIO_CONFIG_ANDROID_AUDIOPRESENTATION {
+ OMX_U32 nSize; /**< size of the structure in bytes */
+ OMX_VERSIONTYPE nVersion; /**< OMX specification version information */
+ OMX_S32 nPresentationId; /**< presentation id */
+ OMX_S32 nProgramId; /**< program id */
+} OMX_AUDIO_CONFIG_ANDROID_AUDIOPRESENTATION;
+
#ifdef __cplusplus
}
#endif /* __cplusplus */
diff --git a/headers/media_plugin/media/openmax/OMX_IndexExt.h b/headers/media_plugin/media/openmax/OMX_IndexExt.h
index 716d959..479e9b8 100644
--- a/headers/media_plugin/media/openmax/OMX_IndexExt.h
+++ b/headers/media_plugin/media/openmax/OMX_IndexExt.h
@@ -64,6 +64,8 @@
OMX_IndexParamAudioAndroidEac3, /**< reference: OMX_AUDIO_PARAM_ANDROID_EAC3TYPE */
OMX_IndexParamAudioProfileQuerySupported, /**< reference: OMX_AUDIO_PARAM_ANDROID_PROFILETYPE */
OMX_IndexParamAudioAndroidAacDrcPresentation, /**< reference: OMX_AUDIO_PARAM_ANDROID_AACDRCPRESENTATIONTYPE */
+ OMX_IndexParamAudioAndroidAc4, /**< reference: OMX_AUDIO_PARAM_ANDROID_AC4TYPE */
+ OMX_IndexConfigAudioPresentation, /**< reference: OMX_AUDIO_CONFIG_ANDROID_AUDIOPRESENTATION */
OMX_IndexExtAudioEndUnused,
/* Image parameters and configurations */
diff --git a/include/android/multinetwork.h b/include/android/multinetwork.h
index 4d24680..fa7d908 100644
--- a/include/android/multinetwork.h
+++ b/include/android/multinetwork.h
@@ -110,6 +110,47 @@
#endif /* __ANDROID_API__ >= 23 */
+#if __ANDROID_API__ >= 29
+
+/**
+ * Look up the {|ns_class|, |ns_type|} Resource Record (RR) associated
+ * with Domain Name |dname| on the given |network|.
+ * The typical value for |ns_class| is ns_c_in, while |type| can be any
+ * record type (for instance, ns_t_aaaa or ns_t_txt).
+ *
+ * Returns a file descriptor to watch for read events, or a negative
+ * POSIX error code (see errno.h) if an immediate error occurs.
+ */
+int android_res_nquery(net_handle_t network,
+ const char *dname, int ns_class, int ns_type) __INTRODUCED_IN(29);
+
+/**
+ * Issue the query |msg| on the given |network|.
+ *
+ * Returns a file descriptor to watch for read events, or a negative
+ * POSIX error code (see errno.h) if an immediate error occurs.
+ */
+int android_res_nsend(net_handle_t network,
+ const uint8_t *msg, size_t msglen) __INTRODUCED_IN(29);
+
+/**
+ * Read a result for the query associated with the |fd| descriptor.
+ *
+ * Returns:
+ * < 0: negative POSIX error code (see errno.h for possible values). |rcode| is not set.
+ * >= 0: length of |answer|. |rcode| is the resolver return code (e.g., ns_r_nxdomain)
+ */
+int android_res_nresult(int fd,
+ int *rcode, uint8_t *answer, size_t anslen) __INTRODUCED_IN(29);
+
+/**
+ * Attempts to cancel the in-progress query associated with the |nsend_fd|
+ * descriptor.
+ */
+void android_res_cancel(int nsend_fd) __INTRODUCED_IN(29);
+
+#endif /* __ANDROID_API__ >= 29 */
+
__END_DECLS
#endif // ANDROID_MULTINETWORK_H
diff --git a/include/android/trace.h b/include/android/trace.h
index aa24995..bb7ff28 100644
--- a/include/android/trace.h
+++ b/include/android/trace.h
@@ -33,6 +33,7 @@
#define ANDROID_NATIVE_TRACE_H
#include <stdbool.h>
+#include <stdint.h>
#include <sys/cdefs.h>
#ifdef __cplusplus
@@ -73,6 +74,40 @@
#endif /* __ANDROID_API__ >= 23 */
+#if __ANDROID_API__ >= __ANDROID_API_Q__
+
+/**
+ * Writes a trace message to indicate that a given section of code has
+ * begun. Must be followed by a call to {@link ATrace_endAsyncSection} with the same
+ * methodName and cookie. Unlike {@link ATrace_beginSection} and {@link ATrace_endSection},
+ * asynchronous events do not need to be nested. The name and cookie used to
+ * begin an event must be used to end it.
+ *
+ * \param sectionName The method name to appear in the trace.
+ * \param cookie Unique identifier for distinguishing simultaneous events
+ */
+void ATrace_beginAsyncSection(const char* sectionName, int32_t cookie) __INTRODUCED_IN(29);
+
+/**
+ * Writes a trace message to indicate that the current method has ended.
+ * Must be called exactly once for each call to {@link ATrace_beginAsyncSection}
+ * using the same name and cookie.
+ *
+ * \param methodName The method name to appear in the trace.
+ * \param cookie Unique identifier for distinguishing simultaneous events
+ */
+void ATrace_endAsyncSection(const char* sectionName, int32_t cookie) __INTRODUCED_IN(29);
+
+/**
+ * Writes trace message to indicate the value of a given counter.
+ *
+ * \param counterName The counter name to appear in the trace.
+ * \param counterValue The counter value.
+ */
+void ATrace_setCounter(const char* counterName, int64_t counterValue) __INTRODUCED_IN(29);
+
+#endif /* __ANDROID_API__ >= 29 */
+
#ifdef __cplusplus
};
#endif
diff --git a/include/input/TouchVideoFrame.h b/include/input/TouchVideoFrame.h
new file mode 100644
index 0000000..d68f274
--- /dev/null
+++ b/include/input/TouchVideoFrame.h
@@ -0,0 +1,67 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+#ifndef _LIBINPUT_TOUCHVIDEOFRAME_H
+#define _LIBINPUT_TOUCHVIDEOFRAME_H
+
+#include <stdint.h>
+#include <sys/time.h>
+#include <vector>
+
+namespace android {
+
+/**
+ * Represents data from a single scan of the touchscreen device.
+ * Similar in concept to a video frame, but the touch strength is used as
+ * the values instead.
+ */
+class TouchVideoFrame {
+public:
+ TouchVideoFrame(uint32_t width, uint32_t height, std::vector<int16_t> data,
+ const struct timeval& timestamp) :
+ mWidth(width), mHeight(height), mData(std::move(data)), mTimestamp(timestamp) {
+ }
+
+ /**
+ * Width of the frame
+ */
+ uint32_t getWidth() const { return mWidth; }
+ /**
+ * Height of the frame
+ */
+ uint32_t getHeight() const { return mHeight; }
+ /**
+ * The touch strength data.
+ * The array is a 2-D row-major matrix, with dimensions (height, width).
+ * Total size of the array should equal getHeight() * getWidth().
+ * Data is allowed to be negative.
+ */
+ const std::vector<int16_t>& getData() const { return mData; }
+ /**
+ * Time at which the heatmap was taken.
+ */
+ const struct timeval& getTimestamp() const { return mTimestamp; }
+
+private:
+ uint32_t mWidth;
+ uint32_t mHeight;
+ std::vector<int16_t> mData;
+ struct timeval mTimestamp;
+};
+
+} // namespace android
+
+#endif // _LIBINPUT_TOUCHVIDEOFRAME_H
diff --git a/libs/binder/Parcel.cpp b/libs/binder/Parcel.cpp
index a0a634a..d285030 100644
--- a/libs/binder/Parcel.cpp
+++ b/libs/binder/Parcel.cpp
@@ -467,7 +467,6 @@
status_t Parcel::appendFrom(const Parcel *parcel, size_t offset, size_t len)
{
- const sp<ProcessState> proc(ProcessState::self());
status_t err;
const uint8_t *data = parcel->mData;
const binder_size_t *objects = parcel->mObjects;
@@ -520,6 +519,7 @@
err = NO_ERROR;
if (numObjects > 0) {
+ const sp<ProcessState> proc(ProcessState::self());
// grow objects
if (mObjectsCapacity < mObjectsSize + numObjects) {
size_t newSize = ((mObjectsSize + numObjects)*3)/2;
@@ -878,6 +878,16 @@
return writeNullableTypedVector(val, &Parcel::writeInt64);
}
+status_t Parcel::writeUint64Vector(const std::vector<uint64_t>& val)
+{
+ return writeTypedVector(val, &Parcel::writeUint64);
+}
+
+status_t Parcel::writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val)
+{
+ return writeNullableTypedVector(val, &Parcel::writeUint64);
+}
+
status_t Parcel::writeFloatVector(const std::vector<float>& val)
{
return writeTypedVector(val, &Parcel::writeFloat);
@@ -1739,6 +1749,14 @@
return readTypedVector(val, &Parcel::readInt64);
}
+status_t Parcel::readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const {
+ return readNullableTypedVector(val, &Parcel::readUint64);
+}
+
+status_t Parcel::readUint64Vector(std::vector<uint64_t>* val) const {
+ return readTypedVector(val, &Parcel::readUint64);
+}
+
status_t Parcel::readFloatVector(std::unique_ptr<std::vector<float>>* val) const {
return readNullableTypedVector(val, &Parcel::readFloat);
}
@@ -2559,8 +2577,11 @@
void Parcel::releaseObjects()
{
- const sp<ProcessState> proc(ProcessState::self());
size_t i = mObjectsSize;
+ if (i == 0) {
+ return;
+ }
+ sp<ProcessState> proc(ProcessState::self());
uint8_t* const data = mData;
binder_size_t* const objects = mObjects;
while (i > 0) {
@@ -2573,8 +2594,11 @@
void Parcel::acquireObjects()
{
- const sp<ProcessState> proc(ProcessState::self());
size_t i = mObjectsSize;
+ if (i == 0) {
+ return;
+ }
+ const sp<ProcessState> proc(ProcessState::self());
uint8_t* const data = mData;
binder_size_t* const objects = mObjects;
while (i > 0) {
diff --git a/libs/binder/include/binder/Parcel.h b/libs/binder/include/binder/Parcel.h
index c9c273a..cd151ee 100644
--- a/libs/binder/include/binder/Parcel.h
+++ b/libs/binder/include/binder/Parcel.h
@@ -139,6 +139,8 @@
status_t writeInt32Vector(const std::vector<int32_t>& val);
status_t writeInt64Vector(const std::unique_ptr<std::vector<int64_t>>& val);
status_t writeInt64Vector(const std::vector<int64_t>& val);
+ status_t writeUint64Vector(const std::unique_ptr<std::vector<uint64_t>>& val);
+ status_t writeUint64Vector(const std::vector<uint64_t>& val);
status_t writeFloatVector(const std::unique_ptr<std::vector<float>>& val);
status_t writeFloatVector(const std::vector<float>& val);
status_t writeDoubleVector(const std::unique_ptr<std::vector<double>>& val);
@@ -313,6 +315,8 @@
status_t readInt32Vector(std::vector<int32_t>* val) const;
status_t readInt64Vector(std::unique_ptr<std::vector<int64_t>>* val) const;
status_t readInt64Vector(std::vector<int64_t>* val) const;
+ status_t readUint64Vector(std::unique_ptr<std::vector<uint64_t>>* val) const;
+ status_t readUint64Vector(std::vector<uint64_t>* val) const;
status_t readFloatVector(std::unique_ptr<std::vector<float>>* val) const;
status_t readFloatVector(std::vector<float>* val) const;
status_t readDoubleVector(std::unique_ptr<std::vector<double>>* val) const;
diff --git a/libs/binder/ndk/Android.bp b/libs/binder/ndk/Android.bp
index d799c5f..1b69dfd 100644
--- a/libs/binder/ndk/Android.bp
+++ b/libs/binder/ndk/Android.bp
@@ -23,6 +23,8 @@
"include_apex",
],
+ cflags: ["-Wall", "-Wextra", "-Werror"],
+
srcs: [
"ibinder.cpp",
"ibinder_jni.cpp",
@@ -40,6 +42,10 @@
],
version_script: "libbinder_ndk.map.txt",
+ stubs: {
+ symbol_file: "libbinder_ndk.map.txt",
+ versions: ["29"],
+ },
}
ndk_headers {
diff --git a/libs/binder/ndk/include_ndk/android/binder_auto_utils.h b/libs/binder/ndk/include_ndk/android/binder_auto_utils.h
index c6fcaa4..ff1860e 100644
--- a/libs/binder/ndk/include_ndk/android/binder_auto_utils.h
+++ b/libs/binder/ndk/include_ndk/android/binder_auto_utils.h
@@ -163,9 +163,7 @@
ScopedAResource& operator=(ScopedAResource&&) = delete;
// move-constructing is okay
- ScopedAResource(ScopedAResource&& other) : mT(std::move(other.mT)) {
- other.mT = DEFAULT;
- }
+ ScopedAResource(ScopedAResource&& other) : mT(std::move(other.mT)) { other.mT = DEFAULT; }
private:
T mT;
diff --git a/libs/binder/ndk/include_ndk/android/binder_parcel.h b/libs/binder/ndk/include_ndk/android/binder_parcel.h
index 866af70..2258210 100644
--- a/libs/binder/ndk/include_ndk/android/binder_parcel.h
+++ b/libs/binder/ndk/include_ndk/android/binder_parcel.h
@@ -149,7 +149,49 @@
* not required to be null-terminated. If the object at index is null, then this should be null.
*/
typedef const char* (*AParcel_stringArrayElementGetter)(const void* arrayData, size_t index,
- size_t* outLength);
+ int32_t* outLength);
+
+/**
+ * This is called to allocate an array of size 'length'. If length is -1, then a 'null' array (or
+ * equivalent) should be created.
+ *
+ * See also AParcel_readParcelableArray
+ *
+ * \param arrayData some external representation of an array
+ * \param length the length to allocate this array to
+ *
+ * \return true if allocation succeeded. If length is -1, a true return here means that a 'null'
+ * value (or equivalent) was successfully stored.
+ */
+typedef bool (*AParcel_parcelableArrayAllocator)(void* arrayData, int32_t length);
+
+/**
+ * This is called to parcel the underlying data from an arrayData object at index.
+ *
+ * See also AParcel_writeParcelableArray
+ *
+ * \param parcel parcel to write the parcelable to
+ * \param arrayData some external representation of an array of parcelables (a user-defined type).
+ * \param index the index of the value to be retrieved.
+ *
+ * \return status (usually returned from other parceling functions). STATUS_OK for success.
+ */
+typedef binder_status_t (*AParcel_writeParcelableElement)(AParcel* parcel, const void* arrayData,
+ size_t index);
+
+/**
+ * This is called to set an underlying value in an arrayData object at index.
+ *
+ * See also AParcel_readParcelableArray
+ *
+ * \param parcel parcel to read the parcelable from
+ * \param arrayData some external representation of an array of parcelables (a user-defined type).
+ * \param index the index of the value to be set.
+ *
+ * \return status (usually returned from other parceling functions). STATUS_OK for success.
+ */
+typedef binder_status_t (*AParcel_readParcelableElement)(const AParcel* parcel, void* arrayData,
+ size_t index);
// @START-PRIMITIVE-VECTOR-GETTERS
/**
@@ -497,6 +539,40 @@
AParcel_stringArrayElementAllocator elementAllocator)
__INTRODUCED_IN(29);
+/**
+ * Writes an array of parcelables (user-defined types) to the next location in a non-null parcel.
+ *
+ * \param parcel the parcel to write to.
+ * \param arrayData an array of size 'length' (or null if length is -1, may be null if length is 0).
+ * \param length the length of arrayData or -1 if this represents a null array.
+ * \param elementWriter function to be called for every array index to write the user-defined type
+ * at that location.
+ *
+ * \return STATUS_OK on successful write.
+ */
+binder_status_t AParcel_writeParcelableArray(AParcel* parcel, const void* arrayData, int32_t length,
+ AParcel_writeParcelableElement elementWriter)
+ __INTRODUCED_IN(29);
+
+/**
+ * Reads an array of parcelables (user-defined types) from the next location in a non-null parcel.
+ *
+ * First, allocator will be called with the length of the array. If the allocation succeeds and the
+ * length is greater than zero, elementReader will be called for every index to read the
+ * corresponding parcelable.
+ *
+ * \param parcel the parcel to read from.
+ * \param arrayData some external representation of an array.
+ * \param allocator the callback that will be called to allocate the array.
+ * \param elementReader the callback that will be called to fill out individual elements.
+ *
+ * \return STATUS_OK on successful read.
+ */
+binder_status_t AParcel_readParcelableArray(const AParcel* parcel, void* arrayData,
+ AParcel_parcelableArrayAllocator allocator,
+ AParcel_readParcelableElement elementReader)
+ __INTRODUCED_IN(29);
+
// @START-PRIMITIVE-READ-WRITE
/**
* Writes int32_t value to the next location in a non-null parcel.
diff --git a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
index f99c3a9..f3bc31b 100644
--- a/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
+++ b/libs/binder/ndk/include_ndk/android/binder_parcel_utils.h
@@ -43,7 +43,7 @@
if (length < 0) return false;
std::vector<T>* vec = static_cast<std::vector<T>*>(vectorData);
- if (length > vec->max_size()) return false;
+ if (static_cast<size_t>(length) > vec->max_size()) return false;
vec->resize(length);
*outBuffer = vec->data();
@@ -65,7 +65,7 @@
*vec = std::optional<std::vector<T>>(std::vector<T>{});
- if (length > (*vec)->max_size()) return false;
+ if (static_cast<size_t>(length) > (*vec)->max_size()) return false;
(*vec)->resize(length);
*outBuffer = (*vec)->data();
@@ -88,7 +88,7 @@
if (length < 0) return false;
std::vector<T>* vec = static_cast<std::vector<T>*>(vectorData);
- if (length > vec->max_size()) return false;
+ if (static_cast<size_t>(length) > vec->max_size()) return false;
vec->resize(length);
return true;
@@ -116,7 +116,7 @@
*vec = std::optional<std::vector<T>>(std::vector<T>{});
- if (length > (*vec)->max_size()) return false;
+ if (static_cast<size_t>(length) > (*vec)->max_size()) return false;
(*vec)->resize(length);
return true;
@@ -299,7 +299,7 @@
* index.
*/
static inline const char* AParcel_stdVectorStringElementGetter(const void* vectorData, size_t index,
- size_t* outLength) {
+ int32_t* outLength) {
const std::vector<std::string>* vec = static_cast<const std::vector<std::string>*>(vectorData);
const std::string& element = vec->at(index);
@@ -327,7 +327,7 @@
*/
static inline const char* AParcel_nullableStdVectorStringElementGetter(const void* vectorData,
size_t index,
- size_t* outLength) {
+ int32_t* outLength) {
const std::optional<std::vector<std::optional<std::string>>>* vec =
static_cast<const std::optional<std::vector<std::optional<std::string>>>*>(vectorData);
const std::optional<std::string>& element = vec->value().at(index);
@@ -420,6 +420,46 @@
AParcel_nullableStdVectorStringElementAllocator);
}
+/**
+ * Writes a parcelable object of type P inside a std::vector<P> at index 'index' to 'parcel'.
+ */
+template <typename P>
+binder_status_t AParcel_writeStdVectorParcelableElement(AParcel* parcel, const void* vectorData,
+ size_t index) {
+ const std::vector<P>* vector = static_cast<const std::vector<P>*>(vectorData);
+ return vector->at(index).writeToParcel(parcel);
+}
+
+/**
+ * Reads a parcelable object of type P inside a std::vector<P> at index 'index' from 'parcel'.
+ */
+template <typename P>
+binder_status_t AParcel_readStdVectorParcelableElement(const AParcel* parcel, void* vectorData,
+ size_t index) {
+ std::vector<P>* vector = static_cast<std::vector<P>*>(vectorData);
+ return vector->at(index).readFromParcel(parcel);
+}
+
+/**
+ * Convenience API for writing a std::vector<P>
+ */
+template <typename P>
+static inline binder_status_t AParcel_writeVector(AParcel* parcel, const std::vector<P>& vec) {
+ const void* vectorData = static_cast<const void*>(&vec);
+ return AParcel_writeParcelableArray(parcel, vectorData, vec.size(),
+ AParcel_writeStdVectorParcelableElement<P>);
+}
+
+/**
+ * Convenience API for reading a std::vector<P>
+ */
+template <typename P>
+static inline binder_status_t AParcel_readVector(const AParcel* parcel, std::vector<P>* vec) {
+ void* vectorData = static_cast<void*>(vec);
+ return AParcel_readParcelableArray(parcel, vectorData, AParcel_stdVectorExternalAllocator<P>,
+ AParcel_readStdVectorParcelableElement<P>);
+}
+
// @START
/**
* Writes a vector of int32_t to the next location in a non-null parcel.
diff --git a/libs/binder/ndk/libbinder_ndk.map.txt b/libs/binder/ndk/libbinder_ndk.map.txt
index 4328b6e..ee7132f 100644
--- a/libs/binder/ndk/libbinder_ndk.map.txt
+++ b/libs/binder/ndk/libbinder_ndk.map.txt
@@ -40,6 +40,7 @@
AParcel_readInt32Array;
AParcel_readInt64;
AParcel_readInt64Array;
+ AParcel_readParcelableArray;
AParcel_readParcelFileDescriptor;
AParcel_readStatusHeader;
AParcel_readString;
@@ -64,6 +65,7 @@
AParcel_writeInt32Array;
AParcel_writeInt64;
AParcel_writeInt64Array;
+ AParcel_writeParcelableArray;
AParcel_writeParcelFileDescriptor;
AParcel_writeStatusHeader;
AParcel_writeString;
diff --git a/libs/binder/ndk/parcel.cpp b/libs/binder/ndk/parcel.cpp
index 2d68559..ae2276e 100644
--- a/libs/binder/ndk/parcel.cpp
+++ b/libs/binder/ndk/parcel.cpp
@@ -173,7 +173,7 @@
Parcel* rawParcel = parcel->get();
- for (size_t i = 0; i < length; i++) {
+ for (int32_t i = 0; i < length; i++) {
status = (rawParcel->*write)(getter(arrayData, i));
if (status != STATUS_OK) return PruneStatusT(status);
@@ -197,7 +197,7 @@
if (length <= 0) return STATUS_OK;
- for (size_t i = 0; i < length; i++) {
+ for (int32_t i = 0; i < length; i++) {
T readTarget;
status = (rawParcel->*read)(&readTarget);
if (status != STATUS_OK) return PruneStatusT(status);
@@ -376,12 +376,12 @@
if (status != STATUS_OK) return status;
if (length <= 0) return STATUS_OK;
- for (size_t i = 0; i < length; i++) {
- size_t length = 0;
- const char* str = getter(arrayData, i, &length);
- if (str == nullptr && length != -1) return STATUS_BAD_VALUE;
+ for (int32_t i = 0; i < length; i++) {
+ int32_t elementLength = 0;
+ const char* str = getter(arrayData, i, &elementLength);
+ if (str == nullptr && elementLength != -1) return STATUS_BAD_VALUE;
- binder_status_t status = AParcel_writeString(parcel, str, length);
+ binder_status_t status = AParcel_writeString(parcel, str, elementLength);
if (status != STATUS_OK) return status;
}
@@ -392,7 +392,7 @@
// allocator.
struct StringArrayElementAllocationAdapter {
void* arrayData; // stringData from the NDK
- size_t index; // index into the string array
+ int32_t index; // index into the string array
AParcel_stringArrayElementAllocator elementAllocator;
static bool Allocator(void* stringData, int32_t length, char** buffer) {
@@ -433,6 +433,45 @@
return STATUS_OK;
}
+binder_status_t AParcel_writeParcelableArray(AParcel* parcel, const void* arrayData, int32_t length,
+ AParcel_writeParcelableElement elementWriter) {
+ // we have no clue if arrayData represents a null object or not, we can only infer from length
+ bool arrayIsNull = length < 0;
+ binder_status_t status = WriteAndValidateArraySize(parcel, arrayIsNull, length);
+ if (status != STATUS_OK) return status;
+ if (length <= 0) return STATUS_OK;
+
+ for (int32_t i = 0; i < length; i++) {
+ binder_status_t status = elementWriter(parcel, arrayData, i);
+ if (status != STATUS_OK) return status;
+ }
+
+ return STATUS_OK;
+}
+
+binder_status_t AParcel_readParcelableArray(const AParcel* parcel, void* arrayData,
+ AParcel_parcelableArrayAllocator allocator,
+ AParcel_readParcelableElement elementReader) {
+ const Parcel* rawParcel = parcel->get();
+
+ int32_t length;
+ status_t status = rawParcel->readInt32(&length);
+
+ if (status != STATUS_OK) return PruneStatusT(status);
+ if (length < -1) return STATUS_BAD_VALUE;
+
+ if (!allocator(arrayData, length)) return STATUS_NO_MEMORY;
+
+ if (length == -1) return STATUS_OK; // null array
+
+ for (int32_t i = 0; i < length; i++) {
+ binder_status_t status = elementReader(parcel, arrayData, i);
+ if (status != STATUS_OK) return status;
+ }
+
+ return STATUS_OK;
+}
+
// See gen_parcel_helper.py. These auto-generated read/write methods use the same types for
// libbinder and this library.
// @START
diff --git a/libs/binder/tests/binderLibTest.cpp b/libs/binder/tests/binderLibTest.cpp
index cd37d49..ae04b0f 100644
--- a/libs/binder/tests/binderLibTest.cpp
+++ b/libs/binder/tests/binderLibTest.cpp
@@ -72,6 +72,7 @@
BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
+ BINDER_LIB_TEST_ECHO_VECTOR,
};
pid_t start_server_process(int arg2, bool usePoll = false)
@@ -1060,6 +1061,21 @@
EXPECT_EQ(NO_ERROR, ret2);
}
+TEST_F(BinderLibTest, VectorSent) {
+ Parcel data, reply;
+ sp<IBinder> server = addServer();
+ ASSERT_TRUE(server != nullptr);
+
+ std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
+ data.writeUint64Vector(testValue);
+
+ status_t ret = server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply);
+ EXPECT_EQ(NO_ERROR, ret);
+ std::vector<uint64_t> readValue;
+ ret = reply.readUint64Vector(&readValue);
+ EXPECT_EQ(readValue, testValue);
+}
+
class BinderLibTestService : public BBinder
{
public:
@@ -1363,6 +1379,14 @@
reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
return NO_ERROR;
}
+ case BINDER_LIB_TEST_ECHO_VECTOR: {
+ std::vector<uint64_t> vector;
+ auto err = data.readUint64Vector(&vector);
+ if (err != NO_ERROR)
+ return err;
+ reply->writeUint64Vector(vector);
+ return NO_ERROR;
+ }
default:
return UNKNOWN_TRANSACTION;
};
@@ -1422,7 +1446,7 @@
}
IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
- epoll_fd = epoll_create1(0);
+ epoll_fd = epoll_create1(EPOLL_CLOEXEC);
if (epoll_fd == -1) {
return 1;
}
diff --git a/libs/binder/tests/binderValueTypeTest.cpp b/libs/binder/tests/binderValueTypeTest.cpp
index 15949d4..f8922b0 100644
--- a/libs/binder/tests/binderValueTypeTest.cpp
+++ b/libs/binder/tests/binderValueTypeTest.cpp
@@ -75,13 +75,13 @@
VALUE_TYPE_TEST(bool, Boolean, true)
VALUE_TYPE_TEST(int32_t, Int, 31337)
-VALUE_TYPE_TEST(int64_t, Long, 13370133701337l)
+VALUE_TYPE_TEST(int64_t, Long, 13370133701337L)
VALUE_TYPE_TEST(double, Double, 3.14159265358979323846)
VALUE_TYPE_TEST(String16, String, String16("Lovely"))
VALUE_TYPE_VECTOR_TEST(bool, Boolean, true)
VALUE_TYPE_VECTOR_TEST(int32_t, Int, 31337)
-VALUE_TYPE_VECTOR_TEST(int64_t, Long, 13370133701337l)
+VALUE_TYPE_VECTOR_TEST(int64_t, Long, 13370133701337L)
VALUE_TYPE_VECTOR_TEST(double, Double, 3.14159265358979323846)
VALUE_TYPE_VECTOR_TEST(String16, String, String16("Lovely"))
diff --git a/libs/graphicsenv/GraphicsEnv.cpp b/libs/graphicsenv/GraphicsEnv.cpp
index c2a6764..dfdda0c 100644
--- a/libs/graphicsenv/GraphicsEnv.cpp
+++ b/libs/graphicsenv/GraphicsEnv.cpp
@@ -135,8 +135,8 @@
}
void GraphicsEnv::setAngleInfo(const std::string path, const std::string appName,
- bool developerOptIn, const int rulesFd, const long rulesOffset,
- const long rulesLength) {
+ const std::string developerOptIn, const int rulesFd,
+ const long rulesOffset, const long rulesLength) {
if (!mAnglePath.empty()) {
ALOGV("ignoring attempt to change ANGLE path from '%s' to '%s'", mAnglePath.c_str(),
path.c_str());
@@ -153,7 +153,13 @@
mAngleAppName = appName;
}
- mAngleDeveloperOptIn = developerOptIn;
+ if (!mAngleDeveloperOptIn.empty()) {
+ ALOGV("ignoring attempt to change ANGLE application opt-in from '%s' to '%s'",
+ mAngleDeveloperOptIn.c_str(), developerOptIn.c_str());
+ } else {
+ ALOGV("setting ANGLE application opt-in to '%s'", developerOptIn.c_str());
+ mAngleDeveloperOptIn = developerOptIn;
+ }
ALOGV("setting ANGLE rules file descriptor to '%i'", rulesFd);
mAngleRulesFd = rulesFd;
@@ -182,8 +188,8 @@
return mAngleAppName.c_str();
}
-bool GraphicsEnv::getAngleDeveloperOptIn() {
- return mAngleDeveloperOptIn;
+const char* GraphicsEnv::getAngleDeveloperOptIn() {
+ return mAngleDeveloperOptIn.c_str();
}
int GraphicsEnv::getAngleRulesFd() {
diff --git a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
index 20e4d66..4ec53f1 100644
--- a/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
+++ b/libs/graphicsenv/include/graphicsenv/GraphicsEnv.h
@@ -44,12 +44,12 @@
// (libraries must be stored uncompressed and page aligned); such elements
// in the search path must have a '!' after the zip filename, e.g.
// /system/app/ANGLEPrebuilt/ANGLEPrebuilt.apk!/lib/arm64-v8a
- void setAngleInfo(const std::string path, const std::string appName, bool devOptIn,
+ void setAngleInfo(const std::string path, const std::string appName, std::string devOptIn,
const int rulesFd, const long rulesOffset, const long rulesLength);
android_namespace_t* getAngleNamespace();
const char* getAngleAppName();
const char* getAngleAppPref();
- bool getAngleDeveloperOptIn();
+ const char* getAngleDeveloperOptIn();
int getAngleRulesFd();
long getAngleRulesOffset();
long getAngleRulesLength();
@@ -69,7 +69,7 @@
std::string mDriverPath;
std::string mAnglePath;
std::string mAngleAppName;
- bool mAngleDeveloperOptIn;
+ std::string mAngleDeveloperOptIn;
int mAngleRulesFd;
long mAngleRulesOffset;
long mAngleRulesLength;
diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp
index 127fcd6..d1c732b 100644
--- a/libs/gui/Android.bp
+++ b/libs/gui/Android.bp
@@ -31,7 +31,6 @@
"-Werror",
],
cppflags: [
- "-std=c++1z",
"-Weverything",
// The static constructors and destructors in this library have not been noted to
@@ -123,6 +122,7 @@
shared_libs: [
"android.hardware.graphics.common@1.1",
+ "libbase",
"libsync",
"libbinder",
"libbufferhub",
diff --git a/libs/gui/BufferHubProducer.cpp b/libs/gui/BufferHubProducer.cpp
index ed773e0..16952a6 100644
--- a/libs/gui/BufferHubProducer.cpp
+++ b/libs/gui/BufferHubProducer.cpp
@@ -520,7 +520,7 @@
}
auto buffer_producer = buffers_[slot].mBufferProducer;
- queue_->Enqueue(buffer_producer, size_t(slot), 0ULL);
+ queue_->Enqueue(buffer_producer, size_t(slot), 0U);
buffers_[slot].mBufferState.cancel();
buffers_[slot].mFence = fence;
ALOGV("cancelBuffer: slot %d", slot);
diff --git a/libs/gui/FrameTimestamps.cpp b/libs/gui/FrameTimestamps.cpp
index 85ae433..96e9a85 100644
--- a/libs/gui/FrameTimestamps.cpp
+++ b/libs/gui/FrameTimestamps.cpp
@@ -18,10 +18,10 @@
#define LOG_TAG "FrameEvents"
+#include <android-base/stringprintf.h>
#include <cutils/compiler.h> // For CC_[UN]LIKELY
#include <inttypes.h>
#include <utils/Log.h>
-#include <utils/String8.h>
#include <algorithm>
#include <limits>
@@ -29,6 +29,7 @@
namespace android {
+using base::StringAppendF;
// ============================================================================
// FrameEvents
@@ -86,50 +87,49 @@
releaseFence->getSignalTime();
}
-static void dumpFenceTime(String8& outString, const char* name,
- bool pending, const FenceTime& fenceTime) {
- outString.appendFormat("--- %s", name);
+static void dumpFenceTime(std::string& outString, const char* name, bool pending,
+ const FenceTime& fenceTime) {
+ StringAppendF(&outString, "--- %s", name);
nsecs_t signalTime = fenceTime.getCachedSignalTime();
if (Fence::isValidTimestamp(signalTime)) {
- outString.appendFormat("%" PRId64 "\n", signalTime);
+ StringAppendF(&outString, "%" PRId64 "\n", signalTime);
} else if (pending || signalTime == Fence::SIGNAL_TIME_PENDING) {
- outString.appendFormat("Pending\n");
+ outString.append("Pending\n");
} else if (&fenceTime == FenceTime::NO_FENCE.get()){
- outString.appendFormat("N/A\n");
+ outString.append("N/A\n");
} else {
- outString.appendFormat("Error\n");
+ outString.append("Error\n");
}
}
-void FrameEvents::dump(String8& outString) const
-{
+void FrameEvents::dump(std::string& outString) const {
if (!valid) {
return;
}
- outString.appendFormat("-- Frame %" PRIu64 "\n", frameNumber);
- outString.appendFormat("--- Posted \t%" PRId64 "\n", postedTime);
- outString.appendFormat("--- Req. Present\t%" PRId64 "\n", requestedPresentTime);
+ StringAppendF(&outString, "-- Frame %" PRIu64 "\n", frameNumber);
+ StringAppendF(&outString, "--- Posted \t%" PRId64 "\n", postedTime);
+ StringAppendF(&outString, "--- Req. Present\t%" PRId64 "\n", requestedPresentTime);
- outString.appendFormat("--- Latched \t");
+ outString.append("--- Latched \t");
if (FrameEvents::isValidTimestamp(latchTime)) {
- outString.appendFormat("%" PRId64 "\n", latchTime);
+ StringAppendF(&outString, "%" PRId64 "\n", latchTime);
} else {
- outString.appendFormat("Pending\n");
+ outString.append("Pending\n");
}
- outString.appendFormat("--- Refresh (First)\t");
+ outString.append("--- Refresh (First)\t");
if (FrameEvents::isValidTimestamp(firstRefreshStartTime)) {
- outString.appendFormat("%" PRId64 "\n", firstRefreshStartTime);
+ StringAppendF(&outString, "%" PRId64 "\n", firstRefreshStartTime);
} else {
- outString.appendFormat("Pending\n");
+ outString.append("Pending\n");
}
- outString.appendFormat("--- Refresh (Last)\t");
+ outString.append("--- Refresh (Last)\t");
if (FrameEvents::isValidTimestamp(lastRefreshStartTime)) {
- outString.appendFormat("%" PRId64 "\n", lastRefreshStartTime);
+ StringAppendF(&outString, "%" PRId64 "\n", lastRefreshStartTime);
} else {
- outString.appendFormat("Pending\n");
+ outString.append("Pending\n");
}
dumpFenceTime(outString, "Acquire \t",
@@ -139,11 +139,11 @@
dumpFenceTime(outString, "Display Present \t",
!addPostCompositeCalled, *displayPresentFence);
- outString.appendFormat("--- DequeueReady \t");
+ outString.append("--- DequeueReady \t");
if (FrameEvents::isValidTimestamp(dequeueReadyTime)) {
- outString.appendFormat("%" PRId64 "\n", dequeueReadyTime);
+ StringAppendF(&outString, "%" PRId64 "\n", dequeueReadyTime);
} else {
- outString.appendFormat("Pending\n");
+ outString.append("Pending\n");
}
dumpFenceTime(outString, "Release \t",
@@ -206,11 +206,11 @@
return lhs.valid;
}
-void FrameEventHistory::dump(String8& outString) const {
+void FrameEventHistory::dump(std::string& outString) const {
auto earliestFrame = std::min_element(
mFrames.begin(), mFrames.end(), &FrameNumberLessThan);
if (!earliestFrame->valid) {
- outString.appendFormat("-- N/A\n");
+ outString.append("-- N/A\n");
return;
}
for (auto frame = earliestFrame; frame != mFrames.end(); ++frame) {
diff --git a/libs/gui/GuiConfig.cpp b/libs/gui/GuiConfig.cpp
index bc0c83c..3ec20ee 100644
--- a/libs/gui/GuiConfig.cpp
+++ b/libs/gui/GuiConfig.cpp
@@ -18,8 +18,7 @@
namespace android {
-void appendGuiConfigString(String8& configStr)
-{
+void appendGuiConfigString(std::string& configStr) {
static const char* config =
" [libgui"
#ifdef DONT_USE_FENCE_SYNC
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index 7d26151..2d6be26 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -651,6 +651,45 @@
&reply);
return result;
}
+
+ virtual status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
+ uint64_t timestamp,
+ DisplayedFrameStats* outStats) const {
+ if (!outStats) return BAD_VALUE;
+
+ Parcel data, reply;
+ data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
+ data.writeStrongBinder(display);
+ data.writeUint64(maxFrames);
+ data.writeUint64(timestamp);
+
+ status_t result =
+ remote()->transact(BnSurfaceComposer::GET_DISPLAYED_CONTENT_SAMPLE, data, &reply);
+
+ if (result != NO_ERROR) {
+ return result;
+ }
+
+ result = reply.readUint64(&outStats->numFrames);
+ if (result != NO_ERROR) {
+ return result;
+ }
+
+ result = reply.readUint64Vector(&outStats->component_0_sample);
+ if (result != NO_ERROR) {
+ return result;
+ }
+ result = reply.readUint64Vector(&outStats->component_1_sample);
+ if (result != NO_ERROR) {
+ return result;
+ }
+ result = reply.readUint64Vector(&outStats->component_2_sample);
+ if (result != NO_ERROR) {
+ return result;
+ }
+ result = reply.readUint64Vector(&outStats->component_3_sample);
+ return result;
+ }
};
// Out-of-line virtual method definition to trigger vtable emission in this
@@ -990,7 +1029,7 @@
reply->writeInt32(static_cast<int32_t>(defaultDataspace));
reply->writeInt32(static_cast<int32_t>(defaultPixelFormat));
reply->writeInt32(static_cast<int32_t>(wideColorGamutDataspace));
- reply->writeInt32(static_cast<int32_t>(wideColorGamutDataspace));
+ reply->writeInt32(static_cast<int32_t>(wideColorGamutPixelFormat));
}
return NO_ERROR;
}
@@ -1055,6 +1094,36 @@
return setDisplayContentSamplingEnabled(display, enable,
static_cast<uint8_t>(componentMask), maxFrames);
}
+ case GET_DISPLAYED_CONTENT_SAMPLE: {
+ CHECK_INTERFACE(ISurfaceComposer, data, reply);
+
+ sp<IBinder> display = data.readStrongBinder();
+ uint64_t maxFrames = 0;
+ uint64_t timestamp = 0;
+
+ status_t result = data.readUint64(&maxFrames);
+ if (result != NO_ERROR) {
+ ALOGE("getDisplayedContentSample failure in reading max frames: %d", result);
+ return result;
+ }
+
+ result = data.readUint64(×tamp);
+ if (result != NO_ERROR) {
+ ALOGE("getDisplayedContentSample failure in reading timestamp: %d", result);
+ return result;
+ }
+
+ DisplayedFrameStats stats;
+ result = getDisplayedContentSample(display, maxFrames, timestamp, &stats);
+ if (result == NO_ERROR) {
+ reply->writeUint64(stats.numFrames);
+ reply->writeUint64Vector(stats.component_0_sample);
+ reply->writeUint64Vector(stats.component_1_sample);
+ reply->writeUint64Vector(stats.component_2_sample);
+ reply->writeUint64Vector(stats.component_3_sample);
+ }
+ return result;
+ }
default: {
return BBinder::onTransact(code, data, reply, flags);
}
diff --git a/libs/gui/ITransactionCompletedListener.cpp b/libs/gui/ITransactionCompletedListener.cpp
index 95b1038..1be55e6 100644
--- a/libs/gui/ITransactionCompletedListener.cpp
+++ b/libs/gui/ITransactionCompletedListener.cpp
@@ -59,7 +59,15 @@
if (err != NO_ERROR) {
return err;
}
- err = output->writeInt64(presentTime);
+ if (presentFence) {
+ err = output->writeBool(true);
+ if (err != NO_ERROR) {
+ return err;
+ }
+ err = output->write(*presentFence);
+ } else {
+ err = output->writeBool(false);
+ }
if (err != NO_ERROR) {
return err;
}
@@ -71,10 +79,18 @@
if (err != NO_ERROR) {
return err;
}
- err = input->readInt64(&presentTime);
+ bool hasFence = false;
+ err = input->readBool(&hasFence);
if (err != NO_ERROR) {
return err;
}
+ if (hasFence) {
+ presentFence = new Fence();
+ err = input->read(*presentFence);
+ if (err != NO_ERROR) {
+ return err;
+ }
+ }
return input->readParcelableVector(&surfaceStats);
}
diff --git a/libs/gui/LayerDebugInfo.cpp b/libs/gui/LayerDebugInfo.cpp
index ccde9e0..cdde9a2 100644
--- a/libs/gui/LayerDebugInfo.cpp
+++ b/libs/gui/LayerDebugInfo.cpp
@@ -16,13 +16,14 @@
#include <gui/LayerDebugInfo.h>
+#include <android-base/stringprintf.h>
+
#include <ui/DebugUtils.h>
#include <binder/Parcel.h>
-#include <utils/String8.h>
-
using namespace android;
+using android::base::StringAppendF;
#define RETURN_ON_ERROR(X) do {status_t res = (X); if (res != NO_ERROR) return res;} while(false)
@@ -108,38 +109,37 @@
}
std::string to_string(const LayerDebugInfo& info) {
- String8 result;
+ std::string result;
- result.appendFormat("+ %s (%s)\n", info.mType.c_str(), info.mName.c_str());
+ StringAppendF(&result, "+ %s (%s)\n", info.mType.c_str(), info.mName.c_str());
info.mTransparentRegion.dump(result, "TransparentRegion");
info.mVisibleRegion.dump(result, "VisibleRegion");
info.mSurfaceDamageRegion.dump(result, "SurfaceDamageRegion");
- result.appendFormat(" layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), ",
- info.mLayerStack, info.mZ, static_cast<double>(info.mX), static_cast<double>(info.mY),
- info.mWidth, info.mHeight);
+ StringAppendF(&result, " layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), ",
+ info.mLayerStack, info.mZ, static_cast<double>(info.mX),
+ static_cast<double>(info.mY), info.mWidth, info.mHeight);
- result.appendFormat("crop=%s, ", to_string(info.mCrop).c_str());
- result.appendFormat("isOpaque=%1d, invalidate=%1d, ", info.mIsOpaque, info.mContentDirty);
- result.appendFormat("dataspace=%s, ", dataspaceDetails(info.mDataSpace).c_str());
- result.appendFormat("pixelformat=%s, ", decodePixelFormat(info.mPixelFormat).c_str());
- result.appendFormat("color=(%.3f,%.3f,%.3f,%.3f), flags=0x%08x, ",
- static_cast<double>(info.mColor.r), static_cast<double>(info.mColor.g),
- static_cast<double>(info.mColor.b), static_cast<double>(info.mColor.a),
- info.mFlags);
- result.appendFormat("tr=[%.2f, %.2f][%.2f, %.2f]",
- static_cast<double>(info.mMatrix[0][0]), static_cast<double>(info.mMatrix[0][1]),
- static_cast<double>(info.mMatrix[1][0]), static_cast<double>(info.mMatrix[1][1]));
+ StringAppendF(&result, "crop=%s, ", to_string(info.mCrop).c_str());
+ StringAppendF(&result, "isOpaque=%1d, invalidate=%1d, ", info.mIsOpaque, info.mContentDirty);
+ StringAppendF(&result, "dataspace=%s, ", dataspaceDetails(info.mDataSpace).c_str());
+ StringAppendF(&result, "pixelformat=%s, ", decodePixelFormat(info.mPixelFormat).c_str());
+ StringAppendF(&result, "color=(%.3f,%.3f,%.3f,%.3f), flags=0x%08x, ",
+ static_cast<double>(info.mColor.r), static_cast<double>(info.mColor.g),
+ static_cast<double>(info.mColor.b), static_cast<double>(info.mColor.a),
+ info.mFlags);
+ StringAppendF(&result, "tr=[%.2f, %.2f][%.2f, %.2f]", static_cast<double>(info.mMatrix[0][0]),
+ static_cast<double>(info.mMatrix[0][1]), static_cast<double>(info.mMatrix[1][0]),
+ static_cast<double>(info.mMatrix[1][1]));
result.append("\n");
- result.appendFormat(" parent=%s\n", info.mParentName.c_str());
- result.appendFormat(" activeBuffer=[%4ux%4u:%4u,%s],",
- info.mActiveBufferWidth, info.mActiveBufferHeight,
- info.mActiveBufferStride,
- decodePixelFormat(info.mActiveBufferFormat).c_str());
- result.appendFormat(" queued-frames=%d, mRefreshPending=%d",
- info.mNumQueuedFrames, info.mRefreshPending);
+ StringAppendF(&result, " parent=%s\n", info.mParentName.c_str());
+ StringAppendF(&result, " activeBuffer=[%4ux%4u:%4u,%s],", info.mActiveBufferWidth,
+ info.mActiveBufferHeight, info.mActiveBufferStride,
+ decodePixelFormat(info.mActiveBufferFormat).c_str());
+ StringAppendF(&result, " queued-frames=%d, mRefreshPending=%d", info.mNumQueuedFrames,
+ info.mRefreshPending);
result.append("\n");
- return std::string(result.c_str());
+ return result;
}
} // android
diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp
index 407eecb..35ce6e3 100644
--- a/libs/gui/LayerState.cpp
+++ b/libs/gui/LayerState.cpp
@@ -16,6 +16,8 @@
#define LOG_TAG "LayerState"
+#include <inttypes.h>
+
#include <utils/Errors.h>
#include <binder/Parcel.h>
#include <gui/ISurfaceComposerClient.h>
@@ -27,7 +29,7 @@
status_t layer_state_t::write(Parcel& output) const
{
output.writeStrongBinder(surface);
- output.writeUint32(what);
+ output.writeUint64(what);
output.writeFloat(x);
output.writeFloat(y);
output.writeInt32(z);
@@ -57,6 +59,7 @@
output.writeUint32(transform);
output.writeBool(transformToDisplayInverse);
output.write(crop);
+ output.write(frame);
if (buffer) {
output.writeBool(true);
output.write(*buffer);
@@ -97,7 +100,7 @@
status_t layer_state_t::read(const Parcel& input)
{
surface = input.readStrongBinder();
- what = input.readUint32();
+ what = input.readUint64();
x = input.readFloat();
y = input.readFloat();
z = input.readInt32();
@@ -133,6 +136,7 @@
transform = input.readUint32();
transformToDisplayInverse = input.readBool();
input.read(crop);
+ input.read(frame);
buffer = new GraphicBuffer();
if (input.readBool()) {
input.read(*buffer);
@@ -320,6 +324,10 @@
what |= eCropChanged;
crop = other.crop;
}
+ if (other.what & eFrameChanged) {
+ what |= eFrameChanged;
+ frame = other.frame;
+ }
if (other.what & eBufferChanged) {
what |= eBufferChanged;
buffer = other.buffer;
@@ -366,7 +374,7 @@
if ((other.what & what) != other.what) {
ALOGE("Unmerged SurfaceComposer Transaction properties. LayerState::merge needs updating? "
- "other.what=0x%X what=0x%X",
+ "other.what=0x%" PRIu64 " what=0x%" PRIu64,
other.what, what);
}
}
diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp
index 405d228..9586219 100644
--- a/libs/gui/SurfaceComposerClient.cpp
+++ b/libs/gui/SurfaceComposerClient.cpp
@@ -609,6 +609,20 @@
return *this;
}
+SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrame(
+ const sp<SurfaceControl>& sc, const Rect& frame) {
+ layer_state_t* s = getLayerState(sc);
+ if (!s) {
+ mStatus = BAD_INDEX;
+ return *this;
+ }
+ s->what |= layer_state_t::eFrameChanged;
+ s->frame = frame;
+
+ registerSurfaceControlForCallback(sc);
+ return *this;
+}
+
SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setBuffer(
const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer) {
layer_state_t* s = getLayerState(sc);
@@ -1106,6 +1120,12 @@
maxFrames);
}
+status_t SurfaceComposerClient::getDisplayedContentSample(const sp<IBinder>& display,
+ uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats) {
+ return ComposerService::getComposerService()->getDisplayedContentSample(display, maxFrames,
+ timestamp, outStats);
+}
// ----------------------------------------------------------------------------
status_t ScreenshotClient::capture(const sp<IBinder>& display, const ui::Dataspace reqDataSpace,
diff --git a/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp b/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
index 8af1a67..e64ba9b 100644
--- a/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
+++ b/libs/gui/bufferqueue/1.0/H2BGraphicBufferProducer.cpp
@@ -901,7 +901,7 @@
int const* constFds = static_cast<int const*>(baseFds.get());
numFds = baseNumFds;
if (l->unflatten(constBuffer, size, constFds, numFds) != NO_ERROR) {
- for (auto nhA : nhAA) {
+ for (const auto& nhA : nhAA) {
for (auto nh : nhA) {
if (nh != nullptr) {
native_handle_close(nh);
@@ -912,8 +912,8 @@
return false;
}
- for (auto nhA : nhAA) {
- for (auto nh : nhA) {
+ for (const auto& nhA : nhAA) {
+ for (const auto& nh : nhA) {
if (nh != nullptr) {
native_handle_delete(nh);
}
diff --git a/libs/gui/include/gui/FrameTimestamps.h b/libs/gui/include/gui/FrameTimestamps.h
index e06e40f..df02494 100644
--- a/libs/gui/include/gui/FrameTimestamps.h
+++ b/libs/gui/include/gui/FrameTimestamps.h
@@ -30,7 +30,6 @@
struct FrameEvents;
class FrameEventHistoryDelta;
-class String8;
// Identifiers for all the events that may be recorded or reported.
@@ -72,7 +71,7 @@
bool hasDequeueReadyInfo() const;
void checkFencesForCompletion();
- void dump(String8& outString) const;
+ void dump(std::string& outString) const;
bool valid{false};
int connectId{0};
@@ -112,7 +111,7 @@
FrameEvents* getFrame(uint64_t frameNumber);
FrameEvents* getFrame(uint64_t frameNumber, size_t* iHint);
void checkFencesForCompletion();
- void dump(String8& outString) const;
+ void dump(std::string& outString) const;
static constexpr size_t MAX_FRAME_HISTORY = 8;
diff --git a/libs/gui/include/gui/GuiConfig.h b/libs/gui/include/gui/GuiConfig.h
index b020ed9..7aa5432 100644
--- a/libs/gui/include/gui/GuiConfig.h
+++ b/libs/gui/include/gui/GuiConfig.h
@@ -17,12 +17,12 @@
#ifndef ANDROID_GUI_CONFIG_H
#define ANDROID_GUI_CONFIG_H
-#include <utils/String8.h>
+#include <string>
namespace android {
// Append the libgui configuration details to configStr.
-void appendGuiConfigString(String8& configStr);
+void appendGuiConfigString(std::string& configStr);
}; // namespace android
diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h
index 41369c8..3052c0b 100644
--- a/libs/gui/include/gui/ISurfaceComposer.h
+++ b/libs/gui/include/gui/ISurfaceComposer.h
@@ -27,10 +27,11 @@
#include <binder/IInterface.h>
+#include <ui/DisplayedFrameStats.h>
#include <ui/FrameStats.h>
-#include <ui/PixelFormat.h>
#include <ui/GraphicBuffer.h>
#include <ui/GraphicTypes.h>
+#include <ui/PixelFormat.h>
#include <vector>
@@ -308,6 +309,14 @@
virtual status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
uint8_t componentMask,
uint64_t maxFrames) const = 0;
+
+ /* Returns statistics on the color profile of the last frame displayed for a given display
+ *
+ * Requires the ACCESS_SURFACE_FLINGER permission.
+ */
+ virtual status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
+ uint64_t timestamp,
+ DisplayedFrameStats* outStats) const = 0;
};
// ----------------------------------------------------------------------------
@@ -349,6 +358,7 @@
GET_COLOR_MANAGEMENT,
GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES,
SET_DISPLAY_CONTENT_SAMPLING_ENABLED,
+ GET_DISPLAYED_CONTENT_SAMPLE,
};
virtual status_t onTransact(uint32_t code, const Parcel& data,
diff --git a/libs/gui/include/gui/ITransactionCompletedListener.h b/libs/gui/include/gui/ITransactionCompletedListener.h
index 5c41c21..8acfa7a 100644
--- a/libs/gui/include/gui/ITransactionCompletedListener.h
+++ b/libs/gui/include/gui/ITransactionCompletedListener.h
@@ -21,6 +21,7 @@
#include <binder/Parcelable.h>
#include <binder/SafeInterface.h>
+#include <ui/Fence.h>
#include <utils/Timers.h>
#include <cstdint>
@@ -65,7 +66,7 @@
status_t readFromParcel(const Parcel* input) override;
nsecs_t latchTime = -1;
- nsecs_t presentTime = -1;
+ sp<Fence> presentFence = nullptr;
std::vector<SurfaceStats> surfaceStats;
};
diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h
index 3cfee9e..02c6be2 100644
--- a/libs/gui/include/gui/LayerState.h
+++ b/libs/gui/include/gui/LayerState.h
@@ -83,6 +83,7 @@
eListenerCallbacksChanged = 0x20000000,
eInputInfoChanged = 0x40000000,
eCornerRadiusChanged = 0x80000000,
+ eFrameChanged = 0x1'00000000,
};
layer_state_t()
@@ -104,6 +105,7 @@
transform(0),
transformToDisplayInverse(false),
crop(Rect::INVALID_RECT),
+ frame(Rect::INVALID_RECT),
dataspace(ui::Dataspace::UNKNOWN),
surfaceDamageRegion(),
api(-1),
@@ -124,7 +126,7 @@
float dsdy{0};
};
sp<IBinder> surface;
- uint32_t what;
+ uint64_t what;
float x;
float y;
int32_t z;
@@ -157,6 +159,7 @@
uint32_t transform;
bool transformToDisplayInverse;
Rect crop;
+ Rect frame;
sp<GraphicBuffer> buffer;
sp<Fence> acquireFence;
ui::Dataspace dataspace;
diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h
index ba943a0..8e3ba78 100644
--- a/libs/gui/include/gui/SurfaceComposerClient.h
+++ b/libs/gui/include/gui/SurfaceComposerClient.h
@@ -30,6 +30,7 @@
#include <utils/SortedVector.h>
#include <utils/threads.h>
+#include <ui/DisplayedFrameStats.h>
#include <ui/FrameStats.h>
#include <ui/GraphicTypes.h>
#include <ui/PixelFormat.h>
@@ -295,6 +296,7 @@
Transaction& setTransformToDisplayInverse(const sp<SurfaceControl>& sc,
bool transformToDisplayInverse);
Transaction& setCrop(const sp<SurfaceControl>& sc, const Rect& crop);
+ Transaction& setFrame(const sp<SurfaceControl>& sc, const Rect& frame);
Transaction& setBuffer(const sp<SurfaceControl>& sc, const sp<GraphicBuffer>& buffer);
Transaction& setAcquireFence(const sp<SurfaceControl>& sc, const sp<Fence>& fence);
Transaction& setDataspace(const sp<SurfaceControl>& sc, ui::Dataspace dataspace);
@@ -389,6 +391,9 @@
static status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
uint8_t componentMask, uint64_t maxFrames);
+ static status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
+ uint64_t timestamp, DisplayedFrameStats* outStats);
+
private:
virtual void onFirstRef();
diff --git a/libs/gui/tests/Android.bp b/libs/gui/tests/Android.bp
index 6de641d..f020a40 100644
--- a/libs/gui/tests/Android.bp
+++ b/libs/gui/tests/Android.bp
@@ -37,6 +37,7 @@
shared_libs: [
"android.hardware.configstore@1.0",
"android.hardware.configstore-utils",
+ "libbase",
"liblog",
"libEGL",
"libGLESv1_CM",
diff --git a/libs/gui/tests/DisplayedContentSampling_test.cpp b/libs/gui/tests/DisplayedContentSampling_test.cpp
index f9d5dd6..5443812 100644
--- a/libs/gui/tests/DisplayedContentSampling_test.cpp
+++ b/libs/gui/tests/DisplayedContentSampling_test.cpp
@@ -104,4 +104,19 @@
0);
EXPECT_EQ(OK, status);
}
+
+TEST_F(DisplayedContentSamplingTest, SampleCollectionCoherentWithSupportMask) {
+ if (shouldSkipTest()) return;
+
+ DisplayedFrameStats stats;
+ status_t status = mComposerClient->getDisplayedContentSample(mDisplayToken, 0, 0, &stats);
+ EXPECT_EQ(OK, status);
+ if (stats.numFrames <= 0) return;
+
+ if (componentMask & (0x1 << 0)) EXPECT_NE(0, stats.component_0_sample.size());
+ if (componentMask & (0x1 << 1)) EXPECT_NE(0, stats.component_1_sample.size());
+ if (componentMask & (0x1 << 2)) EXPECT_NE(0, stats.component_2_sample.size());
+ if (componentMask & (0x1 << 3)) EXPECT_NE(0, stats.component_3_sample.size());
+}
+
} // namespace android
diff --git a/libs/gui/tests/EndToEndNativeInputTest.cpp b/libs/gui/tests/EndToEndNativeInputTest.cpp
index 86e9c23..60542bd 100644
--- a/libs/gui/tests/EndToEndNativeInputTest.cpp
+++ b/libs/gui/tests/EndToEndNativeInputTest.cpp
@@ -24,11 +24,15 @@
#include <memory>
+#include <android/native_window.h>
+
#include <binder/Binder.h>
#include <binder/IServiceManager.h>
#include <binder/Parcel.h>
#include <binder/ProcessState.h>
+#include <gui/ISurfaceComposer.h>
+#include <gui/Surface.h>
#include <gui/SurfaceComposerClient.h>
#include <gui/SurfaceControl.h>
@@ -37,6 +41,7 @@
#include <input/InputTransport.h>
#include <input/Input.h>
+#include <ui/DisplayInfo.h>
#include <ui/Rect.h>
#include <ui/Region.h>
@@ -44,6 +49,8 @@
namespace android {
namespace test {
+using Transaction = SurfaceComposerClient::Transaction;
+
sp<IInputFlinger> getInputFlinger() {
sp<IBinder> input(defaultServiceManager()->getService(
String16("inputflinger")));
@@ -58,9 +65,8 @@
class InputSurface {
public:
- InputSurface(const sp<SurfaceComposerClient>& scc, int width, int height) {
- mSurfaceControl = scc->createSurface(String8("Test Surface"), 0, 0, PIXEL_FORMAT_RGBA_8888,
- ISurfaceComposerClient::eFXSurfaceColor);
+ InputSurface(const sp<SurfaceControl> &sc, int width, int height) {
+ mSurfaceControl = sc;
InputChannel::openInputChannelPair("testchannels", mServerChannel, mClientChannel);
mServerChannel->setToken(new BBinder());
@@ -73,6 +79,31 @@
mInputConsumer = new InputConsumer(mClientChannel);
}
+ static std::unique_ptr<InputSurface> makeColorInputSurface(const sp<SurfaceComposerClient> &scc,
+ int width, int height) {
+ sp<SurfaceControl> surfaceControl =
+ scc->createSurface(String8("Test Surface"), 0 /* bufHeight */, 0 /* bufWidth */,
+ PIXEL_FORMAT_RGBA_8888, ISurfaceComposerClient::eFXSurfaceColor);
+ return std::make_unique<InputSurface>(surfaceControl, width, height);
+ }
+
+ static std::unique_ptr<InputSurface> makeBufferInputSurface(
+ const sp<SurfaceComposerClient> &scc, int width, int height) {
+ sp<SurfaceControl> surfaceControl =
+ scc->createSurface(String8("Test Buffer Surface"), width, height,
+ PIXEL_FORMAT_RGBA_8888, 0 /* flags */);
+ return std::make_unique<InputSurface>(surfaceControl, width, height);
+ }
+
+ static std::unique_ptr<InputSurface> makeContainerInputSurface(
+ const sp<SurfaceComposerClient> &scc, int width, int height) {
+ sp<SurfaceControl> surfaceControl =
+ scc->createSurface(String8("Test Container Surface"), 0 /* bufHeight */,
+ 0 /* bufWidth */, PIXEL_FORMAT_RGBA_8888,
+ ISurfaceComposerClient::eFXSurfaceContainer);
+ return std::make_unique<InputSurface>(surfaceControl, width, height);
+ }
+
InputEvent* consumeEvent() {
waitForEventAvailable();
@@ -180,6 +211,15 @@
void SetUp() {
mComposerClient = new SurfaceComposerClient;
ASSERT_EQ(NO_ERROR, mComposerClient->initCheck());
+
+ DisplayInfo info;
+ auto display = mComposerClient->getBuiltInDisplay(ISurfaceComposer::eDisplayIdMain);
+ SurfaceComposerClient::getDisplayInfo(display, &info);
+
+ // After a new buffer is queued, SurfaceFlinger is notified and will
+ // latch the new buffer on next vsync. Let's heuristically wait for 3
+ // vsyncs.
+ mBufferPostDelay = int32_t(1e6 / info.fps) * 3;
}
void TearDown() {
@@ -187,10 +227,23 @@
}
std::unique_ptr<InputSurface> makeSurface(int width, int height) {
- return std::make_unique<InputSurface>(mComposerClient, width, height);
+ return InputSurface::makeColorInputSurface(mComposerClient, width, height);
+ }
+
+ void postBuffer(const sp<SurfaceControl> &layer) {
+ // wait for previous transactions (such as setSize) to complete
+ Transaction().apply(true);
+ ANativeWindow_Buffer buffer = {};
+ EXPECT_EQ(NO_ERROR, layer->getSurface()->lock(&buffer, nullptr));
+ ASSERT_EQ(NO_ERROR, layer->getSurface()->unlockAndPost());
+ // Request an empty transaction to get applied synchronously to ensure the buffer is
+ // latched.
+ Transaction().apply(true);
+ usleep(mBufferPostDelay);
}
sp<SurfaceComposerClient> mComposerClient;
+ int32_t mBufferPostDelay;
};
void injectTap(int x, int y) {
@@ -267,5 +320,124 @@
surface->expectTap(1, 1);
}
+// Surface Insets are set to offset the client content and draw a border around the client surface
+// (such as shadows in dialogs). Inputs sent to the client are offset such that 0,0 is the start
+// of the client content.
+TEST_F(InputSurfacesTest, input_respects_surface_insets) {
+ std::unique_ptr<InputSurface> bgSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> fgSurface = makeSurface(100, 100);
+ bgSurface->showAt(100, 100);
+
+ fgSurface->mInputInfo.surfaceInset = 5;
+ fgSurface->showAt(100, 100);
+
+ injectTap(106, 106);
+ fgSurface->expectTap(1, 1);
+
+ injectTap(101, 101);
+ bgSurface->expectTap(1, 1);
+}
+
+// Ensure a surface whose insets are cropped, handles the touch offset correctly. ref:b/120413463
+TEST_F(InputSurfacesTest, input_respects_cropped_surface_insets) {
+ std::unique_ptr<InputSurface> parentSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> childSurface = makeSurface(100, 100);
+ parentSurface->showAt(100, 100);
+
+ childSurface->mInputInfo.surfaceInset = 10;
+ childSurface->showAt(100, 100);
+
+ childSurface->doTransaction([&](auto &t, auto &sc) {
+ t.setPosition(sc, -5, -5);
+ t.reparent(sc, parentSurface->mSurfaceControl->getHandle());
+ });
+
+ injectTap(106, 106);
+ childSurface->expectTap(1, 1);
+
+ injectTap(101, 101);
+ parentSurface->expectTap(1, 1);
+}
+
+// Ensure we ignore transparent region when getting screen bounds when positioning input frame.
+TEST_F(InputSurfacesTest, input_ignores_transparent_region) {
+ std::unique_ptr<InputSurface> surface = makeSurface(100, 100);
+ surface->doTransaction([](auto &t, auto &sc) {
+ Region transparentRegion(Rect(0, 0, 10, 10));
+ t.setTransparentRegionHint(sc, transparentRegion);
+ });
+ surface->showAt(100, 100);
+ injectTap(101, 101);
+ surface->expectTap(1, 1);
+}
+
+// Ensure we send the input to the right surface when the surface visibility changes due to the
+// first buffer being submitted. ref: b/120839715
+TEST_F(InputSurfacesTest, input_respects_buffer_layer_buffer) {
+ std::unique_ptr<InputSurface> bgSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> bufferSurface =
+ InputSurface::makeBufferInputSurface(mComposerClient, 100, 100);
+
+ bgSurface->showAt(10, 10);
+ bufferSurface->showAt(10, 10);
+
+ injectTap(11, 11);
+ bgSurface->expectTap(1, 1);
+
+ postBuffer(bufferSurface->mSurfaceControl);
+ injectTap(11, 11);
+ bufferSurface->expectTap(1, 1);
+}
+
+TEST_F(InputSurfacesTest, input_respects_buffer_layer_alpha) {
+ std::unique_ptr<InputSurface> bgSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> bufferSurface =
+ InputSurface::makeBufferInputSurface(mComposerClient, 100, 100);
+ postBuffer(bufferSurface->mSurfaceControl);
+
+ bgSurface->showAt(10, 10);
+ bufferSurface->showAt(10, 10);
+
+ injectTap(11, 11);
+ bufferSurface->expectTap(1, 1);
+
+ bufferSurface->doTransaction([](auto &t, auto &sc) { t.setAlpha(sc, 0.0); });
+
+ injectTap(11, 11);
+ bgSurface->expectTap(1, 1);
+}
+
+TEST_F(InputSurfacesTest, input_respects_color_layer_alpha) {
+ std::unique_ptr<InputSurface> bgSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> fgSurface = makeSurface(100, 100);
+
+ bgSurface->showAt(10, 10);
+ fgSurface->showAt(10, 10);
+
+ injectTap(11, 11);
+ fgSurface->expectTap(1, 1);
+
+ fgSurface->doTransaction([](auto &t, auto &sc) { t.setAlpha(sc, 0.0); });
+
+ injectTap(11, 11);
+ bgSurface->expectTap(1, 1);
+}
+
+TEST_F(InputSurfacesTest, input_respects_container_layer_visiblity) {
+ std::unique_ptr<InputSurface> bgSurface = makeSurface(100, 100);
+ std::unique_ptr<InputSurface> containerSurface =
+ InputSurface::makeContainerInputSurface(mComposerClient, 100, 100);
+
+ bgSurface->showAt(10, 10);
+ containerSurface->showAt(10, 10);
+
+ injectTap(11, 11);
+ containerSurface->expectTap(1, 1);
+
+ containerSurface->doTransaction([](auto &t, auto &sc) { t.hide(sc); });
+
+ injectTap(11, 11);
+ bgSurface->expectTap(1, 1);
+}
}
}
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index cb1756f..67afbd6 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -207,7 +207,7 @@
}
TEST_F(SurfaceTest, QueryDefaultBuffersDataSpace) {
- const android_dataspace TEST_DATASPACE = HAL_DATASPACE_SRGB;
+ const android_dataspace TEST_DATASPACE = HAL_DATASPACE_V0_SRGB;
sp<IGraphicBufferProducer> producer;
sp<IGraphicBufferConsumer> consumer;
BufferQueue::createBufferQueue(&producer, &consumer);
@@ -652,6 +652,11 @@
uint64_t /*maxFrames*/) const override {
return NO_ERROR;
}
+ status_t getDisplayedContentSample(const sp<IBinder>& /*display*/, uint64_t /*maxFrames*/,
+ uint64_t /*timestamp*/,
+ DisplayedFrameStats* /*outStats*/) const override {
+ return NO_ERROR;
+ }
virtual status_t getColorManagement(bool* /*outGetColorManagement*/) const { return NO_ERROR; }
diff --git a/libs/renderengine/Android.bp b/libs/renderengine/Android.bp
index beaf9ee..d872f02 100644
--- a/libs/renderengine/Android.bp
+++ b/libs/renderengine/Android.bp
@@ -8,7 +8,6 @@
"-Wunused",
"-Wunreachable-code",
],
- cppflags: ["-std=c++1z"],
}
cc_defaults {
@@ -19,6 +18,7 @@
"-DEGL_EGLEXT_PROTOTYPES",
],
shared_libs: [
+ "libbase",
"libcutils",
"libEGL",
"libGLESv1_CM",
@@ -46,7 +46,7 @@
filegroup {
name: "librenderengine_gl_sources",
srcs: [
- "gl/GLES20RenderEngine.cpp",
+ "gl/GLESRenderEngine.cpp",
"gl/GLExtensions.cpp",
"gl/GLFramebuffer.cpp",
"gl/GLImage.cpp",
diff --git a/libs/renderengine/RenderEngine.cpp b/libs/renderengine/RenderEngine.cpp
index 8be1c3c..6dd7283 100644
--- a/libs/renderengine/RenderEngine.cpp
+++ b/libs/renderengine/RenderEngine.cpp
@@ -19,7 +19,7 @@
#include <cutils/properties.h>
#include <log/log.h>
#include <private/gui/SyncFeatures.h>
-#include "gl/GLES20RenderEngine.h"
+#include "gl/GLESRenderEngine.h"
namespace android {
namespace renderengine {
@@ -29,10 +29,10 @@
property_get(PROPERTY_DEBUG_RENDERENGINE_BACKEND, prop, "gles");
if (strcmp(prop, "gles") == 0) {
ALOGD("RenderEngine GLES Backend");
- return renderengine::gl::GLES20RenderEngine::create(hwcFormat, featureFlags);
+ return renderengine::gl::GLESRenderEngine::create(hwcFormat, featureFlags);
}
ALOGE("UNKNOWN BackendType: %s, create GLES RenderEngine.", prop);
- return renderengine::gl::GLES20RenderEngine::create(hwcFormat, featureFlags);
+ return renderengine::gl::GLESRenderEngine::create(hwcFormat, featureFlags);
}
RenderEngine::~RenderEngine() = default;
diff --git a/libs/renderengine/gl/GLES20RenderEngine.cpp b/libs/renderengine/gl/GLESRenderEngine.cpp
similarity index 75%
rename from libs/renderengine/gl/GLES20RenderEngine.cpp
rename to libs/renderengine/gl/GLESRenderEngine.cpp
index 7adda83..53b0e4c 100644
--- a/libs/renderengine/gl/GLES20RenderEngine.cpp
+++ b/libs/renderengine/gl/GLESRenderEngine.cpp
@@ -19,7 +19,7 @@
#define LOG_TAG "RenderEngine"
#define ATRACE_TAG ATRACE_TAG_GRAPHICS
-#include "GLES20RenderEngine.h"
+#include "GLESRenderEngine.h"
#include <math.h>
#include <fstream>
@@ -27,6 +27,7 @@
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
+#include <android-base/stringprintf.h>
#include <cutils/compiler.h>
#include <renderengine/Mesh.h>
#include <renderengine/Texture.h>
@@ -36,7 +37,6 @@
#include <ui/Rect.h>
#include <ui/Region.h>
#include <utils/KeyedVector.h>
-#include <utils/String8.h>
#include <utils/Trace.h>
#include "GLExtensions.h"
#include "GLFramebuffer.h"
@@ -109,6 +109,7 @@
namespace renderengine {
namespace gl {
+using base::StringAppendF;
using ui::Dataspace;
static status_t selectConfigForAttribute(EGLDisplay dpy, EGLint const* attrs, EGLint attribute,
@@ -221,8 +222,7 @@
return err;
}
-std::unique_ptr<GLES20RenderEngine> GLES20RenderEngine::create(int hwcFormat,
- uint32_t featureFlags) {
+std::unique_ptr<GLESRenderEngine> GLESRenderEngine::create(int hwcFormat, uint32_t featureFlags) {
// initialize EGL for the default display
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (!eglInitialize(display, nullptr, nullptr)) {
@@ -242,28 +242,48 @@
bool useContextPriority = extensions.hasContextPriority() &&
(featureFlags & RenderEngine::USE_HIGH_PRIORITY_CONTEXT);
- EGLContext ctxt = createEglContext(display, config, EGL_NO_CONTEXT, useContextPriority);
+ EGLContext protectedContext = EGL_NO_CONTEXT;
+ if (extensions.hasProtectedContent()) {
+ protectedContext = createEglContext(display, config, nullptr, useContextPriority,
+ Protection::PROTECTED);
+ ALOGE_IF(protectedContext == EGL_NO_CONTEXT, "Can't create protected context");
+ }
+
+ EGLContext ctxt = createEglContext(display, config, protectedContext, useContextPriority,
+ Protection::UNPROTECTED);
// if can't create a GL context, we can only abort.
LOG_ALWAYS_FATAL_IF(ctxt == EGL_NO_CONTEXT, "EGLContext creation failed");
EGLSurface dummy = EGL_NO_SURFACE;
if (!extensions.hasSurfacelessContext()) {
- dummy = createDummyEglPbufferSurface(display, config, hwcFormat);
+ dummy = createDummyEglPbufferSurface(display, config, hwcFormat, Protection::UNPROTECTED);
LOG_ALWAYS_FATAL_IF(dummy == EGL_NO_SURFACE, "can't create dummy pbuffer");
}
-
EGLBoolean success = eglMakeCurrent(display, dummy, dummy, ctxt);
LOG_ALWAYS_FATAL_IF(!success, "can't make dummy pbuffer current");
-
extensions.initWithGLStrings(glGetString(GL_VENDOR), glGetString(GL_RENDERER),
glGetString(GL_VERSION), glGetString(GL_EXTENSIONS));
+ // In order to have protected contents in GPU composition, the OpenGL ES extension
+ // GL_EXT_protected_textures must be supported. If it's not supported, reset
+ // protected context to EGL_NO_CONTEXT to indicate that protected contents is not supported.
+ if (!extensions.hasProtectedTexture()) {
+ protectedContext = EGL_NO_CONTEXT;
+ }
+
+ EGLSurface protectedDummy = EGL_NO_SURFACE;
+ if (protectedContext != EGL_NO_CONTEXT && !extensions.hasSurfacelessContext()) {
+ protectedDummy =
+ createDummyEglPbufferSurface(display, config, hwcFormat, Protection::PROTECTED);
+ ALOGE_IF(protectedDummy == EGL_NO_SURFACE, "can't create protected dummy pbuffer");
+ }
+
// now figure out what version of GL did we actually get
GlesVersion version = parseGlesVersion(extensions.getVersion());
// initialize the renderer while GL is current
- std::unique_ptr<GLES20RenderEngine> engine;
+ std::unique_ptr<GLESRenderEngine> engine;
switch (version) {
case GLES_VERSION_1_0:
case GLES_VERSION_1_1:
@@ -271,8 +291,8 @@
break;
case GLES_VERSION_2_0:
case GLES_VERSION_3_0:
- engine = std::make_unique<GLES20RenderEngine>(featureFlags, display, config, ctxt,
- dummy);
+ engine = std::make_unique<GLESRenderEngine>(featureFlags, display, config, ctxt, dummy,
+ protectedContext, protectedDummy);
break;
}
@@ -287,17 +307,17 @@
return engine;
}
-EGLConfig GLES20RenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
+EGLConfig GLESRenderEngine::chooseEglConfig(EGLDisplay display, int format, bool logConfig) {
status_t err;
EGLConfig config;
- // First try to get an ES2 config
- err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
+ // First try to get an ES3 config
+ err = selectEGLConfig(display, format, EGL_OPENGL_ES3_BIT, &config);
if (err != NO_ERROR) {
- // If ES2 fails, try ES1
- err = selectEGLConfig(display, format, EGL_OPENGL_ES_BIT, &config);
+ // If ES3 fails, try to get an ES2 config
+ err = selectEGLConfig(display, format, EGL_OPENGL_ES2_BIT, &config);
if (err != NO_ERROR) {
- // still didn't work, probably because we're on the emulator...
+ // If ES2 still doesn't work, probably because we're on the emulator.
// try a simplified query
ALOGW("no suitable EGLConfig found, trying a simpler query");
err = selectEGLConfig(display, format, 0, &config);
@@ -326,13 +346,16 @@
return config;
}
-GLES20RenderEngine::GLES20RenderEngine(uint32_t featureFlags, EGLDisplay display, EGLConfig config,
- EGLContext ctxt, EGLSurface dummy)
+GLESRenderEngine::GLESRenderEngine(uint32_t featureFlags, EGLDisplay display, EGLConfig config,
+ EGLContext ctxt, EGLSurface dummy, EGLContext protectedContext,
+ EGLSurface protectedDummy)
: renderengine::impl::RenderEngine(featureFlags),
mEGLDisplay(display),
mEGLConfig(config),
mEGLContext(ctxt),
mDummySurface(dummy),
+ mProtectedEGLContext(protectedContext),
+ mProtectedDummySurface(protectedDummy),
mVpWidth(0),
mVpHeight(0),
mUseColorManagement(featureFlags & USE_COLOR_MANAGEMENT) {
@@ -342,6 +365,17 @@
glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
glPixelStorei(GL_PACK_ALIGNMENT, 4);
+ // Initialize protected EGL Context.
+ if (mProtectedEGLContext != EGL_NO_CONTEXT) {
+ EGLBoolean success = eglMakeCurrent(display, mProtectedDummySurface, mProtectedDummySurface,
+ mProtectedEGLContext);
+ ALOGE_IF(!success, "can't make protected context current");
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
+ success = eglMakeCurrent(display, mDummySurface, mDummySurface, mEGLContext);
+ LOG_ALWAYS_FATAL_IF(!success, "can't make default context current");
+ }
+
const uint16_t protTexData[] = {0};
glGenTextures(1, &mProtectedTexName);
glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
@@ -382,28 +416,29 @@
}
}
-GLES20RenderEngine::~GLES20RenderEngine() {
+GLESRenderEngine::~GLESRenderEngine() {
eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
eglTerminate(mEGLDisplay);
}
-std::unique_ptr<Framebuffer> GLES20RenderEngine::createFramebuffer() {
+std::unique_ptr<Framebuffer> GLESRenderEngine::createFramebuffer() {
return std::make_unique<GLFramebuffer>(*this);
}
-std::unique_ptr<Image> GLES20RenderEngine::createImage() {
+std::unique_ptr<Image> GLESRenderEngine::createImage() {
return std::make_unique<GLImage>(*this);
}
-void GLES20RenderEngine::primeCache() const {
- ProgramCache::getInstance().primeCache(mFeatureFlags & USE_COLOR_MANAGEMENT);
+void GLESRenderEngine::primeCache() const {
+ ProgramCache::getInstance().primeCache(mInProtectedContext ? mProtectedEGLContext : mEGLContext,
+ mFeatureFlags & USE_COLOR_MANAGEMENT);
}
-bool GLES20RenderEngine::isCurrent() const {
+bool GLESRenderEngine::isCurrent() const {
return mEGLDisplay == eglGetCurrentDisplay() && mEGLContext == eglGetCurrentContext();
}
-base::unique_fd GLES20RenderEngine::flush() {
+base::unique_fd GLESRenderEngine::flush() {
if (!GLExtensions::getInstance().hasNativeFenceSync()) {
return base::unique_fd();
}
@@ -427,7 +462,7 @@
return fenceFd;
}
-bool GLES20RenderEngine::finish() {
+bool GLESRenderEngine::finish() {
if (!GLExtensions::getInstance().hasFenceSync()) {
ALOGW("no synchronization support");
return false;
@@ -455,7 +490,7 @@
return true;
}
-bool GLES20RenderEngine::waitFence(base::unique_fd fenceFd) {
+bool GLESRenderEngine::waitFence(base::unique_fd fenceFd) {
if (!GLExtensions::getInstance().hasNativeFenceSync() ||
!GLExtensions::getInstance().hasWaitSync()) {
return false;
@@ -485,13 +520,13 @@
return true;
}
-void GLES20RenderEngine::clearWithColor(float red, float green, float blue, float alpha) {
+void GLESRenderEngine::clearWithColor(float red, float green, float blue, float alpha) {
glClearColor(red, green, blue, alpha);
glClear(GL_COLOR_BUFFER_BIT);
}
-void GLES20RenderEngine::fillRegionWithColor(const Region& region, float red, float green,
- float blue, float alpha) {
+void GLESRenderEngine::fillRegionWithColor(const Region& region, float red, float green, float blue,
+ float alpha) {
size_t c;
Rect const* r = region.getArray(&c);
Mesh mesh(Mesh::TRIANGLES, c * 6, 2);
@@ -514,7 +549,7 @@
drawMesh(mesh);
}
-void GLES20RenderEngine::setScissor(const Rect& region) {
+void GLESRenderEngine::setScissor(const Rect& region) {
// Invert y-coordinate to map to GL-space.
int32_t canvasHeight = mFboHeight;
int32_t glBottom = canvasHeight - region.bottom;
@@ -523,29 +558,33 @@
glEnable(GL_SCISSOR_TEST);
}
-void GLES20RenderEngine::disableScissor() {
+void GLESRenderEngine::disableScissor() {
glDisable(GL_SCISSOR_TEST);
}
-void GLES20RenderEngine::genTextures(size_t count, uint32_t* names) {
+void GLESRenderEngine::genTextures(size_t count, uint32_t* names) {
glGenTextures(count, names);
}
-void GLES20RenderEngine::deleteTextures(size_t count, uint32_t const* names) {
+void GLESRenderEngine::deleteTextures(size_t count, uint32_t const* names) {
glDeleteTextures(count, names);
}
-void GLES20RenderEngine::bindExternalTextureImage(uint32_t texName, const Image& image) {
+void GLESRenderEngine::bindExternalTextureImage(uint32_t texName, const Image& image) {
const GLImage& glImage = static_cast<const GLImage&>(image);
const GLenum target = GL_TEXTURE_EXTERNAL_OES;
glBindTexture(target, texName);
+ if (supportsProtectedContent()) {
+ glTexParameteri(target, GL_TEXTURE_PROTECTED_EXT,
+ glImage.isProtected() ? GL_TRUE : GL_FALSE);
+ }
if (glImage.getEGLImage() != EGL_NO_IMAGE_KHR) {
glEGLImageTargetTexture2DOES(target, static_cast<GLeglImageOES>(glImage.getEGLImage()));
}
}
-status_t GLES20RenderEngine::bindFrameBuffer(Framebuffer* framebuffer) {
+status_t GLESRenderEngine::bindFrameBuffer(Framebuffer* framebuffer) {
GLFramebuffer* glFramebuffer = static_cast<GLFramebuffer*>(framebuffer);
EGLImageKHR eglImage = glFramebuffer->getEGLImage();
uint32_t textureName = glFramebuffer->getTextureName();
@@ -553,6 +592,10 @@
// Bind the texture and turn our EGLImage into a texture
glBindTexture(GL_TEXTURE_2D, textureName);
+ if (supportsProtectedContent()) {
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_PROTECTED_EXT,
+ mInProtectedContext ? GL_TRUE : GL_FALSE);
+ }
glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, (GLeglImageOES)eglImage);
// Bind the Framebuffer to render into
@@ -569,14 +612,14 @@
return glStatus == GL_FRAMEBUFFER_COMPLETE_OES ? NO_ERROR : BAD_VALUE;
}
-void GLES20RenderEngine::unbindFrameBuffer(Framebuffer* /* framebuffer */) {
+void GLESRenderEngine::unbindFrameBuffer(Framebuffer* /* framebuffer */) {
mFboHeight = 0;
// back to main framebuffer
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
-void GLES20RenderEngine::checkErrors() const {
+void GLESRenderEngine::checkErrors() const {
do {
// there could be more than one error flag
GLenum error = glGetError();
@@ -585,15 +628,35 @@
} while (true);
}
-status_t GLES20RenderEngine::drawLayers(const DisplaySettings& /*settings*/,
- const std::vector<LayerSettings>& /*layers*/,
- ANativeWindowBuffer* const /*buffer*/,
- base::unique_fd* /*displayFence*/) const {
+bool GLESRenderEngine::supportsProtectedContent() const {
+ return mProtectedEGLContext != EGL_NO_CONTEXT;
+}
+
+bool GLESRenderEngine::useProtectedContext(bool useProtectedContext) {
+ if (useProtectedContext == mInProtectedContext) {
+ return true;
+ }
+ if (useProtectedContext && mProtectedEGLContext == EGL_NO_CONTEXT) {
+ return false;
+ }
+ const EGLSurface surface = useProtectedContext ? mProtectedDummySurface : mDummySurface;
+ const EGLContext context = useProtectedContext ? mProtectedEGLContext : mEGLContext;
+ const bool success = eglMakeCurrent(mEGLDisplay, surface, surface, context) == EGL_TRUE;
+ if (success) {
+ mInProtectedContext = useProtectedContext;
+ }
+ return success;
+}
+
+status_t GLESRenderEngine::drawLayers(const DisplaySettings& /*settings*/,
+ const std::vector<LayerSettings>& /*layers*/,
+ ANativeWindowBuffer* const /*buffer*/,
+ base::unique_fd* /*displayFence*/) const {
return NO_ERROR;
}
-void GLES20RenderEngine::setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop,
- ui::Transform::orientation_flags rotation) {
+void GLESRenderEngine::setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop,
+ ui::Transform::orientation_flags rotation) {
int32_t l = sourceCrop.left;
int32_t r = sourceCrop.right;
int32_t b = sourceCrop.bottom;
@@ -625,9 +688,8 @@
mVpHeight = vph;
}
-void GLES20RenderEngine::setupLayerBlending(bool premultipliedAlpha, bool opaque,
- bool disableTexture, const half4& color,
- float cornerRadius) {
+void GLESRenderEngine::setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
+ const half4& color, float cornerRadius) {
mState.isPremultipliedAlpha = premultipliedAlpha;
mState.isOpaque = opaque;
mState.color = color;
@@ -645,23 +707,23 @@
}
}
-void GLES20RenderEngine::setSourceY410BT2020(bool enable) {
+void GLESRenderEngine::setSourceY410BT2020(bool enable) {
mState.isY410BT2020 = enable;
}
-void GLES20RenderEngine::setSourceDataSpace(Dataspace source) {
+void GLESRenderEngine::setSourceDataSpace(Dataspace source) {
mDataSpace = source;
}
-void GLES20RenderEngine::setOutputDataSpace(Dataspace dataspace) {
+void GLESRenderEngine::setOutputDataSpace(Dataspace dataspace) {
mOutputDataSpace = dataspace;
}
-void GLES20RenderEngine::setDisplayMaxLuminance(const float maxLuminance) {
+void GLESRenderEngine::setDisplayMaxLuminance(const float maxLuminance) {
mState.displayMaxLuminance = maxLuminance;
}
-void GLES20RenderEngine::setupLayerTexturing(const Texture& texture) {
+void GLESRenderEngine::setupLayerTexturing(const Texture& texture) {
GLuint target = texture.getTextureTarget();
glBindTexture(target, texture.getTextureName());
GLenum filter = GL_NEAREST;
@@ -677,7 +739,7 @@
mState.textureEnabled = true;
}
-void GLES20RenderEngine::setupLayerBlackedOut() {
+void GLESRenderEngine::setupLayerBlackedOut() {
glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
Texture texture(Texture::TEXTURE_2D, mProtectedTexName);
texture.setDimensions(1, 1); // FIXME: we should get that from somewhere
@@ -685,19 +747,19 @@
mState.textureEnabled = true;
}
-void GLES20RenderEngine::setColorTransform(const mat4& colorTransform) {
+void GLESRenderEngine::setColorTransform(const mat4& colorTransform) {
mState.colorMatrix = colorTransform;
}
-void GLES20RenderEngine::disableTexturing() {
+void GLESRenderEngine::disableTexturing() {
mState.textureEnabled = false;
}
-void GLES20RenderEngine::disableBlending() {
+void GLESRenderEngine::disableBlending() {
glDisable(GL_BLEND);
}
-void GLES20RenderEngine::setupFillWithColor(float r, float g, float b, float a) {
+void GLESRenderEngine::setupFillWithColor(float r, float g, float b, float a) {
mState.isPremultipliedAlpha = true;
mState.isOpaque = false;
mState.color = half4(r, g, b, a);
@@ -705,11 +767,11 @@
glDisable(GL_BLEND);
}
-void GLES20RenderEngine::setupCornerRadiusCropSize(float width, float height) {
+void GLESRenderEngine::setupCornerRadiusCropSize(float width, float height) {
mState.cropSize = half2(width, height);
}
-void GLES20RenderEngine::drawMesh(const Mesh& mesh) {
+void GLESRenderEngine::drawMesh(const Mesh& mesh) {
ATRACE_CALL();
if (mesh.getTexCoordsSize()) {
glEnableVertexAttribArray(Program::texCoords);
@@ -824,7 +886,9 @@
Description::dataSpaceToTransferFunction(outputTransfer);
}
- ProgramCache::getInstance().useProgram(managedState);
+ ProgramCache::getInstance().useProgram(mInProtectedContext ? mProtectedEGLContext
+ : mEGLContext,
+ managedState);
glDrawArrays(mesh.getPrimitive(), 0, mesh.getVertexCount());
@@ -835,7 +899,9 @@
writePPM(out.str().c_str(), mVpWidth, mVpHeight);
}
} else {
- ProgramCache::getInstance().useProgram(mState);
+ ProgramCache::getInstance().useProgram(mInProtectedContext ? mProtectedEGLContext
+ : mEGLContext,
+ mState);
glDrawArrays(mesh.getPrimitive(), 0, mesh.getVertexCount());
}
@@ -849,33 +915,34 @@
}
}
-size_t GLES20RenderEngine::getMaxTextureSize() const {
+size_t GLESRenderEngine::getMaxTextureSize() const {
return mMaxTextureSize;
}
-size_t GLES20RenderEngine::getMaxViewportDims() const {
+size_t GLESRenderEngine::getMaxViewportDims() const {
return mMaxViewportDims[0] < mMaxViewportDims[1] ? mMaxViewportDims[0] : mMaxViewportDims[1];
}
-void GLES20RenderEngine::dump(String8& result) {
+void GLESRenderEngine::dump(std::string& result) {
const GLExtensions& extensions = GLExtensions::getInstance();
+ ProgramCache& cache = ProgramCache::getInstance();
- result.appendFormat("EGL implementation : %s\n", extensions.getEGLVersion());
- result.appendFormat("%s\n", extensions.getEGLExtensions());
-
- result.appendFormat("GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
- extensions.getVersion());
- result.appendFormat("%s\n", extensions.getExtensions());
-
- result.appendFormat("RenderEngine program cache size: %zu\n",
- ProgramCache::getInstance().getSize());
-
- result.appendFormat("RenderEngine last dataspace conversion: (%s) to (%s)\n",
- dataspaceDetails(static_cast<android_dataspace>(mDataSpace)).c_str(),
- dataspaceDetails(static_cast<android_dataspace>(mOutputDataSpace)).c_str());
+ StringAppendF(&result, "EGL implementation : %s\n", extensions.getEGLVersion());
+ StringAppendF(&result, "%s\n", extensions.getEGLExtensions());
+ StringAppendF(&result, "GLES: %s, %s, %s\n", extensions.getVendor(), extensions.getRenderer(),
+ extensions.getVersion());
+ StringAppendF(&result, "%s\n", extensions.getExtensions());
+ StringAppendF(&result, "RenderEngine is in protected context : %d\n", mInProtectedContext);
+ StringAppendF(&result, "RenderEngine program cache size for unprotected context: %zu\n",
+ cache.getSize(mEGLContext));
+ StringAppendF(&result, "RenderEngine program cache size for protected context: %zu\n",
+ cache.getSize(mProtectedEGLContext));
+ StringAppendF(&result, "RenderEngine last dataspace conversion: (%s) to (%s)\n",
+ dataspaceDetails(static_cast<android_dataspace>(mDataSpace)).c_str(),
+ dataspaceDetails(static_cast<android_dataspace>(mOutputDataSpace)).c_str());
}
-GLES20RenderEngine::GlesVersion GLES20RenderEngine::parseGlesVersion(const char* str) {
+GLESRenderEngine::GlesVersion GLESRenderEngine::parseGlesVersion(const char* str) {
int major, minor;
if (sscanf(str, "OpenGL ES-CM %d.%d", &major, &minor) != 2) {
if (sscanf(str, "OpenGL ES %d.%d", &major, &minor) != 2) {
@@ -893,16 +960,19 @@
return GLES_VERSION_1_0;
}
-EGLContext GLES20RenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
- EGLContext shareContext, bool useContextPriority) {
+EGLContext GLESRenderEngine::createEglContext(EGLDisplay display, EGLConfig config,
+ EGLContext shareContext, bool useContextPriority,
+ Protection protection) {
EGLint renderableType = 0;
if (config == EGL_NO_CONFIG) {
- renderableType = EGL_OPENGL_ES2_BIT;
+ renderableType = EGL_OPENGL_ES3_BIT;
} else if (!eglGetConfigAttrib(display, config, EGL_RENDERABLE_TYPE, &renderableType)) {
LOG_ALWAYS_FATAL("can't query EGLConfig RENDERABLE_TYPE");
}
EGLint contextClientVersion = 0;
- if (renderableType & EGL_OPENGL_ES2_BIT) {
+ if (renderableType & EGL_OPENGL_ES3_BIT) {
+ contextClientVersion = 3;
+ } else if (renderableType & EGL_OPENGL_ES2_BIT) {
contextClientVersion = 2;
} else if (renderableType & EGL_OPENGL_ES_BIT) {
contextClientVersion = 1;
@@ -911,36 +981,58 @@
}
std::vector<EGLint> contextAttributes;
- contextAttributes.reserve(5);
+ contextAttributes.reserve(7);
contextAttributes.push_back(EGL_CONTEXT_CLIENT_VERSION);
contextAttributes.push_back(contextClientVersion);
if (useContextPriority) {
contextAttributes.push_back(EGL_CONTEXT_PRIORITY_LEVEL_IMG);
contextAttributes.push_back(EGL_CONTEXT_PRIORITY_HIGH_IMG);
}
+ if (protection == Protection::PROTECTED) {
+ contextAttributes.push_back(EGL_PROTECTED_CONTENT_EXT);
+ contextAttributes.push_back(EGL_TRUE);
+ }
contextAttributes.push_back(EGL_NONE);
- return eglCreateContext(display, config, shareContext, contextAttributes.data());
+ EGLContext context = eglCreateContext(display, config, shareContext, contextAttributes.data());
+
+ if (contextClientVersion == 3 && context == EGL_NO_CONTEXT) {
+ // eglGetConfigAttrib indicated we can create GLES 3 context, but we failed, thus
+ // EGL_NO_CONTEXT so that we can abort.
+ if (config != EGL_NO_CONFIG) {
+ return context;
+ }
+ // If |config| is EGL_NO_CONFIG, we speculatively try to create GLES 3 context, so we should
+ // try to fall back to GLES 2.
+ contextAttributes[1] = 2;
+ context = eglCreateContext(display, config, shareContext, contextAttributes.data());
+ }
+
+ return context;
}
-EGLSurface GLES20RenderEngine::createDummyEglPbufferSurface(EGLDisplay display, EGLConfig config,
- int hwcFormat) {
+EGLSurface GLESRenderEngine::createDummyEglPbufferSurface(EGLDisplay display, EGLConfig config,
+ int hwcFormat, Protection protection) {
EGLConfig dummyConfig = config;
if (dummyConfig == EGL_NO_CONFIG) {
dummyConfig = chooseEglConfig(display, hwcFormat, /*logConfig*/ true);
}
std::vector<EGLint> attributes;
- attributes.reserve(5);
+ attributes.reserve(7);
attributes.push_back(EGL_WIDTH);
attributes.push_back(1);
attributes.push_back(EGL_HEIGHT);
attributes.push_back(1);
+ if (protection == Protection::PROTECTED) {
+ attributes.push_back(EGL_PROTECTED_CONTENT_EXT);
+ attributes.push_back(EGL_TRUE);
+ }
attributes.push_back(EGL_NONE);
return eglCreatePbufferSurface(display, dummyConfig, attributes.data());
}
-bool GLES20RenderEngine::isHdrDataSpace(const Dataspace dataSpace) const {
+bool GLESRenderEngine::isHdrDataSpace(const Dataspace dataSpace) const {
const Dataspace standard = static_cast<Dataspace>(dataSpace & Dataspace::STANDARD_MASK);
const Dataspace transfer = static_cast<Dataspace>(dataSpace & Dataspace::TRANSFER_MASK);
return standard == Dataspace::STANDARD_BT2020 &&
@@ -957,7 +1049,7 @@
// input data space or output data space is HDR data space, and the input transfer function
// doesn't match the output transfer function, we would enable an intermediate transfrom to
// XYZ color space.
-bool GLES20RenderEngine::needsXYZTransformMatrix() const {
+bool GLESRenderEngine::needsXYZTransformMatrix() const {
const bool isInputHdrDataSpace = isHdrDataSpace(mDataSpace);
const bool isOutputHdrDataSpace = isHdrDataSpace(mOutputDataSpace);
const Dataspace inputTransfer = static_cast<Dataspace>(mDataSpace & Dataspace::TRANSFER_MASK);
diff --git a/libs/renderengine/gl/GLES20RenderEngine.h b/libs/renderengine/gl/GLESRenderEngine.h
similarity index 84%
rename from libs/renderengine/gl/GLES20RenderEngine.h
rename to libs/renderengine/gl/GLESRenderEngine.h
index a9f8cad..07e5585 100644
--- a/libs/renderengine/gl/GLES20RenderEngine.h
+++ b/libs/renderengine/gl/GLESRenderEngine.h
@@ -14,8 +14,8 @@
* limitations under the License.
*/
-#ifndef SF_GLES20RENDERENGINE_H_
-#define SF_GLES20RENDERENGINE_H_
+#ifndef SF_GLESRENDERENGINE_H_
+#define SF_GLESRENDERENGINE_H_
#include <stdint.h>
#include <sys/types.h>
@@ -30,8 +30,6 @@
namespace android {
-class String8;
-
namespace renderengine {
class Mesh;
@@ -41,14 +39,15 @@
class GLImage;
-class GLES20RenderEngine : public impl::RenderEngine {
+class GLESRenderEngine : public impl::RenderEngine {
public:
- static std::unique_ptr<GLES20RenderEngine> create(int hwcFormat, uint32_t featureFlags);
+ static std::unique_ptr<GLESRenderEngine> create(int hwcFormat, uint32_t featureFlags);
static EGLConfig chooseEglConfig(EGLDisplay display, int format, bool logConfig);
- GLES20RenderEngine(uint32_t featureFlags, // See RenderEngine::FeatureFlag
- EGLDisplay display, EGLConfig config, EGLContext ctxt, EGLSurface dummy);
- ~GLES20RenderEngine() override;
+ GLESRenderEngine(uint32_t featureFlags, // See RenderEngine::FeatureFlag
+ EGLDisplay display, EGLConfig config, EGLContext ctxt, EGLSurface dummy,
+ EGLContext protectedContext, EGLSurface protectedDummy);
+ ~GLESRenderEngine() override;
std::unique_ptr<Framebuffer> createFramebuffer() override;
std::unique_ptr<Image> createImage() override;
@@ -70,6 +69,9 @@
void unbindFrameBuffer(Framebuffer* framebuffer) override;
void checkErrors() const override;
+ bool isProtected() const override { return mInProtectedContext; }
+ bool supportsProtectedContent() const override;
+ bool useProtectedContext(bool useProtectedContext) override;
status_t drawLayers(const DisplaySettings& settings, const std::vector<LayerSettings>& layers,
ANativeWindowBuffer* const buffer,
base::unique_fd* displayFence) const override;
@@ -79,7 +81,7 @@
EGLConfig getEGLConfig() const { return mEGLConfig; }
protected:
- void dump(String8& result) override;
+ void dump(std::string& result) override;
void setViewportAndProjection(size_t vpw, size_t vph, Rect sourceCrop,
ui::Transform::orientation_flags rotation) override;
void setupLayerBlending(bool premultipliedAlpha, bool opaque, bool disableTexture,
@@ -114,20 +116,22 @@
static GlesVersion parseGlesVersion(const char* str);
static EGLContext createEglContext(EGLDisplay display, EGLConfig config,
- EGLContext shareContext, bool useContextPriority);
+ EGLContext shareContext, bool useContextPriority,
+ Protection protection);
static EGLSurface createDummyEglPbufferSurface(EGLDisplay display, EGLConfig config,
- int hwcFormat);
+ int hwcFormat, Protection protection);
// A data space is considered HDR data space if it has BT2020 color space
// with PQ or HLG transfer function.
bool isHdrDataSpace(const ui::Dataspace dataSpace) const;
bool needsXYZTransformMatrix() const;
- void setEGLHandles(EGLDisplay display, EGLConfig config, EGLContext ctxt, EGLSurface dummy);
EGLDisplay mEGLDisplay;
EGLConfig mEGLConfig;
EGLContext mEGLContext;
EGLSurface mDummySurface;
+ EGLContext mProtectedEGLContext;
+ EGLSurface mProtectedDummySurface;
GLuint mProtectedTexName;
GLint mMaxViewportDims[2];
GLint mMaxTextureSize;
@@ -148,6 +152,7 @@
mat4 mBt2020ToSrgb;
mat4 mBt2020ToDisplayP3;
+ bool mInProtectedContext = false;
int32_t mFboHeight = 0;
// Current dataspace of layer being rendered
@@ -165,4 +170,4 @@
} // namespace renderengine
} // namespace android
-#endif /* SF_GLES20RENDERENGINE_H_ */
+#endif /* SF_GLESRENDERENGINE_H_ */
diff --git a/libs/renderengine/gl/GLExtensions.cpp b/libs/renderengine/gl/GLExtensions.cpp
index ce83dd5..2924b0e 100644
--- a/libs/renderengine/gl/GLExtensions.cpp
+++ b/libs/renderengine/gl/GLExtensions.cpp
@@ -60,6 +60,11 @@
mRenderer = (char const*)renderer;
mVersion = (char const*)version;
mExtensions = (char const*)extensions;
+
+ ExtensionSet extensionSet(mExtensions.c_str());
+ if (extensionSet.hasExtension("GL_EXT_protected_textures")) {
+ mHasProtectedTexture = true;
+ }
}
char const* GLExtensions::getVendor() const {
diff --git a/libs/renderengine/gl/GLExtensions.h b/libs/renderengine/gl/GLExtensions.h
index 2a654d5..ef00009 100644
--- a/libs/renderengine/gl/GLExtensions.h
+++ b/libs/renderengine/gl/GLExtensions.h
@@ -40,6 +40,7 @@
bool hasProtectedContent() const { return mHasProtectedContent; }
bool hasContextPriority() const { return mHasContextPriority; }
bool hasSurfacelessContext() const { return mHasSurfacelessContext; }
+ bool hasProtectedTexture() const { return mHasProtectedTexture; }
void initWithGLStrings(GLubyte const* vendor, GLubyte const* renderer, GLubyte const* version,
GLubyte const* extensions);
@@ -65,12 +66,12 @@
bool mHasProtectedContent = false;
bool mHasContextPriority = false;
bool mHasSurfacelessContext = false;
+ bool mHasProtectedTexture = false;
String8 mVendor;
String8 mRenderer;
String8 mVersion;
String8 mExtensions;
-
String8 mEGLVersion;
String8 mEGLExtensions;
diff --git a/libs/renderengine/gl/GLFramebuffer.cpp b/libs/renderengine/gl/GLFramebuffer.cpp
index 2bd4e7f..4a519bb 100644
--- a/libs/renderengine/gl/GLFramebuffer.cpp
+++ b/libs/renderengine/gl/GLFramebuffer.cpp
@@ -21,13 +21,13 @@
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <nativebase/nativebase.h>
-#include "GLES20RenderEngine.h"
+#include "GLESRenderEngine.h"
namespace android {
namespace renderengine {
namespace gl {
-GLFramebuffer::GLFramebuffer(const GLES20RenderEngine& engine)
+GLFramebuffer::GLFramebuffer(const GLESRenderEngine& engine)
: mEGLDisplay(engine.getEGLDisplay()), mEGLImage(EGL_NO_IMAGE_KHR) {
glGenTextures(1, &mTextureName);
glGenFramebuffers(1, &mFramebufferName);
@@ -39,7 +39,7 @@
eglDestroyImageKHR(mEGLDisplay, mEGLImage);
}
-bool GLFramebuffer::setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer) {
+bool GLFramebuffer::setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer, bool isProtected) {
if (mEGLImage != EGL_NO_IMAGE_KHR) {
eglDestroyImageKHR(mEGLDisplay, mEGLImage);
mEGLImage = EGL_NO_IMAGE_KHR;
@@ -48,8 +48,13 @@
}
if (nativeBuffer) {
+ EGLint attributes[] = {
+ isProtected ? EGL_PROTECTED_CONTENT_EXT : EGL_NONE,
+ isProtected ? EGL_TRUE : EGL_NONE,
+ EGL_NONE,
+ };
mEGLImage = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID,
- nativeBuffer, nullptr);
+ nativeBuffer, attributes);
if (mEGLImage == EGL_NO_IMAGE_KHR) {
return false;
}
diff --git a/libs/renderengine/gl/GLFramebuffer.h b/libs/renderengine/gl/GLFramebuffer.h
index 90c6f4a..5043c59 100644
--- a/libs/renderengine/gl/GLFramebuffer.h
+++ b/libs/renderengine/gl/GLFramebuffer.h
@@ -28,14 +28,14 @@
namespace renderengine {
namespace gl {
-class GLES20RenderEngine;
+class GLESRenderEngine;
class GLFramebuffer : public renderengine::Framebuffer {
public:
- explicit GLFramebuffer(const GLES20RenderEngine& engine);
+ explicit GLFramebuffer(const GLESRenderEngine& engine);
~GLFramebuffer() override;
- bool setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer) override;
+ bool setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer, bool isProtected) override;
EGLImageKHR getEGLImage() const { return mEGLImage; }
uint32_t getTextureName() const { return mTextureName; }
uint32_t getFramebufferName() const { return mFramebufferName; }
diff --git a/libs/renderengine/gl/GLImage.cpp b/libs/renderengine/gl/GLImage.cpp
index 5a92093..587cb31 100644
--- a/libs/renderengine/gl/GLImage.cpp
+++ b/libs/renderengine/gl/GLImage.cpp
@@ -19,7 +19,7 @@
#include <vector>
#include <log/log.h>
-#include "GLES20RenderEngine.h"
+#include "GLESRenderEngine.h"
#include "GLExtensions.h"
namespace android {
@@ -43,7 +43,7 @@
return attrs;
}
-GLImage::GLImage(const GLES20RenderEngine& engine) : mEGLDisplay(engine.getEGLDisplay()) {}
+GLImage::GLImage(const GLESRenderEngine& engine) : mEGLDisplay(engine.getEGLDisplay()) {}
GLImage::~GLImage() {
setNativeWindowBuffer(nullptr, false);
@@ -65,6 +65,7 @@
ALOGE("failed to create EGLImage: %#x", eglGetError());
return false;
}
+ mProtected = isProtected;
}
return true;
diff --git a/libs/renderengine/gl/GLImage.h b/libs/renderengine/gl/GLImage.h
index 0e451f8..59d6ce3 100644
--- a/libs/renderengine/gl/GLImage.h
+++ b/libs/renderengine/gl/GLImage.h
@@ -29,20 +29,22 @@
namespace renderengine {
namespace gl {
-class GLES20RenderEngine;
+class GLESRenderEngine;
class GLImage : public renderengine::Image {
public:
- explicit GLImage(const GLES20RenderEngine& engine);
+ explicit GLImage(const GLESRenderEngine& engine);
~GLImage() override;
bool setNativeWindowBuffer(ANativeWindowBuffer* buffer, bool isProtected) override;
EGLImageKHR getEGLImage() const { return mEGLImage; }
+ bool isProtected() const { return mProtected; }
private:
EGLDisplay mEGLDisplay;
EGLImageKHR mEGLImage = EGL_NO_IMAGE_KHR;
+ bool mProtected = false;
DISALLOW_COPY_AND_ASSIGN(GLImage);
};
diff --git a/libs/renderengine/gl/ProgramCache.cpp b/libs/renderengine/gl/ProgramCache.cpp
index d0916ad..bf2354d 100644
--- a/libs/renderengine/gl/ProgramCache.cpp
+++ b/libs/renderengine/gl/ProgramCache.cpp
@@ -77,7 +77,8 @@
return f;
}
-void ProgramCache::primeCache(bool useColorManagement) {
+void ProgramCache::primeCache(EGLContext context, bool useColorManagement) {
+ auto& cache = mCaches[context];
uint32_t shaderCount = 0;
uint32_t keyMask = Key::BLEND_MASK | Key::OPACITY_MASK | Key::ALPHA_MASK | Key::TEXTURE_MASK
| Key::ROUNDED_CORNERS_MASK;
@@ -92,8 +93,8 @@
if (tex != Key::TEXTURE_OFF && tex != Key::TEXTURE_EXT && tex != Key::TEXTURE_2D) {
continue;
}
- if (mCache.count(shaderKey) == 0) {
- mCache.emplace(shaderKey, generateProgram(shaderKey));
+ if (cache.count(shaderKey) == 0) {
+ cache.emplace(shaderKey, generateProgram(shaderKey));
shaderCount++;
}
}
@@ -109,8 +110,8 @@
shaderKey.set(Key::OPACITY_MASK,
(i & 1) ? Key::OPACITY_OPAQUE : Key::OPACITY_TRANSLUCENT);
shaderKey.set(Key::ALPHA_MASK, (i & 2) ? Key::ALPHA_LT_ONE : Key::ALPHA_EQ_ONE);
- if (mCache.count(shaderKey) == 0) {
- mCache.emplace(shaderKey, generateProgram(shaderKey));
+ if (cache.count(shaderKey) == 0) {
+ cache.emplace(shaderKey, generateProgram(shaderKey));
shaderCount++;
}
}
@@ -215,7 +216,7 @@
const highp float c2 = (2413.0 / 4096.0) * 32.0;
const highp float c3 = (2392.0 / 4096.0) * 32.0;
- highp vec3 tmp = pow(color, 1.0 / vec3(m2));
+ highp vec3 tmp = pow(clamp(color, 0.0, 1.0), 1.0 / vec3(m2));
tmp = max(tmp - c1, 0.0) / (c2 - c3 * tmp);
return pow(tmp, 1.0 / vec3(m1));
}
@@ -695,20 +696,21 @@
return std::make_unique<Program>(needs, vs.string(), fs.string());
}
-void ProgramCache::useProgram(const Description& description) {
+void ProgramCache::useProgram(EGLContext context, const Description& description) {
// generate the key for the shader based on the description
Key needs(computeKey(description));
// look-up the program in the cache
- auto it = mCache.find(needs);
- if (it == mCache.end()) {
+ auto& cache = mCaches[context];
+ auto it = cache.find(needs);
+ if (it == cache.end()) {
// we didn't find our program, so generate one...
nsecs_t time = systemTime();
- it = mCache.emplace(needs, generateProgram(needs)).first;
+ it = cache.emplace(needs, generateProgram(needs)).first;
time = systemTime() - time;
- ALOGV(">>> generated new program: needs=%08X, time=%u ms (%zu programs)", needs.mKey,
- uint32_t(ns2ms(time)), mCache.size());
+ ALOGV(">>> generated new program for context %p: needs=%08X, time=%u ms (%zu programs)",
+ context, needs.mKey, uint32_t(ns2ms(time)), cache.size());
}
// here we have a suitable program for this description
diff --git a/libs/renderengine/gl/ProgramCache.h b/libs/renderengine/gl/ProgramCache.h
index 653aaf0..400ad74 100644
--- a/libs/renderengine/gl/ProgramCache.h
+++ b/libs/renderengine/gl/ProgramCache.h
@@ -20,6 +20,7 @@
#include <memory>
#include <unordered_map>
+#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <renderengine/private/Description.h>
#include <utils/Singleton.h>
@@ -178,13 +179,13 @@
~ProgramCache() = default;
// Generate shaders to populate the cache
- void primeCache(bool useColorManagement);
+ void primeCache(const EGLContext context, bool useColorManagement);
- size_t getSize() const { return mCache.size(); }
+ size_t getSize(const EGLContext context) { return mCaches[context].size(); }
// useProgram lookup a suitable program in the cache or generates one
// if none can be found.
- void useProgram(const Description& description);
+ void useProgram(const EGLContext context, const Description& description);
private:
// compute a cache Key from a Description
@@ -206,7 +207,8 @@
// Key/Value map used for caching Programs. Currently the cache
// is never shrunk (and the GL program objects are never deleted).
- std::unordered_map<Key, std::unique_ptr<Program>, Key::Hash> mCache;
+ std::unordered_map<EGLContext, std::unordered_map<Key, std::unique_ptr<Program>, Key::Hash>>
+ mCaches;
};
} // namespace gl
diff --git a/libs/renderengine/include/renderengine/Framebuffer.h b/libs/renderengine/include/renderengine/Framebuffer.h
index 558b9c7..66eb9ef 100644
--- a/libs/renderengine/include/renderengine/Framebuffer.h
+++ b/libs/renderengine/include/renderengine/Framebuffer.h
@@ -27,7 +27,7 @@
public:
virtual ~Framebuffer() = default;
- virtual bool setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer) = 0;
+ virtual bool setNativeWindowBuffer(ANativeWindowBuffer* nativeBuffer, bool isProtected) = 0;
};
} // namespace renderengine
diff --git a/libs/renderengine/include/renderengine/RenderEngine.h b/libs/renderengine/include/renderengine/RenderEngine.h
index bb7f4df..5e88159 100644
--- a/libs/renderengine/include/renderengine/RenderEngine.h
+++ b/libs/renderengine/include/renderengine/RenderEngine.h
@@ -39,7 +39,6 @@
namespace android {
-class String8;
class Rect;
class Region;
@@ -54,6 +53,11 @@
class RenderEngine;
}
+enum class Protection {
+ UNPROTECTED = 1,
+ PROTECTED = 2,
+};
+
class RenderEngine {
public:
enum FeatureFlag {
@@ -76,7 +80,7 @@
virtual void primeCache() const = 0;
// dump the extension strings. always call the base class.
- virtual void dump(String8& result) = 0;
+ virtual void dump(std::string& result) = 0;
virtual bool useNativeFenceSync() const = 0;
virtual bool useWaitSync() const = 0;
@@ -151,6 +155,10 @@
// ----- BEGIN NEW INTERFACE -----
+ virtual bool isProtected() const = 0;
+ virtual bool supportsProtectedContent() const = 0;
+ virtual bool useProtectedContext(bool useProtectedContext) = 0;
+
// Renders layers for a particular display via GPU composition. This method
// should be called for every display that needs to be rendered via the GPU.
// @param settings The display-wide settings that should be applied prior to
@@ -183,12 +191,12 @@
public:
BindNativeBufferAsFramebuffer(RenderEngine& engine, ANativeWindowBuffer* buffer)
: mEngine(engine), mFramebuffer(mEngine.createFramebuffer()), mStatus(NO_ERROR) {
- mStatus = mFramebuffer->setNativeWindowBuffer(buffer)
+ mStatus = mFramebuffer->setNativeWindowBuffer(buffer, mEngine.isProtected())
? mEngine.bindFrameBuffer(mFramebuffer.get())
: NO_MEMORY;
}
~BindNativeBufferAsFramebuffer() {
- mFramebuffer->setNativeWindowBuffer(nullptr);
+ mFramebuffer->setNativeWindowBuffer(nullptr, false);
mEngine.unbindFrameBuffer(mFramebuffer.get());
}
status_t getStatus() const { return mStatus; }
diff --git a/libs/renderengine/tests/Android.bp b/libs/renderengine/tests/Android.bp
index 65b7c82..051b8b6 100644
--- a/libs/renderengine/tests/Android.bp
+++ b/libs/renderengine/tests/Android.bp
@@ -24,6 +24,7 @@
"librenderengine",
],
shared_libs: [
+ "libbase",
"libcutils",
"libEGL",
"libGLESv2",
diff --git a/libs/sensorprivacy/Android.bp b/libs/sensorprivacy/Android.bp
new file mode 100644
index 0000000..e0e3469
--- /dev/null
+++ b/libs/sensorprivacy/Android.bp
@@ -0,0 +1,47 @@
+// Copyright 2018 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.
+
+cc_library_shared {
+ name: "libsensorprivacy",
+
+ aidl: {
+ export_aidl_headers: true,
+ local_include_dirs: ["aidl"],
+ },
+
+ cflags: [
+ "-Wall",
+ "-Wextra",
+ "-Werror",
+ "-Wzero-as-null-pointer-constant",
+ ],
+
+ srcs: [
+ "aidl/android/hardware/ISensorPrivacyListener.aidl",
+ "aidl/android/hardware/ISensorPrivacyManager.aidl",
+ "SensorPrivacyManager.cpp",
+ ],
+
+ shared_libs: [
+ "libbinder",
+ "libcutils",
+ "libutils",
+ "liblog",
+ "libhardware",
+ ],
+
+ export_include_dirs: ["include"],
+
+ export_shared_lib_headers: ["libbinder"],
+}
diff --git a/libs/sensorprivacy/SensorPrivacyManager.cpp b/libs/sensorprivacy/SensorPrivacyManager.cpp
new file mode 100644
index 0000000..1da79a0
--- /dev/null
+++ b/libs/sensorprivacy/SensorPrivacyManager.cpp
@@ -0,0 +1,88 @@
+/*
+ * Copyright (C) 2018 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 <mutex>
+#include <unistd.h>
+
+#include <binder/Binder.h>
+#include <binder/IServiceManager.h>
+#include <sensorprivacy/SensorPrivacyManager.h>
+
+#include <utils/SystemClock.h>
+
+namespace android {
+
+SensorPrivacyManager::SensorPrivacyManager()
+{
+}
+
+sp<hardware::ISensorPrivacyManager> SensorPrivacyManager::getService()
+{
+ std::lock_guard<Mutex> scoped_lock(mLock);
+ int64_t startTime = 0;
+ sp<hardware::ISensorPrivacyManager> service = mService;
+ while (service == nullptr || !IInterface::asBinder(service)->isBinderAlive()) {
+ sp<IBinder> binder = defaultServiceManager()->checkService(String16("sensor_privacy"));
+ if (binder == nullptr) {
+ // Wait for the sensor privacy service to come back...
+ if (startTime == 0) {
+ startTime = uptimeMillis();
+ ALOGI("Waiting for sensor privacy service");
+ } else if ((uptimeMillis() - startTime) > 1000000) {
+ ALOGW("Waiting too long for sensor privacy service, giving up");
+ service = nullptr;
+ break;
+ }
+ usleep(25000);
+ } else {
+ service = interface_cast<hardware::ISensorPrivacyManager>(binder);
+ mService = service;
+ }
+ }
+ return service;
+}
+
+void SensorPrivacyManager::addSensorPrivacyListener(
+ const sp<hardware::ISensorPrivacyListener>& listener)
+{
+ sp<hardware::ISensorPrivacyManager> service = getService();
+ if (service != nullptr) {
+ service->addSensorPrivacyListener(listener);
+ }
+}
+
+void SensorPrivacyManager::removeSensorPrivacyListener(
+ const sp<hardware::ISensorPrivacyListener>& listener)
+{
+ sp<hardware::ISensorPrivacyManager> service = getService();
+ if (service != nullptr) {
+ service->removeSensorPrivacyListener(listener);
+ }
+}
+
+bool SensorPrivacyManager::isSensorPrivacyEnabled()
+{
+ sp<hardware::ISensorPrivacyManager> service = getService();
+ if (service != nullptr) {
+ bool result;
+ service->isSensorPrivacyEnabled(&result);
+ return result;
+ }
+ // if the SensorPrivacyManager is not available then assume sensor privacy is disabled
+ return false;
+}
+
+}; // namespace android
diff --git a/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyListener.aidl b/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyListener.aidl
new file mode 100644
index 0000000..58177d8
--- /dev/null
+++ b/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyListener.aidl
@@ -0,0 +1,24 @@
+/**
+ * Copyright (c) 2018, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware;
+
+/**
+ * @hide
+ */
+oneway interface ISensorPrivacyListener {
+ void onSensorPrivacyChanged(boolean enabled);
+}
diff --git a/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyManager.aidl b/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyManager.aidl
new file mode 100644
index 0000000..4c2d5db
--- /dev/null
+++ b/libs/sensorprivacy/aidl/android/hardware/ISensorPrivacyManager.aidl
@@ -0,0 +1,30 @@
+/**
+ * Copyright (c) 2018, The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.hardware;
+
+import android.hardware.ISensorPrivacyListener;
+
+/** @hide */
+interface ISensorPrivacyManager {
+ void addSensorPrivacyListener(in ISensorPrivacyListener listener);
+
+ void removeSensorPrivacyListener(in ISensorPrivacyListener listener);
+
+ boolean isSensorPrivacyEnabled();
+
+ void setSensorPrivacy(boolean enable);
+}
diff --git a/libs/sensorprivacy/include/sensorprivacy/SensorPrivacyManager.h b/libs/sensorprivacy/include/sensorprivacy/SensorPrivacyManager.h
new file mode 100644
index 0000000..8826595
--- /dev/null
+++ b/libs/sensorprivacy/include/sensorprivacy/SensorPrivacyManager.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+#ifndef ANDROID_SENSOR_PRIVACY_MANAGER_H
+#define ANDROID_SENSOR_PRIVACY_MANAGER_H
+
+#include "android/hardware/ISensorPrivacyListener.h"
+#include "android/hardware/ISensorPrivacyManager.h"
+
+#include <utils/threads.h>
+
+// ---------------------------------------------------------------------------
+namespace android {
+
+class SensorPrivacyManager
+{
+public:
+ SensorPrivacyManager();
+
+ void addSensorPrivacyListener(const sp<hardware::ISensorPrivacyListener>& listener);
+ void removeSensorPrivacyListener(const sp<hardware::ISensorPrivacyListener>& listener);
+ bool isSensorPrivacyEnabled();
+
+private:
+ Mutex mLock;
+ sp<hardware::ISensorPrivacyManager> mService;
+ sp<hardware::ISensorPrivacyManager> getService();
+};
+
+
+}; // namespace android
+// ---------------------------------------------------------------------------
+
+#endif // ANDROID_SENSOR_PRIVACY_MANAGER_H
diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp
index a4d0dd1..956465c 100644
--- a/libs/ui/Android.bp
+++ b/libs/ui/Android.bp
@@ -26,7 +26,6 @@
"-Werror",
],
cppflags: [
- "-std=c++1z",
"-Weverything",
// The static constructors and destructors in this library have not been noted to
diff --git a/libs/ui/BufferHubBuffer.cpp b/libs/ui/BufferHubBuffer.cpp
index e747ee1..0582e1a 100644
--- a/libs/ui/BufferHubBuffer.cpp
+++ b/libs/ui/BufferHubBuffer.cpp
@@ -40,6 +40,7 @@
#include <android-base/unique_fd.h>
#include <ui/BufferHubBuffer.h>
+#include <ui/BufferHubDefs.h>
using android::base::unique_fd;
using android::dvr::BufferTraits;
@@ -61,6 +62,15 @@
// to use Binder.
static constexpr char kBufferHubClientPath[] = "system/buffer_hub/client";
+using BufferHubDefs::AnyClientAcquired;
+using BufferHubDefs::AnyClientGained;
+using BufferHubDefs::AnyClientPosted;
+using BufferHubDefs::IsClientAcquired;
+using BufferHubDefs::IsClientGained;
+using BufferHubDefs::IsClientPosted;
+using BufferHubDefs::IsClientReleased;
+using BufferHubDefs::kHighBitsMask;
+
} // namespace
BufferHubClient::BufferHubClient() : Client(ClientChannelFactory::Create(kBufferHubClientPath)) {}
@@ -71,7 +81,7 @@
BufferHubClient::~BufferHubClient() {}
bool BufferHubClient::IsValid() const {
- return IsConnected() && GetChannelHandle().valid();
+ return IsConnected() && GetChannelHandle().valid();
}
LocalChannelHandle BufferHubClient::TakeChannelHandle() {
@@ -85,22 +95,21 @@
BufferHubBuffer::BufferHubBuffer(uint32_t width, uint32_t height, uint32_t layerCount,
uint32_t format, uint64_t usage, size_t mUserMetadataSize) {
ATRACE_CALL();
- ALOGD("BufferHubBuffer::BufferHubBuffer: width=%u height=%u layerCount=%u, format=%u "
- "usage=%" PRIx64 " mUserMetadataSize=%zu",
- width, height, layerCount, format, usage, mUserMetadataSize);
+ ALOGD("%s: width=%u height=%u layerCount=%u, format=%u usage=%" PRIx64 " mUserMetadataSize=%zu",
+ __FUNCTION__, width, height, layerCount, format, usage, mUserMetadataSize);
auto status =
mClient.InvokeRemoteMethod<DetachedBufferRPC::Create>(width, height, layerCount, format,
usage, mUserMetadataSize);
if (!status) {
- ALOGE("BufferHubBuffer::BufferHubBuffer: Failed to create detached buffer: %s",
+ ALOGE("%s: Failed to create detached buffer: %s", __FUNCTION__,
status.GetErrorMessage().c_str());
mClient.Close(-status.error());
}
const int ret = ImportGraphicBuffer();
if (ret < 0) {
- ALOGE("BufferHubBuffer::BufferHubBuffer: Failed to import buffer: %s", strerror(-ret));
+ ALOGE("%s: Failed to import buffer: %s", __FUNCTION__, strerror(-ret));
mClient.Close(ret);
}
}
@@ -109,7 +118,7 @@
: mClient(std::move(mChannelHandle)) {
const int ret = ImportGraphicBuffer();
if (ret < 0) {
- ALOGE("BufferHubBuffer::BufferHubBuffer: Failed to import buffer: %s", strerror(-ret));
+ ALOGE("%s: Failed to import buffer: %s", __FUNCTION__, strerror(-ret));
mClient.Close(ret);
}
}
@@ -119,14 +128,14 @@
auto status = mClient.InvokeRemoteMethod<DetachedBufferRPC::Import>();
if (!status) {
- ALOGE("BufferHubBuffer::BufferHubBuffer: Failed to import GraphicBuffer: %s",
+ ALOGE("%s: Failed to import GraphicBuffer: %s", __FUNCTION__,
status.GetErrorMessage().c_str());
return -status.error();
}
BufferTraits<LocalHandle> bufferTraits = status.take();
if (bufferTraits.id() < 0) {
- ALOGE("BufferHubBuffer::BufferHubBuffer: Received an invalid id!");
+ ALOGE("%s: Received an invalid id!", __FUNCTION__);
return -EIO;
}
@@ -139,23 +148,35 @@
mMetadata = BufferHubMetadata::Import(std::move(metadataFd));
if (!mMetadata.IsValid()) {
- ALOGE("BufferHubBuffer::ImportGraphicBuffer: invalid metadata.");
+ ALOGE("%s: invalid metadata.", __FUNCTION__);
return -ENOMEM;
}
if (mMetadata.metadata_size() != bufferTraits.metadata_size()) {
- ALOGE("BufferHubBuffer::ImportGraphicBuffer: metadata buffer too small: "
- "%zu, expected: %" PRIu64 ".",
+ ALOGE("%s: metadata buffer too small: %zu, expected: %" PRIu64 ".", __FUNCTION__,
mMetadata.metadata_size(), bufferTraits.metadata_size());
return -ENOMEM;
}
size_t metadataSize = static_cast<size_t>(bufferTraits.metadata_size());
- if (metadataSize < dvr::BufferHubDefs::kMetadataHeaderSize) {
- ALOGE("BufferHubBuffer::ImportGraphicBuffer: metadata too small: %zu", metadataSize);
+ if (metadataSize < BufferHubDefs::kMetadataHeaderSize) {
+ ALOGE("%s: metadata too small: %zu", __FUNCTION__, metadataSize);
return -EINVAL;
}
+ // Populate shortcuts to the atomics in metadata.
+ auto metadata_header = mMetadata.metadata_header();
+ buffer_state_ = &metadata_header->buffer_state;
+ fence_state_ = &metadata_header->fence_state;
+ active_clients_bit_mask_ = &metadata_header->active_clients_bit_mask;
+ // The C++ standard recommends (but does not require) that lock-free atomic operations are
+ // also address-free, that is, suitable for communication between processes using shared
+ // memory.
+ LOG_ALWAYS_FATAL_IF(!std::atomic_is_lock_free(buffer_state_) ||
+ !std::atomic_is_lock_free(fence_state_) ||
+ !std::atomic_is_lock_free(active_clients_bit_mask_),
+ "Atomic variables in ashmen are not lock free.");
+
// Import the buffer: We only need to hold on the native_handle_t here so that
// GraphicBuffer instance can be created in future.
mBufferHandle = bufferTraits.take_buffer_handle();
@@ -175,8 +196,94 @@
mClientStateMask = bufferTraits.client_state_mask();
// TODO(b/112012161) Set up shared fences.
- ALOGD("BufferHubBuffer::ImportGraphicBuffer: id=%d, buffer_state=%" PRIx64 ".", id(),
- mMetadata.metadata_header()->buffer_state.load(std::memory_order_acquire));
+ ALOGD("%s: id=%d, buffer_state=%" PRIx32 ".", __FUNCTION__, id(),
+ buffer_state_->load(std::memory_order_acquire));
+ return 0;
+}
+
+int BufferHubBuffer::Gain() {
+ uint32_t current_buffer_state = buffer_state_->load(std::memory_order_acquire);
+ if (IsClientGained(current_buffer_state, mClientStateMask)) {
+ ALOGV("%s: Buffer is already gained by this client %" PRIx32 ".", __FUNCTION__,
+ mClientStateMask);
+ return 0;
+ }
+ do {
+ if (AnyClientGained(current_buffer_state & (~mClientStateMask)) ||
+ AnyClientAcquired(current_buffer_state)) {
+ ALOGE("%s: Buffer is in use, id=%d mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
+ __FUNCTION__, mId, mClientStateMask, current_buffer_state);
+ return -EBUSY;
+ }
+ // Change the buffer state to gained state, whose value happens to be the same as
+ // mClientStateMask.
+ } while (!buffer_state_->compare_exchange_weak(current_buffer_state, mClientStateMask,
+ std::memory_order_acq_rel,
+ std::memory_order_acquire));
+ // TODO(b/119837586): Update fence state and return GPU fence.
+ return 0;
+}
+
+int BufferHubBuffer::Post() {
+ uint32_t current_buffer_state = buffer_state_->load(std::memory_order_acquire);
+ uint32_t current_active_clients_bit_mask = 0U;
+ uint32_t updated_buffer_state = 0U;
+ do {
+ if (!IsClientGained(current_buffer_state, mClientStateMask)) {
+ ALOGE("%s: Cannot post a buffer that is not gained by this client. buffer_id=%d "
+ "mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
+ __FUNCTION__, mId, mClientStateMask, current_buffer_state);
+ return -EBUSY;
+ }
+ // Set the producer client buffer state to released, other clients' buffer state to posted.
+ current_active_clients_bit_mask = active_clients_bit_mask_->load(std::memory_order_acquire);
+ updated_buffer_state =
+ current_active_clients_bit_mask & (~mClientStateMask) & kHighBitsMask;
+ } while (!buffer_state_->compare_exchange_weak(current_buffer_state, updated_buffer_state,
+ std::memory_order_acq_rel,
+ std::memory_order_acquire));
+ // TODO(b/119837586): Update fence state and return GPU fence if needed.
+ return 0;
+}
+
+int BufferHubBuffer::Acquire() {
+ uint32_t current_buffer_state = buffer_state_->load(std::memory_order_acquire);
+ if (IsClientAcquired(current_buffer_state, mClientStateMask)) {
+ ALOGV("%s: Buffer is already acquired by this client %" PRIx32 ".", __FUNCTION__,
+ mClientStateMask);
+ return 0;
+ }
+ uint32_t updated_buffer_state = 0U;
+ do {
+ if (!IsClientPosted(current_buffer_state, mClientStateMask)) {
+ ALOGE("%s: Cannot acquire a buffer that is not in posted state. buffer_id=%d "
+ "mClientStateMask=%" PRIx32 " state=%" PRIx32 ".",
+ __FUNCTION__, mId, mClientStateMask, current_buffer_state);
+ return -EBUSY;
+ }
+ // Change the buffer state for this consumer from posted to acquired.
+ updated_buffer_state = current_buffer_state ^ mClientStateMask;
+ } while (!buffer_state_->compare_exchange_weak(current_buffer_state, updated_buffer_state,
+ std::memory_order_acq_rel,
+ std::memory_order_acquire));
+ // TODO(b/119837586): Update fence state and return GPU fence.
+ return 0;
+}
+
+int BufferHubBuffer::Release() {
+ uint32_t current_buffer_state = buffer_state_->load(std::memory_order_acquire);
+ if (IsClientReleased(current_buffer_state, mClientStateMask)) {
+ ALOGV("%s: Buffer is already released by this client %" PRIx32 ".", __FUNCTION__,
+ mClientStateMask);
+ return 0;
+ }
+ uint32_t updated_buffer_state = 0U;
+ do {
+ updated_buffer_state = current_buffer_state & (~mClientStateMask);
+ } while (!buffer_state_->compare_exchange_weak(current_buffer_state, updated_buffer_state,
+ std::memory_order_acq_rel,
+ std::memory_order_acquire));
+ // TODO(b/119837586): Update fence state and return GPU fence if needed.
return 0;
}
@@ -189,12 +296,12 @@
Status<LocalChannelHandle> BufferHubBuffer::Duplicate() {
ATRACE_CALL();
- ALOGD("BufferHubBuffer::Duplicate: id=%d.", mId);
+ ALOGD("%s: id=%d.", __FUNCTION__, mId);
auto statusOrHandle = mClient.InvokeRemoteMethod<DetachedBufferRPC::Duplicate>();
if (!statusOrHandle.ok()) {
- ALOGE("BufferHubBuffer::Duplicate: Failed to duplicate buffer (id=%d): %s.", mId,
+ ALOGE("%s: Failed to duplicate buffer (id=%d): %s.", __FUNCTION__, mId,
statusOrHandle.GetErrorMessage().c_str());
}
return statusOrHandle;
diff --git a/libs/ui/BufferHubMetadata.cpp b/libs/ui/BufferHubMetadata.cpp
index 18d9a2c..816707d 100644
--- a/libs/ui/BufferHubMetadata.cpp
+++ b/libs/ui/BufferHubMetadata.cpp
@@ -16,6 +16,7 @@
#include <errno.h>
#include <sys/mman.h>
+#include <limits>
#include <cutils/ashmem.h>
#include <log/log.h>
@@ -29,8 +30,8 @@
} // namespace
-using dvr::BufferHubDefs::kMetadataHeaderSize;
-using dvr::BufferHubDefs::MetadataHeader;
+using BufferHubDefs::kMetadataHeaderSize;
+using BufferHubDefs::MetadataHeader;
/* static */
BufferHubMetadata BufferHubMetadata::Create(size_t userMetadataSize) {
diff --git a/libs/ui/Gralloc2.cpp b/libs/ui/Gralloc2.cpp
index 37cf617..20f27c5 100644
--- a/libs/ui/Gralloc2.cpp
+++ b/libs/ui/Gralloc2.cpp
@@ -42,9 +42,6 @@
for (const auto bit : hardware::hidl_enum_range<BufferUsage>()) {
bits = bits | bit;
}
- // TODO(b/72323293, b/72703005): Remove these additional bits
- bits = bits | (1 << 10) | (1 << 13);
-
return bits;
}();
return valid10UsageBits;
diff --git a/libs/ui/GraphicBuffer.cpp b/libs/ui/GraphicBuffer.cpp
index e606e26..f408fcb 100644
--- a/libs/ui/GraphicBuffer.cpp
+++ b/libs/ui/GraphicBuffer.cpp
@@ -104,6 +104,7 @@
buffer->desc().width, buffer->desc().height,
static_cast<PixelFormat>(buffer->desc().format),
buffer->desc().layers, buffer->desc().usage, buffer->desc().stride);
+ mBufferId = buffer->id();
mBufferHubBuffer = std::move(buffer);
}
#endif // LIBUI_IN_VNDK
diff --git a/libs/ui/GraphicBufferAllocator.cpp b/libs/ui/GraphicBufferAllocator.cpp
index eaba1ed..f56e6b9 100644
--- a/libs/ui/GraphicBufferAllocator.cpp
+++ b/libs/ui/GraphicBufferAllocator.cpp
@@ -24,9 +24,9 @@
#include <grallocusage/GrallocUsageConversion.h>
+#include <android-base/stringprintf.h>
#include <log/log.h>
#include <utils/Singleton.h>
-#include <utils/String8.h>
#include <utils/Trace.h>
#include <ui/Gralloc2.h>
@@ -35,6 +35,8 @@
namespace android {
// ---------------------------------------------------------------------------
+using base::StringAppendF;
+
ANDROID_SINGLETON_STATIC_INSTANCE( GraphicBufferAllocator )
Mutex GraphicBufferAllocator::sLock;
@@ -50,46 +52,37 @@
GraphicBufferAllocator::~GraphicBufferAllocator() {}
-void GraphicBufferAllocator::dump(String8& result) const
-{
+void GraphicBufferAllocator::dump(std::string& result) const {
Mutex::Autolock _l(sLock);
KeyedVector<buffer_handle_t, alloc_rec_t>& list(sAllocList);
size_t total = 0;
- const size_t SIZE = 4096;
- char buffer[SIZE];
- snprintf(buffer, SIZE, "Allocated buffers:\n");
- result.append(buffer);
+ result.append("Allocated buffers:\n");
const size_t c = list.size();
for (size_t i=0 ; i<c ; i++) {
const alloc_rec_t& rec(list.valueAt(i));
if (rec.size) {
- snprintf(buffer, SIZE, "%10p: %7.2f KiB | %4u (%4u) x %4u | %4u | %8X | 0x%" PRIx64
- " | %s\n",
- list.keyAt(i), rec.size/1024.0,
- rec.width, rec.stride, rec.height, rec.layerCount, rec.format,
- rec.usage, rec.requestorName.c_str());
+ StringAppendF(&result,
+ "%10p: %7.2f KiB | %4u (%4u) x %4u | %4u | %8X | 0x%" PRIx64 " | %s\n",
+ list.keyAt(i), rec.size / 1024.0, rec.width, rec.stride, rec.height,
+ rec.layerCount, rec.format, rec.usage, rec.requestorName.c_str());
} else {
- snprintf(buffer, SIZE, "%10p: unknown | %4u (%4u) x %4u | %4u | %8X | 0x%" PRIx64
- " | %s\n",
- list.keyAt(i),
- rec.width, rec.stride, rec.height, rec.layerCount, rec.format,
- rec.usage, rec.requestorName.c_str());
+ StringAppendF(&result,
+ "%10p: unknown | %4u (%4u) x %4u | %4u | %8X | 0x%" PRIx64 " | %s\n",
+ list.keyAt(i), rec.width, rec.stride, rec.height, rec.layerCount,
+ rec.format, rec.usage, rec.requestorName.c_str());
}
- result.append(buffer);
total += rec.size;
}
- snprintf(buffer, SIZE, "Total allocated (estimate): %.2f KB\n", total/1024.0);
- result.append(buffer);
+ StringAppendF(&result, "Total allocated (estimate): %.2f KB\n", total / 1024.0);
- std::string deviceDump = mAllocator->dumpDebugInfo();
- result.append(deviceDump.c_str(), deviceDump.size());
+ result.append(mAllocator->dumpDebugInfo());
}
void GraphicBufferAllocator::dumpToSystemLog()
{
- String8 s;
+ std::string s;
GraphicBufferAllocator::getInstance().dump(s);
- ALOGD("%s", s.string());
+ ALOGD("%s", s.c_str());
}
status_t GraphicBufferAllocator::allocate(uint32_t width, uint32_t height,
@@ -108,6 +101,9 @@
if (layerCount < 1)
layerCount = 1;
+ // TODO(b/72323293, b/72703005): Remove these invalid bits from callers
+ usage &= ~static_cast<uint64_t>((1 << 10) | (1 << 13));
+
Gralloc2::IMapper::BufferDescriptorInfo info = {};
info.width = width;
info.height = height;
diff --git a/libs/ui/Region.cpp b/libs/ui/Region.cpp
index 618c7d6..3bd3748 100644
--- a/libs/ui/Region.cpp
+++ b/libs/ui/Region.cpp
@@ -19,8 +19,9 @@
#include <inttypes.h>
#include <limits.h>
+#include <android-base/stringprintf.h>
+
#include <utils/Log.h>
-#include <utils/String8.h>
#include <utils/CallStack.h>
#include <ui/Rect.h>
@@ -41,6 +42,8 @@
namespace android {
// ----------------------------------------------------------------------------
+using base::StringAppendF;
+
enum {
op_nand = region_operator<Rect>::op_nand,
op_and = region_operator<Rect>::op_and,
@@ -868,16 +871,14 @@
// ----------------------------------------------------------------------------
-void Region::dump(String8& out, const char* what, uint32_t /* flags */) const
-{
+void Region::dump(std::string& out, const char* what, uint32_t /* flags */) const {
const_iterator head = begin();
const_iterator const tail = end();
- out.appendFormat(" Region %s (this=%p, count=%" PRIdPTR ")\n",
- what, this, tail - head);
+ StringAppendF(&out, " Region %s (this=%p, count=%" PRIdPTR ")\n", what, this, tail - head);
while (head != tail) {
- out.appendFormat(" [%3d, %3d, %3d, %3d]\n", head->left, head->top,
- head->right, head->bottom);
+ StringAppendF(&out, " [%3d, %3d, %3d, %3d]\n", head->left, head->top, head->right,
+ head->bottom);
++head;
}
}
diff --git a/libs/ui/UiConfig.cpp b/libs/ui/UiConfig.cpp
index 7730690..0ac863d 100644
--- a/libs/ui/UiConfig.cpp
+++ b/libs/ui/UiConfig.cpp
@@ -18,8 +18,7 @@
namespace android {
-void appendUiConfigString(String8& configStr)
-{
+void appendUiConfigString(std::string& configStr) {
static const char* config =
" [libui]";
configStr.append(config);
diff --git a/libs/ui/include/ui/BufferHubBuffer.h b/libs/ui/include/ui/BufferHubBuffer.h
index 6850b43..90dd391 100644
--- a/libs/ui/include/ui/BufferHubBuffer.h
+++ b/libs/ui/include/ui/BufferHubBuffer.h
@@ -34,11 +34,11 @@
#pragma clang diagnostic ignored "-Wunused-template"
#pragma clang diagnostic ignored "-Wweak-vtables"
#include <pdx/client.h>
-#include <private/dvr/buffer_hub_defs.h>
#include <private/dvr/native_handle_wrapper.h>
#pragma clang diagnostic pop
#include <android/hardware_buffer.h>
+#include <ui/BufferHubDefs.h>
#include <ui/BufferHubMetadata.h>
namespace android {
@@ -86,13 +86,13 @@
const native_handle_t* DuplicateHandle() { return mBufferHandle.DuplicateHandle(); }
// Returns the current value of MetadataHeader::buffer_state.
- uint64_t buffer_state() {
+ uint32_t buffer_state() {
return mMetadata.metadata_header()->buffer_state.load(std::memory_order_acquire);
}
// A state mask which is unique to a buffer hub client among all its siblings sharing the same
// concrete graphic buffer.
- uint64_t client_state_mask() const { return mClientStateMask; }
+ uint32_t client_state_mask() const { return mClientStateMask; }
size_t user_metadata_size() const { return mMetadata.user_metadata_size(); }
@@ -103,6 +103,27 @@
// to read from and/or write into.
bool IsValid() const { return mBufferHandle.IsValid(); }
+ // Gains the buffer for exclusive write permission. Read permission is implied once a buffer is
+ // gained.
+ // The buffer can be gained as long as there is no other client in acquired or gained state.
+ int Gain();
+
+ // Posts the gained buffer for other buffer clients to use the buffer.
+ // The buffer can be posted iff the buffer state for this client is gained.
+ // After posting the buffer, this client is put to released state and does not have access to
+ // the buffer for this cycle of the usage of the buffer.
+ int Post();
+
+ // Acquires the buffer for shared read permission.
+ // The buffer can be acquired iff the buffer state for this client is posted.
+ int Acquire();
+
+ // Releases the buffer.
+ // The buffer can be released from any buffer state.
+ // After releasing the buffer, this client no longer have any permissions to the buffer for the
+ // current cycle of the usage of the buffer.
+ int Release();
+
// Returns the event mask for all the events that are pending on this buffer (see sys/poll.h for
// all possible bits).
pdx::Status<int> GetEventMask(int events) {
@@ -130,7 +151,10 @@
// Global id for the buffer that is consistent across processes.
int mId = -1;
- uint64_t mClientStateMask = 0;
+
+ // Client state mask of this BufferHubBuffer object. It is unique amoung all
+ // clients/users of the buffer.
+ uint32_t mClientStateMask = 0U;
// Stores ground truth of the buffer.
AHardwareBuffer_Desc mBufferDesc;
@@ -141,6 +165,10 @@
// An ashmem-based metadata object. The same shared memory are mapped to the
// bufferhubd daemon and all buffer clients.
BufferHubMetadata mMetadata;
+ // Shortcuts to the atomics inside the header of mMetadata.
+ std::atomic<uint32_t>* buffer_state_ = nullptr;
+ std::atomic<uint32_t>* fence_state_ = nullptr;
+ std::atomic<uint32_t>* active_clients_bit_mask_ = nullptr;
// PDX backend.
BufferHubClient mClient;
diff --git a/libs/ui/include/ui/BufferHubDefs.h b/libs/ui/include/ui/BufferHubDefs.h
new file mode 100644
index 0000000..d259fef
--- /dev/null
+++ b/libs/ui/include/ui/BufferHubDefs.h
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2018 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.
+ */
+
+#ifndef ANDROID_BUFFER_HUB_DEFS_H_
+#define ANDROID_BUFFER_HUB_DEFS_H_
+
+#include <atomic>
+
+#pragma clang diagnostic push
+#pragma clang diagnostic ignored "-Wpacked"
+// TODO(b/118893702): remove dependency once DvrNativeBufferMetadata moved out of libdvr
+#include <dvr/dvr_api.h>
+#pragma clang diagnostic pop
+
+namespace android {
+
+namespace BufferHubDefs {
+
+// Single buffer clients (up to 16) ownership signal.
+// 32-bit atomic unsigned int.
+// Each client takes 2 bits. The first bit locates in the first 16 bits of
+// buffer_state; the second bit locates in the last 16 bits of buffer_state.
+// Client states:
+// Gained state 11. Exclusive write state.
+// Posted state 10.
+// Acquired state 01. Shared read state.
+// Released state 00.
+//
+// MSB LSB
+// | |
+// v v
+// [C15|...|C1|C0|C15| ... |C1|C0]
+
+// Maximum number of clients a buffer can have.
+static constexpr int kMaxNumberOfClients = 16;
+
+// Definition of bit masks.
+// MSB LSB
+// | kHighBitsMask | kLowbitsMask |
+// v v v
+// [b31| ... |b16|b15| ... |b0]
+
+// The location of lower 16 bits in the 32-bit buffer state.
+static constexpr uint32_t kLowbitsMask = (1U << kMaxNumberOfClients) - 1U;
+
+// The location of higher 16 bits in the 32-bit buffer state.
+static constexpr uint32_t kHighBitsMask = ~kLowbitsMask;
+
+// The client bit mask of the first client.
+static constexpr uint32_t kFirstClientBitMask = (1U << kMaxNumberOfClients) + 1U;
+
+// Returns true if any of the client is in gained state.
+static inline bool AnyClientGained(uint32_t state) {
+ uint32_t high_bits = state >> kMaxNumberOfClients;
+ uint32_t low_bits = state & kLowbitsMask;
+ return high_bits == low_bits && low_bits != 0U;
+}
+
+// Returns true if the input client is in gained state.
+static inline bool IsClientGained(uint32_t state, uint32_t client_bit_mask) {
+ return state == client_bit_mask;
+}
+
+// Returns true if any of the client is in posted state.
+static inline bool AnyClientPosted(uint32_t state) {
+ uint32_t high_bits = state >> kMaxNumberOfClients;
+ uint32_t low_bits = state & kLowbitsMask;
+ uint32_t posted_or_acquired = high_bits ^ low_bits;
+ return posted_or_acquired & high_bits;
+}
+
+// Returns true if the input client is in posted state.
+static inline bool IsClientPosted(uint32_t state, uint32_t client_bit_mask) {
+ uint32_t client_bits = state & client_bit_mask;
+ if (client_bits == 0U) return false;
+ uint32_t low_bits = client_bits & kLowbitsMask;
+ return low_bits == 0U;
+}
+
+// Return true if any of the client is in acquired state.
+static inline bool AnyClientAcquired(uint32_t state) {
+ uint32_t high_bits = state >> kMaxNumberOfClients;
+ uint32_t low_bits = state & kLowbitsMask;
+ uint32_t posted_or_acquired = high_bits ^ low_bits;
+ return posted_or_acquired & low_bits;
+}
+
+// Return true if the input client is in acquired state.
+static inline bool IsClientAcquired(uint32_t state, uint32_t client_bit_mask) {
+ uint32_t client_bits = state & client_bit_mask;
+ if (client_bits == 0U) return false;
+ uint32_t high_bits = client_bits & kHighBitsMask;
+ return high_bits == 0U;
+}
+
+// Returns true if all clients are in released state.
+static inline bool IsBufferReleased(uint32_t state) {
+ return state == 0U;
+}
+
+// Returns true if the input client is in released state.
+static inline bool IsClientReleased(uint32_t state, uint32_t client_bit_mask) {
+ return (state & client_bit_mask) == 0U;
+}
+
+// Returns the next available buffer client's client_state_masks.
+// @params union_bits. Union of all existing clients' client_state_masks.
+static inline uint32_t FindNextAvailableClientStateMask(uint32_t union_bits) {
+ uint32_t low_union = union_bits & kLowbitsMask;
+ if (low_union == kLowbitsMask) return 0U;
+ uint32_t incremented = low_union + 1U;
+ uint32_t difference = incremented ^ low_union;
+ uint32_t new_low_bit = (difference + 1U) >> 1;
+ return new_low_bit + (new_low_bit << kMaxNumberOfClients);
+}
+
+struct __attribute__((aligned(8))) MetadataHeader {
+ // Internal data format, which can be updated as long as the size, padding and field alignment
+ // of the struct is consistent within the same ABI. As this part is subject for future updates,
+ // it's not stable cross Android version, so don't have it visible from outside of the Android
+ // platform (include Apps and vendor HAL).
+
+ // Every client takes up one bit from the higher 32 bits and one bit from the lower 32 bits in
+ // buffer_state.
+ std::atomic<uint32_t> buffer_state;
+
+ // Every client takes up one bit in fence_state. Only the lower 32 bits are valid. The upper 32
+ // bits are there for easier manipulation, but the value should be ignored.
+ std::atomic<uint32_t> fence_state;
+
+ // Every client takes up one bit from the higher 32 bits and one bit from the lower 32 bits in
+ // active_clients_bit_mask.
+ std::atomic<uint32_t> active_clients_bit_mask;
+
+ // Explicit padding 4 bytes.
+ uint32_t padding;
+
+ // The index of the buffer queue where the buffer belongs to.
+ uint64_t queue_index;
+
+ // Public data format, which should be updated with caution. See more details in dvr_api.h
+ DvrNativeBufferMetadata metadata;
+};
+
+static_assert(sizeof(MetadataHeader) == 128, "Unexpected MetadataHeader size");
+static constexpr size_t kMetadataHeaderSize = sizeof(MetadataHeader);
+
+} // namespace BufferHubDefs
+
+} // namespace android
+
+#endif // ANDROID_BUFFER_HUB_DEFS_H_
diff --git a/libs/ui/include/ui/BufferHubMetadata.h b/libs/ui/include/ui/BufferHubMetadata.h
index 4261971..2121894 100644
--- a/libs/ui/include/ui/BufferHubMetadata.h
+++ b/libs/ui/include/ui/BufferHubMetadata.h
@@ -17,26 +17,8 @@
#ifndef ANDROID_BUFFER_HUB_METADATA_H_
#define ANDROID_BUFFER_HUB_METADATA_H_
-// We would eliminate the clang warnings introduced by libdpx.
-// TODO(b/112338294): Remove those once BufferHub moved to use Binder
-#pragma clang diagnostic push
-#pragma clang diagnostic ignored "-Wconversion"
-#pragma clang diagnostic ignored "-Wdouble-promotion"
-#pragma clang diagnostic ignored "-Wgnu-case-range"
-#pragma clang diagnostic ignored "-Wgnu-zero-variadic-macro-arguments"
-#pragma clang diagnostic ignored "-Winconsistent-missing-destructor-override"
-#pragma clang diagnostic ignored "-Wnested-anon-types"
-#pragma clang diagnostic ignored "-Wpacked"
-#pragma clang diagnostic ignored "-Wshadow"
-#pragma clang diagnostic ignored "-Wsign-conversion"
-#pragma clang diagnostic ignored "-Wswitch-enum"
-#pragma clang diagnostic ignored "-Wundefined-func-template"
-#pragma clang diagnostic ignored "-Wunused-template"
-#pragma clang diagnostic ignored "-Wweak-vtables"
-#include <private/dvr/buffer_hub_defs.h>
-#pragma clang diagnostic pop
-
#include <android-base/unique_fd.h>
+#include <ui/BufferHubDefs.h>
namespace android {
@@ -84,23 +66,21 @@
bool IsValid() const { return mAshmemFd.get() != -1 && mMetadataHeader != nullptr; }
size_t user_metadata_size() const { return mUserMetadataSize; }
- size_t metadata_size() const {
- return mUserMetadataSize + dvr::BufferHubDefs::kMetadataHeaderSize;
- }
+ size_t metadata_size() const { return mUserMetadataSize + BufferHubDefs::kMetadataHeaderSize; }
const unique_fd& ashmem_fd() const { return mAshmemFd; }
- dvr::BufferHubDefs::MetadataHeader* metadata_header() { return mMetadataHeader; }
+ BufferHubDefs::MetadataHeader* metadata_header() { return mMetadataHeader; }
private:
BufferHubMetadata(size_t userMetadataSize, unique_fd ashmemFd,
- dvr::BufferHubDefs::MetadataHeader* metadataHeader);
+ BufferHubDefs::MetadataHeader* metadataHeader);
BufferHubMetadata(const BufferHubMetadata&) = delete;
void operator=(const BufferHubMetadata&) = delete;
size_t mUserMetadataSize = 0;
unique_fd mAshmemFd;
- dvr::BufferHubDefs::MetadataHeader* mMetadataHeader = nullptr;
+ BufferHubDefs::MetadataHeader* mMetadataHeader = nullptr;
};
} // namespace android
diff --git a/libs/ui/include/ui/DisplayedFrameStats.h b/libs/ui/include/ui/DisplayedFrameStats.h
new file mode 100644
index 0000000..7a70ea1
--- /dev/null
+++ b/libs/ui/include/ui/DisplayedFrameStats.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2018 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 <vector>
+
+namespace android {
+
+struct DisplayedFrameStats {
+ /* The number of frames represented by this sample. */
+ uint64_t numFrames = 0;
+ /* A histogram counting how many times a pixel of a given value was displayed onscreen for
+ * FORMAT_COMPONENT_0. The buckets of the histogram are evenly weighted, the number of buckets
+ * is device specific. eg, for RGBA_8888, if sampleComponent0 is {10, 6, 4, 1} this means that
+ * 10 red pixels were displayed onscreen in range 0x00->0x3F, 6 red pixels
+ * were displayed onscreen in range 0x40->0x7F, etc.
+ */
+ std::vector<uint64_t> component_0_sample = {};
+ /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_1. */
+ std::vector<uint64_t> component_1_sample = {};
+ /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_2. */
+ std::vector<uint64_t> component_2_sample = {};
+ /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_3. */
+ std::vector<uint64_t> component_3_sample = {};
+};
+
+} // namespace android
diff --git a/libs/ui/include/ui/GraphicBuffer.h b/libs/ui/include/ui/GraphicBuffer.h
index 81f6cd9..b73ca2b 100644
--- a/libs/ui/include/ui/GraphicBuffer.h
+++ b/libs/ui/include/ui/GraphicBuffer.h
@@ -153,6 +153,7 @@
uint32_t getLayerCount() const { return static_cast<uint32_t>(layerCount); }
Rect getBounds() const { return Rect(width, height); }
uint64_t getId() const { return mId; }
+ int32_t getBufferId() const { return mBufferId; }
uint32_t getGenerationNumber() const { return mGenerationNumber; }
void setGenerationNumber(uint32_t generation) {
@@ -247,6 +248,12 @@
uint64_t mId;
+ // System unique buffer ID. Note that this is different from mId, which is process unique. For
+ // GraphicBuffer backed by BufferHub, the mBufferId is a system unique identifier that stays the
+ // same cross process for the same chunck of underlying memory. Also note that this only applies
+ // to GraphicBuffers that are backed by BufferHub.
+ int32_t mBufferId = -1;
+
// Stores the generation number of this buffer. If this number does not
// match the BufferQueue's internal generation number (set through
// IGBP::setGenerationNumber), attempts to attach the buffer will fail.
diff --git a/libs/ui/include/ui/GraphicBufferAllocator.h b/libs/ui/include/ui/GraphicBufferAllocator.h
index 14a865e..7e2b230 100644
--- a/libs/ui/include/ui/GraphicBufferAllocator.h
+++ b/libs/ui/include/ui/GraphicBufferAllocator.h
@@ -39,7 +39,6 @@
}
class GraphicBufferMapper;
-class String8;
class GraphicBufferAllocator : public Singleton<GraphicBufferAllocator>
{
@@ -53,7 +52,7 @@
status_t free(buffer_handle_t handle);
- void dump(String8& res) const;
+ void dump(std::string& res) const;
static void dumpToSystemLog();
private:
diff --git a/libs/ui/include/ui/Region.h b/libs/ui/include/ui/Region.h
index 0a09960..79642ae 100644
--- a/libs/ui/include/ui/Region.h
+++ b/libs/ui/include/ui/Region.h
@@ -27,12 +27,11 @@
#include <android-base/macros.h>
+#include <string>
+
namespace android {
// ---------------------------------------------------------------------------
-class String8;
-
-// ---------------------------------------------------------------------------
class Region : public LightFlattenable<Region>
{
public:
@@ -144,8 +143,8 @@
status_t flatten(void* buffer, size_t size) const;
status_t unflatten(void const* buffer, size_t size);
- void dump(String8& out, const char* what, uint32_t flags=0) const;
- void dump(const char* what, uint32_t flags=0) const;
+ void dump(std::string& out, const char* what, uint32_t flags=0) const;
+ void dump(const char* what, uint32_t flags=0) const;
private:
class rasterizer;
diff --git a/libs/ui/include/ui/UiConfig.h b/libs/ui/include/ui/UiConfig.h
index fcf8ed5..d1d6014 100644
--- a/libs/ui/include/ui/UiConfig.h
+++ b/libs/ui/include/ui/UiConfig.h
@@ -17,12 +17,12 @@
#ifndef ANDROID_UI_CONFIG_H
#define ANDROID_UI_CONFIG_H
-#include <utils/String8.h>
+#include <string>
namespace android {
// Append the libui configuration details to configStr.
-void appendUiConfigString(String8& configStr);
+void appendUiConfigString(std::string& configStr);
}; // namespace android
diff --git a/libs/ui/include_vndk/ui/DisplayedFrameStats.h b/libs/ui/include_vndk/ui/DisplayedFrameStats.h
new file mode 120000
index 0000000..6014e19
--- /dev/null
+++ b/libs/ui/include_vndk/ui/DisplayedFrameStats.h
@@ -0,0 +1 @@
+../../include/ui/DisplayedFrameStats.h
\ No newline at end of file
diff --git a/libs/ui/tests/Android.bp b/libs/ui/tests/Android.bp
index fcc6d37..a670b3c 100644
--- a/libs/ui/tests/Android.bp
+++ b/libs/ui/tests/Android.bp
@@ -45,7 +45,7 @@
}
cc_test {
- name: "BufferHubBuffer_test",
+ name: "BufferHub_test",
header_libs: [
"libbufferhub_headers",
"libdvr_headers",
@@ -67,14 +67,7 @@
srcs: [
"BufferHubBuffer_test.cpp",
"BufferHubEventFd_test.cpp",
+ "BufferHubMetadata_test.cpp",
],
cflags: ["-Wall", "-Werror"],
}
-
-cc_test {
- name: "BufferHubMetadata_test",
- header_libs: ["libbufferhub_headers", "libdvr_headers"],
- shared_libs: ["libpdx_default_transport", "libui", "libutils"],
- srcs: ["BufferHubMetadata_test.cpp"],
- cflags: ["-Wall", "-Werror"],
-}
diff --git a/libs/ui/tests/BufferHubBuffer_test.cpp b/libs/ui/tests/BufferHubBuffer_test.cpp
index 6c7d06b..1b339a0 100644
--- a/libs/ui/tests/BufferHubBuffer_test.cpp
+++ b/libs/ui/tests/BufferHubBuffer_test.cpp
@@ -36,9 +36,16 @@
const int kUsage = 0;
const size_t kUserMetadataSize = 0;
-using dvr::BufferHubDefs::IsBufferReleased;
-using dvr::BufferHubDefs::kFirstClientBitMask;
-using dvr::BufferHubDefs::kMetadataHeaderSize;
+using BufferHubDefs::AnyClientAcquired;
+using BufferHubDefs::AnyClientGained;
+using BufferHubDefs::AnyClientPosted;
+using BufferHubDefs::IsBufferReleased;
+using BufferHubDefs::IsClientAcquired;
+using BufferHubDefs::IsClientGained;
+using BufferHubDefs::IsClientPosted;
+using BufferHubDefs::IsClientReleased;
+using BufferHubDefs::kFirstClientBitMask;
+using BufferHubDefs::kMetadataHeaderSize;
using frameworks::bufferhub::V1_0::BufferHubStatus;
using frameworks::bufferhub::V1_0::IBufferClient;
using frameworks::bufferhub::V1_0::IBufferHub;
@@ -48,9 +55,40 @@
using pdx::LocalChannelHandle;
class BufferHubBufferTest : public ::testing::Test {
+protected:
void SetUp() override { android::hardware::ProcessState::self()->startThreadPool(); }
};
+class BufferHubBufferStateTransitionTest : public BufferHubBufferTest {
+protected:
+ void SetUp() override {
+ BufferHubBufferTest::SetUp();
+ CreateTwoClientsOfABuffer();
+ }
+
+ std::unique_ptr<BufferHubBuffer> b1;
+ uint64_t b1ClientMask = 0U;
+ std::unique_ptr<BufferHubBuffer> b2;
+ uint64_t b2ClientMask = 0U;
+
+private:
+ // Creates b1 and b2 as the clients of the same buffer for testing.
+ void CreateTwoClientsOfABuffer();
+};
+
+void BufferHubBufferStateTransitionTest::CreateTwoClientsOfABuffer() {
+ b1 = BufferHubBuffer::Create(kWidth, kHeight, kLayerCount, kFormat, kUsage, kUserMetadataSize);
+ b1ClientMask = b1->client_state_mask();
+ ASSERT_NE(b1ClientMask, 0U);
+ auto statusOrHandle = b1->Duplicate();
+ ASSERT_TRUE(statusOrHandle);
+ LocalChannelHandle h2 = statusOrHandle.take();
+ b2 = BufferHubBuffer::Import(std::move(h2));
+ b2ClientMask = b2->client_state_mask();
+ ASSERT_NE(b2ClientMask, 0U);
+ ASSERT_NE(b2ClientMask, b1ClientMask);
+}
+
TEST_F(BufferHubBufferTest, CreateBufferHubBufferFails) {
// Buffer Creation will fail: BLOB format requires height to be 1.
auto b1 = BufferHubBuffer::Create(kWidth, /*height=*/2, kLayerCount,
@@ -88,7 +126,7 @@
kUserMetadataSize);
int id1 = b1->id();
uint64_t bufferStateMask1 = b1->client_state_mask();
- EXPECT_NE(bufferStateMask1, 0ULL);
+ EXPECT_NE(bufferStateMask1, 0U);
EXPECT_TRUE(b1->IsValid());
EXPECT_EQ(b1->user_metadata_size(), kUserMetadataSize);
@@ -111,7 +149,7 @@
int id2 = b2->id();
uint64_t bufferStateMask2 = b2->client_state_mask();
- EXPECT_NE(bufferStateMask2, 0ULL);
+ EXPECT_NE(bufferStateMask2, 0U);
// These two buffer instances are based on the same physical buffer under the
// hood, so they should share the same id.
@@ -127,192 +165,179 @@
return;
}
-TEST_F(BufferHubBufferTest, AllocateAndFreeBuffer) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferHub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferHub.get());
+TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromReleasedState) {
+ ASSERT_TRUE(IsBufferReleased(b1->buffer_state()));
- // Stride is an output, rfu0 and rfu1 are reserved data slot for future use.
- AHardwareBuffer_Desc aDesc = {kWidth, kHeight, kLayerCount, kFormat,
- kUsage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
- HardwareBufferDescription desc;
- memcpy(&desc, &aDesc, sizeof(HardwareBufferDescription));
-
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::allocateBuffer_cb callback = [&](const auto& outClient, const auto& outStatus) {
- client = outClient;
- ret = outStatus;
- };
- EXPECT_TRUE(bufferHub->allocateBuffer(desc, kUserMetadataSize, callback).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(nullptr, client.get());
-
- EXPECT_EQ(BufferHubStatus::NO_ERROR, client->close());
- EXPECT_EQ(BufferHubStatus::CLIENT_CLOSED, client->close());
+ // Successful gaining the buffer should change the buffer state bit of b1 to
+ // gained state, other client state bits to released state.
+ EXPECT_EQ(b1->Gain(), 0);
+ EXPECT_TRUE(IsClientGained(b1->buffer_state(), b1ClientMask));
}
-TEST_F(BufferHubBufferTest, DuplicateFreedBuffer) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferHub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferHub.get());
+TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromGainedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ auto current_buffer_state = b1->buffer_state();
+ ASSERT_TRUE(IsClientGained(current_buffer_state, b1ClientMask));
- // Stride is an output, rfu0 and rfu1 are reserved data slot for future use.
- AHardwareBuffer_Desc aDesc = {kWidth, kHeight, kLayerCount, kFormat,
- kUsage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
- HardwareBufferDescription desc;
- memcpy(&desc, &aDesc, sizeof(HardwareBufferDescription));
+ // Gaining from gained state by the same client should not return error.
+ EXPECT_EQ(b1->Gain(), 0);
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::allocateBuffer_cb callback = [&](const auto& outClient, const auto& outStatus) {
- client = outClient;
- ret = outStatus;
- };
- EXPECT_TRUE(bufferHub->allocateBuffer(desc, kUserMetadataSize, callback).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(nullptr, client.get());
-
- EXPECT_EQ(BufferHubStatus::NO_ERROR, client->close());
-
- hidl_handle token;
- IBufferClient::duplicate_cb dup_cb = [&](const auto& outToken, const auto& status) {
- token = outToken;
- ret = status;
- };
- EXPECT_TRUE(client->duplicate(dup_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::CLIENT_CLOSED);
- EXPECT_EQ(token.getNativeHandle(), nullptr);
+ // Gaining from gained state by another client should return error.
+ EXPECT_EQ(b2->Gain(), -EBUSY);
}
-TEST_F(BufferHubBufferTest, DuplicateAndImportBuffer) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferhub.get());
+TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromAcquiredState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_EQ(b2->Acquire(), 0);
+ ASSERT_TRUE(AnyClientAcquired(b1->buffer_state()));
- // Stride is an output, rfu0 and rfu1 are reserved data slot for future use.
- AHardwareBuffer_Desc aDesc = {kWidth, kHeight, kLayerCount, kFormat,
- kUsage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
- HardwareBufferDescription desc;
- memcpy(&desc, &aDesc, sizeof(HardwareBufferDescription));
-
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::allocateBuffer_cb alloc_cb = [&](const auto& outClient, const auto& status) {
- client = outClient;
- ret = status;
- };
- ASSERT_TRUE(bufferhub->allocateBuffer(desc, kUserMetadataSize, alloc_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(nullptr, client.get());
-
- hidl_handle token;
- IBufferClient::duplicate_cb dup_cb = [&](const auto& outToken, const auto& status) {
- token = outToken;
- ret = status;
- };
- ASSERT_TRUE(client->duplicate(dup_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(token.getNativeHandle(), nullptr);
- EXPECT_EQ(token->numInts, 1);
- EXPECT_EQ(token->numFds, 0);
-
- sp<IBufferClient> client2;
- IBufferHub::importBuffer_cb import_cb = [&](const auto& outClient, const auto& status) {
- ret = status;
- client2 = outClient;
- };
- ASSERT_TRUE(bufferhub->importBuffer(token, import_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- EXPECT_NE(nullptr, client2.get());
- // TODO(b/116681016): once BufferNode.id() is exposed via BufferHubBuffer, check origin.id =
- // improted.id here.
+ // Gaining from acquired state should fail.
+ EXPECT_EQ(b1->Gain(), -EBUSY);
+ EXPECT_EQ(b2->Gain(), -EBUSY);
}
-// nullptr must not crash the service
-TEST_F(BufferHubBufferTest, ImportNullToken) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferhub.get());
+TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromOtherClientInPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(AnyClientPosted(b1->buffer_state()));
- hidl_handle nullToken;
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::importBuffer_cb import_cb = [&](const auto& outClient, const auto& status) {
- client = outClient;
- ret = status;
- };
- ASSERT_TRUE(bufferhub->importBuffer(nullToken, import_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::INVALID_TOKEN);
- EXPECT_EQ(nullptr, client.get());
+ // Gaining a buffer who has other posted client should succeed.
+ EXPECT_EQ(b1->Gain(), 0);
}
-// This test has a very little chance to fail (number of existing tokens / 2 ^ 32)
-TEST_F(BufferHubBufferTest, ImportInvalidToken) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferhub.get());
+TEST_F(BufferHubBufferStateTransitionTest, GainBuffer_fromSelfInPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(AnyClientPosted(b1->buffer_state()));
- native_handle_t* tokenHandle = native_handle_create(/*numFds=*/0, /*numInts=*/1);
- tokenHandle->data[0] = 0;
-
- hidl_handle invalidToken(tokenHandle);
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::importBuffer_cb import_cb = [&](const auto& outClient, const auto& status) {
- client = outClient;
- ret = status;
- };
- ASSERT_TRUE(bufferhub->importBuffer(invalidToken, import_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::INVALID_TOKEN);
- EXPECT_EQ(nullptr, client.get());
-
- native_handle_delete(tokenHandle);
+ // A posted client should be able to gain the buffer when there is no other clients in
+ // acquired state.
+ EXPECT_EQ(b2->Gain(), 0);
}
-TEST_F(BufferHubBufferTest, ImportFreedBuffer) {
- // TODO(b/116681016): directly test on BufferHubBuffer instead of the service.
- sp<IBufferHub> bufferhub = IBufferHub::getService();
- ASSERT_NE(nullptr, bufferhub.get());
+TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromOtherInGainedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_TRUE(IsClientGained(b1->buffer_state(), b1ClientMask));
- // Stride is an output, rfu0 and rfu1 are reserved data slot for future use.
- AHardwareBuffer_Desc aDesc = {kWidth, kHeight, kLayerCount, kFormat,
- kUsage, /*stride=*/0UL, /*rfu0=*/0UL, /*rfu1=*/0ULL};
- HardwareBufferDescription desc;
- memcpy(&desc, &aDesc, sizeof(HardwareBufferDescription));
+ EXPECT_EQ(b2->Post(), -EBUSY);
+}
- sp<IBufferClient> client;
- BufferHubStatus ret;
- IBufferHub::allocateBuffer_cb alloc_cb = [&](const auto& outClient, const auto& status) {
- client = outClient;
- ret = status;
- };
- ASSERT_TRUE(bufferhub->allocateBuffer(desc, kUserMetadataSize, alloc_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(nullptr, client.get());
+TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromSelfInGainedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_TRUE(IsClientGained(b1->buffer_state(), b1ClientMask));
- hidl_handle token;
- IBufferClient::duplicate_cb dup_cb = [&](const auto& outToken, const auto& status) {
- token = outToken;
- ret = status;
- };
- ASSERT_TRUE(client->duplicate(dup_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::NO_ERROR);
- ASSERT_NE(token.getNativeHandle(), nullptr);
- EXPECT_EQ(token->numInts, 1);
- EXPECT_EQ(token->numFds, 0);
+ EXPECT_EQ(b1->Post(), 0);
+ auto current_buffer_state = b1->buffer_state();
+ EXPECT_TRUE(IsClientReleased(current_buffer_state, b1ClientMask));
+ EXPECT_TRUE(IsClientPosted(current_buffer_state, b2ClientMask));
+}
- // Close the client. Now the token should be invalid.
- client->close();
+TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(AnyClientPosted(b1->buffer_state()));
- sp<IBufferClient> client2;
- IBufferHub::importBuffer_cb import_cb = [&](const auto& outClient, const auto& status) {
- client2 = outClient;
- ret = status;
- };
- EXPECT_TRUE(bufferhub->importBuffer(token, import_cb).isOk());
- EXPECT_EQ(ret, BufferHubStatus::INVALID_TOKEN);
- EXPECT_EQ(nullptr, client2.get());
+ // Post from posted state should fail.
+ EXPECT_EQ(b1->Post(), -EBUSY);
+ EXPECT_EQ(b2->Post(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromAcquiredState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_EQ(b2->Acquire(), 0);
+ ASSERT_TRUE(AnyClientAcquired(b1->buffer_state()));
+
+ // Posting from acquired state should fail.
+ EXPECT_EQ(b1->Post(), -EBUSY);
+ EXPECT_EQ(b2->Post(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, PostBuffer_fromReleasedState) {
+ ASSERT_TRUE(IsBufferReleased(b1->buffer_state()));
+
+ // Posting from released state should fail.
+ EXPECT_EQ(b1->Post(), -EBUSY);
+ EXPECT_EQ(b2->Post(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromSelfInPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(IsClientPosted(b1->buffer_state(), b2ClientMask));
+
+ // Acquire from posted state should pass.
+ EXPECT_EQ(b2->Acquire(), 0);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromOtherInPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(IsClientPosted(b1->buffer_state(), b2ClientMask));
+
+ // Acquire from released state should fail, although there are other clients
+ // in posted state.
+ EXPECT_EQ(b1->Acquire(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromSelfInAcquiredState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_EQ(b2->Acquire(), 0);
+ auto current_buffer_state = b1->buffer_state();
+ ASSERT_TRUE(IsClientAcquired(current_buffer_state, b2ClientMask));
+
+ // Acquiring from acquired state by the same client should not error out.
+ EXPECT_EQ(b2->Acquire(), 0);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromReleasedState) {
+ ASSERT_TRUE(IsBufferReleased(b1->buffer_state()));
+
+ // Acquiring form released state should fail.
+ EXPECT_EQ(b1->Acquire(), -EBUSY);
+ EXPECT_EQ(b2->Acquire(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, AcquireBuffer_fromGainedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_TRUE(AnyClientGained(b1->buffer_state()));
+
+ // Acquiring from gained state should fail.
+ EXPECT_EQ(b1->Acquire(), -EBUSY);
+ EXPECT_EQ(b2->Acquire(), -EBUSY);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInReleasedState) {
+ ASSERT_TRUE(IsBufferReleased(b1->buffer_state()));
+
+ EXPECT_EQ(b1->Release(), 0);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInGainedState) {
+ ASSERT_TRUE(IsBufferReleased(b1->buffer_state()));
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_TRUE(AnyClientGained(b1->buffer_state()));
+
+ EXPECT_EQ(b1->Release(), 0);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInPostedState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_TRUE(AnyClientPosted(b1->buffer_state()));
+
+ EXPECT_EQ(b2->Release(), 0);
+}
+
+TEST_F(BufferHubBufferStateTransitionTest, ReleaseBuffer_fromSelfInAcquiredState) {
+ ASSERT_EQ(b1->Gain(), 0);
+ ASSERT_EQ(b1->Post(), 0);
+ ASSERT_EQ(b2->Acquire(), 0);
+ ASSERT_TRUE(AnyClientAcquired(b1->buffer_state()));
+
+ EXPECT_EQ(b2->Release(), 0);
}
} // namespace
diff --git a/libs/ui/tests/BufferHubEventFd_test.cpp b/libs/ui/tests/BufferHubEventFd_test.cpp
index 8e61c68..92fb33f 100644
--- a/libs/ui/tests/BufferHubEventFd_test.cpp
+++ b/libs/ui/tests/BufferHubEventFd_test.cpp
@@ -19,14 +19,14 @@
#include <sys/epoll.h>
#include <sys/eventfd.h>
-#include <hidl/ServiceManagement.h>
-#include <hwbinder/IPCThreadState.h>
+#include <array>
#include <condition_variable>
#include <mutex>
#include <thread>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include <log/log.h>
#include <ui/BufferHubEventFd.h>
namespace android {
diff --git a/libs/ui/tests/BufferHubMetadata_test.cpp b/libs/ui/tests/BufferHubMetadata_test.cpp
index 14422bf..11f8e57 100644
--- a/libs/ui/tests/BufferHubMetadata_test.cpp
+++ b/libs/ui/tests/BufferHubMetadata_test.cpp
@@ -17,7 +17,7 @@
#include <gtest/gtest.h>
#include <ui/BufferHubMetadata.h>
-using android::dvr::BufferHubDefs::IsBufferReleased;
+using android::BufferHubDefs::IsBufferReleased;
namespace android {
namespace dvr {
diff --git a/libs/ui/tests/GraphicBuffer_test.cpp b/libs/ui/tests/GraphicBuffer_test.cpp
index 95ca2c1..81ab3ac 100644
--- a/libs/ui/tests/GraphicBuffer_test.cpp
+++ b/libs/ui/tests/GraphicBuffer_test.cpp
@@ -39,6 +39,7 @@
std::unique_ptr<BufferHubBuffer> b1 =
BufferHubBuffer::Create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
kTestUsage, /*userMetadataSize=*/0);
+ EXPECT_NE(b1, nullptr);
EXPECT_TRUE(b1->IsValid());
sp<GraphicBuffer> gb(new GraphicBuffer(std::move(b1)));
@@ -51,4 +52,26 @@
EXPECT_EQ(gb->getLayerCount(), kTestLayerCount);
}
+TEST_F(GraphicBufferTest, InvalidBufferIdForNoneBufferHubBuffer) {
+ sp<GraphicBuffer> gb(
+ new GraphicBuffer(kTestWidth, kTestHeight, kTestFormat, kTestLayerCount, kTestUsage));
+ EXPECT_FALSE(gb->isBufferHubBuffer());
+ EXPECT_EQ(gb->getBufferId(), -1);
+}
+
+TEST_F(GraphicBufferTest, BufferIdMatchesBufferHubBufferId) {
+ std::unique_ptr<BufferHubBuffer> b1 =
+ BufferHubBuffer::Create(kTestWidth, kTestHeight, kTestLayerCount, kTestFormat,
+ kTestUsage, /*userMetadataSize=*/0);
+ EXPECT_NE(b1, nullptr);
+ EXPECT_TRUE(b1->IsValid());
+
+ int b1_id = b1->id();
+ EXPECT_GE(b1_id, 0);
+
+ sp<GraphicBuffer> gb(new GraphicBuffer(std::move(b1)));
+ EXPECT_TRUE(gb->isBufferHubBuffer());
+ EXPECT_EQ(gb->getBufferId(), b1_id);
+}
+
} // namespace android
diff --git a/libs/vr/libbufferhub/Android.bp b/libs/vr/libbufferhub/Android.bp
index 43ac79e..fa92830 100644
--- a/libs/vr/libbufferhub/Android.bp
+++ b/libs/vr/libbufferhub/Android.bp
@@ -22,14 +22,12 @@
"buffer_hub_base.cpp",
"buffer_hub_rpc.cpp",
"consumer_buffer.cpp",
- "buffer_client_impl.cpp",
"ion_buffer.cpp",
"producer_buffer.cpp",
]
sharedLibraries = [
"libbase",
- "libbinder",
"libcutils",
"libhardware",
"liblog",
diff --git a/libs/vr/libbufferhub/buffer_client_impl.cpp b/libs/vr/libbufferhub/buffer_client_impl.cpp
deleted file mode 100644
index efa9c28..0000000
--- a/libs/vr/libbufferhub/buffer_client_impl.cpp
+++ /dev/null
@@ -1,87 +0,0 @@
-#include <log/log.h>
-#include <private/dvr/IBufferClient.h>
-
-namespace android {
-namespace dvr {
-
-class BpBufferClient : public BpInterface<IBufferClient> {
- public:
- explicit BpBufferClient(const sp<IBinder>& impl)
- : BpInterface<IBufferClient>(impl) {}
-
- bool isValid() override;
-
- status_t duplicate(uint64_t* outToken) override;
-};
-
-IMPLEMENT_META_INTERFACE(BufferClient, "android.dvr.IBufferClient");
-
-// Transaction code
-enum {
- IS_VALID = IBinder::FIRST_CALL_TRANSACTION,
- DUPLICATE,
-};
-
-bool BpBufferClient::isValid() {
- Parcel data, reply;
- status_t ret =
- data.writeInterfaceToken(IBufferClient::getInterfaceDescriptor());
- if (ret != OK) {
- ALOGE("BpBufferClient::isValid: failed to write into parcel; errno=%d",
- ret);
- return false;
- }
-
- ret = remote()->transact(IS_VALID, data, &reply);
- if (ret == OK) {
- return reply.readBool();
- } else {
- ALOGE("BpBufferClient::isValid: failed to transact; errno=%d", ret);
- return false;
- }
-}
-
-status_t BpBufferClient::duplicate(uint64_t* outToken) {
- Parcel data, reply;
- status_t ret =
- data.writeInterfaceToken(IBufferClient::getInterfaceDescriptor());
- if (ret != OK) {
- ALOGE("BpBufferClient::duplicate: failed to write into parcel; errno=%d",
- ret);
- return ret;
- }
-
- ret = remote()->transact(DUPLICATE, data, &reply);
- if (ret == OK) {
- *outToken = reply.readUint64();
- return OK;
- } else {
- ALOGE("BpBufferClient::duplicate: failed to transact; errno=%d", ret);
- return ret;
- }
-}
-
-status_t BnBufferClient::onTransact(uint32_t code, const Parcel& data,
- Parcel* reply, uint32_t flags) {
- switch (code) {
- case IS_VALID: {
- CHECK_INTERFACE(IBufferClient, data, reply);
- return reply->writeBool(isValid());
- }
- case DUPLICATE: {
- CHECK_INTERFACE(IBufferClient, data, reply);
- uint64_t token = 0;
- status_t ret = duplicate(&token);
- if (ret != OK) {
- return ret;
- }
- return reply->writeUint64(token);
- }
- default:
- // Should not reach except binder defined transactions such as dumpsys
- return BBinder::onTransact(code, data, reply, flags);
- }
-}
-
-} // namespace dvr
-} // namespace android
\ No newline at end of file
diff --git a/libs/vr/libbufferhub/buffer_hub-test.cpp b/libs/vr/libbufferhub/buffer_hub-test.cpp
index 9bcfaa1..1359f4c 100644
--- a/libs/vr/libbufferhub/buffer_hub-test.cpp
+++ b/libs/vr/libbufferhub/buffer_hub-test.cpp
@@ -1,10 +1,12 @@
#include <gtest/gtest.h>
#include <poll.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/bufferhub_rpc.h>
+#include <private/dvr/consumer_buffer.h>
+#include <private/dvr/producer_buffer.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <ui/BufferHubBuffer.h>
+#include <ui/BufferHubDefs.h>
#include <mutex>
#include <thread>
@@ -21,17 +23,17 @@
using android::BufferHubBuffer;
using android::GraphicBuffer;
using android::sp;
+using android::BufferHubDefs::AnyClientAcquired;
+using android::BufferHubDefs::AnyClientGained;
+using android::BufferHubDefs::AnyClientPosted;
+using android::BufferHubDefs::IsBufferReleased;
+using android::BufferHubDefs::IsClientAcquired;
+using android::BufferHubDefs::IsClientPosted;
+using android::BufferHubDefs::IsClientReleased;
+using android::BufferHubDefs::kFirstClientBitMask;
+using android::BufferHubDefs::kMetadataHeaderSize;
using android::dvr::ConsumerBuffer;
using android::dvr::ProducerBuffer;
-using android::dvr::BufferHubDefs::AnyClientAcquired;
-using android::dvr::BufferHubDefs::AnyClientGained;
-using android::dvr::BufferHubDefs::AnyClientPosted;
-using android::dvr::BufferHubDefs::IsBufferReleased;
-using android::dvr::BufferHubDefs::IsClientAcquired;
-using android::dvr::BufferHubDefs::IsClientPosted;
-using android::dvr::BufferHubDefs::IsClientReleased;
-using android::dvr::BufferHubDefs::kFirstClientBitMask;
-using android::dvr::BufferHubDefs::kMetadataHeaderSize;
using android::pdx::LocalChannelHandle;
using android::pdx::LocalHandle;
using android::pdx::Status;
@@ -45,7 +47,7 @@
// Maximum number of consumers for the buffer that only has one producer in the
// test.
const size_t kMaxConsumerCount =
- android::dvr::BufferHubDefs::kMaxNumberOfClients - 1;
+ android::BufferHubDefs::kMaxNumberOfClients - 1;
const int kPollTimeoutMs = 100;
using LibBufferHubTest = ::testing::Test;
@@ -174,7 +176,7 @@
ASSERT_TRUE(p.get() != nullptr);
// It's ok to create up to kMaxConsumerCount consumer buffers.
- uint64_t client_state_masks = p->client_state_mask();
+ uint32_t client_state_masks = p->client_state_mask();
std::array<std::unique_ptr<ConsumerBuffer>, kMaxConsumerCount> cs;
for (size_t i = 0; i < kMaxConsumerCount; i++) {
cs[i] = ConsumerBuffer::Import(p->CreateConsumer());
@@ -183,7 +185,7 @@
EXPECT_EQ(client_state_masks & cs[i]->client_state_mask(), 0U);
client_state_masks |= cs[i]->client_state_mask();
}
- EXPECT_EQ(client_state_masks, ~0ULL);
+ EXPECT_EQ(client_state_masks, ~0U);
// The 64th creation will fail with out-of-memory error.
auto state = p->CreateConsumer();
@@ -372,7 +374,7 @@
std::unique_ptr<ProducerBuffer> p = ProducerBuffer::Create(
kWidth, kHeight, kFormat, kUsage, sizeof(uint64_t));
ASSERT_TRUE(p.get() != nullptr);
- uint64_t producer_state_mask = p->client_state_mask();
+ uint32_t producer_state_mask = p->client_state_mask();
std::array<std::unique_ptr<ConsumerBuffer>, kMaxConsumerCount> cs;
for (size_t i = 0; i < kMaxConsumerCount; ++i) {
@@ -718,7 +720,7 @@
std::unique_ptr<ConsumerBuffer> c1 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c1.get() != nullptr);
- const uint64_t client_state_mask1 = c1->client_state_mask();
+ const uint32_t client_state_mask1 = c1->client_state_mask();
EXPECT_EQ(0, p->GainAsync());
DvrNativeBufferMetadata meta;
@@ -738,7 +740,7 @@
std::unique_ptr<ConsumerBuffer> c2 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c2.get() != nullptr);
- const uint64_t client_state_mask2 = c2->client_state_mask();
+ const uint32_t client_state_mask2 = c2->client_state_mask();
EXPECT_NE(client_state_mask1, client_state_mask2);
EXPECT_EQ(0, RETRY_EINTR(c2->Poll(kPollTimeoutMs)));
EXPECT_EQ(-EBUSY, c2->AcquireAsync(&meta, &fence));
@@ -754,7 +756,7 @@
std::unique_ptr<ConsumerBuffer> c1 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c1.get() != nullptr);
- const uint64_t client_state_mask1 = c1->client_state_mask();
+ const uint32_t client_state_mask1 = c1->client_state_mask();
EXPECT_EQ(0, p->GainAsync());
DvrNativeBufferMetadata meta;
@@ -766,7 +768,7 @@
std::unique_ptr<ConsumerBuffer> c2 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c2.get() != nullptr);
- const uint64_t client_state_mask2 = c2->client_state_mask();
+ const uint32_t client_state_mask2 = c2->client_state_mask();
EXPECT_NE(client_state_mask1, client_state_mask2);
EXPECT_LT(0, RETRY_EINTR(c2->Poll(kPollTimeoutMs)));
LocalHandle invalid_fence;
@@ -780,7 +782,7 @@
std::unique_ptr<ConsumerBuffer> c3 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c3.get() != nullptr);
- const uint64_t client_state_mask3 = c3->client_state_mask();
+ const uint32_t client_state_mask3 = c3->client_state_mask();
EXPECT_NE(client_state_mask1, client_state_mask3);
EXPECT_NE(client_state_mask2, client_state_mask3);
EXPECT_LT(0, RETRY_EINTR(c3->Poll(kPollTimeoutMs)));
@@ -801,7 +803,7 @@
std::unique_ptr<ConsumerBuffer> c4 =
ConsumerBuffer::Import(p->CreateConsumer());
ASSERT_TRUE(c4.get() != nullptr);
- const uint64_t client_state_mask4 = c4->client_state_mask();
+ const uint32_t client_state_mask4 = c4->client_state_mask();
EXPECT_NE(client_state_mask3, client_state_mask4);
EXPECT_GE(0, RETRY_EINTR(c3->Poll(kPollTimeoutMs)));
EXPECT_EQ(-EBUSY, c3->AcquireAsync(&meta, &invalid_fence));
@@ -951,7 +953,7 @@
int b1_id = b1->id();
EXPECT_TRUE(b1->IsValid());
EXPECT_EQ(b1->user_metadata_size(), kUserMetadataSize);
- EXPECT_NE(b1->client_state_mask(), 0ULL);
+ EXPECT_NE(b1->client_state_mask(), 0U);
auto status_or_handle = b1->Duplicate();
EXPECT_TRUE(status_or_handle);
@@ -969,7 +971,7 @@
ASSERT_TRUE(b2 != nullptr);
EXPECT_TRUE(b2->IsValid());
EXPECT_EQ(b2->user_metadata_size(), kUserMetadataSize);
- EXPECT_NE(b2->client_state_mask(), 0ULL);
+ EXPECT_NE(b2->client_state_mask(), 0U);
int b2_id = b2->id();
diff --git a/libs/vr/libbufferhub/buffer_hub_base.cpp b/libs/vr/libbufferhub/buffer_hub_base.cpp
index 2dc427a..8497f3e 100644
--- a/libs/vr/libbufferhub/buffer_hub_base.cpp
+++ b/libs/vr/libbufferhub/buffer_hub_base.cpp
@@ -124,16 +124,16 @@
// memory region will be preserved.
buffer_state_ = &metadata_header_->buffer_state;
ALOGD_IF(TRACE,
- "BufferHubBase::ImportBuffer: id=%d, buffer_state=%" PRIx64 ".",
+ "BufferHubBase::ImportBuffer: id=%d, buffer_state=%" PRIx32 ".",
id(), buffer_state_->load(std::memory_order_acquire));
fence_state_ = &metadata_header_->fence_state;
ALOGD_IF(TRACE,
- "BufferHubBase::ImportBuffer: id=%d, fence_state=%" PRIx64 ".", id(),
+ "BufferHubBase::ImportBuffer: id=%d, fence_state=%" PRIx32 ".", id(),
fence_state_->load(std::memory_order_acquire));
active_clients_bit_mask_ = &metadata_header_->active_clients_bit_mask;
ALOGD_IF(
TRACE,
- "BufferHubBase::ImportBuffer: id=%d, active_clients_bit_mask=%" PRIx64
+ "BufferHubBase::ImportBuffer: id=%d, active_clients_bit_mask=%" PRIx32
".",
id(), active_clients_bit_mask_->load(std::memory_order_acquire));
@@ -171,7 +171,7 @@
// If ready fence is valid, we put that into the epoll set.
epoll_event event;
event.events = EPOLLIN;
- event.data.u64 = client_state_mask();
+ event.data.u32 = client_state_mask();
pending_fence_fd_ = new_fence.Duplicate();
if (epoll_ctl(shared_fence.Get(), EPOLL_CTL_ADD, pending_fence_fd_.Get(),
&event) < 0) {
diff --git a/libs/vr/libbufferhub/consumer_buffer.cpp b/libs/vr/libbufferhub/consumer_buffer.cpp
index 62fb5fd..b6ca64e 100644
--- a/libs/vr/libbufferhub/consumer_buffer.cpp
+++ b/libs/vr/libbufferhub/consumer_buffer.cpp
@@ -36,33 +36,33 @@
return -EINVAL;
// The buffer can be acquired iff the buffer state for this client is posted.
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
if (!BufferHubDefs::IsClientPosted(current_buffer_state,
client_state_mask())) {
ALOGE(
"%s: Failed to acquire the buffer. The buffer is not posted, id=%d "
- "state=%" PRIx64 " client_state_mask=%" PRIx64 ".",
+ "state=%" PRIx32 " client_state_mask=%" PRIx32 ".",
__FUNCTION__, id(), current_buffer_state, client_state_mask());
return -EBUSY;
}
// Change the buffer state for this consumer from posted to acquired.
- uint64_t updated_buffer_state = current_buffer_state ^ client_state_mask();
+ uint32_t updated_buffer_state = current_buffer_state ^ client_state_mask();
while (!buffer_state_->compare_exchange_weak(
current_buffer_state, updated_buffer_state, std::memory_order_acq_rel,
std::memory_order_acquire)) {
ALOGD(
"%s Failed to acquire the buffer. Current buffer state was changed to "
- "%" PRIx64
+ "%" PRIx32
" when trying to acquire the buffer and modify the buffer state to "
- "%" PRIx64 ". About to try again if the buffer is still posted.",
+ "%" PRIx32 ". About to try again if the buffer is still posted.",
__FUNCTION__, current_buffer_state, updated_buffer_state);
if (!BufferHubDefs::IsClientPosted(current_buffer_state,
client_state_mask())) {
ALOGE(
"%s: Failed to acquire the buffer. The buffer is no longer posted, "
- "id=%d state=%" PRIx64 " client_state_mask=%" PRIx64 ".",
+ "id=%d state=%" PRIx32 " client_state_mask=%" PRIx32 ".",
__FUNCTION__, id(), current_buffer_state, client_state_mask());
return -EBUSY;
}
@@ -81,7 +81,7 @@
out_meta->user_metadata_ptr = 0;
}
- uint64_t fence_state = fence_state_->load(std::memory_order_acquire);
+ uint32_t fence_state = fence_state_->load(std::memory_order_acquire);
// If there is an acquire fence from producer, we need to return it.
// The producer state bit mask is kFirstClientBitMask for now.
if (fence_state & BufferHubDefs::kFirstClientBitMask) {
@@ -142,21 +142,21 @@
// Set the buffer state of this client to released if it is not already in
// released state.
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
if (BufferHubDefs::IsClientReleased(current_buffer_state,
client_state_mask())) {
return 0;
}
- uint64_t updated_buffer_state = current_buffer_state & (~client_state_mask());
+ uint32_t updated_buffer_state = current_buffer_state & (~client_state_mask());
while (!buffer_state_->compare_exchange_weak(
current_buffer_state, updated_buffer_state, std::memory_order_acq_rel,
std::memory_order_acquire)) {
ALOGD(
"%s: Failed to release the buffer. Current buffer state was changed to "
- "%" PRIx64
+ "%" PRIx32
" when trying to release the buffer and modify the buffer state to "
- "%" PRIx64 ". About to try again.",
+ "%" PRIx32 ". About to try again.",
__FUNCTION__, current_buffer_state, updated_buffer_state);
// The failure of compare_exchange_weak updates current_buffer_state.
updated_buffer_state = current_buffer_state & (~client_state_mask());
diff --git a/libs/vr/libbufferhub/include/private/dvr/IBufferClient.h b/libs/vr/libbufferhub/include/private/dvr/IBufferClient.h
deleted file mode 100644
index 31bf79d..0000000
--- a/libs/vr/libbufferhub/include/private/dvr/IBufferClient.h
+++ /dev/null
@@ -1,33 +0,0 @@
-#ifndef ANDROID_DVR_IBUFFERCLIENT_H
-#define ANDROID_DVR_IBUFFERCLIENT_H
-
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-
-namespace android {
-namespace dvr {
-
-// Interface for acessing BufferHubBuffer remotely.
-class IBufferClient : public IInterface {
- public:
- DECLARE_META_INTERFACE(BufferClient);
-
- // Checks if the buffer node is valid.
- virtual bool isValid() = 0;
-
- // Duplicates the client. Token_out will be set to a new token when succeed,
- // and not changed when failed.
- virtual status_t duplicate(uint64_t* outToken) = 0;
-};
-
-// BnInterface for IBufferClient. Should only be created in bufferhub service.
-class BnBufferClient : public BnInterface<IBufferClient> {
- public:
- virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
- uint32_t flags = 0);
-};
-
-} // namespace dvr
-} // namespace android
-
-#endif // ANDROID_DVR_IBUFFERCLIENT_H
\ No newline at end of file
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
index 09feb73..440a59d 100644
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
+++ b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_base.h
@@ -90,13 +90,13 @@
int cid() const { return cid_; }
// Returns the buffer buffer state.
- uint64_t buffer_state() {
+ uint32_t buffer_state() {
return buffer_state_->load(std::memory_order_acquire);
};
// A state mask which is unique to a buffer hub client among all its siblings
// sharing the same concrete graphic buffer.
- uint64_t client_state_mask() const { return client_state_mask_; }
+ uint32_t client_state_mask() const { return client_state_mask_; }
// The following methods return settings of the first buffer. Currently,
// it is only possible to create multi-buffer BufferHubBases with the same
@@ -132,11 +132,11 @@
// IonBuffer that is shared between bufferhubd, producer, and consumers.
size_t metadata_buf_size_{0};
size_t user_metadata_size_{0};
- BufferHubDefs::MetadataHeader* metadata_header_{nullptr};
- void* user_metadata_ptr_{nullptr};
- std::atomic<uint64_t>* buffer_state_{nullptr};
- std::atomic<uint64_t>* fence_state_{nullptr};
- std::atomic<uint64_t>* active_clients_bit_mask_{nullptr};
+ BufferHubDefs::MetadataHeader* metadata_header_ = nullptr;
+ void* user_metadata_ptr_ = nullptr;
+ std::atomic<uint32_t>* buffer_state_ = nullptr;
+ std::atomic<uint32_t>* fence_state_ = nullptr;
+ std::atomic<uint32_t>* active_clients_bit_mask_ = nullptr;
LocalHandle shared_acquire_fence_;
LocalHandle shared_release_fence_;
@@ -159,7 +159,7 @@
// Client bit mask which indicates the locations of this client object in the
// buffer_state_.
- uint64_t client_state_mask_{0ULL};
+ uint32_t client_state_mask_{0U};
IonBuffer buffer_;
IonBuffer metadata_buffer_;
};
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h
deleted file mode 100644
index 1daeed9..0000000
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_client.h
+++ /dev/null
@@ -1,10 +0,0 @@
-#ifndef ANDROID_DVR_BUFFER_HUB_CLIENT_H_
-#define ANDROID_DVR_BUFFER_HUB_CLIENT_H_
-
-// TODO(b/116855254): This header is completely deprecated and replaced by
-// consumer_buffer.h and producer_buffer.h. Remove this file once all references
-// to it has been removed.
-#include <private/dvr/consumer_buffer.h>
-#include <private/dvr/producer_buffer.h>
-
-#endif // ANDROID_DVR_BUFFER_HUB_CLIENT_H_
diff --git a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
index 400def7..f2c40fe 100644
--- a/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
+++ b/libs/vr/libbufferhub/include/private/dvr/buffer_hub_defs.h
@@ -8,8 +8,7 @@
#include <pdx/rpc/remote_method.h>
#include <pdx/rpc/serializable.h>
#include <private/dvr/native_handle_wrapper.h>
-
-#include <atomic>
+#include <ui/BufferHubDefs.h>
namespace android {
namespace dvr {
@@ -20,136 +19,55 @@
static constexpr uint32_t kMetadataUsage =
GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN;
-// Single buffer clients (up to 32) ownership signal.
-// 64-bit atomic unsigned int.
-// Each client takes 2 bits. The first bit locates in the first 32 bits of
-// buffer_state; the second bit locates in the last 32 bits of buffer_state.
-// Client states:
-// Gained state 11. Exclusive write state.
-// Posted state 10.
-// Acquired state 01. Shared read state.
-// Released state 00.
-//
-// MSB LSB
-// | |
-// v v
-// [C31|...|C1|C0|C31| ... |C1|C0]
+// See more details in libs/ui/include/ui/BufferHubDefs.h
+static constexpr int kMaxNumberOfClients =
+ android::BufferHubDefs::kMaxNumberOfClients;
+static constexpr uint32_t kLowbitsMask = android::BufferHubDefs::kLowbitsMask;
+static constexpr uint32_t kHighBitsMask = android::BufferHubDefs::kHighBitsMask;
+static constexpr uint32_t kFirstClientBitMask =
+ android::BufferHubDefs::kFirstClientBitMask;
-// Maximum number of clients a buffer can have.
-static constexpr int kMaxNumberOfClients = 32;
-
-// Definition of bit masks.
-// MSB LSB
-// | kHighBitsMask | kLowbitsMask |
-// v v v
-// [b63| ... |b32|b31| ... |b0]
-
-// The location of lower 32 bits in the 64-bit buffer state.
-static constexpr uint64_t kLowbitsMask = (1ULL << kMaxNumberOfClients) - 1ULL;
-
-// The location of higher 32 bits in the 64-bit buffer state.
-static constexpr uint64_t kHighBitsMask = ~kLowbitsMask;
-
-// The client bit mask of the first client.
-static constexpr uint64_t kFirstClientBitMask =
- (1ULL << kMaxNumberOfClients) + 1ULL;
-
-// Returns true if any of the client is in gained state.
-static inline bool AnyClientGained(uint64_t state) {
- uint64_t high_bits = state >> kMaxNumberOfClients;
- uint64_t low_bits = state & kLowbitsMask;
- return high_bits == low_bits && low_bits != 0ULL;
+static inline bool AnyClientGained(uint32_t state) {
+ return android::BufferHubDefs::AnyClientGained(state);
}
-// Returns true if the input client is in gained state.
-static inline bool IsClientGained(uint64_t state, uint64_t client_bit_mask) {
- return state == client_bit_mask;
+static inline bool IsClientGained(uint32_t state, uint32_t client_bit_mask) {
+ return android::BufferHubDefs::IsClientGained(state, client_bit_mask);
}
-// Returns true if any of the client is in posted state.
-static inline bool AnyClientPosted(uint64_t state) {
- uint64_t high_bits = state >> kMaxNumberOfClients;
- uint64_t low_bits = state & kLowbitsMask;
- uint64_t posted_or_acquired = high_bits ^ low_bits;
- return posted_or_acquired & high_bits;
+static inline bool AnyClientPosted(uint32_t state) {
+ return android::BufferHubDefs::AnyClientPosted(state);
}
-// Returns true if the input client is in posted state.
-static inline bool IsClientPosted(uint64_t state, uint64_t client_bit_mask) {
- uint64_t client_bits = state & client_bit_mask;
- if (client_bits == 0ULL)
- return false;
- uint64_t low_bits = client_bits & kLowbitsMask;
- return low_bits == 0ULL;
+static inline bool IsClientPosted(uint32_t state, uint32_t client_bit_mask) {
+ return android::BufferHubDefs::IsClientPosted(state, client_bit_mask);
}
-// Return true if any of the client is in acquired state.
-static inline bool AnyClientAcquired(uint64_t state) {
- uint64_t high_bits = state >> kMaxNumberOfClients;
- uint64_t low_bits = state & kLowbitsMask;
- uint64_t posted_or_acquired = high_bits ^ low_bits;
- return posted_or_acquired & low_bits;
+static inline bool AnyClientAcquired(uint32_t state) {
+ return android::BufferHubDefs::AnyClientAcquired(state);
}
-// Return true if the input client is in acquired state.
-static inline bool IsClientAcquired(uint64_t state, uint64_t client_bit_mask) {
- uint64_t client_bits = state & client_bit_mask;
- if (client_bits == 0ULL)
- return false;
- uint64_t high_bits = client_bits & kHighBitsMask;
- return high_bits == 0ULL;
+static inline bool IsClientAcquired(uint32_t state, uint32_t client_bit_mask) {
+ return android::BufferHubDefs::IsClientAcquired(state, client_bit_mask);
}
-// Returns true if all clients are in released state.
-static inline bool IsBufferReleased(uint64_t state) { return state == 0ULL; }
+static inline bool IsBufferReleased(uint32_t state) {
+ return android::BufferHubDefs::IsBufferReleased(state);
+}
-// Returns true if the input client is in released state.
-static inline bool IsClientReleased(uint64_t state, uint64_t client_bit_mask) {
- return (state & client_bit_mask) == 0ULL;
+static inline bool IsClientReleased(uint32_t state, uint32_t client_bit_mask) {
+ return android::BufferHubDefs::IsClientReleased(state, client_bit_mask);
}
// Returns the next available buffer client's client_state_masks.
// @params union_bits. Union of all existing clients' client_state_masks.
-static inline uint64_t FindNextAvailableClientStateMask(uint64_t union_bits) {
- uint64_t low_union = union_bits & kLowbitsMask;
- if (low_union == kLowbitsMask)
- return 0ULL;
- uint64_t incremented = low_union + 1ULL;
- uint64_t difference = incremented ^ low_union;
- uint64_t new_low_bit = (difference + 1ULL) >> 1;
- return new_low_bit + (new_low_bit << kMaxNumberOfClients);
+static inline uint32_t FindNextAvailableClientStateMask(uint32_t union_bits) {
+ return android::BufferHubDefs::FindNextAvailableClientStateMask(union_bits);
}
-struct __attribute__((packed, aligned(8))) MetadataHeader {
- // Internal data format, which can be updated as long as the size, padding and
- // field alignment of the struct is consistent within the same ABI. As this
- // part is subject for future updates, it's not stable cross Android version,
- // so don't have it visible from outside of the Android platform (include Apps
- // and vendor HAL).
-
- // Every client takes up one bit from the higher 32 bits and one bit from the
- // lower 32 bits in buffer_state.
- std::atomic<uint64_t> buffer_state;
-
- // Every client takes up one bit in fence_state. Only the lower 32 bits are
- // valid. The upper 32 bits are there for easier manipulation, but the value
- // should be ignored.
- std::atomic<uint64_t> fence_state;
-
- // Every client takes up one bit from the higher 32 bits and one bit from the
- // lower 32 bits in active_clients_bit_mask.
- std::atomic<uint64_t> active_clients_bit_mask;
-
- // The index of the buffer queue where the buffer belongs to.
- uint64_t queue_index;
-
- // Public data format, which should be updated with caution. See more details
- // in dvr_api.h
- DvrNativeBufferMetadata metadata;
-};
-
-static_assert(sizeof(MetadataHeader) == 136, "Unexpected MetadataHeader size");
-static constexpr size_t kMetadataHeaderSize = sizeof(MetadataHeader);
+using MetadataHeader = android::BufferHubDefs::MetadataHeader;
+static constexpr size_t kMetadataHeaderSize =
+ android::BufferHubDefs::kMetadataHeaderSize;
} // namespace BufferHubDefs
@@ -159,7 +77,7 @@
BufferTraits() = default;
BufferTraits(const native_handle_t* buffer_handle,
const FileHandleType& metadata_handle, int id,
- uint64_t client_state_mask, uint64_t metadata_size,
+ uint32_t client_state_mask, uint64_t metadata_size,
uint32_t width, uint32_t height, uint32_t layer_count,
uint32_t format, uint64_t usage, uint32_t stride,
const FileHandleType& acquire_fence_fd,
@@ -189,7 +107,7 @@
// same buffer channel has uniqued state bit among its siblings. For a
// producer buffer the bit must be kFirstClientBitMask; for a consumer the bit
// must be one of the kConsumerStateMask.
- uint64_t client_state_mask() const { return client_state_mask_; }
+ uint32_t client_state_mask() const { return client_state_mask_; }
uint64_t metadata_size() const { return metadata_size_; }
uint32_t width() { return width_; }
@@ -213,7 +131,7 @@
private:
// BufferHub specific traits.
int id_ = -1;
- uint64_t client_state_mask_;
+ uint32_t client_state_mask_;
uint64_t metadata_size_;
// Traits for a GraphicBuffer.
diff --git a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
index 5ff4e00..f1cd0b4 100644
--- a/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
+++ b/libs/vr/libbufferhub/include/private/dvr/bufferhub_rpc.h
@@ -99,7 +99,7 @@
public:
BufferDescription() = default;
BufferDescription(const IonBuffer& buffer, const IonBuffer& metadata, int id,
- int buffer_cid, uint64_t client_state_mask,
+ int buffer_cid, uint32_t client_state_mask,
const FileHandleType& acquire_fence_fd,
const FileHandleType& release_fence_fd)
: id_(id),
@@ -123,7 +123,7 @@
// State mask of the buffer client. Each BufferHub client backed by the
// same buffer channel has uniqued state bit among its siblings.
- uint64_t client_state_mask() const { return client_state_mask_; }
+ uint32_t client_state_mask() const { return client_state_mask_; }
FileHandleType take_acquire_fence() { return std::move(acquire_fence_fd_); }
FileHandleType take_release_fence() { return std::move(release_fence_fd_); }
@@ -133,7 +133,7 @@
private:
int id_{-1};
int buffer_cid_{-1};
- uint64_t client_state_mask_{0};
+ uint32_t client_state_mask_{0U};
// Two IonBuffers: one for the graphic buffer and one for metadata.
NativeBufferHandle<FileHandleType> buffer_;
NativeBufferHandle<FileHandleType> metadata_;
diff --git a/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h b/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h
index ae70b77..a5c6ca2 100644
--- a/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h
+++ b/libs/vr/libbufferhub/include/private/dvr/native_handle_wrapper.h
@@ -2,6 +2,8 @@
#define ANDROID_DVR_NATIVE_HANDLE_WRAPPER_H_
#include <cutils/native_handle.h>
+#include <log/log.h>
+#include <pdx/rpc/serializable.h>
#include <vector>
diff --git a/libs/vr/libbufferhub/producer_buffer.cpp b/libs/vr/libbufferhub/producer_buffer.cpp
index de03fad..5274bf2 100644
--- a/libs/vr/libbufferhub/producer_buffer.cpp
+++ b/libs/vr/libbufferhub/producer_buffer.cpp
@@ -80,20 +80,20 @@
return error;
// The buffer can be posted iff the buffer state for this client is gained.
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
if (!BufferHubDefs::IsClientGained(current_buffer_state,
client_state_mask())) {
- ALOGE("%s: not gained, id=%d state=%" PRIx64 ".", __FUNCTION__, id(),
+ ALOGE("%s: not gained, id=%d state=%" PRIx32 ".", __FUNCTION__, id(),
current_buffer_state);
return -EBUSY;
}
// Set the producer client buffer state to released, other clients' buffer
// state to posted.
- uint64_t current_active_clients_bit_mask =
+ uint32_t current_active_clients_bit_mask =
active_clients_bit_mask_->load(std::memory_order_acquire);
- uint64_t updated_buffer_state = current_active_clients_bit_mask &
+ uint32_t updated_buffer_state = current_active_clients_bit_mask &
(~client_state_mask()) &
BufferHubDefs::kHighBitsMask;
while (!buffer_state_->compare_exchange_weak(
@@ -101,16 +101,16 @@
std::memory_order_acquire)) {
ALOGD(
"%s: Failed to post the buffer. Current buffer state was changed to "
- "%" PRIx64
+ "%" PRIx32
" when trying to post the buffer and modify the buffer state to "
- "%" PRIx64
+ "%" PRIx32
". About to try again if the buffer is still gained by this client.",
__FUNCTION__, current_buffer_state, updated_buffer_state);
if (!BufferHubDefs::IsClientGained(current_buffer_state,
client_state_mask())) {
ALOGE(
"%s: Failed to post the buffer. The buffer is no longer gained, "
- "id=%d state=%" PRIx64 ".",
+ "id=%d state=%" PRIx32 ".",
__FUNCTION__, id(), current_buffer_state);
return -EBUSY;
}
@@ -164,9 +164,9 @@
if (!out_meta)
return -EINVAL;
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
- ALOGD_IF(TRACE, "%s: buffer=%d, state=%" PRIx64 ".", __FUNCTION__, id(),
+ ALOGD_IF(TRACE, "%s: buffer=%d, state=%" PRIx32 ".", __FUNCTION__, id(),
current_buffer_state);
if (BufferHubDefs::IsClientGained(current_buffer_state,
@@ -178,20 +178,20 @@
BufferHubDefs::AnyClientGained(current_buffer_state) ||
(BufferHubDefs::AnyClientPosted(current_buffer_state) &&
!gain_posted_buffer)) {
- ALOGE("%s: not released id=%d state=%" PRIx64 ".", __FUNCTION__, id(),
+ ALOGE("%s: not released id=%d state=%" PRIx32 ".", __FUNCTION__, id(),
current_buffer_state);
return -EBUSY;
}
// Change the buffer state to gained state.
- uint64_t updated_buffer_state = client_state_mask();
+ uint32_t updated_buffer_state = client_state_mask();
while (!buffer_state_->compare_exchange_weak(
current_buffer_state, updated_buffer_state, std::memory_order_acq_rel,
std::memory_order_acquire)) {
ALOGD(
"%s: Failed to gain the buffer. Current buffer state was changed to "
- "%" PRIx64
+ "%" PRIx32
" when trying to gain the buffer and modify the buffer state to "
- "%" PRIx64
+ "%" PRIx32
". About to try again if the buffer is still not read by other "
"clients.",
__FUNCTION__, current_buffer_state, updated_buffer_state);
@@ -202,7 +202,7 @@
!gain_posted_buffer)) {
ALOGE(
"%s: Failed to gain the buffer. The buffer is no longer released. "
- "id=%d state=%" PRIx64 ".",
+ "id=%d state=%" PRIx32 ".",
__FUNCTION__, id(), current_buffer_state);
return -EBUSY;
}
@@ -221,18 +221,20 @@
out_meta->user_metadata_ptr = 0;
}
- uint64_t current_fence_state = fence_state_->load(std::memory_order_acquire);
- uint64_t current_active_clients_bit_mask =
+ uint32_t current_fence_state = fence_state_->load(std::memory_order_acquire);
+ uint32_t current_active_clients_bit_mask =
active_clients_bit_mask_->load(std::memory_order_acquire);
- // If there is an release fence from consumer, we need to return it.
+ // If there are release fence(s) from consumer(s), we need to return it to the
+ // consumer(s).
// TODO(b/112007999) add an atomic variable in metadata header in shared
// memory to indicate which client is the last producer of the buffer.
// Currently, assume the first client is the only producer to the buffer.
if (current_fence_state & current_active_clients_bit_mask &
(~BufferHubDefs::kFirstClientBitMask)) {
*out_fence = shared_release_fence_.Duplicate();
- out_meta->release_fence_mask =
- current_fence_state & current_active_clients_bit_mask;
+ out_meta->release_fence_mask = current_fence_state &
+ current_active_clients_bit_mask &
+ (~BufferHubDefs::kFirstClientBitMask);
}
return 0;
@@ -287,11 +289,11 @@
// TODO(b/112338294) Keep here for reference. Remove it after new logic is
// written.
- /* uint64_t buffer_state = buffer_state_->load(std::memory_order_acquire);
+ /* uint32_t buffer_state = buffer_state_->load(std::memory_order_acquire);
if (!BufferHubDefs::IsClientGained(
buffer_state, BufferHubDefs::kFirstClientStateMask)) {
// Can only detach a ProducerBuffer when it's in gained state.
- ALOGW("ProducerBuffer::Detach: The buffer (id=%d, state=0x%" PRIx64
+ ALOGW("ProducerBuffer::Detach: The buffer (id=%d, state=0x%" PRIx32
") is not in gained state.",
id(), buffer_state);
return {};
diff --git a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
index def7c6b..53ab2b2 100644
--- a/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
+++ b/libs/vr/libbufferhubqueue/include/private/dvr/buffer_hub_queue_client.h
@@ -13,10 +13,11 @@
// in these headers and their dependencies.
#include <pdx/client.h>
#include <pdx/status.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_parcelable.h>
#include <private/dvr/bufferhub_rpc.h>
+#include <private/dvr/consumer_buffer.h>
#include <private/dvr/epoll_file_descriptor.h>
+#include <private/dvr/producer_buffer.h>
#if defined(__clang__)
#pragma clang diagnostic pop
diff --git a/libs/vr/libbufferhubqueue/include/private/dvr/epoll_file_descriptor.h b/libs/vr/libbufferhubqueue/include/private/dvr/epoll_file_descriptor.h
index 6e303a5..2f14f7c 100644
--- a/libs/vr/libbufferhubqueue/include/private/dvr/epoll_file_descriptor.h
+++ b/libs/vr/libbufferhubqueue/include/private/dvr/epoll_file_descriptor.h
@@ -28,7 +28,7 @@
return -EALREADY;
}
- fd_.reset(epoll_create(64));
+ fd_.reset(epoll_create1(EPOLL_CLOEXEC));
if (fd_.get() < 0)
return -errno;
diff --git a/libs/vr/libbufferhubqueue/tests/buffer_hub_queue-test.cpp b/libs/vr/libbufferhubqueue/tests/buffer_hub_queue-test.cpp
index fd6ca43..159d6dc 100644
--- a/libs/vr/libbufferhubqueue/tests/buffer_hub_queue-test.cpp
+++ b/libs/vr/libbufferhubqueue/tests/buffer_hub_queue-test.cpp
@@ -1,8 +1,9 @@
#include <base/logging.h>
#include <binder/Parcel.h>
#include <dvr/dvr_api.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_client.h>
+#include <private/dvr/consumer_buffer.h>
+#include <private/dvr/producer_buffer.h>
#include <gtest/gtest.h>
#include <poll.h>
diff --git a/libs/vr/libdisplay/display_manager_client.cpp b/libs/vr/libdisplay/display_manager_client.cpp
index 974c231..fdeeb70 100644
--- a/libs/vr/libdisplay/display_manager_client.cpp
+++ b/libs/vr/libdisplay/display_manager_client.cpp
@@ -1,7 +1,6 @@
#include "include/private/dvr/display_manager_client.h"
#include <pdx/default_transport/client_channel_factory.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_client.h>
#include <private/dvr/display_protocol.h>
#include <utils/Log.h>
diff --git a/libs/vr/libdisplay/include/private/dvr/display_client.h b/libs/vr/libdisplay/include/private/dvr/display_client.h
index caf3182..f8f5b3d 100644
--- a/libs/vr/libdisplay/include/private/dvr/display_client.h
+++ b/libs/vr/libdisplay/include/private/dvr/display_client.h
@@ -5,7 +5,6 @@
#include <hardware/hwcomposer.h>
#include <pdx/client.h>
#include <pdx/file_handle.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_client.h>
#include <private/dvr/display_protocol.h>
diff --git a/libs/vr/libdvr/dvr_buffer.cpp b/libs/vr/libdvr/dvr_buffer.cpp
index baf1f2f..c11706f 100644
--- a/libs/vr/libdvr/dvr_buffer.cpp
+++ b/libs/vr/libdvr/dvr_buffer.cpp
@@ -2,7 +2,8 @@
#include <android/hardware_buffer.h>
#include <dvr/dvr_shared_buffers.h>
-#include <private/dvr/buffer_hub_client.h>
+#include <private/dvr/consumer_buffer.h>
+#include <private/dvr/producer_buffer.h>
#include <ui/GraphicBuffer.h>
#include "dvr_internal.h"
diff --git a/libs/vr/libdvr/dvr_display_manager.cpp b/libs/vr/libdvr/dvr_display_manager.cpp
index 852f9a4..fe91b14 100644
--- a/libs/vr/libdvr/dvr_display_manager.cpp
+++ b/libs/vr/libdvr/dvr_display_manager.cpp
@@ -2,8 +2,8 @@
#include <dvr/dvr_buffer.h>
#include <pdx/rpc/variant.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_client.h>
+#include <private/dvr/consumer_buffer.h>
#include <private/dvr/display_client.h>
#include <private/dvr/display_manager_client.h>
diff --git a/libs/vr/libdvr/include/dvr/dvr_api.h b/libs/vr/libdvr/include/dvr/dvr_api.h
index fef8512..e383bb2 100644
--- a/libs/vr/libdvr/include/dvr/dvr_api.h
+++ b/libs/vr/libdvr/include/dvr/dvr_api.h
@@ -412,6 +412,7 @@
// existing data members. If new fields need to be added, please take extra care
// to make sure that new data field is padded properly the size of the struct
// stays same.
+// TODO(b/118893702): move the definition to libnativewindow or libui
struct ALIGNED_DVR_STRUCT(8) DvrNativeBufferMetadata {
#ifdef __cplusplus
DvrNativeBufferMetadata()
@@ -465,11 +466,11 @@
// Only applicable for metadata retrieved from GainAsync. This indicates which
// consumer has pending fence that producer should epoll on.
- uint64_t release_fence_mask;
+ uint32_t release_fence_mask;
// Reserved bytes for so that the struct is forward compatible and padding to
// 104 bytes so the size is a multiple of 8.
- int32_t reserved[8];
+ int32_t reserved[9];
};
#ifdef __cplusplus
diff --git a/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp b/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
index 2d5f004..df06097 100644
--- a/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
+++ b/libs/vr/libdvr/tests/dvr_buffer_queue-test.cpp
@@ -62,7 +62,7 @@
buffer_removed_count_);
}
- DvrWriteBufferQueue* write_queue_{nullptr};
+ DvrWriteBufferQueue* write_queue_ = nullptr;
int buffer_available_count_{0};
int buffer_removed_count_{0};
};
diff --git a/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp b/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
index fa0adf0..f72dabc 100644
--- a/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
+++ b/libs/vr/libpdx_default_transport/pdx_benchmarks.cpp
@@ -66,7 +66,7 @@
prctl(PR_SET_NAME, reinterpret_cast<unsigned long>(name.c_str()), 0, 0, 0);
}
-constexpr uint64_t kNanosPerSecond = 1000000000llu;
+constexpr uint64_t kNanosPerSecond = 1000000000LLU;
uint64_t GetClockNs() {
timespec t;
diff --git a/libs/vr/libvrflinger/acquired_buffer.h b/libs/vr/libvrflinger/acquired_buffer.h
index 1a200aa..9e35a39 100644
--- a/libs/vr/libvrflinger/acquired_buffer.h
+++ b/libs/vr/libvrflinger/acquired_buffer.h
@@ -2,7 +2,7 @@
#define ANDROID_DVR_SERVICES_DISPLAYD_ACQUIRED_BUFFER_H_
#include <pdx/file_handle.h>
-#include <private/dvr/buffer_hub_client.h>
+#include <private/dvr/consumer_buffer.h>
#include <memory>
@@ -43,7 +43,7 @@
// Accessors for the underlying BufferConsumer, the acquire fence, and the
// use-case specific sequence value from the acquisition (see
- // private/dvr/buffer_hub_client.h).
+ // private/dvr/consumer_buffer.h).
std::shared_ptr<BufferConsumer> buffer() const { return buffer_; }
int acquire_fence() const { return acquire_fence_.Get(); }
diff --git a/libs/vr/libvrflinger/display_service.h b/libs/vr/libvrflinger/display_service.h
index 6fad58e..e0f2edd 100644
--- a/libs/vr/libvrflinger/display_service.h
+++ b/libs/vr/libvrflinger/display_service.h
@@ -4,7 +4,6 @@
#include <dvr/dvr_api.h>
#include <pdx/service.h>
#include <pdx/status.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/bufferhub_rpc.h>
#include <private/dvr/display_protocol.h>
diff --git a/libs/vr/libvrflinger/epoll_event_dispatcher.cpp b/libs/vr/libvrflinger/epoll_event_dispatcher.cpp
index 962c745..1cf5f17 100644
--- a/libs/vr/libvrflinger/epoll_event_dispatcher.cpp
+++ b/libs/vr/libvrflinger/epoll_event_dispatcher.cpp
@@ -11,7 +11,7 @@
namespace dvr {
EpollEventDispatcher::EpollEventDispatcher() {
- epoll_fd_.Reset(epoll_create(64));
+ epoll_fd_.Reset(epoll_create1(EPOLL_CLOEXEC));
if (!epoll_fd_) {
ALOGE("Failed to create epoll fd: %s", strerror(errno));
return;
diff --git a/libs/vr/libvrflinger/hardware_composer.h b/libs/vr/libvrflinger/hardware_composer.h
index 94a2337..6c25b3e 100644
--- a/libs/vr/libvrflinger/hardware_composer.h
+++ b/libs/vr/libvrflinger/hardware_composer.h
@@ -22,7 +22,6 @@
#include <dvr/dvr_vsync.h>
#include <pdx/file_handle.h>
#include <pdx/rpc/variant.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/shared_buffer_helpers.h>
#include <private/dvr/vsync_service.h>
diff --git a/libs/vr/libvrflinger/tests/Android.bp b/libs/vr/libvrflinger/tests/Android.bp
index 9a1d2e5..c884cb3 100644
--- a/libs/vr/libvrflinger/tests/Android.bp
+++ b/libs/vr/libvrflinger/tests/Android.bp
@@ -32,7 +32,6 @@
"-Wall",
"-Werror",
],
- cppflags: ["-std=c++1z"],
name: "vrflinger_test",
// TODO(b/117568153): Temporarily opt out using libcrt.
diff --git a/libs/vr/libvrsensor/pose_client.cpp b/libs/vr/libvrsensor/pose_client.cpp
index 710d75a..c72f75e 100644
--- a/libs/vr/libvrsensor/pose_client.cpp
+++ b/libs/vr/libvrsensor/pose_client.cpp
@@ -8,8 +8,8 @@
#include <pdx/client.h>
#include <pdx/default_transport/client_channel_factory.h>
#include <pdx/file_handle.h>
-#include <private/dvr/buffer_hub_client.h>
#include <private/dvr/buffer_hub_queue_client.h>
+#include <private/dvr/consumer_buffer.h>
#include <private/dvr/display_client.h>
#include <private/dvr/pose-ipc.h>
#include <private/dvr/shared_buffer_helpers.h>
diff --git a/opengl/include/EGL/eglext.h b/opengl/include/EGL/eglext.h
index ad4ffd7..501bf58 100644
--- a/opengl/include/EGL/eglext.h
+++ b/opengl/include/EGL/eglext.h
@@ -28,17 +28,17 @@
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/*
-** This header is generated from the Khronos OpenGL / OpenGL ES XML
-** API Registry. The current version of the Registry, generator scripts
+** This header is generated from the Khronos EGL XML API Registry.
+** The current version of the Registry, generator scripts
** used to make the header, and the header can be found at
** http://www.khronos.org/registry/egl
**
-** Khronos $Git commit SHA1: bae3518c48 $ on $Git commit date: 2018-05-17 10:56:57 -0700 $
+** Khronos $Git commit SHA1: 726475c203 $ on $Git commit date: 2018-10-03 23:51:49 -0700 $
*/
#include <EGL/eglplatform.h>
-#define EGL_EGLEXT_VERSION 20180517
+#define EGL_EGLEXT_VERSION 20181204
/* Generated C header for:
* API: egl
@@ -681,6 +681,7 @@
#ifndef EGL_EXT_device_drm
#define EGL_EXT_device_drm 1
#define EGL_DRM_DEVICE_FILE_EXT 0x3233
+#define EGL_DRM_MASTER_FD_EXT 0x333C
#endif /* EGL_EXT_device_drm */
#ifndef EGL_EXT_device_enumeration
@@ -716,6 +717,11 @@
#define EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT 0x3362
#endif /* EGL_EXT_gl_colorspace_display_p3_linear */
+#ifndef EGL_EXT_gl_colorspace_display_p3_passthrough
+#define EGL_EXT_gl_colorspace_display_p3_passthrough 1
+#define EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT 0x3490
+#endif /* EGL_EXT_gl_colorspace_display_p3_passthrough */
+
#ifndef EGL_EXT_gl_colorspace_scrgb
#define EGL_EXT_gl_colorspace_scrgb 1
#define EGL_GL_COLORSPACE_SCRGB_EXT 0x3351
diff --git a/opengl/libs/Android.bp b/opengl/libs/Android.bp
index 583aec9..c80b79a 100644
--- a/opengl/libs/Android.bp
+++ b/opengl/libs/Android.bp
@@ -197,6 +197,7 @@
defaults: ["gles_libs_defaults"],
srcs: ["GLES_CM/gl.cpp"],
cflags: ["-DLOG_TAG=\"libGLESv1\""],
+ version_script: "libGLESv1_CM.map.txt",
}
//##############################################################################
diff --git a/opengl/libs/EGL/Loader.cpp b/opengl/libs/EGL/Loader.cpp
index 6edadcd..f5cf3dc 100644
--- a/opengl/libs/EGL/Loader.cpp
+++ b/opengl/libs/EGL/Loader.cpp
@@ -41,6 +41,12 @@
extern "C" {
android_namespace_t* android_get_exported_namespace(const char*);
+ typedef enum ANGLEPreference {
+ ANGLE_PREFER_DEFAULT = 0,
+ ANGLE_PREFER_NATIVE = 1,
+ ANGLE_PREFER_ANGLE = 2,
+ } ANGLEPreference;
+
// TODO(ianelliott@): Get the following from an ANGLE header:
// Version-1 API:
typedef bool (*fpANGLEGetUtilityAPI)(unsigned int* versionToUse);
@@ -524,6 +530,17 @@
return nullptr;
}
+static ANGLEPreference getAngleDevOption(const char* devOption) {
+ if (devOption == nullptr)
+ return ANGLE_PREFER_DEFAULT;
+
+ if (strcmp(devOption, "angle") == 0) {
+ return ANGLE_PREFER_ANGLE;
+ } else if (strcmp(devOption, "native") == 0) {
+ return ANGLE_PREFER_NATIVE;
+ }
+ return ANGLE_PREFER_DEFAULT;
+}
static bool check_angle_rules(void* so, const char* app_name) {
bool use_angle = false;
@@ -537,33 +554,17 @@
property_get("ro.product.manufacturer", manufacturer, "UNSET");
property_get("ro.product.model", model, "UNSET");
- // TODO: Replace this with the new function name once the version-1 API is removed:
- fpANGLEGetUtilityAPI ANGLEGetUtilityAPI =
- (fpANGLEGetUtilityAPI)dlsym(so, "ANGLEGetUtilityAPI");
+ fpANGLEGetFeatureSupportUtilAPIVersion ANGLEGetFeatureSupportUtilAPIVersion =
+ (fpANGLEGetFeatureSupportUtilAPIVersion)dlsym(so, "ANGLEGetFeatureSupportUtilAPIVersion");
- if (ANGLEGetUtilityAPI) {
+ if (ANGLEGetFeatureSupportUtilAPIVersion) {
// Negotiate the interface version by requesting most recent known to the platform
unsigned int versionToUse = 2;
- // TODO: Replace this with the new function name once the version-1 API is removed:
- if ((ANGLEGetUtilityAPI)(&versionToUse)) {
+ if ((ANGLEGetFeatureSupportUtilAPIVersion)(&versionToUse)) {
// Add and remove versions below as needed
switch(versionToUse) {
- case 1: {
- ALOGV("Using version 1 of ANGLE feature-support library");
- fpAndroidUseANGLEForApplication AndroidUseANGLEForApplication =
- (fpAndroidUseANGLEForApplication)dlsym(so, "AndroidUseANGLEForApplication");
-
- if (AndroidUseANGLEForApplication) {
- use_angle = (AndroidUseANGLEForApplication)(rules_fd, rules_offset,
- rules_length, app_name_str.c_str(),
- manufacturer, model);
- } else {
- ALOGW("Cannot find AndroidUseANGLEForApplication in ANGLE feature-support library");
- }
- }
- break;
case 2: {
ALOGV("Using version 2 of ANGLE feature-support library");
void* rules_handle = nullptr;
@@ -630,7 +631,7 @@
ALOGW("Cannot use ANGLE feature-support library, it is older than supported by EGL, requested version %u", versionToUse);
}
} else {
- ALOGW("Cannot find ANGLEGetUtilityAPI function");
+ ALOGW("Cannot find ANGLEGetFeatureSupportUtilAPIVersion function");
}
ALOGV("Close temporarily-loaded ANGLE opt-in/out logic");
@@ -646,15 +647,19 @@
char prop[PROPERTY_VALUE_MAX];
const char* app_name = android::GraphicsEnv::getInstance().getAngleAppName();
- bool developer_opt_in = android::GraphicsEnv::getInstance().getAngleDeveloperOptIn();
+ const char* developer_opt_in = android::GraphicsEnv::getInstance().getAngleDeveloperOptIn();
// Determine whether or not to use ANGLE:
- bool use_angle = developer_opt_in;
+ ANGLEPreference developer_option = getAngleDevOption(developer_opt_in);
+ bool use_angle = (developer_option == ANGLE_PREFER_ANGLE);
if (use_angle) {
ALOGV("User set \"Developer Options\" to force the use of ANGLE");
} else if (cnx->angleDecided) {
use_angle = cnx->useAngle;
+ } else if (developer_option == ANGLE_PREFER_NATIVE) {
+ ALOGV("User set \"Developer Options\" to force the use of Native");
+ use_angle = false;
} else {
// The "Developer Options" value wasn't set to force the use of ANGLE. Need to temporarily
// load ANGLE and call the updatable opt-in/out logic:
diff --git a/opengl/libs/EGL/egl_display.cpp b/opengl/libs/EGL/egl_display.cpp
index 4433af0..c100db7 100644
--- a/opengl/libs/EGL/egl_display.cpp
+++ b/opengl/libs/EGL/egl_display.cpp
@@ -378,7 +378,8 @@
if (wideColorBoardConfig && hasColorSpaceSupport) {
mExtensionString.append(
"EGL_EXT_gl_colorspace_scrgb EGL_EXT_gl_colorspace_scrgb_linear "
- "EGL_EXT_gl_colorspace_display_p3_linear EGL_EXT_gl_colorspace_display_p3 ");
+ "EGL_EXT_gl_colorspace_display_p3_linear EGL_EXT_gl_colorspace_display_p3 "
+ "EGL_EXT_gl_colorspace_display_p3_passthrough ");
}
bool hasHdrBoardConfig =
diff --git a/opengl/libs/EGL/egl_platform_entries.cpp b/opengl/libs/EGL/egl_platform_entries.cpp
index 547a669..79166a7 100644
--- a/opengl/libs/EGL/egl_platform_entries.cpp
+++ b/opengl/libs/EGL/egl_platform_entries.cpp
@@ -461,11 +461,13 @@
if (colorspace == EGL_GL_COLORSPACE_LINEAR_KHR) {
return HAL_DATASPACE_UNKNOWN;
} else if (colorspace == EGL_GL_COLORSPACE_SRGB_KHR) {
- return HAL_DATASPACE_SRGB;
+ return HAL_DATASPACE_V0_SRGB;
} else if (colorspace == EGL_GL_COLORSPACE_DISPLAY_P3_EXT) {
return HAL_DATASPACE_DISPLAY_P3;
} else if (colorspace == EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT) {
return HAL_DATASPACE_DISPLAY_P3_LINEAR;
+ } else if (colorspace == EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT) {
+ return HAL_DATASPACE_DISPLAY_P3;
} else if (colorspace == EGL_GL_COLORSPACE_SCRGB_EXT) {
return HAL_DATASPACE_V0_SCRGB;
} else if (colorspace == EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT) {
@@ -510,6 +512,9 @@
if (findExtension(dp->disp.queryString.extensions, "EGL_EXT_gl_colorspace_display_p3_linear")) {
colorSpaces.push_back(EGL_GL_COLORSPACE_DISPLAY_P3_LINEAR_EXT);
}
+ if (findExtension(dp->disp.queryString.extensions, "EGL_EXT_gl_colorspace_display_p3_passthrough")) {
+ colorSpaces.push_back(EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT);
+ }
return colorSpaces;
}
@@ -527,6 +532,7 @@
case EGL_GL_COLORSPACE_LINEAR_KHR:
case EGL_GL_COLORSPACE_SRGB_KHR:
case EGL_GL_COLORSPACE_DISPLAY_P3_EXT:
+ case EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT:
case EGL_GL_COLORSPACE_SCRGB_LINEAR_EXT:
case EGL_GL_COLORSPACE_SCRGB_EXT:
case EGL_GL_COLORSPACE_BT2020_LINEAR_EXT:
diff --git a/opengl/tests/EGLTest/EGL_test.cpp b/opengl/tests/EGLTest/EGL_test.cpp
index 459b135..cca91c3 100644
--- a/opengl/tests/EGLTest/EGL_test.cpp
+++ b/opengl/tests/EGLTest/EGL_test.cpp
@@ -217,6 +217,7 @@
// Test that display-p3 extensions exist
ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3"));
ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_linear"));
+ ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_passthrough"));
// Use 8-bit to keep forcus on Display-P3 aspect
EGLint attrs[] = {
@@ -289,6 +290,59 @@
EXPECT_TRUE(eglDestroySurface(mEglDisplay, eglSurface));
}
+TEST_F(EGLTest, EGLDisplayP3Passthrough) {
+ EGLConfig config;
+ EGLBoolean success;
+
+ if (!hasWideColorDisplay) {
+ // skip this test if device does not have wide-color display
+ std::cerr << "[ ] Device does not support wide-color, test skipped" << std::endl;
+ return;
+ }
+
+ // Test that display-p3 extensions exist
+ ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3"));
+ ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_linear"));
+ ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_passthrough"));
+
+ get8BitConfig(config);
+
+ struct DummyConsumer : public BnConsumerListener {
+ void onFrameAvailable(const BufferItem& /* item */) override {}
+ void onBuffersReleased() override {}
+ void onSidebandStreamChanged() override {}
+ };
+
+ // Create a EGLSurface
+ sp<IGraphicBufferProducer> producer;
+ sp<IGraphicBufferConsumer> consumer;
+ BufferQueue::createBufferQueue(&producer, &consumer);
+ consumer->consumerConnect(new DummyConsumer, false);
+ sp<Surface> mSTC = new Surface(producer);
+ sp<ANativeWindow> mANW = mSTC;
+ EGLint winAttrs[] = {
+ // clang-format off
+ EGL_GL_COLORSPACE_KHR, EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT,
+ EGL_NONE, EGL_NONE
+ // clang-format on
+ };
+
+ EGLSurface eglSurface = eglCreateWindowSurface(mEglDisplay, config, mANW.get(), winAttrs);
+ ASSERT_EQ(EGL_SUCCESS, eglGetError());
+ ASSERT_NE(EGL_NO_SURFACE, eglSurface);
+
+ android_dataspace dataspace =
+ static_cast<android_dataspace>(ANativeWindow_getBuffersDataSpace(mANW.get()));
+ ASSERT_EQ(dataspace, HAL_DATASPACE_DISPLAY_P3);
+
+ EGLint value;
+ success = eglQuerySurface(mEglDisplay, eglSurface, EGL_GL_COLORSPACE_KHR, &value);
+ ASSERT_EQ(EGL_UNSIGNED_TRUE, success);
+ ASSERT_EQ(EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT, value);
+
+ EXPECT_TRUE(eglDestroySurface(mEglDisplay, eglSurface));
+}
+
TEST_F(EGLTest, EGLDisplayP31010102) {
EGLint numConfigs;
EGLConfig config;
@@ -303,6 +357,7 @@
// Test that display-p3 extensions exist
ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3"));
ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_linear"));
+ ASSERT_TRUE(hasEglExtension(mEglDisplay, "EGL_EXT_gl_colorspace_display_p3_passthrough"));
// Use 8-bit to keep forcus on Display-P3 aspect
EGLint attrs[] = {
diff --git a/opengl/tests/lib/include/EGLUtils.h b/opengl/tests/lib/include/EGLUtils.h
index eb9571d..cfa378f 100644
--- a/opengl/tests/lib/include/EGLUtils.h
+++ b/opengl/tests/lib/include/EGLUtils.h
@@ -280,6 +280,8 @@
return String8("EGL_GL_COLORSPACE_SRGB_KHR");
case EGL_GL_COLORSPACE_DISPLAY_P3_EXT:
return String8("EGL_GL_COLORSPACE_DISPLAY_P3_EXT");
+ case EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT:
+ return String8("EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT");
case EGL_GL_COLORSPACE_LINEAR_KHR:
return String8("EGL_GL_COLORSPACE_LINEAR_KHR");
default:
diff --git a/opengl/tools/glgen2/registry/egl.xml b/opengl/tools/glgen2/registry/egl.xml
index 26771e1..8d661ae 100644
--- a/opengl/tools/glgen2/registry/egl.xml
+++ b/opengl/tools/glgen2/registry/egl.xml
@@ -894,6 +894,11 @@
<unused start="0x3481" end="0x348F"/>
</enums>
+ <enums namespace="EGL" start="0x3490" end="0x349F" vendor="EXT" comment="Reserved for Courtney Goeltzenleuchter - Android (gitlab EGL bug 69)">
+ <enum value="0x3490" name="EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT"/>
+ <unused start="0x3491" end="0x349F"/>
+ </enums>
+
<!-- Please remember that new enumerant allocations must be obtained by
request to the Khronos API registrar (see comments at the top of this
file) File requests in the Khronos Bugzilla, EGL project, Registry
@@ -903,8 +908,8 @@
<!-- Reservable for future use. To generate a new range, allocate multiples
of 16 starting at the lowest available point in this block. -->
- <enums namespace="EGL" start="0x3490" end="0x3FFF" vendor="KHR" comment="Reserved for future use">
- <unused start="0x3490" end="0x3FFF"/>
+ <enums namespace="EGL" start="0x34A0" end="0x3FFF" vendor="KHR" comment="Reserved for future use">
+ <unused start="0x34A0" end="0x3FFF"/>
</enums>
<enums namespace="EGL" start="0x8F70" end="0x8F7F" vendor="HI" comment="For Mark Callow, Khronos bug 4055. Shared with GL.">
@@ -2250,6 +2255,11 @@
<enum name="EGL_GL_COLORSPACE_DISPLAY_P3_EXT"/>
</require>
</extension>
+ <extension name="EGL_EXT_gl_colorspace_display_p3_passthrough" supported="egl">
+ <require>
+ <enum name="EGL_GL_COLORSPACE_DISPLAY_P3_PASSTHROUGH_EXT"/>
+ </require>
+ </extension>
<extension name="EGL_EXT_image_dma_buf_import" supported="egl">
<require>
<enum name="EGL_LINUX_DMA_BUF_EXT"/>
diff --git a/services/bufferhub/Android.bp b/services/bufferhub/Android.bp
index f9aaa20..72d210c 100644
--- a/services/bufferhub/Android.bp
+++ b/services/bufferhub/Android.bp
@@ -29,10 +29,8 @@
"BufferNode.cpp",
],
header_libs: [
- "libbufferhub_headers",
"libdvr_headers",
"libnativewindow_headers",
- "libpdx_headers",
],
shared_libs: [
"android.frameworks.bufferhub@1.0",
@@ -56,10 +54,8 @@
"main_bufferhub.cpp"
],
header_libs: [
- "libbufferhub_headers",
"libdvr_headers",
"libnativewindow_headers",
- "libpdx_headers",
],
shared_libs: [
"android.frameworks.bufferhub@1.0",
diff --git a/services/bufferhub/BufferClient.cpp b/services/bufferhub/BufferClient.cpp
index 7459517..e312011 100644
--- a/services/bufferhub/BufferClient.cpp
+++ b/services/bufferhub/BufferClient.cpp
@@ -17,6 +17,7 @@
#include <bufferhub/BufferClient.h>
#include <bufferhub/BufferHubService.h>
#include <hidl/HidlSupport.h>
+#include <log/log.h>
namespace android {
namespace frameworks {
diff --git a/services/bufferhub/BufferHubService.cpp b/services/bufferhub/BufferHubService.cpp
index b0869fe..2663812 100644
--- a/services/bufferhub/BufferHubService.cpp
+++ b/services/bufferhub/BufferHubService.cpp
@@ -39,7 +39,8 @@
BufferHubIdGenerator::getInstance().getId());
if (node == nullptr || !node->IsValid()) {
ALOGE("%s: creating BufferNode failed.", __FUNCTION__);
- _hidl_cb(/*bufferClient=*/nullptr, /*status=*/BufferHubStatus::ALLOCATION_FAILED);
+ _hidl_cb(/*status=*/BufferHubStatus::ALLOCATION_FAILED, /*bufferClient=*/nullptr,
+ /*bufferTraits=*/{});
return Void();
}
@@ -48,7 +49,13 @@
std::lock_guard<std::mutex> lock(mClientSetMutex);
mClientSet.emplace(client);
- _hidl_cb(/*bufferClient=*/client, /*status=*/BufferHubStatus::NO_ERROR);
+ BufferTraits bufferTraits = {/*bufferDesc=*/description,
+ /*bufferHandle=*/hidl_handle(node->buffer_handle()),
+ // TODO(b/116681016): return real data to client
+ /*bufferInfo=*/hidl_handle()};
+
+ _hidl_cb(/*status=*/BufferHubStatus::NO_ERROR, /*bufferClient=*/client,
+ /*bufferTraits=*/bufferTraits);
return Void();
}
@@ -56,7 +63,8 @@
importBuffer_cb _hidl_cb) {
if (!tokenHandle.getNativeHandle() || tokenHandle->numFds != 0 || tokenHandle->numInts != 1) {
// nullptr handle or wrong format
- _hidl_cb(/*bufferClient=*/nullptr, /*status=*/BufferHubStatus::INVALID_TOKEN);
+ _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
+ /*bufferTraits=*/{});
return Void();
}
@@ -68,7 +76,8 @@
auto iter = mTokenMap.find(token);
if (iter == mTokenMap.end()) {
// Invalid token
- _hidl_cb(/*bufferClient=*/nullptr, /*status=*/BufferHubStatus::INVALID_TOKEN);
+ _hidl_cb(/*status=*/BufferHubStatus::INVALID_TOKEN, /*bufferClient=*/nullptr,
+ /*bufferTraits=*/{});
return Void();
}
@@ -81,15 +90,37 @@
if (!originClient) {
// Should not happen since token should be removed if already gone
ALOGE("%s: original client %p gone!", __FUNCTION__, originClientWp.unsafe_get());
- _hidl_cb(/*bufferClient=*/nullptr, /*status=*/BufferHubStatus::BUFFER_FREED);
+ _hidl_cb(/*status=*/BufferHubStatus::BUFFER_FREED, /*bufferClient=*/nullptr,
+ /*bufferTraits=*/{});
return Void();
}
sp<BufferClient> client = new BufferClient(*originClient);
+ uint32_t clientStateMask = client->getBufferNode()->AddNewActiveClientsBitToMask();
+ if (clientStateMask == 0U) {
+ // Reach max client count
+ ALOGE("%s: import failed, BufferNode#%u reached maximum clients.", __FUNCTION__,
+ client->getBufferNode()->id());
+ _hidl_cb(/*status=*/BufferHubStatus::MAX_CLIENT, /*bufferClient=*/nullptr,
+ /*bufferTraits=*/{});
+ return Void();
+ }
std::lock_guard<std::mutex> lock(mClientSetMutex);
mClientSet.emplace(client);
- _hidl_cb(/*bufferClient=*/client, /*status=*/BufferHubStatus::NO_ERROR);
+
+ std::shared_ptr<BufferNode> node = client->getBufferNode();
+
+ HardwareBufferDescription bufferDesc;
+ memcpy(&bufferDesc, &node->buffer_desc(), sizeof(HardwareBufferDescription));
+
+ BufferTraits bufferTraits = {/*bufferDesc=*/bufferDesc,
+ /*bufferHandle=*/hidl_handle(node->buffer_handle()),
+ // TODO(b/116681016): return real data to client
+ /*bufferInfo=*/hidl_handle()};
+
+ _hidl_cb(/*status=*/BufferHubStatus::NO_ERROR, /*bufferClient=*/client,
+ /*bufferTraits=*/bufferTraits);
return Void();
}
diff --git a/services/bufferhub/BufferNode.cpp b/services/bufferhub/BufferNode.cpp
index ec84849..da19a6f 100644
--- a/services/bufferhub/BufferNode.cpp
+++ b/services/bufferhub/BufferNode.cpp
@@ -2,7 +2,7 @@
#include <bufferhub/BufferHubService.h>
#include <bufferhub/BufferNode.h>
-#include <private/dvr/buffer_hub_defs.h>
+#include <log/log.h>
#include <ui/GraphicBufferAllocator.h>
namespace android {
@@ -14,11 +14,18 @@
void BufferNode::InitializeMetadata() {
// Using placement new here to reuse shared memory instead of new allocation
// Initialize the atomic variables to zero.
- dvr::BufferHubDefs::MetadataHeader* metadata_header = metadata_.metadata_header();
- buffer_state_ = new (&metadata_header->buffer_state) std::atomic<uint64_t>(0);
- fence_state_ = new (&metadata_header->fence_state) std::atomic<uint64_t>(0);
+ BufferHubDefs::MetadataHeader* metadata_header = metadata_.metadata_header();
+ buffer_state_ = new (&metadata_header->buffer_state) std::atomic<uint32_t>(0);
+ fence_state_ = new (&metadata_header->fence_state) std::atomic<uint32_t>(0);
active_clients_bit_mask_ =
- new (&metadata_header->active_clients_bit_mask) std::atomic<uint64_t>(0);
+ new (&metadata_header->active_clients_bit_mask) std::atomic<uint32_t>(0);
+ // The C++ standard recommends (but does not require) that lock-free atomic operations are
+ // also address-free, that is, suitable for communication between processes using shared
+ // memory.
+ LOG_ALWAYS_FATAL_IF(!std::atomic_is_lock_free(buffer_state_) ||
+ !std::atomic_is_lock_free(fence_state_) ||
+ !std::atomic_is_lock_free(active_clients_bit_mask_),
+ "Atomic variables in ashmen are not lock free.");
}
// Allocates a new BufferNode.
@@ -75,21 +82,22 @@
}
}
-uint64_t BufferNode::GetActiveClientsBitMask() const {
+uint32_t BufferNode::GetActiveClientsBitMask() const {
return active_clients_bit_mask_->load(std::memory_order_acquire);
}
-uint64_t BufferNode::AddNewActiveClientsBitToMask() {
- uint64_t current_active_clients_bit_mask = GetActiveClientsBitMask();
- uint64_t client_state_mask = 0ULL;
- uint64_t updated_active_clients_bit_mask = 0ULL;
+uint32_t BufferNode::AddNewActiveClientsBitToMask() {
+ uint32_t current_active_clients_bit_mask = GetActiveClientsBitMask();
+ uint32_t client_state_mask = 0U;
+ uint32_t updated_active_clients_bit_mask = 0U;
do {
- client_state_mask = dvr::BufferHubDefs::FindNextAvailableClientStateMask(
- current_active_clients_bit_mask);
- if (client_state_mask == 0ULL) {
- ALOGE("%s: reached the maximum number of channels per buffer node: 32.", __FUNCTION__);
+ client_state_mask =
+ BufferHubDefs::FindNextAvailableClientStateMask(current_active_clients_bit_mask);
+ if (client_state_mask == 0U) {
+ ALOGE("%s: reached the maximum number of channels per buffer node: %d.", __FUNCTION__,
+ BufferHubDefs::kMaxNumberOfClients);
errno = E2BIG;
- return 0ULL;
+ return 0U;
}
updated_active_clients_bit_mask = current_active_clients_bit_mask | client_state_mask;
} while (!(active_clients_bit_mask_->compare_exchange_weak(current_active_clients_bit_mask,
@@ -99,7 +107,7 @@
return client_state_mask;
}
-void BufferNode::RemoveClientsBitFromMask(const uint64_t& value) {
+void BufferNode::RemoveClientsBitFromMask(const uint32_t& value) {
active_clients_bit_mask_->fetch_and(~value);
}
diff --git a/services/bufferhub/include/bufferhub/BufferClient.h b/services/bufferhub/include/bufferhub/BufferClient.h
index 7f5d3a6..66ed4bd 100644
--- a/services/bufferhub/include/bufferhub/BufferClient.h
+++ b/services/bufferhub/include/bufferhub/BufferClient.h
@@ -49,6 +49,9 @@
Return<BufferHubStatus> close() override;
Return<void> duplicate(duplicate_cb _hidl_cb) override;
+ // Non-binder functions
+ const std::shared_ptr<BufferNode>& getBufferNode() const { return mBufferNode; }
+
private:
BufferClient(wp<BufferHubService> service, const std::shared_ptr<BufferNode>& node)
: mService(service), mBufferNode(node) {}
diff --git a/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h b/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h
index c5b2cde..b51fcda 100644
--- a/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h
+++ b/services/bufferhub/include/bufferhub/BufferHubIdGenerator.h
@@ -32,7 +32,7 @@
class BufferHubIdGenerator {
public:
// 0 is considered invalid
- static constexpr uint32_t kInvalidId = 0UL;
+ static constexpr uint32_t kInvalidId = 0U;
// Get the singleton instance of this class
static BufferHubIdGenerator& getInstance();
diff --git a/services/bufferhub/include/bufferhub/BufferNode.h b/services/bufferhub/include/bufferhub/BufferNode.h
index 94ef505..cf56c33 100644
--- a/services/bufferhub/include/bufferhub/BufferNode.h
+++ b/services/bufferhub/include/bufferhub/BufferNode.h
@@ -3,6 +3,7 @@
#include <android/hardware_buffer.h>
#include <bufferhub/BufferHubIdGenerator.h>
+#include <cutils/native_handle.h>
#include <ui/BufferHubMetadata.h>
namespace android {
@@ -37,19 +38,19 @@
// Gets the current value of active_clients_bit_mask in metadata_ with
// std::memory_order_acquire, so that all previous releases of
// active_clients_bit_mask from all threads will be returned here.
- uint64_t GetActiveClientsBitMask() const;
+ uint32_t GetActiveClientsBitMask() const;
// Find and add a new client_state_mask to active_clients_bit_mask in
// metadata_.
// Return the new client_state_mask that is added to active_clients_bit_mask.
- // Return 0ULL if there are already 32 bp clients of the buffer.
- uint64_t AddNewActiveClientsBitToMask();
+ // Return 0U if there are already 16 clients of the buffer.
+ uint32_t AddNewActiveClientsBitToMask();
// Removes the value from active_clients_bit_mask in metadata_ with
// std::memory_order_release, so that the change will be visible to any
// acquire of active_clients_bit_mask_ in any threads after the succeed of
// this operation.
- void RemoveClientsBitFromMask(const uint64_t& value);
+ void RemoveClientsBitFromMask(const uint32_t& value);
private:
// Helper method for constructors to initialize atomic metadata header
@@ -74,14 +75,14 @@
// buffer_state_ tracks the state of the buffer. Buffer can be in one of these
// four states: gained, posted, acquired, released.
- std::atomic<uint64_t>* buffer_state_ = nullptr;
+ std::atomic<uint32_t>* buffer_state_ = nullptr;
// TODO(b/112012161): add comments to fence_state_.
- std::atomic<uint64_t>* fence_state_ = nullptr;
+ std::atomic<uint32_t>* fence_state_ = nullptr;
// active_clients_bit_mask_ tracks all the bp clients of the buffer. It is the
// union of all client_state_mask of all bp clients.
- std::atomic<uint64_t>* active_clients_bit_mask_ = nullptr;
+ std::atomic<uint32_t>* active_clients_bit_mask_ = nullptr;
};
} // namespace implementation
diff --git a/services/bufferhub/tests/Android.bp b/services/bufferhub/tests/Android.bp
index 3967886..e565374 100644
--- a/services/bufferhub/tests/Android.bp
+++ b/services/bufferhub/tests/Android.bp
@@ -1,16 +1,17 @@
cc_test {
- name: "BufferNode_test",
- srcs: ["BufferNode_test.cpp"],
+ name: "BufferHubServer_test",
+ srcs: [
+ "BufferNode_test.cpp",
+ "BufferHubIdGenerator_test.cpp",
+ ],
cflags: [
- "-DLOG_TAG=\"BufferNode_test\"",
+ "-DLOG_TAG=\"BufferHubServer_test\"",
"-DTRACE=0",
"-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
],
header_libs: [
- "libbufferhub_headers",
"libdvr_headers",
"libnativewindow_headers",
- "libpdx_headers",
],
shared_libs: [
"libbufferhubservice",
@@ -19,22 +20,4 @@
static_libs: [
"libgmock",
],
- // TODO(b/117568153): Temporarily opt out using libcrt.
- no_libcrt: true,
}
-
-cc_test {
- name: "BufferHubIdGenerator_test",
- srcs: ["BufferHubIdGenerator_test.cpp"],
- cflags: [
- "-DLOG_TAG=\"BufferHubIdGenerator_test\"",
- "-DTRACE=0",
- "-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
- ],
- shared_libs: [
- "libbufferhubservice",
- ],
- static_libs: [
- "libgmock",
- ],
-}
\ No newline at end of file
diff --git a/services/bufferhub/tests/BufferNode_test.cpp b/services/bufferhub/tests/BufferNode_test.cpp
index df31d78..dbf10e8 100644
--- a/services/bufferhub/tests/BufferNode_test.cpp
+++ b/services/bufferhub/tests/BufferNode_test.cpp
@@ -1,7 +1,9 @@
-#include <bufferhub/BufferNode.h>
#include <errno.h>
+
+#include <bufferhub/BufferNode.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
+#include <ui/BufferHubDefs.h>
#include <ui/GraphicBufferMapper.h>
namespace android {
@@ -20,7 +22,6 @@
const uint32_t kFormat = 1;
const uint64_t kUsage = 0;
const size_t kUserMetadataSize = 0;
-const size_t kMaxClientsCount = dvr::BufferHubDefs::kMaxNumberOfClients;
class BufferNodeTest : public ::testing::Test {
protected:
@@ -55,23 +56,23 @@
}
TEST_F(BufferNodeTest, TestAddNewActiveClientsBitToMask_twoNewClients) {
- uint64_t new_client_state_mask_1 = buffer_node->AddNewActiveClientsBitToMask();
+ uint32_t new_client_state_mask_1 = buffer_node->AddNewActiveClientsBitToMask();
EXPECT_EQ(buffer_node->GetActiveClientsBitMask(), new_client_state_mask_1);
// Request and add a new client_state_mask again.
// Active clients bit mask should be the union of the two new
// client_state_masks.
- uint64_t new_client_state_mask_2 = buffer_node->AddNewActiveClientsBitToMask();
+ uint32_t new_client_state_mask_2 = buffer_node->AddNewActiveClientsBitToMask();
EXPECT_EQ(buffer_node->GetActiveClientsBitMask(),
new_client_state_mask_1 | new_client_state_mask_2);
}
TEST_F(BufferNodeTest, TestAddNewActiveClientsBitToMask_32NewClients) {
- uint64_t new_client_state_mask = 0ULL;
- uint64_t current_mask = 0ULL;
- uint64_t expected_mask = 0ULL;
+ uint32_t new_client_state_mask = 0U;
+ uint32_t current_mask = 0U;
+ uint32_t expected_mask = 0U;
- for (int i = 0; i < kMaxClientsCount; ++i) {
+ for (int i = 0; i < BufferHubDefs::kMaxNumberOfClients; ++i) {
new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
EXPECT_NE(new_client_state_mask, 0);
EXPECT_FALSE(new_client_state_mask & current_mask);
@@ -82,14 +83,14 @@
// Method should fail upon requesting for more than maximum allowable clients.
new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
- EXPECT_EQ(new_client_state_mask, 0ULL);
+ EXPECT_EQ(new_client_state_mask, 0U);
EXPECT_EQ(errno, E2BIG);
}
TEST_F(BufferNodeTest, TestRemoveActiveClientsBitFromMask) {
buffer_node->AddNewActiveClientsBitToMask();
- uint64_t current_mask = buffer_node->GetActiveClientsBitMask();
- uint64_t new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
+ uint32_t current_mask = buffer_node->GetActiveClientsBitMask();
+ uint32_t new_client_state_mask = buffer_node->AddNewActiveClientsBitToMask();
EXPECT_NE(buffer_node->GetActiveClientsBitMask(), current_mask);
buffer_node->RemoveClientsBitFromMask(new_client_state_mask);
diff --git a/services/inputflinger/Android.bp b/services/inputflinger/Android.bp
index 4a8b613..1fbc6bf 100644
--- a/services/inputflinger/Android.bp
+++ b/services/inputflinger/Android.bp
@@ -15,8 +15,6 @@
cc_library_shared {
name: "libinputflinger",
- cpp_std: "c++17",
-
srcs: [
"InputDispatcher.cpp",
"InputManager.cpp",
@@ -60,8 +58,6 @@
cc_library_shared {
name: "libinputreader",
- cpp_std: "c++17",
-
srcs: [
"EventHub.cpp",
"InputReader.cpp",
@@ -100,8 +96,6 @@
cc_library_shared {
name: "libinputflinger_base",
- cpp_std: "c++17",
-
srcs: [
"InputListener.cpp",
"InputReaderBase.cpp",
diff --git a/services/inputflinger/EventHub.cpp b/services/inputflinger/EventHub.cpp
index 31057f6..f7802b9 100644
--- a/services/inputflinger/EventHub.cpp
+++ b/services/inputflinger/EventHub.cpp
@@ -69,8 +69,12 @@
namespace android {
+static constexpr bool DEBUG = false;
+
static const char *WAKE_LOCK_ID = "KeyEvents";
static const char *DEVICE_PATH = "/dev/input";
+// v4l2 devices go directly into /dev
+static const char *VIDEO_DEVICE_PATH = "/dev";
static inline const char* toString(bool value) {
return value ? "true" : "false";
@@ -98,6 +102,13 @@
}
}
+/**
+ * Return true if name matches "v4l-touch*"
+ */
+static bool isV4lTouchNode(const char* name) {
+ return strstr(name, "v4l-touch") == name;
+}
+
// --- Global Functions ---
uint32_t getAbsAxisUsage(int32_t axis, uint32_t deviceClasses) {
@@ -203,19 +214,22 @@
mPendingEventCount(0), mPendingEventIndex(0), mPendingINotify(false) {
acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);
- mEpollFd = epoll_create(EPOLL_SIZE_HINT);
- LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance. errno=%d", errno);
+ mEpollFd = epoll_create1(EPOLL_CLOEXEC);
+ LOG_ALWAYS_FATAL_IF(mEpollFd < 0, "Could not create epoll instance: %s", strerror(errno));
mINotifyFd = inotify_init();
- int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
- LOG_ALWAYS_FATAL_IF(result < 0, "Could not register INotify for %s. errno=%d",
- DEVICE_PATH, errno);
+ mInputWd = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);
+ LOG_ALWAYS_FATAL_IF(mInputWd < 0, "Could not register INotify for %s: %s",
+ DEVICE_PATH, strerror(errno));
+ mVideoWd = inotify_add_watch(mINotifyFd, VIDEO_DEVICE_PATH, IN_DELETE | IN_CREATE);
+ LOG_ALWAYS_FATAL_IF(mVideoWd < 0, "Could not register INotify for %s: %s",
+ VIDEO_DEVICE_PATH, strerror(errno));
struct epoll_event eventItem;
memset(&eventItem, 0, sizeof(eventItem));
eventItem.events = EPOLLIN;
eventItem.data.fd = mINotifyFd;
- result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
+ int result = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, mINotifyFd, &eventItem);
LOG_ALWAYS_FATAL_IF(result != 0, "Could not add INotify to epoll instance. errno=%d", errno);
int wakeFds[2];
@@ -1063,26 +1077,45 @@
AKEYCODE_BUTTON_START, AKEYCODE_BUTTON_SELECT, AKEYCODE_BUTTON_MODE,
};
-status_t EventHub::registerDeviceForEpollLocked(Device* device) {
- struct epoll_event eventItem;
- memset(&eventItem, 0, sizeof(eventItem));
- eventItem.events = EPOLLIN;
- if (mUsingEpollWakeup) {
- eventItem.events |= EPOLLWAKEUP;
- }
- eventItem.data.fd = device->fd;
- if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, device->fd, &eventItem)) {
- ALOGE("Could not add device fd to epoll instance. errno=%d", errno);
+status_t EventHub::registerFdForEpoll(int fd) {
+ struct epoll_event eventItem = {};
+ eventItem.events = EPOLLIN | EPOLLWAKEUP;
+ eventItem.data.fd = fd;
+ if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) {
+ ALOGE("Could not add fd to epoll instance: %s", strerror(errno));
return -errno;
}
return OK;
}
+status_t EventHub::unregisterFdFromEpoll(int fd) {
+ if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, fd, nullptr)) {
+ ALOGW("Could not remove fd from epoll instance: %s", strerror(errno));
+ return -errno;
+ }
+ return OK;
+}
+
+status_t EventHub::registerDeviceForEpollLocked(Device* device) {
+ if (device == nullptr) {
+ if (DEBUG) {
+ LOG_ALWAYS_FATAL("Cannot call registerDeviceForEpollLocked with null Device");
+ }
+ return BAD_VALUE;
+ }
+ status_t result = registerFdForEpoll(device->fd);
+ if (result != OK) {
+ ALOGE("Could not add input device fd to epoll for device %" PRId32, device->id);
+ }
+ return result;
+}
+
status_t EventHub::unregisterDeviceFromEpollLocked(Device* device) {
if (device->hasValidFd()) {
- if (epoll_ctl(mEpollFd, EPOLL_CTL_DEL, device->fd, nullptr)) {
- ALOGW("Could not remove device fd from epoll instance. errno=%d", errno);
- return -errno;
+ status_t result = unregisterFdFromEpoll(device->fd);
+ if (result != OK) {
+ ALOGW("Could not remove input device fd from epoll for device %" PRId32, device->id);
+ return result;
}
}
return OK;
@@ -1103,7 +1136,7 @@
// Get device name.
if(ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) < 1) {
- //fprintf(stderr, "could not get device name for %s, %s\n", devicePath, strerror(errno));
+ ALOGE("Could not get device name for %s: %s", devicePath, strerror(errno));
} else {
buffer[sizeof(buffer) - 1] = '\0';
identifier.name = buffer;
@@ -1646,8 +1679,6 @@
status_t EventHub::readNotifyLocked() {
int res;
- char devname[PATH_MAX];
- char *filename;
char event_buf[512];
int event_size;
int event_pos = 0;
@@ -1661,22 +1692,27 @@
ALOGW("could not get event, %s\n", strerror(errno));
return -1;
}
- //printf("got %d bytes of event information\n", res);
-
- strcpy(devname, DEVICE_PATH);
- filename = devname + strlen(devname);
- *filename++ = '/';
while(res >= (int)sizeof(*event)) {
event = (struct inotify_event *)(event_buf + event_pos);
- //printf("%d: %08x \"%s\"\n", event->wd, event->mask, event->len ? event->name : "");
if(event->len) {
- strcpy(filename, event->name);
- if(event->mask & IN_CREATE) {
- openDeviceLocked(devname);
- } else {
- ALOGI("Removing device '%s' due to inotify event\n", devname);
- closeDeviceByPathLocked(devname);
+ if (event->wd == mInputWd) {
+ std::string filename = StringPrintf("%s/%s", DEVICE_PATH, event->name);
+ if(event->mask & IN_CREATE) {
+ openDeviceLocked(filename.c_str());
+ } else {
+ ALOGI("Removing device '%s' due to inotify event\n", filename.c_str());
+ closeDeviceByPathLocked(filename.c_str());
+ }
+ }
+ else if (event->wd == mVideoWd) {
+ if (isV4lTouchNode(event->name)) {
+ std::string filename = StringPrintf("%s/%s", VIDEO_DEVICE_PATH, event->name);
+ ALOGV("Received an inotify event for a video device %s", filename.c_str());
+ }
+ }
+ else {
+ LOG_ALWAYS_FATAL("Unexpected inotify event, wd = %i", event->wd);
}
}
event_size = sizeof(*event) + event->len;
diff --git a/services/inputflinger/InputDispatcher.cpp b/services/inputflinger/InputDispatcher.cpp
index 885348e..6879a73 100644
--- a/services/inputflinger/InputDispatcher.cpp
+++ b/services/inputflinger/InputDispatcher.cpp
@@ -97,6 +97,9 @@
// Number of recent events to keep for debugging purposes.
constexpr size_t RECENT_QUEUE_MAX_SIZE = 10;
+// Sequence number for synthesized or injected events.
+constexpr uint32_t SYNTHESIZED_EVENT_SEQUENCE_NUM = 0;
+
static inline nsecs_t now() {
return systemTime(SYSTEM_TIME_MONOTONIC);
@@ -710,7 +713,7 @@
entry->policyFlags = policyFlags;
entry->repeatCount += 1;
} else {
- KeyEntry* newEntry = new KeyEntry(currentTime,
+ KeyEntry* newEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
entry->deviceId, entry->source, entry->displayId, policyFlags,
entry->action, entry->flags, entry->keyCode, entry->scanCode,
entry->metaState, entry->repeatCount + 1, entry->downTime);
@@ -1663,11 +1666,17 @@
void InputDispatcher::addWindowTargetLocked(const sp<InputWindowHandle>& windowHandle,
int32_t targetFlags, BitSet32 pointerIds, Vector<InputTarget>& inputTargets) {
+ sp<InputChannel> inputChannel = getInputChannelLocked(windowHandle->getToken());
+ if (inputChannel == nullptr) {
+ ALOGW("Window %s already unregistered input channel", windowHandle->getName().c_str());
+ return;
+ }
+
inputTargets.push();
const InputWindowInfo* windowInfo = windowHandle->getInfo();
InputTarget& target = inputTargets.editTop();
- target.inputChannel = getInputChannelLocked(windowHandle->getToken());
+ target.inputChannel = inputChannel;
target.flags = targetFlags;
target.xOffset = - windowInfo->frameLeft;
target.yOffset = - windowInfo->frameTop;
@@ -2468,6 +2477,7 @@
}
MotionEntry* splitMotionEntry = new MotionEntry(
+ originalMotionEntry->sequenceNum,
originalMotionEntry->eventTime,
originalMotionEntry->deviceId,
originalMotionEntry->source,
@@ -2501,7 +2511,8 @@
{ // acquire lock
AutoMutex _l(mLock);
- ConfigurationChangedEntry* newEntry = new ConfigurationChangedEntry(args->eventTime);
+ ConfigurationChangedEntry* newEntry =
+ new ConfigurationChangedEntry(args->sequenceNum, args->eventTime);
needWake = enqueueInboundEventLocked(newEntry);
} // release lock
@@ -2606,7 +2617,7 @@
mLock.lock();
}
- KeyEntry* newEntry = new KeyEntry(args->eventTime,
+ KeyEntry* newEntry = new KeyEntry(args->sequenceNum, args->eventTime,
args->deviceId, args->source, args->displayId, policyFlags,
args->action, flags, keyCode, args->scanCode,
metaState, repeatCount, args->downTime);
@@ -2690,7 +2701,7 @@
}
// Just enqueue a new motion event.
- MotionEntry* newEntry = new MotionEntry(args->eventTime,
+ MotionEntry* newEntry = new MotionEntry(args->sequenceNum, args->eventTime,
args->deviceId, args->source, args->displayId, policyFlags,
args->action, args->actionButton, args->flags,
args->metaState, args->buttonState,
@@ -2734,7 +2745,8 @@
{ // acquire lock
AutoMutex _l(mLock);
- DeviceResetEntry* newEntry = new DeviceResetEntry(args->eventTime, args->deviceId);
+ DeviceResetEntry* newEntry =
+ new DeviceResetEntry(args->sequenceNum, args->eventTime, args->deviceId);
needWake = enqueueInboundEventLocked(newEntry);
} // release lock
@@ -2793,7 +2805,7 @@
}
mLock.lock();
- firstInjectedEntry = new KeyEntry(keyEvent.getEventTime(),
+ firstInjectedEntry = new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, keyEvent.getEventTime(),
keyEvent.getDeviceId(), keyEvent.getSource(), keyEvent.getDisplayId(),
policyFlags, action, flags,
keyEvent.getKeyCode(), keyEvent.getScanCode(), keyEvent.getMetaState(),
@@ -2825,7 +2837,7 @@
mLock.lock();
const nsecs_t* sampleEventTimes = motionEvent->getSampleEventTimes();
const PointerCoords* samplePointerCoords = motionEvent->getSamplePointerCoords();
- firstInjectedEntry = new MotionEntry(*sampleEventTimes,
+ firstInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, *sampleEventTimes,
motionEvent->getDeviceId(), motionEvent->getSource(), motionEvent->getDisplayId(),
policyFlags,
action, actionButton, motionEvent->getFlags(),
@@ -2839,7 +2851,8 @@
for (size_t i = motionEvent->getHistorySize(); i > 0; i--) {
sampleEventTimes += 1;
samplePointerCoords += pointerCount;
- MotionEntry* nextInjectedEntry = new MotionEntry(*sampleEventTimes,
+ MotionEntry* nextInjectedEntry = new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM,
+ *sampleEventTimes,
motionEvent->getDeviceId(), motionEvent->getSource(),
motionEvent->getDisplayId(), policyFlags,
action, actionButton, motionEvent->getFlags(),
@@ -4273,9 +4286,10 @@
// --- InputDispatcher::EventEntry ---
-InputDispatcher::EventEntry::EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags) :
- refCount(1), type(type), eventTime(eventTime), policyFlags(policyFlags),
- injectionState(nullptr), dispatchInProgress(false) {
+InputDispatcher::EventEntry::EventEntry(uint32_t sequenceNum, int32_t type,
+ nsecs_t eventTime, uint32_t policyFlags) :
+ sequenceNum(sequenceNum), refCount(1), type(type), eventTime(eventTime),
+ policyFlags(policyFlags), injectionState(nullptr), dispatchInProgress(false) {
}
InputDispatcher::EventEntry::~EventEntry() {
@@ -4301,8 +4315,9 @@
// --- InputDispatcher::ConfigurationChangedEntry ---
-InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(nsecs_t eventTime) :
- EventEntry(TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
+InputDispatcher::ConfigurationChangedEntry::ConfigurationChangedEntry(
+ uint32_t sequenceNum, nsecs_t eventTime) :
+ EventEntry(sequenceNum, TYPE_CONFIGURATION_CHANGED, eventTime, 0) {
}
InputDispatcher::ConfigurationChangedEntry::~ConfigurationChangedEntry() {
@@ -4315,8 +4330,9 @@
// --- InputDispatcher::DeviceResetEntry ---
-InputDispatcher::DeviceResetEntry::DeviceResetEntry(nsecs_t eventTime, int32_t deviceId) :
- EventEntry(TYPE_DEVICE_RESET, eventTime, 0),
+InputDispatcher::DeviceResetEntry::DeviceResetEntry(
+ uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
+ EventEntry(sequenceNum, TYPE_DEVICE_RESET, eventTime, 0),
deviceId(deviceId) {
}
@@ -4331,11 +4347,11 @@
// --- InputDispatcher::KeyEntry ---
-InputDispatcher::KeyEntry::KeyEntry(nsecs_t eventTime,
+InputDispatcher::KeyEntry::KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
int32_t repeatCount, nsecs_t downTime) :
- EventEntry(TYPE_KEY, eventTime, policyFlags),
+ EventEntry(sequenceNum, TYPE_KEY, eventTime, policyFlags),
deviceId(deviceId), source(source), displayId(displayId), action(action), flags(flags),
keyCode(keyCode), scanCode(scanCode), metaState(metaState),
repeatCount(repeatCount), downTime(downTime),
@@ -4366,7 +4382,7 @@
// --- InputDispatcher::MotionEntry ---
-InputDispatcher::MotionEntry::MotionEntry(nsecs_t eventTime, int32_t deviceId,
+InputDispatcher::MotionEntry::MotionEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
uint32_t source, int32_t displayId, uint32_t policyFlags, int32_t action,
int32_t actionButton,
int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags,
@@ -4374,7 +4390,7 @@
uint32_t pointerCount,
const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
float xOffset, float yOffset) :
- EventEntry(TYPE_MOTION, eventTime, policyFlags),
+ EventEntry(sequenceNum, TYPE_MOTION, eventTime, policyFlags),
eventTime(eventTime),
deviceId(deviceId), source(source), displayId(displayId), action(action),
actionButton(actionButton), flags(flags), metaState(metaState), buttonState(buttonState),
@@ -4688,7 +4704,7 @@
for (size_t i = 0; i < mKeyMementos.size(); i++) {
const KeyMemento& memento = mKeyMementos.itemAt(i);
if (shouldCancelKey(memento, options)) {
- outEvents.push(new KeyEntry(currentTime,
+ outEvents.push(new KeyEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
AKEY_EVENT_ACTION_UP, memento.flags | AKEY_EVENT_FLAG_CANCELED,
memento.keyCode, memento.scanCode, memento.metaState, 0, memento.downTime));
@@ -4698,7 +4714,7 @@
for (size_t i = 0; i < mMotionMementos.size(); i++) {
const MotionMemento& memento = mMotionMementos.itemAt(i);
if (shouldCancelMotion(memento, options)) {
- outEvents.push(new MotionEntry(currentTime,
+ outEvents.push(new MotionEntry(SYNTHESIZED_EVENT_SEQUENCE_NUM, currentTime,
memento.deviceId, memento.source, memento.displayId, memento.policyFlags,
memento.hovering
? AMOTION_EVENT_ACTION_HOVER_EXIT
diff --git a/services/inputflinger/InputDispatcher.h b/services/inputflinger/InputDispatcher.h
index 73bcc25..05b5dad 100644
--- a/services/inputflinger/InputDispatcher.h
+++ b/services/inputflinger/InputDispatcher.h
@@ -454,6 +454,7 @@
TYPE_MOTION
};
+ uint32_t sequenceNum;
mutable int32_t refCount;
int32_t type;
nsecs_t eventTime;
@@ -469,13 +470,13 @@
virtual void appendDescription(std::string& msg) const = 0;
protected:
- EventEntry(int32_t type, nsecs_t eventTime, uint32_t policyFlags);
+ EventEntry(uint32_t sequenceNum, int32_t type, nsecs_t eventTime, uint32_t policyFlags);
virtual ~EventEntry();
void releaseInjectionState();
};
struct ConfigurationChangedEntry : EventEntry {
- explicit ConfigurationChangedEntry(nsecs_t eventTime);
+ explicit ConfigurationChangedEntry(uint32_t sequenceNum, nsecs_t eventTime);
virtual void appendDescription(std::string& msg) const;
protected:
@@ -485,7 +486,7 @@
struct DeviceResetEntry : EventEntry {
int32_t deviceId;
- DeviceResetEntry(nsecs_t eventTime, int32_t deviceId);
+ DeviceResetEntry(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId);
virtual void appendDescription(std::string& msg) const;
protected:
@@ -515,7 +516,7 @@
InterceptKeyResult interceptKeyResult; // set based on the interception result
nsecs_t interceptKeyWakeupTime; // used with INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER
- KeyEntry(nsecs_t eventTime,
+ KeyEntry(uint32_t sequenceNum, nsecs_t eventTime,
int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode, int32_t metaState,
int32_t repeatCount, nsecs_t downTime);
@@ -544,7 +545,7 @@
PointerProperties pointerProperties[MAX_POINTERS];
PointerCoords pointerCoords[MAX_POINTERS];
- MotionEntry(nsecs_t eventTime,
+ MotionEntry(uint32_t sequenceNum, nsecs_t eventTime,
int32_t deviceId, uint32_t source, int32_t displayId, uint32_t policyFlags,
int32_t action, int32_t actionButton, int32_t flags,
int32_t metaState, int32_t buttonState, int32_t edgeFlags,
diff --git a/services/inputflinger/InputListener.cpp b/services/inputflinger/InputListener.cpp
index 25a39a8..b4eb370 100644
--- a/services/inputflinger/InputListener.cpp
+++ b/services/inputflinger/InputListener.cpp
@@ -26,13 +26,14 @@
// --- NotifyConfigurationChangedArgs ---
-NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(nsecs_t eventTime) :
- eventTime(eventTime) {
+NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(
+ uint32_t sequenceNum, nsecs_t eventTime) :
+ NotifyArgs(sequenceNum), eventTime(eventTime) {
}
NotifyConfigurationChangedArgs::NotifyConfigurationChangedArgs(
const NotifyConfigurationChangedArgs& other) :
- eventTime(other.eventTime) {
+ NotifyArgs(other.sequenceNum), eventTime(other.eventTime) {
}
void NotifyConfigurationChangedArgs::notify(const sp<InputListenerInterface>& listener) const {
@@ -42,19 +43,19 @@
// --- NotifyKeyArgs ---
-NotifyKeyArgs::NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source,
- int32_t displayId, uint32_t policyFlags,
+NotifyKeyArgs::NotifyKeyArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
+ uint32_t source, int32_t displayId, uint32_t policyFlags,
int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode,
int32_t metaState, nsecs_t downTime) :
- eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId),
- policyFlags(policyFlags),
+ NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId), source(source),
+ displayId(displayId), policyFlags(policyFlags),
action(action), flags(flags), keyCode(keyCode), scanCode(scanCode),
metaState(metaState), downTime(downTime) {
}
NotifyKeyArgs::NotifyKeyArgs(const NotifyKeyArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId), source(other.source),
- displayId(other.displayId), policyFlags(other.policyFlags),
+ NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId),
+ source(other.source), displayId(other.displayId), policyFlags(other.policyFlags),
action(other.action), flags(other.flags),
keyCode(other.keyCode), scanCode(other.scanCode),
metaState(other.metaState), downTime(other.downTime) {
@@ -67,20 +68,22 @@
// --- NotifyMotionArgs ---
-NotifyMotionArgs::NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source,
- int32_t displayId, uint32_t policyFlags,
+NotifyMotionArgs::NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId,
+ uint32_t source, int32_t displayId, uint32_t policyFlags,
int32_t action, int32_t actionButton, int32_t flags, int32_t metaState,
int32_t buttonState, int32_t edgeFlags, uint32_t deviceTimestamp,
uint32_t pointerCount,
const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
- float xPrecision, float yPrecision, nsecs_t downTime) :
- eventTime(eventTime), deviceId(deviceId), source(source), displayId(displayId),
- policyFlags(policyFlags),
+ float xPrecision, float yPrecision, nsecs_t downTime,
+ const std::vector<TouchVideoFrame>& videoFrames) :
+ NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId), source(source),
+ displayId(displayId), policyFlags(policyFlags),
action(action), actionButton(actionButton),
flags(flags), metaState(metaState), buttonState(buttonState),
edgeFlags(edgeFlags), deviceTimestamp(deviceTimestamp),
pointerCount(pointerCount),
- xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime) {
+ xPrecision(xPrecision), yPrecision(yPrecision), downTime(downTime),
+ videoFrames(videoFrames) {
for (uint32_t i = 0; i < pointerCount; i++) {
this->pointerProperties[i].copyFrom(pointerProperties[i]);
this->pointerCoords[i].copyFrom(pointerCoords[i]);
@@ -88,13 +91,14 @@
}
NotifyMotionArgs::NotifyMotionArgs(const NotifyMotionArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId), source(other.source),
- displayId(other.displayId), policyFlags(other.policyFlags),
+ NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId),
+ source(other.source), displayId(other.displayId), policyFlags(other.policyFlags),
action(other.action), actionButton(other.actionButton), flags(other.flags),
metaState(other.metaState), buttonState(other.buttonState),
edgeFlags(other.edgeFlags),
deviceTimestamp(other.deviceTimestamp), pointerCount(other.pointerCount),
- xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime) {
+ xPrecision(other.xPrecision), yPrecision(other.yPrecision), downTime(other.downTime),
+ videoFrames(other.videoFrames) {
for (uint32_t i = 0; i < pointerCount; i++) {
pointerProperties[i].copyFrom(other.pointerProperties[i]);
pointerCoords[i].copyFrom(other.pointerCoords[i]);
@@ -108,14 +112,14 @@
// --- NotifySwitchArgs ---
-NotifySwitchArgs::NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags,
+NotifySwitchArgs::NotifySwitchArgs(uint32_t sequenceNum, nsecs_t eventTime, uint32_t policyFlags,
uint32_t switchValues, uint32_t switchMask) :
- eventTime(eventTime), policyFlags(policyFlags),
+ NotifyArgs(sequenceNum), eventTime(eventTime), policyFlags(policyFlags),
switchValues(switchValues), switchMask(switchMask) {
}
NotifySwitchArgs::NotifySwitchArgs(const NotifySwitchArgs& other) :
- eventTime(other.eventTime), policyFlags(other.policyFlags),
+ NotifyArgs(other.sequenceNum), eventTime(other.eventTime), policyFlags(other.policyFlags),
switchValues(other.switchValues), switchMask(other.switchMask) {
}
@@ -126,12 +130,13 @@
// --- NotifyDeviceResetArgs ---
-NotifyDeviceResetArgs::NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId) :
- eventTime(eventTime), deviceId(deviceId) {
+NotifyDeviceResetArgs::NotifyDeviceResetArgs(
+ uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId) :
+ NotifyArgs(sequenceNum), eventTime(eventTime), deviceId(deviceId) {
}
NotifyDeviceResetArgs::NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other) :
- eventTime(other.eventTime), deviceId(other.deviceId) {
+ NotifyArgs(other.sequenceNum), eventTime(other.eventTime), deviceId(other.deviceId) {
}
void NotifyDeviceResetArgs::notify(const sp<InputListenerInterface>& listener) const {
diff --git a/services/inputflinger/InputReader.cpp b/services/inputflinger/InputReader.cpp
index 9e748d8..73fcb11 100644
--- a/services/inputflinger/InputReader.cpp
+++ b/services/inputflinger/InputReader.cpp
@@ -236,8 +236,8 @@
|| (action == AKEY_EVENT_ACTION_UP
&& (lastButtonState & buttonState)
&& !(currentButtonState & buttonState))) {
- NotifyKeyArgs args(when, deviceId, source, displayId, policyFlags,
- action, 0, keyCode, 0, context->getGlobalMetaState(), when);
+ NotifyKeyArgs args(context->getNextSequenceNum(), when, deviceId, source, displayId,
+ policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when);
context->getListener()->notifyKey(&args);
}
}
@@ -254,14 +254,13 @@
}
-
// --- InputReader ---
InputReader::InputReader(const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener) :
mContext(this), mEventHub(eventHub), mPolicy(policy),
- mGlobalMetaState(0), mGeneration(1),
+ mNextSequenceNum(1), mGlobalMetaState(0), mGeneration(1),
mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX),
mConfigurationChangesToRefresh(0) {
mQueuedListener = new QueuedInputListener(listener);
@@ -547,7 +546,7 @@
updateGlobalMetaStateLocked();
// Enqueue configuration changed.
- NotifyConfigurationChangedArgs args(when);
+ NotifyConfigurationChangedArgs args(mContext.getNextSequenceNum(), when);
mQueuedListener->notifyConfigurationChanged(&args);
}
@@ -945,6 +944,9 @@
return mReader->mEventHub.get();
}
+uint32_t InputReader::ContextImpl::getNextSequenceNum() {
+ return (mReader->mNextSequenceNum)++;
+}
// --- InputDevice ---
@@ -1265,7 +1267,7 @@
}
void InputDevice::notifyReset(nsecs_t when) {
- NotifyDeviceResetArgs args(when, mId);
+ NotifyDeviceResetArgs args(mContext->getNextSequenceNum(), when, mId);
mContext->getListener()->notifyDeviceReset(&args);
}
@@ -2038,7 +2040,8 @@
void SwitchInputMapper::sync(nsecs_t when) {
if (mUpdatedSwitchMask) {
uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask;
- NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask);
+ NotifySwitchArgs args(mContext->getNextSequenceNum(), when, 0, updatedSwitchValues,
+ mUpdatedSwitchMask);
getListener()->notifySwitch(&args);
mUpdatedSwitchMask = 0;
@@ -2420,8 +2423,8 @@
policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT;
}
- NotifyKeyArgs args(when, getDeviceId(), mSource, getDisplayId(), policyFlags,
- down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
+ NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
+ getDisplayId(), policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,
AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime);
getListener()->notifyKey(&args);
}
@@ -2823,20 +2826,21 @@
while (!released.isEmpty()) {
int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit());
buttonState &= ~actionButton;
- NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, displayId, policyFlags,
+ NotifyMotionArgs releaseArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, displayId, policyFlags,
AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0,
metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
+ mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&releaseArgs);
}
}
- NotifyMotionArgs args(when, getDeviceId(), mSource, displayId, policyFlags,
- motionEventAction, 0, 0, metaState, currentButtonState,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), mSource,
+ displayId, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState,
AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
+ mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
if (buttonsPressed) {
@@ -2844,11 +2848,11 @@
while (!pressed.isEmpty()) {
int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit());
buttonState |= actionButton;
- NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, displayId, policyFlags,
- AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0,
- metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
+ NotifyMotionArgs pressArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS,
+ actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
+ mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&pressArgs);
}
}
@@ -2858,11 +2862,11 @@
// Send hover move after UP to tell the application that the mouse is hovering now.
if (motionEventAction == AMOTION_EVENT_ACTION_UP
&& (mSource == AINPUT_SOURCE_MOUSE)) {
- NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, displayId, policyFlags,
- AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
+ NotifyMotionArgs hoverArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, displayId, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
+ mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&hoverArgs);
}
@@ -2871,11 +2875,12 @@
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
- NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
+ NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, displayId, policyFlags,
AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState,
AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- mXPrecision, mYPrecision, downTime);
+ mXPrecision, mYPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&scrollArgs);
}
}
@@ -3002,11 +3007,12 @@
int32_t metaState = mContext->getGlobalMetaState();
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor);
- NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, displayId, policyFlags,
+ NotifyMotionArgs scrollArgs(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, displayId, policyFlags,
AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0,
AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- 0, 0, 0);
+ 0, 0, 0, /* videoFrames */ {});
getListener()->notifyMotion(&scrollArgs);
}
@@ -3439,7 +3445,17 @@
} else {
viewportTypeToUse = ViewportType::VIEWPORT_INTERNAL;
}
- return mConfig.getDisplayViewportByType(viewportTypeToUse);
+
+ std::optional<DisplayViewport> viewport =
+ mConfig.getDisplayViewportByType(viewportTypeToUse);
+ if (!viewport && viewportTypeToUse == ViewportType::VIEWPORT_EXTERNAL) {
+ ALOGW("Input device %s should be associated with external display, "
+ "fallback to internal one for the external viewport is not found.",
+ getDeviceName().c_str());
+ viewport = mConfig.getDisplayViewportByType(ViewportType::VIEWPORT_INTERNAL);
+ }
+
+ return viewport;
}
DisplayViewport newViewport;
@@ -4694,7 +4710,8 @@
int32_t metaState = mContext->getGlobalMetaState();
policyFlags |= POLICY_FLAG_VIRTUAL;
- NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, mViewport.displayId,
+ NotifyKeyArgs args(mContext->getNextSequenceNum(), when, getDeviceId(), AINPUT_SOURCE_KEYBOARD,
+ mViewport.displayId,
policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime);
getListener()->notifyKey(&args);
}
@@ -5387,11 +5404,12 @@
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y);
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0,
metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- 0, 0, mPointerGesture.downTime);
+ 0, 0, mPointerGesture.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6310,12 +6328,13 @@
mPointerSimple.down = false;
// Send up.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
- AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
- /* deviceTimestamp */ 0,
- 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
- mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
+ AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0,
+ /* deviceTimestamp */ 0,
+ 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
+ mOrientedXPrecision, mOrientedYPrecision,
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6323,12 +6342,13 @@
mPointerSimple.hovering = false;
// Send hover exit.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6338,22 +6358,24 @@
mPointerSimple.downTime = when;
// Send down.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
// Send move.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6362,24 +6384,26 @@
mPointerSimple.hovering = true;
// Send hover enter.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState,
mCurrentRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
// Send hover move.
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState,
mCurrentRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6395,12 +6419,13 @@
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll);
pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll);
- NotifyMotionArgs args(when, getDeviceId(), mSource, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ mSource, mViewport.displayId, policyFlags,
AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0,
/* deviceTimestamp */ 0,
1, &mPointerSimple.currentProperties, &pointerCoords,
mOrientedXPrecision, mOrientedYPrecision,
- mPointerSimple.downTime);
+ mPointerSimple.downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -6458,10 +6483,11 @@
}
}
- NotifyMotionArgs args(when, getDeviceId(), source, mViewport.displayId, policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ source, mViewport.displayId, policyFlags,
action, actionButton, flags, metaState, buttonState, edgeFlags,
deviceTimestamp, pointerCount, pointerProperties, pointerCoords,
- xPrecision, yPrecision, downTime);
+ xPrecision, yPrecision, downTime, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
@@ -7382,11 +7408,11 @@
// TODO: Use the input device configuration to control this behavior more finely.
uint32_t policyFlags = 0;
- NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE,
- policyFlags,
+ NotifyMotionArgs args(mContext->getNextSequenceNum(), when, getDeviceId(),
+ AINPUT_SOURCE_JOYSTICK, ADISPLAY_ID_NONE, policyFlags,
AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE,
/* deviceTimestamp */ 0, 1, &pointerProperties, &pointerCoords,
- 0, 0, 0);
+ 0, 0, 0, /* videoFrames */ {});
getListener()->notifyMotion(&args);
}
diff --git a/services/inputflinger/InputReader.h b/services/inputflinger/InputReader.h
index 13f1bed..35f3c23 100644
--- a/services/inputflinger/InputReader.h
+++ b/services/inputflinger/InputReader.h
@@ -96,6 +96,8 @@
virtual InputReaderPolicyInterface* getPolicy() = 0;
virtual InputListenerInterface* getListener() = 0;
virtual EventHubInterface* getEventHub() = 0;
+
+ virtual uint32_t getNextSequenceNum() = 0;
};
@@ -168,6 +170,7 @@
virtual InputReaderPolicyInterface* getPolicy();
virtual InputListenerInterface* getListener();
virtual EventHubInterface* getEventHub();
+ virtual uint32_t getNextSequenceNum();
} mContext;
friend class ContextImpl;
@@ -183,6 +186,9 @@
InputReaderConfiguration mConfig;
+ // used by InputReaderContext::getNextSequenceNum() as a counter for event sequence numbers
+ uint32_t mNextSequenceNum;
+
// The event queue.
static const int EVENT_BUFFER_SIZE = 256;
RawEvent mEventBuffer[EVENT_BUFFER_SIZE];
diff --git a/services/inputflinger/include/EventHub.h b/services/inputflinger/include/EventHub.h
index e2c7e82..1ddb978 100644
--- a/services/inputflinger/include/EventHub.h
+++ b/services/inputflinger/include/EventHub.h
@@ -391,6 +391,8 @@
bool isDeviceEnabled(int32_t deviceId);
status_t enableDevice(int32_t deviceId);
status_t disableDevice(int32_t deviceId);
+ status_t registerFdForEpoll(int fd);
+ status_t unregisterFdFromEpoll(int fd);
status_t registerDeviceForEpollLocked(Device* device);
status_t unregisterDeviceFromEpollLocked(Device* device);
@@ -450,6 +452,9 @@
int mWakeReadPipeFd;
int mWakeWritePipeFd;
+ int mInputWd;
+ int mVideoWd;
+
// Epoll FD list size hint.
static const int EPOLL_SIZE_HINT = 8;
diff --git a/services/inputflinger/include/InputListener.h b/services/inputflinger/include/InputListener.h
index a3d919b..2442cc0 100644
--- a/services/inputflinger/include/InputListener.h
+++ b/services/inputflinger/include/InputListener.h
@@ -17,7 +17,10 @@
#ifndef _UI_INPUT_LISTENER_H
#define _UI_INPUT_LISTENER_H
+#include <vector>
+
#include <input/Input.h>
+#include <input/TouchVideoFrame.h>
#include <utils/RefBase.h>
#include <utils/Vector.h>
@@ -28,6 +31,12 @@
/* Superclass of all input event argument objects */
struct NotifyArgs {
+ uint32_t sequenceNum;
+
+ inline NotifyArgs() : sequenceNum(0) { }
+
+ inline explicit NotifyArgs(uint32_t sequenceNum) : sequenceNum(sequenceNum) { }
+
virtual ~NotifyArgs() { }
virtual void notify(const sp<InputListenerInterface>& listener) const = 0;
@@ -40,7 +49,7 @@
inline NotifyConfigurationChangedArgs() { }
- explicit NotifyConfigurationChangedArgs(nsecs_t eventTime);
+ NotifyConfigurationChangedArgs(uint32_t sequenceNum, nsecs_t eventTime);
NotifyConfigurationChangedArgs(const NotifyConfigurationChangedArgs& other);
@@ -66,9 +75,9 @@
inline NotifyKeyArgs() { }
- NotifyKeyArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId,
- uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode, int32_t scanCode,
- int32_t metaState, nsecs_t downTime);
+ NotifyKeyArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source,
+ int32_t displayId, uint32_t policyFlags, int32_t action, int32_t flags, int32_t keyCode,
+ int32_t scanCode, int32_t metaState, nsecs_t downTime);
NotifyKeyArgs(const NotifyKeyArgs& other);
@@ -104,16 +113,18 @@
float xPrecision;
float yPrecision;
nsecs_t downTime;
+ std::vector<TouchVideoFrame> videoFrames;
inline NotifyMotionArgs() { }
- NotifyMotionArgs(nsecs_t eventTime, int32_t deviceId, uint32_t source, int32_t displayId,
- uint32_t policyFlags,
+ NotifyMotionArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId, uint32_t source,
+ int32_t displayId, uint32_t policyFlags,
int32_t action, int32_t actionButton, int32_t flags,
int32_t metaState, int32_t buttonState,
int32_t edgeFlags, uint32_t deviceTimestamp, uint32_t pointerCount,
const PointerProperties* pointerProperties, const PointerCoords* pointerCoords,
- float xPrecision, float yPrecision, nsecs_t downTime);
+ float xPrecision, float yPrecision, nsecs_t downTime,
+ const std::vector<TouchVideoFrame>& videoFrames);
NotifyMotionArgs(const NotifyMotionArgs& other);
@@ -132,7 +143,7 @@
inline NotifySwitchArgs() { }
- NotifySwitchArgs(nsecs_t eventTime, uint32_t policyFlags,
+ NotifySwitchArgs(uint32_t sequenceNum, nsecs_t eventTime, uint32_t policyFlags,
uint32_t switchValues, uint32_t switchMask);
NotifySwitchArgs(const NotifySwitchArgs& other);
@@ -151,7 +162,7 @@
inline NotifyDeviceResetArgs() { }
- NotifyDeviceResetArgs(nsecs_t eventTime, int32_t deviceId);
+ NotifyDeviceResetArgs(uint32_t sequenceNum, nsecs_t eventTime, int32_t deviceId);
NotifyDeviceResetArgs(const NotifyDeviceResetArgs& other);
diff --git a/services/inputflinger/tests/Android.bp b/services/inputflinger/tests/Android.bp
index 389a57c..5b275fb 100644
--- a/services/inputflinger/tests/Android.bp
+++ b/services/inputflinger/tests/Android.bp
@@ -2,7 +2,6 @@
cc_test {
name: "inputflinger_tests",
- cpp_std: "c++17",
srcs: [
"InputReader_test.cpp",
"InputDispatcher_test.cpp",
diff --git a/services/inputflinger/tests/InputReader_test.cpp b/services/inputflinger/tests/InputReader_test.cpp
index 04b87d5..b5d2090 100644
--- a/services/inputflinger/tests/InputReader_test.cpp
+++ b/services/inputflinger/tests/InputReader_test.cpp
@@ -841,13 +841,14 @@
int32_t mGlobalMetaState;
bool mUpdateGlobalMetaStateWasCalled;
int32_t mGeneration;
+ uint32_t mNextSequenceNum;
public:
FakeInputReaderContext(const sp<EventHubInterface>& eventHub,
const sp<InputReaderPolicyInterface>& policy,
const sp<InputListenerInterface>& listener) :
mEventHub(eventHub), mPolicy(policy), mListener(listener),
- mGlobalMetaState(0) {
+ mGlobalMetaState(0), mNextSequenceNum(1) {
}
virtual ~FakeInputReaderContext() { }
@@ -911,6 +912,10 @@
virtual void dispatchExternalStylusState(const StylusState&) {
}
+
+ virtual uint32_t getNextSequenceNum() {
+ return mNextSequenceNum++;
+ }
};
@@ -1556,6 +1561,39 @@
ASSERT_EQ(1, event.value);
}
+TEST_F(InputReaderTest, DeviceReset_IncrementsSequenceNumber) {
+ constexpr int32_t deviceId = 1;
+ constexpr uint32_t deviceClass = INPUT_DEVICE_CLASS_KEYBOARD;
+ InputDevice* device = mReader->newDevice(deviceId, 0, "fake", deviceClass);
+ // Must add at least one mapper or the device will be ignored!
+ FakeInputMapper* mapper = new FakeInputMapper(device, AINPUT_SOURCE_KEYBOARD);
+ device->addMapper(mapper);
+ mReader->setNextDevice(device);
+ addDevice(deviceId, "fake", deviceClass, nullptr);
+
+ NotifyDeviceResetArgs resetArgs;
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs));
+ uint32_t prevSequenceNum = resetArgs.sequenceNum;
+
+ disableDevice(deviceId, device);
+ mReader->loopOnce();
+ mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs);
+ ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum);
+ prevSequenceNum = resetArgs.sequenceNum;
+
+ enableDevice(deviceId, device);
+ mReader->loopOnce();
+ mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs);
+ ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum);
+ prevSequenceNum = resetArgs.sequenceNum;
+
+ disableDevice(deviceId, device);
+ mReader->loopOnce();
+ mFakeListener->assertNotifyDeviceResetWasCalled(&resetArgs);
+ ASSERT_TRUE(prevSequenceNum < resetArgs.sequenceNum);
+ prevSequenceNum = resetArgs.sequenceNum;
+}
+
// --- InputDeviceTest ---
@@ -6246,4 +6284,34 @@
ASSERT_EQ(DISPLAY_ID, args.displayId);
}
+/**
+ * Expect fallback to internal viewport if device is external and external viewport is not present.
+ */
+TEST_F(MultiTouchInputMapperTest, Viewports_Fallback) {
+ MultiTouchInputMapper* mapper = new MultiTouchInputMapper(mDevice);
+ prepareAxes(POSITION);
+ addConfigurationProperty("touch.deviceType", "touchScreen");
+ prepareDisplay(DISPLAY_ORIENTATION_0);
+ mDevice->setExternal(true);
+ addMapperAndConfigure(mapper);
+
+ ASSERT_EQ(AINPUT_SOURCE_TOUCHSCREEN, mapper->getSources());
+
+ NotifyMotionArgs motionArgs;
+
+ // Expect the event to be sent to the internal viewport,
+ // because an external viewport is not present.
+ processPosition(mapper, 100, 100);
+ processSync(mapper);
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
+ ASSERT_EQ(ADISPLAY_ID_DEFAULT, motionArgs.displayId);
+
+ // Expect the event to be sent to the external viewport if it is present.
+ prepareSecondaryDisplay(ViewportType::VIEWPORT_EXTERNAL);
+ processPosition(mapper, 100, 100);
+ processSync(mapper);
+ ASSERT_NO_FATAL_FAILURE(mFakeListener->assertNotifyMotionWasCalled(&motionArgs));
+ ASSERT_EQ(SECONDARY_DISPLAY_ID, motionArgs.displayId);
+}
+
} // namespace android
diff --git a/services/sensorservice/Android.bp b/services/sensorservice/Android.bp
index f87fcdc..33a2747 100644
--- a/services/sensorservice/Android.bp
+++ b/services/sensorservice/Android.bp
@@ -41,6 +41,7 @@
"liblog",
"libbinder",
"libsensor",
+ "libsensorprivacy",
"libcrypto",
"libbase",
"libhidlbase",
@@ -53,8 +54,8 @@
static_libs: ["android.hardware.sensors@1.0-convert"],
- // our public headers depend on libsensor
- export_shared_lib_headers: ["libsensor"],
+ // our public headers depend on libsensor and libsensorprivacy
+ export_shared_lib_headers: ["libsensor", "libsensorprivacy"],
}
cc_binary {
@@ -64,6 +65,7 @@
shared_libs: [
"libsensorservice",
+ "libsensorprivacy",
"libbinder",
"libutils",
],
diff --git a/services/sensorservice/SensorDevice.cpp b/services/sensorservice/SensorDevice.cpp
index f2336cb..9b2cd50 100644
--- a/services/sensorservice/SensorDevice.cpp
+++ b/services/sensorservice/SensorDevice.cpp
@@ -467,6 +467,10 @@
size_t eventsToRead = std::min({availableEvents, maxNumEventsToRead, mEventBuffer.size()});
if (eventsToRead > 0) {
if (mEventQueue->read(mEventBuffer.data(), eventsToRead)) {
+ // Notify the Sensors HAL that sensor events have been read. This is required to support
+ // the use of writeBlocking by the Sensors HAL.
+ mEventQueueFlag->wake(asBaseType(EventQueueFlagBits::EVENTS_READ));
+
for (size_t i = 0; i < eventsToRead; i++) {
convertToSensorEvent(mEventBuffer[i], &buffer[i]);
}
diff --git a/services/sensorservice/SensorEventConnection.cpp b/services/sensorservice/SensorEventConnection.cpp
index 8dc80cc..b66cbcf 100644
--- a/services/sensorservice/SensorEventConnection.cpp
+++ b/services/sensorservice/SensorEventConnection.cpp
@@ -32,8 +32,9 @@
const String16& opPackageName, bool hasSensorAccess)
: mService(service), mUid(uid), mWakeLockRefCount(0), mHasLooperCallbacks(false),
mDead(false), mDataInjectionMode(isDataInjectionMode), mEventCache(nullptr),
- mCacheSize(0), mMaxCacheSize(0), mPackageName(packageName), mOpPackageName(opPackageName),
- mDestroyed(false), mHasSensorAccess(hasSensorAccess) {
+ mCacheSize(0), mMaxCacheSize(0), mTimeOfLastEventDrop(0), mEventsDropped(0),
+ mPackageName(packageName), mOpPackageName(opPackageName), mDestroyed(false),
+ mHasSensorAccess(hasSensorAccess) {
mChannel = new BitTube(mService->mSocketBufferSize);
#if DEBUG_CONNECTIONS
mEventsReceived = mEventsSentFromCache = mEventsSent = 0;
@@ -278,7 +279,7 @@
}
} else {
// Regular sensor event, just copy it to the scratch buffer.
- if (mHasSensorAccess) {
+ if (hasSensorAccess()) {
scratch[count++] = buffer[i];
}
}
@@ -289,7 +290,7 @@
buffer[i].meta_data.sensor == sensor_handle)));
}
} else {
- if (mHasSensorAccess) {
+ if (hasSensorAccess()) {
scratch = const_cast<sensors_event_t *>(buffer);
count = numEvents;
} else {
@@ -320,7 +321,7 @@
}
int index_wake_up_event = -1;
- if (mHasSensorAccess) {
+ if (hasSensorAccess()) {
index_wake_up_event = findWakeUpSensorEventLocked(scratch, count);
if (index_wake_up_event >= 0) {
scratch[index_wake_up_event].flags |= WAKE_UP_SENSOR_EVENT_NEEDS_ACK;
@@ -374,6 +375,10 @@
mHasSensorAccess = hasAccess;
}
+bool SensorService::SensorEventConnection::hasSensorAccess() {
+ return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
+}
+
void SensorService::SensorEventConnection::reAllocateCacheLocked(sensors_event_t const* scratch,
int count) {
sensors_event_t *eventCache_new;
@@ -405,9 +410,6 @@
reAllocateCacheLocked(events, count);
} else {
// The events do not fit within the cache: drop the oldest events.
- ALOGW("Dropping events from cache (%d / %d) to save %d newer events", mCacheSize,
- mMaxCacheSize, count);
-
int freeSpace = mMaxCacheSize - mCacheSize;
// Drop up to the currently cached number of events to make room for new events
@@ -419,6 +421,18 @@
// Determine the number of new events to copy into the cache
int eventsToCopy = std::min(mMaxCacheSize, count);
+ constexpr nsecs_t kMinimumTimeBetweenDropLogNs = 2 * 1000 * 1000 * 1000; // 2 sec
+ if (events[0].timestamp - mTimeOfLastEventDrop > kMinimumTimeBetweenDropLogNs) {
+ ALOGW("Dropping %d cached events (%d/%d) to save %d/%d new events. %d events previously"
+ " dropped", cachedEventsToDrop, mCacheSize, mMaxCacheSize, eventsToCopy,
+ count, mEventsDropped);
+ mEventsDropped = 0;
+ mTimeOfLastEventDrop = events[0].timestamp;
+ } else {
+ // Record the number dropped
+ mEventsDropped += cachedEventsToDrop + newEventsToDrop;
+ }
+
// Check for any flush complete events in the events that will be dropped
countFlushCompleteEventsLocked(mEventCache, cachedEventsToDrop);
countFlushCompleteEventsLocked(events, newEventsToDrop);
@@ -481,7 +495,7 @@
for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
const int numEventsToWrite = helpers::min(mCacheSize - numEventsSent, maxWriteSize);
int index_wake_up_event = -1;
- if (mHasSensorAccess) {
+ if (hasSensorAccess()) {
index_wake_up_event =
findWakeUpSensorEventLocked(mEventCache + numEventsSent, numEventsToWrite);
if (index_wake_up_event >= 0) {
diff --git a/services/sensorservice/SensorEventConnection.h b/services/sensorservice/SensorEventConnection.h
index eefd81a..7077880 100644
--- a/services/sensorservice/SensorEventConnection.h
+++ b/services/sensorservice/SensorEventConnection.h
@@ -130,6 +130,10 @@
void updateLooperRegistration(const sp<Looper>& looper); void
updateLooperRegistrationLocked(const sp<Looper>& looper);
+ // Returns whether sensor access is available based on both the uid being active and sensor
+ // privacy not being enabled.
+ bool hasSensorAccess();
+
sp<SensorService> const mService;
sp<BitTube> mChannel;
uid_t mUid;
@@ -165,6 +169,8 @@
sensors_event_t *mEventCache;
int mCacheSize, mMaxCacheSize;
+ int64_t mTimeOfLastEventDrop;
+ int mEventsDropped;
String8 mPackageName;
const String16 mOpPackageName;
#if DEBUG_CONNECTIONS
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 85450f8..9a37ff1 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -29,6 +29,7 @@
#include <openssl/hmac.h>
#include <openssl/rand.h>
#include <sensor/SensorEventQueue.h>
+#include <sensorprivacy/SensorPrivacyManager.h>
#include <utils/SystemClock.h>
#include "BatteryService.h"
@@ -88,6 +89,7 @@
: mInitCheck(NO_INIT), mSocketBufferSize(SOCKET_BUFFER_SIZE_NON_BATCHED),
mWakeLockAcquired(false) {
mUidPolicy = new UidPolicy(this);
+ mSensorPrivacyPolicy = new SensorPrivacyPolicy(this);
}
bool SensorService::initializeHmacKey() {
@@ -286,6 +288,9 @@
// Start watching UID changes to apply policy.
mUidPolicy->registerSelf();
+
+ // Start watching sensor privacy changes
+ mSensorPrivacyPolicy->registerSelf();
}
}
}
@@ -338,6 +343,7 @@
delete entry.second;
}
mUidPolicy->unregisterSelf();
+ mSensorPrivacyPolicy->unregisterSelf();
}
status_t SensorService::dump(int fd, const Vector<String16>& args) {
@@ -364,35 +370,16 @@
}
mCurrentOperatingMode = RESTRICTED;
- // temporarily stop all sensor direct report
- for (auto &i : mDirectConnections) {
- sp<SensorDirectConnection> connection(i.promote());
- if (connection != nullptr) {
- connection->stopAll(true /* backupRecord */);
- }
- }
-
- dev.disableAllSensors();
- // Clear all pending flush connections for all active sensors. If one of the active
- // connections has called flush() and the underlying sensor has been disabled before a
- // flush complete event is returned, we need to remove the connection from this queue.
- for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
- mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
- }
+ // temporarily stop all sensor direct report and disable sensors
+ disableAllSensorsLocked();
mWhiteListedPackage.setTo(String8(args[1]));
return status_t(NO_ERROR);
} else if (args.size() == 1 && args[0] == String16("enable")) {
// If currently in restricted mode, reset back to NORMAL mode else ignore.
if (mCurrentOperatingMode == RESTRICTED) {
mCurrentOperatingMode = NORMAL;
- dev.enableAllSensors();
- // recover all sensor direct report
- for (auto &i : mDirectConnections) {
- sp<SensorDirectConnection> connection(i.promote());
- if (connection != nullptr) {
- connection->recoverAll();
- }
- }
+ // enable sensors and recover all sensor direct report
+ enableAllSensorsLocked();
}
if (mCurrentOperatingMode == DATA_INJECTION) {
resetToNormalModeLocked();
@@ -477,6 +464,8 @@
case DATA_INJECTION:
result.appendFormat(" DATA_INJECTION : %s\n", mWhiteListedPackage.string());
}
+ result.appendFormat("Sensor Privacy: %s\n",
+ mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
result.appendFormat("%zd active connections\n", mActiveConnections.size());
for (size_t i=0 ; i < mActiveConnections.size() ; i++) {
@@ -519,6 +508,52 @@
return NO_ERROR;
}
+void SensorService::disableAllSensors() {
+ Mutex::Autolock _l(mLock);
+ disableAllSensorsLocked();
+}
+
+void SensorService::disableAllSensorsLocked() {
+ SensorDevice& dev(SensorDevice::getInstance());
+ for (auto &i : mDirectConnections) {
+ sp<SensorDirectConnection> connection(i.promote());
+ if (connection != nullptr) {
+ connection->stopAll(true /* backupRecord */);
+ }
+ }
+ dev.disableAllSensors();
+ // Clear all pending flush connections for all active sensors. If one of the active
+ // connections has called flush() and the underlying sensor has been disabled before a
+ // flush complete event is returned, we need to remove the connection from this queue.
+ for (size_t i=0 ; i< mActiveSensors.size(); ++i) {
+ mActiveSensors.valueAt(i)->clearAllPendingFlushConnections();
+ }
+}
+
+void SensorService::enableAllSensors() {
+ Mutex::Autolock _l(mLock);
+ enableAllSensorsLocked();
+}
+
+void SensorService::enableAllSensorsLocked() {
+ // sensors should only be enabled if the operating state is not restricted and sensor
+ // privacy is not enabled.
+ if (mCurrentOperatingMode == RESTRICTED || mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
+ ALOGW("Sensors cannot be enabled: mCurrentOperatingMode = %d, sensor privacy = %s",
+ mCurrentOperatingMode,
+ mSensorPrivacyPolicy->isSensorPrivacyEnabled() ? "enabled" : "disabled");
+ return;
+ }
+ SensorDevice& dev(SensorDevice::getInstance());
+ dev.enableAllSensors();
+ for (auto &i : mDirectConnections) {
+ sp<SensorDirectConnection> connection(i.promote());
+ if (connection != nullptr) {
+ connection->recoverAll();
+ }
+ }
+}
+
// NOTE: This is a remote API - make sure all args are validated
status_t SensorService::shellCommand(int in, int out, int err, Vector<String16>& args) {
if (!checkCallingPermission(sManageSensorsPermission, nullptr, nullptr)) {
@@ -1076,6 +1111,12 @@
const native_handle *resource) {
Mutex::Autolock _l(mLock);
+ // No new direct connections are allowed when sensor privacy is enabled
+ if (mSensorPrivacyPolicy->isSensorPrivacyEnabled()) {
+ ALOGE("Cannot create new direct connections when sensor privacy is enabled");
+ return nullptr;
+ }
+
struct sensors_direct_mem_t mem = {
.type = type,
.format = format,
@@ -1753,4 +1794,31 @@
return mActiveUids.find(uid) != mActiveUids.end();
}
+void SensorService::SensorPrivacyPolicy::registerSelf() {
+ SensorPrivacyManager spm;
+ mSensorPrivacyEnabled = spm.isSensorPrivacyEnabled();
+ spm.addSensorPrivacyListener(this);
+}
+
+void SensorService::SensorPrivacyPolicy::unregisterSelf() {
+ SensorPrivacyManager spm;
+ spm.removeSensorPrivacyListener(this);
+}
+
+bool SensorService::SensorPrivacyPolicy::isSensorPrivacyEnabled() {
+ return mSensorPrivacyEnabled;
+}
+
+binder::Status SensorService::SensorPrivacyPolicy::onSensorPrivacyChanged(bool enabled) {
+ mSensorPrivacyEnabled = enabled;
+ sp<SensorService> service = mService.promote();
+ if (service != nullptr) {
+ if (enabled) {
+ service->disableAllSensors();
+ } else {
+ service->enableAllSensors();
+ }
+ }
+ return binder::Status::ok();
+}
}; // namespace android
diff --git a/services/sensorservice/SensorService.h b/services/sensorservice/SensorService.h
index 24b0dd7..136ee27 100644
--- a/services/sensorservice/SensorService.h
+++ b/services/sensorservice/SensorService.h
@@ -26,6 +26,7 @@
#include <sensor/ISensorServer.h>
#include <sensor/ISensorEventConnection.h>
#include <sensor/Sensor.h>
+#include "android/hardware/BnSensorPrivacyListener.h"
#include <utils/AndroidThreads.h>
#include <utils/KeyedVector.h>
@@ -132,6 +133,30 @@
std::unordered_map<uid_t, bool> mOverrideUids;
};
+ // Sensor privacy allows a user to disable access to all sensors on the device. When
+ // enabled sensor privacy will prevent all apps, including active apps, from accessing
+ // sensors, they will not receive trigger nor on-change events, flush event behavior
+ // does not change, and recurring events are the same as the first one delivered when
+ // sensor privacy was enabled. All sensor direct connections will be stopped as well
+ // and new direct connections will not be allowed while sensor privacy is enabled.
+ // Once sensor privacy is disabled access to sensors will be restored for active
+ // apps, previously stopped direct connections will be restarted, and new direct
+ // connections will be allowed again.
+ class SensorPrivacyPolicy : public hardware::BnSensorPrivacyListener {
+ public:
+ explicit SensorPrivacyPolicy(wp<SensorService> service) : mService(service) {}
+ void registerSelf();
+ void unregisterSelf();
+
+ bool isSensorPrivacyEnabled();
+
+ binder::Status onSensorPrivacyChanged(bool enabled);
+
+ private:
+ wp<SensorService> mService;
+ std::atomic_bool mSensorPrivacyEnabled;
+ };
+
enum Mode {
// The regular operating mode where any application can register/unregister/call flush on
// sensors.
@@ -275,6 +300,13 @@
// Prints the shell command help
status_t printHelp(int out);
+ // temporarily stops all active direct connections and disables all sensors
+ void disableAllSensors();
+ void disableAllSensorsLocked();
+ // restarts the previously stopped direct connections and enables all sensors
+ void enableAllSensors();
+ void enableAllSensorsLocked();
+
static uint8_t sHmacGlobalKey[128];
static bool sHmacGlobalKeyIsValid;
@@ -309,6 +341,7 @@
Vector<SensorRegistrationInfo> mLastNSensorRegistrations;
sp<UidPolicy> mUidPolicy;
+ sp<SensorPrivacyPolicy> mSensorPrivacyPolicy;
};
} // namespace android
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index 22e4d1e..0106b25 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -139,6 +139,7 @@
"Scheduler/DispSyncSource.cpp",
"Scheduler/EventControlThread.cpp",
"Scheduler/EventThread.cpp",
+ "Scheduler/IdleTimer.cpp",
"Scheduler/LayerHistory.cpp",
"Scheduler/MessageQueue.cpp",
"Scheduler/Scheduler.cpp",
diff --git a/services/surfaceflinger/BufferLayer.cpp b/services/surfaceflinger/BufferLayer.cpp
index 9b1c0db..0a3be71 100644
--- a/services/surfaceflinger/BufferLayer.cpp
+++ b/services/surfaceflinger/BufferLayer.cpp
@@ -396,6 +396,7 @@
}
// Capture the old state of the layer for comparisons later
+ Mutex::Autolock lock(mStateMutex);
const State& s(getDrawingState());
const bool oldOpacity = isOpaque(s);
sp<GraphicBuffer> oldBuffer = mActiveBuffer;
@@ -431,26 +432,25 @@
}
ui::Dataspace dataSpace = getDrawingDataSpace();
- // treat modern dataspaces as legacy dataspaces whenever possible, until
- // we can trust the buffer producers
+ // translate legacy dataspaces to modern dataspaces
switch (dataSpace) {
- case ui::Dataspace::V0_SRGB:
- dataSpace = ui::Dataspace::SRGB;
+ case ui::Dataspace::SRGB:
+ dataSpace = ui::Dataspace::V0_SRGB;
break;
- case ui::Dataspace::V0_SRGB_LINEAR:
- dataSpace = ui::Dataspace::SRGB_LINEAR;
+ case ui::Dataspace::SRGB_LINEAR:
+ dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
break;
- case ui::Dataspace::V0_JFIF:
- dataSpace = ui::Dataspace::JFIF;
+ case ui::Dataspace::JFIF:
+ dataSpace = ui::Dataspace::V0_JFIF;
break;
- case ui::Dataspace::V0_BT601_625:
- dataSpace = ui::Dataspace::BT601_625;
+ case ui::Dataspace::BT601_625:
+ dataSpace = ui::Dataspace::V0_BT601_625;
break;
- case ui::Dataspace::V0_BT601_525:
- dataSpace = ui::Dataspace::BT601_525;
+ case ui::Dataspace::BT601_525:
+ dataSpace = ui::Dataspace::V0_BT601_525;
break;
- case ui::Dataspace::V0_BT709:
- dataSpace = ui::Dataspace::BT709;
+ case ui::Dataspace::BT709:
+ dataSpace = ui::Dataspace::V0_BT709;
break;
default:
break;
@@ -503,7 +503,7 @@
// FIXME: postedRegion should be dirty & bounds
// transform the dirty region to window-manager space
- return getTransform().transform(Region(getBufferSize(s)));
+ return getTransformLocked().transform(Region(getBufferSize(s)));
}
// transaction
@@ -551,7 +551,7 @@
// h/w composer set-up
bool BufferLayer::allTransactionsSignaled() {
- auto headFrameNumber = getHeadFrameNumber();
+ auto headFrameNumber = getHeadFrameNumberLocked();
bool matchingFramesFound = false;
bool allTransactionsApplied = true;
Mutex::Autolock lock(mLocalSyncPointMutex);
@@ -604,6 +604,7 @@
void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
ATRACE_CALL();
+ Mutex::Autolock lock(mStateMutex);
const State& s(getDrawingState());
computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
@@ -622,9 +623,9 @@
* minimal value)? Or, we could make GL behave like HWC -- but this feel
* like more of a hack.
*/
- const Rect bounds{computeBounds()}; // Rounds from FloatRect
+ const Rect bounds{computeBoundsLocked()}; // Rounds from FloatRect
- ui::Transform t = getTransform();
+ ui::Transform t = getTransformLocked();
Rect win = bounds;
const int bufferWidth = getBufferSize(s).getWidth();
const int bufferHeight = getBufferSize(s).getHeight();
@@ -643,7 +644,7 @@
texCoords[2] = vec2(right, 1.0f - bottom);
texCoords[3] = vec2(right, 1.0f - top);
- const auto roundedCornerState = getRoundedCornerState();
+ const auto roundedCornerState = getRoundedCornerStateLocked();
const auto cropRect = roundedCornerState.cropRect;
setupRoundedCornersCropCoordinates(win, cropRect);
@@ -665,7 +666,12 @@
}
uint64_t BufferLayer::getHeadFrameNumber() const {
- if (hasFrameUpdate()) {
+ Mutex::Autolock lock(mStateMutex);
+ return getHeadFrameNumberLocked();
+}
+
+uint64_t BufferLayer::getHeadFrameNumberLocked() const {
+ if (hasFrameUpdateLocked()) {
return getFrameNumber();
} else {
return mCurrentFrameNumber;
@@ -692,7 +698,7 @@
std::swap(bufWidth, bufHeight);
}
- if (getTransformToDisplayInverse()) {
+ if (getTransformToDisplayInverseLocked()) {
uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
if (invTransform & ui::Transform::ROT_90) {
std::swap(bufWidth, bufHeight);
diff --git a/services/surfaceflinger/BufferLayer.h b/services/surfaceflinger/BufferLayer.h
index 690a4e5..98ae286 100644
--- a/services/surfaceflinger/BufferLayer.h
+++ b/services/surfaceflinger/BufferLayer.h
@@ -69,7 +69,11 @@
bool isOpaque(const Layer::State& s) const override;
// isVisible - true if this layer is visible, false otherwise
- bool isVisible() const override;
+ bool isVisible() const override EXCLUDES(mStateMutex);
+
+ // isProtected - true if the layer may contain protected content in the
+ // GRALLOC_USAGE_PROTECTED sense.
+ bool isProtected() const override;
// isFixedSize - true if content has a fixed size
bool isFixedSize() const override;
@@ -87,7 +91,7 @@
bool onPostComposition(const std::optional<DisplayId>& displayId,
const std::shared_ptr<FenceTime>& glDoneFence,
const std::shared_ptr<FenceTime>& presentFence,
- const CompositorTiming& compositorTiming) override;
+ const CompositorTiming& compositorTiming) override EXCLUDES(mStateMutex);
// latchBuffer - called each time the screen is redrawn and returns whether
// the visible regions need to be recomputed (this is a fairly heavy
@@ -97,13 +101,13 @@
// releaseFence will be populated with a native fence that fires when
// composition has completed.
Region latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,
- const sp<Fence>& releaseFence) override;
+ const sp<Fence>& releaseFence) override EXCLUDES(mStateMutex);
bool isBufferLatched() const override { return mRefreshPending; }
void notifyAvailableFrames() override;
- bool hasReadyFrame() const override;
+ bool hasReadyFrame() const override EXCLUDES(mStateMutex);
// Returns the current scaling mode, unless mOverrideScalingMode
// is set, in which case, it returns mOverrideScalingMode
@@ -114,19 +118,24 @@
// Functions that must be implemented by derived classes
// -----------------------------------------------------------------------
private:
- virtual bool fenceHasSignaled() const = 0;
+ virtual bool fenceHasSignaled() const EXCLUDES(mStateMutex) = 0;
virtual nsecs_t getDesiredPresentTime() = 0;
- virtual std::shared_ptr<FenceTime> getCurrentFenceTime() const = 0;
+ std::shared_ptr<FenceTime> getCurrentFenceTime() const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return getCurrentFenceTimeLocked();
+ }
+
+ virtual std::shared_ptr<FenceTime> getCurrentFenceTimeLocked() const REQUIRES(mStateMutex) = 0;
virtual void getDrawingTransformMatrix(float *matrix) = 0;
- virtual uint32_t getDrawingTransform() const = 0;
- virtual ui::Dataspace getDrawingDataSpace() const = 0;
- virtual Rect getDrawingCrop() const = 0;
+ virtual uint32_t getDrawingTransform() const REQUIRES(mStateMutex) = 0;
+ virtual ui::Dataspace getDrawingDataSpace() const REQUIRES(mStateMutex) = 0;
+ virtual Rect getDrawingCrop() const REQUIRES(mStateMutex) = 0;
virtual uint32_t getDrawingScalingMode() const = 0;
- virtual Region getDrawingSurfaceDamage() const = 0;
- virtual const HdrMetadata& getDrawingHdrMetadata() const = 0;
- virtual int getDrawingApi() const = 0;
+ virtual Region getDrawingSurfaceDamage() const EXCLUDES(mStateMutex) = 0;
+ virtual const HdrMetadata& getDrawingHdrMetadata() const EXCLUDES(mStateMutex) = 0;
+ virtual int getDrawingApi() const EXCLUDES(mStateMutex) = 0;
virtual PixelFormat getPixelFormat() const = 0;
virtual uint64_t getFrameNumber() const = 0;
@@ -134,27 +143,21 @@
virtual bool getAutoRefresh() const = 0;
virtual bool getSidebandStreamChanged() const = 0;
- virtual std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions) = 0;
+ virtual std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions)
+ EXCLUDES(mStateMutex) = 0;
- virtual bool hasFrameUpdate() const = 0;
+ virtual bool hasFrameUpdateLocked() const REQUIRES(mStateMutex) = 0;
virtual void setFilteringEnabled(bool enabled) = 0;
- virtual status_t bindTextureImage() = 0;
+ virtual status_t bindTextureImage() EXCLUDES(mStateMutex) = 0;
virtual status_t updateTexImage(bool& recomputeVisibleRegions, nsecs_t latchTime,
- const sp<Fence>& flushFence) = 0;
+ const sp<Fence>& flushFence) REQUIRES(mStateMutex) = 0;
- virtual status_t updateActiveBuffer() = 0;
+ virtual status_t updateActiveBuffer() REQUIRES(mStateMutex) = 0;
virtual status_t updateFrameNumber(nsecs_t latchTime) = 0;
- virtual void setHwcLayerBuffer(DisplayId displayId) = 0;
-
- // -----------------------------------------------------------------------
-
-public:
- // isProtected - true if the layer may contain protected content in the
- // GRALLOC_USAGE_PROTECTED sense.
- bool isProtected() const;
+ virtual void setHwcLayerBuffer(DisplayId displayId) EXCLUDES(mStateMutex) = 0;
protected:
// Loads the corresponding system property once per process
@@ -163,10 +166,15 @@
// Check all of the local sync points to ensure that all transactions
// which need to have been applied prior to the frame which is about to
// be latched have signaled
- bool allTransactionsSignaled();
+ bool allTransactionsSignaled() REQUIRES(mStateMutex);
static bool getOpacityForFormat(uint32_t format);
+ bool hasFrameUpdate() const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return hasFrameUpdateLocked();
+ }
+
// from GLES
const uint32_t mTextureName;
@@ -175,9 +183,12 @@
bool needsFiltering(const RenderArea& renderArea) const;
// drawing
- void drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const;
+ void drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const
+ EXCLUDES(mStateMutex);
- uint64_t getHeadFrameNumber() const;
+ uint64_t getHeadFrameNumber() const EXCLUDES(mStateMutex);
+
+ uint64_t getHeadFrameNumberLocked() const REQUIRES(mStateMutex);
uint32_t mCurrentScalingMode{NATIVE_WINDOW_SCALING_MODE_FREEZE};
@@ -189,7 +200,7 @@
bool mRefreshPending{false};
- Rect getBufferSize(const State& s) const override;
+ Rect getBufferSize(const State& s) const override REQUIRES(mStateMutex);
};
} // namespace android
diff --git a/services/surfaceflinger/BufferQueueLayer.cpp b/services/surfaceflinger/BufferQueueLayer.cpp
index b784d11..3341b98 100644
--- a/services/surfaceflinger/BufferQueueLayer.cpp
+++ b/services/surfaceflinger/BufferQueueLayer.cpp
@@ -51,7 +51,7 @@
return history;
}
-bool BufferQueueLayer::getTransformToDisplayInverse() const {
+bool BufferQueueLayer::getTransformToDisplayInverseLocked() const {
return mConsumer->getTransformToDisplayInverse();
}
@@ -131,7 +131,7 @@
return mConsumer->getTimestamp();
}
-std::shared_ptr<FenceTime> BufferQueueLayer::getCurrentFenceTime() const {
+std::shared_ptr<FenceTime> BufferQueueLayer::getCurrentFenceTimeLocked() const {
return mConsumer->getCurrentFenceTime();
}
@@ -192,6 +192,7 @@
std::optional<Region> BufferQueueLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
bool sidebandStreamChanged = true;
+ Mutex::Autolock lock(mStateMutex);
if (mSidebandStreamChanged.compare_exchange_strong(sidebandStreamChanged, false)) {
// mSidebandStreamChanged was changed to false
// replicated in LayerBE until FE/BE is ready to be synchronized
@@ -200,15 +201,15 @@
setTransactionFlags(eTransactionNeeded);
mFlinger->setTransactionFlags(eTraversalNeeded);
}
- recomputeVisibleRegions = true;
+ recomputeVisibleRegions = true;
const State& s(getDrawingState());
- return getTransform().transform(Region(Rect(s.active_legacy.w, s.active_legacy.h)));
+ return getTransformLocked().transform(Region(Rect(s.active_legacy.w, s.active_legacy.h)));
}
return {};
}
-bool BufferQueueLayer::hasFrameUpdate() const {
+bool BufferQueueLayer::hasFrameUpdateLocked() const {
return mQueuedFrames > 0;
}
@@ -228,16 +229,18 @@
// buffer mode.
bool queuedBuffer = false;
const int32_t layerID = getSequence();
- LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
+ status_t updateResult;
+ LayerRejecter r(mState.drawing, getCurrentState(), recomputeVisibleRegions,
getProducerStickyTransform() != 0, mName.string(), mOverrideScalingMode,
- getTransformToDisplayInverse(), mFreezeGeometryUpdates);
+ getTransformToDisplayInverseLocked(), mFreezeGeometryUpdates);
const nsecs_t expectedPresentTime = mFlinger->mUseScheduler
? mFlinger->mScheduler->mPrimaryDispSync->expectedPresentTime()
: mFlinger->mPrimaryDispSync->expectedPresentTime();
- status_t updateResult =
- mConsumer->updateTexImage(&r, expectedPresentTime, &mAutoRefresh, &queuedBuffer,
- mLastFrameNumberReceived, releaseFence);
+
+ updateResult = mConsumer->updateTexImage(&r, expectedPresentTime, &mAutoRefresh, &queuedBuffer,
+ mLastFrameNumberReceived, releaseFence);
+
if (updateResult == BufferQueue::PRESENT_LATER) {
// Producer doesn't want buffer to be displayed yet. Signal a
// layer update so we check again at the next opportunity.
@@ -451,7 +454,8 @@
mConsumer->setContentsChangedListener(this);
mConsumer->setName(mName);
- if (mFlinger->isLayerTripleBufferingDisabled()) {
+ // BufferQueueCore::mMaxDequeuedBufferCount is default to 1
+ if (!mFlinger->isLayerTripleBufferingDisabled()) {
mProducer->setMaxDequeuedBufferCount(2);
}
diff --git a/services/surfaceflinger/BufferQueueLayer.h b/services/surfaceflinger/BufferQueueLayer.h
index ae0b705..f9da044 100644
--- a/services/surfaceflinger/BufferQueueLayer.h
+++ b/services/surfaceflinger/BufferQueueLayer.h
@@ -44,7 +44,7 @@
std::vector<OccupancyTracker::Segment> getOccupancyHistory(bool forceFlush) override;
- bool getTransformToDisplayInverse() const override;
+ bool getTransformToDisplayInverseLocked() const override REQUIRES(mStateMutex);
// If a buffer was replaced this frame, release the former buffer
void releasePendingBuffer(nsecs_t dequeueReadyTime) override;
@@ -64,12 +64,12 @@
private:
nsecs_t getDesiredPresentTime() override;
- std::shared_ptr<FenceTime> getCurrentFenceTime() const override;
+ std::shared_ptr<FenceTime> getCurrentFenceTimeLocked() const override REQUIRES(mStateMutex);
void getDrawingTransformMatrix(float *matrix) override;
- uint32_t getDrawingTransform() const override;
- ui::Dataspace getDrawingDataSpace() const override;
- Rect getDrawingCrop() const override;
+ uint32_t getDrawingTransform() const override REQUIRES(mStateMutex);
+ ui::Dataspace getDrawingDataSpace() const override REQUIRES(mStateMutex);
+ Rect getDrawingCrop() const override REQUIRES(mStateMutex);
uint32_t getDrawingScalingMode() const override;
Region getDrawingSurfaceDamage() const override;
const HdrMetadata& getDrawingHdrMetadata() const override;
@@ -81,17 +81,18 @@
bool getAutoRefresh() const override;
bool getSidebandStreamChanged() const override;
- std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions) override;
+ std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions) override
+ EXCLUDES(mStateMutex);
- bool hasFrameUpdate() const override;
+ bool hasFrameUpdateLocked() const override REQUIRES(mStateMutex);
void setFilteringEnabled(bool enabled) override;
status_t bindTextureImage() override;
status_t updateTexImage(bool& recomputeVisibleRegions, nsecs_t latchTime,
- const sp<Fence>& releaseFence) override;
+ const sp<Fence>& releaseFence) override REQUIRES(mStateMutex);
- status_t updateActiveBuffer() override;
+ status_t updateActiveBuffer() override REQUIRES(mStateMutex);
status_t updateFrameNumber(nsecs_t latchTime) override;
void setHwcLayerBuffer(DisplayId displayId) override;
diff --git a/services/surfaceflinger/BufferStateLayer.cpp b/services/surfaceflinger/BufferStateLayer.cpp
index 1f71a44..8091b94 100644
--- a/services/surfaceflinger/BufferStateLayer.cpp
+++ b/services/surfaceflinger/BufferStateLayer.cpp
@@ -70,128 +70,163 @@
}
bool BufferStateLayer::willPresentCurrentTransaction() const {
+ Mutex::Autolock lock(mStateMutex);
// Returns true if the most recent Transaction applied to CurrentState will be presented.
return getSidebandStreamChanged() || getAutoRefresh() ||
- (mCurrentState.modified && mCurrentState.buffer != nullptr);
+ (mState.current.modified && mState.current.buffer != nullptr);
}
-bool BufferStateLayer::getTransformToDisplayInverse() const {
- return mCurrentState.transformToDisplayInverse;
+bool BufferStateLayer::getTransformToDisplayInverseLocked() const {
+ return mState.current.transformToDisplayInverse;
}
-void BufferStateLayer::pushPendingState() {
- if (!mCurrentState.modified) {
+void BufferStateLayer::pushPendingStateLocked() {
+ if (!mState.current.modified) {
return;
}
- mPendingStates.push_back(mCurrentState);
- ATRACE_INT(mTransactionName.string(), mPendingStates.size());
+ mState.pending.push_back(mState.current);
+ ATRACE_INT(mTransactionName.string(), mState.pending.size());
}
bool BufferStateLayer::applyPendingStates(Layer::State* stateToCommit) {
- const bool stateUpdateAvailable = !mPendingStates.empty();
- while (!mPendingStates.empty()) {
+ const bool stateUpdateAvailable = !mState.pending.empty();
+ while (!mState.pending.empty()) {
popPendingState(stateToCommit);
}
- mCurrentStateModified = stateUpdateAvailable && mCurrentState.modified;
- mCurrentState.modified = false;
+ mCurrentStateModified = stateUpdateAvailable && mState.current.modified;
+ mState.current.modified = false;
return stateUpdateAvailable;
}
-Rect BufferStateLayer::getCrop(const Layer::State& s) const {
- return (getEffectiveScalingMode() == NATIVE_WINDOW_SCALING_MODE_SCALE_CROP)
- ? GLConsumer::scaleDownCrop(s.crop, s.active.w, s.active.h)
- : s.crop;
+// Crop that applies to the window
+Rect BufferStateLayer::getCrop(const Layer::State& /*s*/) const {
+ return Rect::INVALID_RECT;
}
bool BufferStateLayer::setTransform(uint32_t transform) {
- if (mCurrentState.transform == transform) return false;
- mCurrentState.sequence++;
- mCurrentState.transform = transform;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.transform == transform) return false;
+ mState.current.sequence++;
+ mState.current.transform = transform;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setTransformToDisplayInverse(bool transformToDisplayInverse) {
- if (mCurrentState.transformToDisplayInverse == transformToDisplayInverse) return false;
- mCurrentState.sequence++;
- mCurrentState.transformToDisplayInverse = transformToDisplayInverse;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.transformToDisplayInverse == transformToDisplayInverse) return false;
+ mState.current.sequence++;
+ mState.current.transformToDisplayInverse = transformToDisplayInverse;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setCrop(const Rect& crop) {
- if (mCurrentState.crop == crop) return false;
- mCurrentState.sequence++;
- mCurrentState.crop = crop;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.crop == crop) return false;
+ mState.current.sequence++;
+ mState.current.crop = crop;
+ mState.current.modified = true;
+ setTransactionFlags(eTransactionNeeded);
+ return true;
+}
+
+bool BufferStateLayer::setFrame(const Rect& frame) {
+ int x = frame.left;
+ int y = frame.top;
+ int w = frame.getWidth();
+ int h = frame.getHeight();
+
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.active.transform.tx() == x && mState.current.active.transform.ty() == y &&
+ mState.current.active.w == w && mState.current.active.h == h) {
+ return false;
+ }
+
+ if (!frame.isValid()) {
+ x = y = w = h = 0;
+ }
+ mState.current.active.transform.set(x, y);
+ mState.current.active.w = w;
+ mState.current.active.h = h;
+
+ mState.current.sequence++;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setBuffer(const sp<GraphicBuffer>& buffer) {
- if (mCurrentState.buffer) {
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.buffer) {
mReleasePreviousBuffer = true;
}
- mCurrentState.sequence++;
- mCurrentState.buffer = buffer;
- mCurrentState.modified = true;
+ mState.current.sequence++;
+ mState.current.buffer = buffer;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setAcquireFence(const sp<Fence>& fence) {
+ Mutex::Autolock lock(mStateMutex);
// The acquire fences of BufferStateLayers have already signaled before they are set
mCallbackHandleAcquireTime = fence->getSignalTime();
- mCurrentState.acquireFence = fence;
- mCurrentState.modified = true;
+ mState.current.acquireFence = fence;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setDataspace(ui::Dataspace dataspace) {
- if (mCurrentState.dataspace == dataspace) return false;
- mCurrentState.sequence++;
- mCurrentState.dataspace = dataspace;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.dataspace == dataspace) return false;
+ mState.current.sequence++;
+ mState.current.dataspace = dataspace;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setHdrMetadata(const HdrMetadata& hdrMetadata) {
- if (mCurrentState.hdrMetadata == hdrMetadata) return false;
- mCurrentState.sequence++;
- mCurrentState.hdrMetadata = hdrMetadata;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.hdrMetadata == hdrMetadata) return false;
+ mState.current.sequence++;
+ mState.current.hdrMetadata = hdrMetadata;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setSurfaceDamageRegion(const Region& surfaceDamage) {
- mCurrentState.sequence++;
- mCurrentState.surfaceDamageRegion = surfaceDamage;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.sequence++;
+ mState.current.surfaceDamageRegion = surfaceDamage;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setApi(int32_t api) {
- if (mCurrentState.api == api) return false;
- mCurrentState.sequence++;
- mCurrentState.api = api;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.api == api) return false;
+ mState.current.sequence++;
+ mState.current.api = api;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool BufferStateLayer::setSidebandStream(const sp<NativeHandle>& sidebandStream) {
- if (mCurrentState.sidebandStream == sidebandStream) return false;
- mCurrentState.sequence++;
- mCurrentState.sidebandStream = sidebandStream;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.sidebandStream == sidebandStream) return false;
+ mState.current.sequence++;
+ mState.current.sidebandStream = sidebandStream;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
if (!mSidebandStreamChanged.exchange(true)) {
@@ -225,7 +260,10 @@
mFlinger->getTransactionCompletedThread().registerPendingLatchedCallbackHandle(handle);
// Store so latched time and release fence can be set
- mCurrentState.callbackHandles.push_back(handle);
+ {
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.callbackHandles.push_back(handle);
+ }
} else { // If this layer will NOT need to be relatched and presented this frame
// Notify the transaction completed thread this handle is done
@@ -239,49 +277,34 @@
return willPresent;
}
-bool BufferStateLayer::setSize(uint32_t w, uint32_t h) {
- if (mCurrentState.active.w == w && mCurrentState.active.h == h) return false;
- mCurrentState.active.w = w;
- mCurrentState.active.h = h;
- mCurrentState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
-bool BufferStateLayer::setPosition(float x, float y, bool /*immediate*/) {
- if (mCurrentState.active.transform.tx() == x && mCurrentState.active.transform.ty() == y)
- return false;
-
- mCurrentState.active.transform.set(x, y);
-
- mCurrentState.sequence++;
- mCurrentState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
-}
-
bool BufferStateLayer::setTransparentRegionHint(const Region& transparent) {
- mCurrentState.transparentRegionHint = transparent;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.transparentRegionHint = transparent;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
-bool BufferStateLayer::setMatrix(const layer_state_t::matrix22_t& matrix,
- bool allowNonRectPreservingTransforms) {
- ui::Transform t;
- t.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
-
- if (!allowNonRectPreservingTransforms && !t.preserveRects()) {
- ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
- return false;
+Rect BufferStateLayer::getBufferSize(const State& s) const {
+ // for buffer state layers we use the display frame size as the buffer size.
+ if (getActiveWidth(s) < UINT32_MAX && getActiveHeight(s) < UINT32_MAX) {
+ return Rect(getActiveWidth(s), getActiveHeight(s));
}
- mCurrentState.sequence++;
- mCurrentState.active.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
- mCurrentState.modified = true;
- setTransactionFlags(eTransactionNeeded);
- return true;
+ // if the display frame is not defined, use the parent bounds as the buffer size.
+ const auto& p = mDrawingParent.promote();
+ if (p != nullptr) {
+ Rect parentBounds = Rect(p->computeBounds(Region()));
+ if (!parentBounds.isEmpty()) {
+ return parentBounds;
+ }
+ }
+
+ // if there is no parent layer, use the buffer's bounds as the buffer size
+ if (s.buffer) {
+ return s.buffer->getBounds();
+ }
+ return Rect::INVALID_RECT;
}
// -----------------------------------------------------------------------
@@ -293,6 +316,7 @@
return true;
}
+ Mutex::Autolock lock(mStateMutex);
return getDrawingState().acquireFence->getStatus() == Fence::Status::Signaled;
}
@@ -301,7 +325,7 @@
return 0;
}
-std::shared_ptr<FenceTime> BufferStateLayer::getCurrentFenceTime() const {
+std::shared_ptr<FenceTime> BufferStateLayer::getCurrentFenceTimeLocked() const {
return std::make_shared<FenceTime>(getDrawingState().acquireFence);
}
@@ -317,8 +341,14 @@
return getDrawingState().dataspace;
}
+// Crop that applies to the buffer
Rect BufferStateLayer::getDrawingCrop() const {
- return Rect::INVALID_RECT;
+ const State& s(getDrawingState());
+
+ if (s.crop.isEmpty() && s.buffer) {
+ return s.buffer->getBounds();
+ }
+ return s.crop;
}
uint32_t BufferStateLayer::getDrawingScalingMode() const {
@@ -326,14 +356,17 @@
}
Region BufferStateLayer::getDrawingSurfaceDamage() const {
+ Mutex::Autolock lock(mStateMutex);
return getDrawingState().surfaceDamageRegion;
}
const HdrMetadata& BufferStateLayer::getDrawingHdrMetadata() const {
+ Mutex::Autolock lock(mStateMutex);
return getDrawingState().hdrMetadata;
}
int BufferStateLayer::getDrawingApi() const {
+ Mutex::Autolock lock(mStateMutex);
return getDrawingState().api;
}
@@ -358,6 +391,7 @@
}
std::optional<Region> BufferStateLayer::latchSidebandStream(bool& recomputeVisibleRegions) {
+ Mutex::Autolock lock(mStateMutex);
if (mSidebandStreamChanged.exchange(false)) {
const State& s(getDrawingState());
// mSidebandStreamChanged was true
@@ -369,12 +403,12 @@
}
recomputeVisibleRegions = true;
- return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
+ return getTransformLocked().transform(Region(Rect(s.active.w, s.active.h)));
}
return {};
}
-bool BufferStateLayer::hasFrameUpdate() const {
+bool BufferStateLayer::hasFrameUpdateLocked() const {
return mCurrentStateModified && getCurrentState().buffer != nullptr;
}
@@ -384,6 +418,10 @@
}
status_t BufferStateLayer::bindTextureImage() {
+ Mutex::Autolock lock(mStateMutex);
+ return bindTextureImageLocked();
+}
+status_t BufferStateLayer::bindTextureImageLocked() {
const State& s(getDrawingState());
auto& engine(mFlinger->getRenderEngine());
@@ -488,7 +526,7 @@
auto incomingStatus = releaseFence->getStatus();
if (incomingStatus == Fence::Status::Invalid) {
ALOGE("New fence has invalid state");
- mDrawingState.acquireFence = releaseFence;
+ mState.drawing.acquireFence = releaseFence;
mFlinger->mTimeStats->onDestroy(layerID);
return BAD_VALUE;
}
@@ -499,16 +537,16 @@
char fenceName[32] = {};
snprintf(fenceName, 32, "%.28s:%d", mName.string(), mFrameNumber);
sp<Fence> mergedFence =
- Fence::merge(fenceName, mDrawingState.acquireFence, releaseFence);
+ Fence::merge(fenceName, mState.drawing.acquireFence, releaseFence);
if (!mergedFence.get()) {
ALOGE("failed to merge release fences");
// synchronization is broken, the best we can do is hope fences
// signal in order so the new fence will act like a union
- mDrawingState.acquireFence = releaseFence;
+ mState.drawing.acquireFence = releaseFence;
mFlinger->mTimeStats->onDestroy(layerID);
return BAD_VALUE;
}
- mDrawingState.acquireFence = mergedFence;
+ mState.drawing.acquireFence = mergedFence;
} else if (incomingStatus == Fence::Status::Unsignaled) {
// If one fence has signaled and the other hasn't, the unsignaled
// fence will approximately correspond with the correct timestamp.
@@ -517,7 +555,7 @@
// by this point, they will have both signaled and only the timestamp
// will be slightly off; any dependencies after this point will
// already have been met.
- mDrawingState.acquireFence = releaseFence;
+ mState.drawing.acquireFence = releaseFence;
}
} else {
// Bind the new buffer to the GL texture.
@@ -526,7 +564,7 @@
// by glEGLImageTargetTexture2DOES, which this method calls. Newer
// devices will either call this in Layer::onDraw, or (if it's not
// a GL-composited layer) not at all.
- status_t err = bindTextureImage();
+ status_t err = bindTextureImageLocked();
if (err != NO_ERROR) {
mFlinger->mTimeStats->onDestroy(layerID);
return BAD_VALUE;
@@ -535,7 +573,7 @@
// TODO(marissaw): properly support mTimeStats
mFlinger->mTimeStats->setPostTime(layerID, getFrameNumber(), getName().c_str(), latchTime);
- mFlinger->mTimeStats->setAcquireFence(layerID, getFrameNumber(), getCurrentFenceTime());
+ mFlinger->mTimeStats->setAcquireFence(layerID, getFrameNumber(), getCurrentFenceTimeLocked());
mFlinger->mTimeStats->setLatchTime(layerID, getFrameNumber(), latchTime);
return NO_ERROR;
@@ -562,6 +600,7 @@
}
void BufferStateLayer::setHwcLayerBuffer(DisplayId displayId) {
+ Mutex::Autolock lock(mStateMutex);
auto& hwcInfo = getBE().mHwcLayers[displayId];
auto& hwcLayer = hwcInfo.layer;
diff --git a/services/surfaceflinger/BufferStateLayer.h b/services/surfaceflinger/BufferStateLayer.h
index 315d5af..655353c 100644
--- a/services/surfaceflinger/BufferStateLayer.h
+++ b/services/surfaceflinger/BufferStateLayer.h
@@ -41,13 +41,14 @@
bool shouldPresentNow(nsecs_t expectedPresentTime) const override;
- bool getTransformToDisplayInverse() const override;
+ bool getTransformToDisplayInverseLocked() const override REQUIRES(mStateMutex);
uint32_t doTransactionResize(uint32_t flags, Layer::State* /*stateToCommit*/) override {
return flags;
}
- void pushPendingState() override;
- bool applyPendingStates(Layer::State* stateToCommit) override;
+
+ void pushPendingStateLocked() override REQUIRES(mStateMutex);
+ bool applyPendingStates(Layer::State* stateToCommit) override REQUIRES(mStateMutex);
uint32_t getActiveWidth(const Layer::State& s) const override { return s.active.w; }
uint32_t getActiveHeight(const Layer::State& s) const override { return s.active.h; }
@@ -59,49 +60,56 @@
}
Rect getCrop(const Layer::State& s) const;
- bool setTransform(uint32_t transform) override;
- bool setTransformToDisplayInverse(bool transformToDisplayInverse) override;
- bool setCrop(const Rect& crop) override;
- bool setBuffer(const sp<GraphicBuffer>& buffer) override;
- bool setAcquireFence(const sp<Fence>& fence) override;
- bool setDataspace(ui::Dataspace dataspace) override;
- bool setHdrMetadata(const HdrMetadata& hdrMetadata) override;
- bool setSurfaceDamageRegion(const Region& surfaceDamage) override;
- bool setApi(int32_t api) override;
- bool setSidebandStream(const sp<NativeHandle>& sidebandStream) override;
- bool setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) override;
-
- bool setSize(uint32_t w, uint32_t h) override;
- bool setPosition(float x, float y, bool immediate) override;
- bool setTransparentRegionHint(const Region& transparent) override;
- bool setMatrix(const layer_state_t::matrix22_t& matrix,
- bool allowNonRectPreservingTransforms) override;
+ bool setTransform(uint32_t transform) override EXCLUDES(mStateMutex);
+ bool setTransformToDisplayInverse(bool transformToDisplayInverse) override
+ EXCLUDES(mStateMutex);
+ bool setCrop(const Rect& crop) override EXCLUDES(mStateMutex);
+ bool setFrame(const Rect& frame) override EXCLUDES(mStateMutex);
+ bool setBuffer(const sp<GraphicBuffer>& buffer) override EXCLUDES(mStateMutex);
+ bool setAcquireFence(const sp<Fence>& fence) override EXCLUDES(mStateMutex);
+ bool setDataspace(ui::Dataspace dataspace) override EXCLUDES(mStateMutex);
+ bool setHdrMetadata(const HdrMetadata& hdrMetadata) override EXCLUDES(mStateMutex);
+ bool setSurfaceDamageRegion(const Region& surfaceDamage) override EXCLUDES(mStateMutex);
+ bool setApi(int32_t api) override EXCLUDES(mStateMutex);
+ bool setSidebandStream(const sp<NativeHandle>& sidebandStream) override EXCLUDES(mStateMutex);
+ bool setTransactionCompletedListeners(const std::vector<sp<CallbackHandle>>& handles) override
+ EXCLUDES(mStateMutex);
// Override to ignore legacy layer state properties that are not used by BufferStateLayer
- bool setCrop_legacy(const Rect& /*crop*/, bool /*immediate*/) override { return false; };
+ bool setSize(uint32_t /*w*/, uint32_t /*h*/) override { return false; }
+ bool setPosition(float /*x*/, float /*y*/, bool /*immediate*/) override { return false; }
+ bool setTransparentRegionHint(const Region& transparent) override;
+ bool setMatrix(const layer_state_t::matrix22_t& /*matrix*/,
+ bool /*allowNonRectPreservingTransforms*/) override {
+ return false;
+ }
+ bool setCrop_legacy(const Rect& /*crop*/, bool /*immediate*/) override { return false; }
+ bool setOverrideScalingMode(int32_t /*overrideScalingMode*/) override { return false; }
void deferTransactionUntil_legacy(const sp<IBinder>& /*barrierHandle*/,
uint64_t /*frameNumber*/) override {}
void deferTransactionUntil_legacy(const sp<Layer>& /*barrierLayer*/,
uint64_t /*frameNumber*/) override {}
+
+ Rect getBufferSize(const State& s) const override REQUIRES(mStateMutex);
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// Interface implementation for BufferLayer
// -----------------------------------------------------------------------
- bool fenceHasSignaled() const override;
+ bool fenceHasSignaled() const override EXCLUDES(mStateMutex);
private:
nsecs_t getDesiredPresentTime() override;
- std::shared_ptr<FenceTime> getCurrentFenceTime() const override;
+ std::shared_ptr<FenceTime> getCurrentFenceTimeLocked() const override REQUIRES(mStateMutex);
void getDrawingTransformMatrix(float *matrix) override;
- uint32_t getDrawingTransform() const override;
- ui::Dataspace getDrawingDataSpace() const override;
- Rect getDrawingCrop() const override;
+ uint32_t getDrawingTransform() const override REQUIRES(mStateMutex);
+ ui::Dataspace getDrawingDataSpace() const override REQUIRES(mStateMutex);
+ Rect getDrawingCrop() const override REQUIRES(mStateMutex);
uint32_t getDrawingScalingMode() const override;
- Region getDrawingSurfaceDamage() const override;
- const HdrMetadata& getDrawingHdrMetadata() const override;
- int getDrawingApi() const override;
+ Region getDrawingSurfaceDamage() const override EXCLUDES(mStateMutex);
+ const HdrMetadata& getDrawingHdrMetadata() const override EXCLUDES(mStateMutex);
+ int getDrawingApi() const override EXCLUDES(mStateMutex);
PixelFormat getPixelFormat() const override;
uint64_t getFrameNumber() const override;
@@ -109,24 +117,26 @@
bool getAutoRefresh() const override;
bool getSidebandStreamChanged() const override;
- std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions) override;
+ std::optional<Region> latchSidebandStream(bool& recomputeVisibleRegions) override
+ EXCLUDES(mStateMutex);
- bool hasFrameUpdate() const override;
+ bool hasFrameUpdateLocked() const override REQUIRES(mStateMutex);
void setFilteringEnabled(bool enabled) override;
- status_t bindTextureImage() override;
+ status_t bindTextureImage() override EXCLUDES(mStateMutex);
status_t updateTexImage(bool& recomputeVisibleRegions, nsecs_t latchTime,
- const sp<Fence>& releaseFence) override;
+ const sp<Fence>& releaseFence) override REQUIRES(mStateMutex);
- status_t updateActiveBuffer() override;
+ status_t updateActiveBuffer() override REQUIRES(mStateMutex);
status_t updateFrameNumber(nsecs_t latchTime) override;
- void setHwcLayerBuffer(DisplayId displayId) override;
+ void setHwcLayerBuffer(DisplayId displayId) override EXCLUDES(mStateMutex);
private:
void onFirstRef() override;
bool willPresentCurrentTransaction() const;
+ status_t bindTextureImageLocked() REQUIRES(mStateMutex);
static const std::array<float, 16> IDENTITY_MATRIX;
diff --git a/services/surfaceflinger/ColorLayer.cpp b/services/surfaceflinger/ColorLayer.cpp
index f27f6aa..cb7642e 100644
--- a/services/surfaceflinger/ColorLayer.cpp
+++ b/services/surfaceflinger/ColorLayer.cpp
@@ -40,15 +40,16 @@
void ColorLayer::onDraw(const RenderArea& renderArea, const Region& /* clip */,
bool useIdentityTransform) {
+ Mutex::Autolock lock(mStateMutex);
half4 color = getColor();
if (color.a > 0) {
renderengine::Mesh mesh(renderengine::Mesh::TRIANGLE_FAN, 4, 2);
computeGeometry(renderArea, mesh, useIdentityTransform);
auto& engine(mFlinger->getRenderEngine());
- Rect win{computeBounds()};
+ Rect win{computeBoundsLocked()};
- const auto roundedCornerState = getRoundedCornerState();
+ const auto roundedCornerState = getRoundedCornerStateLocked();
const auto cropRect = roundedCornerState.cropRect;
setupRoundedCornersCropCoordinates(win, cropRect);
@@ -91,6 +92,7 @@
}
getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
+ Mutex::Autolock lock(mStateMutex);
half4 color = getColor();
error = hwcLayer->setColor({static_cast<uint8_t>(std::round(255.0f * color.r)),
static_cast<uint8_t>(std::round(255.0f * color.g)),
@@ -111,12 +113,12 @@
}
getBE().compositionInfo.hwc.transform = HWC2::Transform::None;
- error = hwcLayer->setColorTransform(getColorTransform());
+ error = hwcLayer->setColorTransform(getColorTransformLocked());
if (error != HWC2::Error::None) {
ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
to_string(error).c_str(), static_cast<int32_t>(error));
}
- getBE().compositionInfo.hwc.colorTransform = getColorTransform();
+ getBE().compositionInfo.hwc.colorTransform = getColorTransformLocked();
error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
if (error != HWC2::Error::None) {
diff --git a/services/surfaceflinger/ColorLayer.h b/services/surfaceflinger/ColorLayer.h
index d1b1697..5850a2e 100644
--- a/services/surfaceflinger/ColorLayer.h
+++ b/services/surfaceflinger/ColorLayer.h
@@ -29,12 +29,12 @@
~ColorLayer() override;
virtual const char* getTypeId() const { return "ColorLayer"; }
- virtual void onDraw(const RenderArea& renderArea, const Region& clip,
- bool useIdentityTransform);
- bool isVisible() const override;
+ virtual void onDraw(const RenderArea& renderArea, const Region& clip, bool useIdentityTransform)
+ EXCLUDES(mStateMutex);
+ bool isVisible() const override EXCLUDES(mStateMutex);
void setPerFrameData(DisplayId displayId, const ui::Transform& transform, const Rect& viewport,
- int32_t supportedPerFrameMetadata) override;
+ int32_t supportedPerFrameMetadata) override EXCLUDES(mStateMutex);
bool onPreComposition(nsecs_t /*refreshStartTime*/) override { return false; }
diff --git a/services/surfaceflinger/Colorizer.h b/services/surfaceflinger/Colorizer.h
index d56b1c8..b7d61ce 100644
--- a/services/surfaceflinger/Colorizer.h
+++ b/services/surfaceflinger/Colorizer.h
@@ -17,7 +17,7 @@
#ifndef ANDROID_SURFACE_FLINGER_COLORIZER_H
#define ANDROID_SURFACE_FLINGER_COLORIZER_H
-#include <utils/String8.h>
+#include <android-base/stringprintf.h>
namespace android {
@@ -40,19 +40,19 @@
: mEnabled(enabled) {
}
- void colorize(String8& out, color c) {
+ void colorize(std::string& out, color c) {
if (mEnabled) {
- out.appendFormat("\e[%dm", c);
+ base::StringAppendF(&out, "\e[%dm", c);
}
}
- void bold(String8& out) {
+ void bold(std::string& out) {
if (mEnabled) {
out.append("\e[1m");
}
}
- void reset(String8& out) {
+ void reset(std::string& out) {
if (mEnabled) {
out.append("\e[0m");
}
diff --git a/services/surfaceflinger/ContainerLayer.h b/services/surfaceflinger/ContainerLayer.h
index 413844b..6c4f7c8 100644
--- a/services/surfaceflinger/ContainerLayer.h
+++ b/services/surfaceflinger/ContainerLayer.h
@@ -31,7 +31,7 @@
const char* getTypeId() const override { return "ContainerLayer"; }
void onDraw(const RenderArea& renderArea, const Region& clip,
bool useIdentityTransform) override;
- bool isVisible() const override;
+ bool isVisible() const override EXCLUDES(mStateMutex);
void setPerFrameData(DisplayId displayId, const ui::Transform& transform, const Rect& viewport,
int32_t supportedPerFrameMetadata) override;
diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp
index 1215bd9..2003fb1 100644
--- a/services/surfaceflinger/DisplayDevice.cpp
+++ b/services/surfaceflinger/DisplayDevice.cpp
@@ -54,6 +54,7 @@
// retrieve triple buffer setting from configstore
using namespace android::hardware::configstore;
using namespace android::hardware::configstore::V1_0;
+using android::base::StringAppendF;
using android::ui::ColorMode;
using android::ui::Dataspace;
using android::ui::Hdr;
@@ -97,7 +98,7 @@
Dataspace colorModeToDataspace(ColorMode mode) {
switch (mode) {
case ColorMode::SRGB:
- return Dataspace::SRGB;
+ return Dataspace::V0_SRGB;
case ColorMode::DISPLAY_P3:
return Dataspace::DISPLAY_P3;
case ColorMode::DISPLAY_BT2020:
@@ -221,6 +222,7 @@
: lastCompositionHadVisibleLayers(false),
mFlinger(args.flinger),
mDisplayToken(args.displayToken),
+ mSequenceId(args.sequenceId),
mId(args.displayId),
mNativeWindow(args.nativeWindow),
mGraphicBuffer(nullptr),
@@ -364,6 +366,15 @@
return mDisplaySurface->prepareFrame(compositionType);
}
+void DisplayDevice::setProtected(bool useProtected) {
+ uint64_t usageFlags = GRALLOC_USAGE_HW_RENDER;
+ if (useProtected) {
+ usageFlags |= GRALLOC_USAGE_PROTECTED;
+ }
+ const int status = native_window_set_usage(mNativeWindow.get(), usageFlags);
+ ALOGE_IF(status != NO_ERROR, "Unable to set BQ usage bits for protected content: %d", status);
+}
+
sp<GraphicBuffer> DisplayDevice::dequeueBuffer() {
int fd;
ANativeWindowBuffer* buffer;
@@ -412,10 +423,9 @@
if (mGraphicBuffer == nullptr) {
ALOGE("No buffer is ready for display [%s]", mDisplayName.c_str());
} else {
- int fd = mBufferReady.release();
-
status_t res = mNativeWindow->queueBuffer(mNativeWindow.get(),
- mGraphicBuffer->getNativeBuffer(), fd);
+ mGraphicBuffer->getNativeBuffer(),
+ dup(mBufferReady));
if (res != NO_ERROR) {
ALOGE("Error when queueing buffer for display [%s]: %d", mDisplayName.c_str(), res);
// We risk blocking on dequeueBuffer if the primary display failed
@@ -424,9 +434,12 @@
LOG_ALWAYS_FATAL("ANativeWindow::queueBuffer failed with error: %d", res);
} else {
mNativeWindow->cancelBuffer(mNativeWindow.get(),
- mGraphicBuffer->getNativeBuffer(), fd);
+ mGraphicBuffer->getNativeBuffer(),
+ dup(mBufferReady));
}
}
+
+ mBufferReady.reset();
mGraphicBuffer = nullptr;
}
}
@@ -715,33 +728,33 @@
mDisplayName.c_str());
}
-void DisplayDevice::dump(String8& result) const {
+void DisplayDevice::dump(std::string& result) const {
const ui::Transform& tr(mGlobalTransform);
ANativeWindow* const window = mNativeWindow.get();
- result.appendFormat("+ %s\n", getDebugName().c_str());
- result.appendFormat(" layerStack=%u, (%4dx%4d), ANativeWindow=%p "
- "format=%d, orient=%2d (type=%08x), flips=%u, isSecure=%d, "
- "powerMode=%d, activeConfig=%d, numLayers=%zu\n",
- mLayerStack, mDisplayWidth, mDisplayHeight, window,
- ANativeWindow_getFormat(window), mOrientation, tr.getType(),
- getPageFlipCount(), mIsSecure, mPowerMode, mActiveConfig,
- mVisibleLayersSortedByZ.size());
- result.appendFormat(" v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], s:[%d,%d,%d,%d],"
- "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
- mViewport.left, mViewport.top, mViewport.right, mViewport.bottom,
- mFrame.left, mFrame.top, mFrame.right, mFrame.bottom, mScissor.left,
- mScissor.top, mScissor.right, mScissor.bottom, tr[0][0], tr[1][0], tr[2][0],
- tr[0][1], tr[1][1], tr[2][1], tr[0][2], tr[1][2], tr[2][2]);
+ StringAppendF(&result, "+ %s\n", getDebugName().c_str());
+ StringAppendF(&result,
+ " layerStack=%u, (%4dx%4d), ANativeWindow=%p "
+ "format=%d, orient=%2d (type=%08x), flips=%u, isSecure=%d, "
+ "powerMode=%d, activeConfig=%d, numLayers=%zu\n",
+ mLayerStack, mDisplayWidth, mDisplayHeight, window,
+ ANativeWindow_getFormat(window), mOrientation, tr.getType(), getPageFlipCount(),
+ mIsSecure, mPowerMode, mActiveConfig, mVisibleLayersSortedByZ.size());
+ StringAppendF(&result,
+ " v:[%d,%d,%d,%d], f:[%d,%d,%d,%d], s:[%d,%d,%d,%d],"
+ "transform:[[%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f][%0.3f,%0.3f,%0.3f]]\n",
+ mViewport.left, mViewport.top, mViewport.right, mViewport.bottom, mFrame.left,
+ mFrame.top, mFrame.right, mFrame.bottom, mScissor.left, mScissor.top,
+ mScissor.right, mScissor.bottom, tr[0][0], tr[1][0], tr[2][0], tr[0][1], tr[1][1],
+ tr[2][1], tr[0][2], tr[1][2], tr[2][2]);
auto const surface = static_cast<Surface*>(window);
ui::Dataspace dataspace = surface->getBuffersDataSpace();
- result.appendFormat(" wideColorGamut=%d, hdr10=%d, colorMode=%s, dataspace: %s (%d)\n",
- mHasWideColorGamut, mHasHdr10, decodeColorMode(mActiveColorMode).c_str(),
- dataspaceDetails(static_cast<android_dataspace>(dataspace)).c_str(),
- dataspace);
+ StringAppendF(&result, " wideColorGamut=%d, hdr10=%d, colorMode=%s, dataspace: %s (%d)\n",
+ mHasWideColorGamut, mHasHdr10, decodeColorMode(mActiveColorMode).c_str(),
+ dataspaceDetails(static_cast<android_dataspace>(dataspace)).c_str(), dataspace);
String8 surfaceDump;
mDisplaySurface->dumpAsString(surfaceDump);
- result.append(surfaceDump);
+ result.append(surfaceDump.string(), surfaceDump.size());
}
// Map dataspace/intent to the best matched dataspace/colorMode/renderIntent
@@ -814,7 +827,7 @@
bool DisplayDevice::hasRenderIntent(RenderIntent intent) const {
// assume a render intent is supported when SRGB supports it; we should
// get rid of that assumption.
- auto iter = mColorModes.find(getColorModeKey(Dataspace::SRGB, intent));
+ auto iter = mColorModes.find(getColorModeKey(Dataspace::V0_SRGB, intent));
return iter != mColorModes.end() && iter->second.renderIntent == intent;
}
diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h
index eb2c5c3..2c2a3ab 100644
--- a/services/surfaceflinger/DisplayDevice.h
+++ b/services/surfaceflinger/DisplayDevice.h
@@ -37,7 +37,6 @@
#include <ui/Transform.h>
#include <utils/Mutex.h>
#include <utils/RefBase.h>
-#include <utils/String8.h>
#include <utils/Timers.h>
#include "DisplayHardware/DisplayIdentification.h"
@@ -113,6 +112,7 @@
const std::optional<DisplayId>& getId() const { return mId; }
const wp<IBinder>& getDisplayToken() const { return mDisplayToken; }
+ int32_t getSequenceId() const { return mSequenceId; }
int32_t getSupportedPerFrameMetadata() const { return mSupportedPerFrameMetadata; }
@@ -146,6 +146,7 @@
ui::Dataspace* outDataspace, ui::ColorMode* outMode,
ui::RenderIntent* outIntent) const;
+ void setProtected(bool useProtected);
// Queues the drawn buffer for consumption by HWC.
void queueBuffer(HWComposer& hwc);
// Allocates a buffer as scratch space for GPU composition
@@ -201,11 +202,12 @@
*/
uint32_t getPageFlipCount() const;
std::string getDebugName() const;
- void dump(String8& result) const;
+ void dump(std::string& result) const;
private:
const sp<SurfaceFlinger> mFlinger;
const wp<IBinder> mDisplayToken;
+ const int32_t mSequenceId;
std::optional<DisplayId> mId;
@@ -333,6 +335,7 @@
const wp<IBinder> displayToken;
const std::optional<DisplayId> displayId;
+ int32_t sequenceId{0};
bool isVirtual{false};
bool isSecure{false};
sp<ANativeWindow> nativeWindow;
diff --git a/services/surfaceflinger/DisplayHardware/ComposerHal.cpp b/services/surfaceflinger/DisplayHardware/ComposerHal.cpp
index 3b7ed15..d6237cb 100644
--- a/services/surfaceflinger/DisplayHardware/ComposerHal.cpp
+++ b/services/surfaceflinger/DisplayHardware/ComposerHal.cpp
@@ -1079,6 +1079,31 @@
maxFrames);
}
+Error Composer::getDisplayedContentSample(Display display, uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats) {
+ if (!outStats) {
+ return Error::BAD_PARAMETER;
+ }
+ if (!mClient_2_3) {
+ return Error::UNSUPPORTED;
+ }
+ Error error = kDefaultError;
+ mClient_2_3->getDisplayedContentSample(display, maxFrames, timestamp,
+ [&](const auto tmpError, auto tmpNumFrames,
+ const auto& tmpSamples0, const auto& tmpSamples1,
+ const auto& tmpSamples2, const auto& tmpSamples3) {
+ error = tmpError;
+ if (error == Error::NONE) {
+ outStats->numFrames = tmpNumFrames;
+ outStats->component_0_sample = tmpSamples0;
+ outStats->component_1_sample = tmpSamples1;
+ outStats->component_2_sample = tmpSamples2;
+ outStats->component_3_sample = tmpSamples3;
+ }
+ });
+ return error;
+}
+
CommandReader::~CommandReader()
{
resetData();
diff --git a/services/surfaceflinger/DisplayHardware/ComposerHal.h b/services/surfaceflinger/DisplayHardware/ComposerHal.h
index 0db12a1..38ee7ad 100644
--- a/services/surfaceflinger/DisplayHardware/ComposerHal.h
+++ b/services/surfaceflinger/DisplayHardware/ComposerHal.h
@@ -30,6 +30,7 @@
#include <composer-command-buffer/2.3/ComposerCommandBuffer.h>
#include <gui/HdrMetadata.h>
#include <math/mat4.h>
+#include <ui/DisplayedFrameStats.h>
#include <ui/GraphicBuffer.h>
#include <utils/StrongPointer.h>
@@ -194,6 +195,8 @@
uint8_t* outComponentMask) = 0;
virtual Error setDisplayContentSamplingEnabled(Display display, bool enabled,
uint8_t componentMask, uint64_t maxFrames) = 0;
+ virtual Error getDisplayedContentSample(Display display, uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats) = 0;
virtual Error getDisplayCapabilities(Display display,
std::vector<DisplayCapability>* outCapabilities) = 0;
};
@@ -400,6 +403,8 @@
uint8_t* outComponentMask) override;
Error setDisplayContentSamplingEnabled(Display display, bool enabled, uint8_t componentMask,
uint64_t maxFrames) override;
+ Error getDisplayedContentSample(Display display, uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats) override;
Error getDisplayCapabilities(Display display,
std::vector<DisplayCapability>* outCapabilities) override;
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.cpp b/services/surfaceflinger/DisplayHardware/HWC2.cpp
index 733a5da..d2aa4ad 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWC2.cpp
@@ -562,6 +562,12 @@
return static_cast<Error>(intError);
}
+Error Display::getDisplayedContentSample(uint64_t maxFrames, uint64_t timestamp,
+ android::DisplayedFrameStats* outStats) const {
+ auto intError = mComposer.getDisplayedContentSample(mId, maxFrames, timestamp, outStats);
+ return static_cast<Error>(intError);
+}
+
Error Display::getReleaseFences(
std::unordered_map<Layer*, sp<Fence>>* outFences) const
{
diff --git a/services/surfaceflinger/DisplayHardware/HWC2.h b/services/surfaceflinger/DisplayHardware/HWC2.h
index 2d65051..f5cb97e 100644
--- a/services/surfaceflinger/DisplayHardware/HWC2.h
+++ b/services/surfaceflinger/DisplayHardware/HWC2.h
@@ -40,6 +40,7 @@
#include "PowerAdvisor.h"
namespace android {
+ struct DisplayedFrameStats;
class Fence;
class FloatRect;
class GraphicBuffer;
@@ -243,6 +244,8 @@
[[clang::warn_unused_result]] Error setDisplayContentSamplingEnabled(bool enabled,
uint8_t componentMask,
uint64_t maxFrames) const;
+ [[clang::warn_unused_result]] Error getDisplayedContentSample(
+ uint64_t maxFrames, uint64_t timestamp, android::DisplayedFrameStats* outStats) const;
[[clang::warn_unused_result]] Error getReleaseFences(
std::unordered_map<Layer*,
android::sp<android::Fence>>* outFences) const;
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.cpp b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
index b27344d..0497571 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.cpp
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.cpp
@@ -770,15 +770,25 @@
return NO_ERROR;
}
+status_t HWComposer::getDisplayedContentSample(DisplayId displayId, uint64_t maxFrames,
+ uint64_t timestamp, DisplayedFrameStats* outStats) {
+ RETURN_IF_INVALID_DISPLAY(displayId, BAD_INDEX);
+ const auto error =
+ mDisplayData[displayId].hwcDisplay->getDisplayedContentSample(maxFrames, timestamp,
+ outStats);
+ RETURN_IF_HWC_ERROR(error, displayId, UNKNOWN_ERROR);
+ return NO_ERROR;
+}
+
bool HWComposer::isUsingVrComposer() const {
return getComposer()->isUsingVrComposer();
}
-void HWComposer::dump(String8& result) const {
+void HWComposer::dump(std::string& result) const {
// TODO: In order to provide a dump equivalent to HWC1, we need to shadow
// all the state going into the layers. This is probably better done in
// Layer itself, but it's going to take a bit of work to get there.
- result.append(mHwcDevice->dump().c_str());
+ result.append(mHwcDevice->dump());
}
std::optional<DisplayId> HWComposer::toPhysicalDisplayId(hwc2_display_t hwcDisplayId) const {
diff --git a/services/surfaceflinger/DisplayHardware/HWComposer.h b/services/surfaceflinger/DisplayHardware/HWComposer.h
index 3f1328e..d9a0916 100644
--- a/services/surfaceflinger/DisplayHardware/HWComposer.h
+++ b/services/surfaceflinger/DisplayHardware/HWComposer.h
@@ -36,8 +36,8 @@
namespace android {
+struct DisplayedFrameStats;
class GraphicBuffer;
-class String8;
class TestableSurfaceFlinger;
struct CompositionInfo;
@@ -133,6 +133,8 @@
uint8_t* outComponentMask);
status_t setDisplayContentSamplingEnabled(DisplayId displayId, bool enabled,
uint8_t componentMask, uint64_t maxFrames);
+ status_t getDisplayedContentSample(DisplayId displayId, uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats);
// Events handling ---------------------------------------------------------
@@ -161,7 +163,7 @@
bool isUsingVrComposer() const;
// for debugging ----------------------------------------------------------
- void dump(String8& out) const;
+ void dump(std::string& out) const;
Hwc2::Composer* getComposer() const { return mHwcDevice->getComposer(); }
diff --git a/services/surfaceflinger/FrameTracker.cpp b/services/surfaceflinger/FrameTracker.cpp
index 1539873..f4cc49b 100644
--- a/services/surfaceflinger/FrameTracker.cpp
+++ b/services/surfaceflinger/FrameTracker.cpp
@@ -19,6 +19,7 @@
#include <inttypes.h>
+#include <android-base/stringprintf.h>
#include <android/log.h>
#include <utils/String8.h>
@@ -230,17 +231,17 @@
mFrameRecords[idx].actualPresentTime < INT64_MAX;
}
-void FrameTracker::dumpStats(String8& result) const {
+void FrameTracker::dumpStats(std::string& result) const {
Mutex::Autolock lock(mMutex);
processFencesLocked();
const size_t o = mOffset;
for (size_t i = 1; i < NUM_FRAME_RECORDS; i++) {
const size_t index = (o+i) % NUM_FRAME_RECORDS;
- result.appendFormat("%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n",
- mFrameRecords[index].desiredPresentTime,
- mFrameRecords[index].actualPresentTime,
- mFrameRecords[index].frameReadyTime);
+ base::StringAppendF(&result, "%" PRId64 "\t%" PRId64 "\t%" PRId64 "\n",
+ mFrameRecords[index].desiredPresentTime,
+ mFrameRecords[index].actualPresentTime,
+ mFrameRecords[index].frameReadyTime);
}
result.append("\n");
}
diff --git a/services/surfaceflinger/FrameTracker.h b/services/surfaceflinger/FrameTracker.h
index b4a9fd6..555dcc1 100644
--- a/services/surfaceflinger/FrameTracker.h
+++ b/services/surfaceflinger/FrameTracker.h
@@ -90,7 +90,7 @@
void logAndResetStats(const String8& name);
// dumpStats dump appends the current frame display time history to the result string.
- void dumpStats(String8& result) const;
+ void dumpStats(std::string& result) const;
private:
struct FrameRecord {
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index f53ffae..f4b3cdd 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -25,6 +25,8 @@
#include <sys/types.h>
#include <algorithm>
+#include <android-base/stringprintf.h>
+
#include <cutils/compiler.h>
#include <cutils/native_handle.h>
#include <cutils/properties.h>
@@ -63,6 +65,8 @@
namespace android {
+using base::StringAppendF;
+
std::atomic<int32_t> Layer::sSequence{1};
Layer::Layer(const LayerCreationArgs& args)
@@ -79,35 +83,35 @@
mTransactionName = String8("TX - ") + mName;
- mCurrentState.active_legacy.w = args.w;
- mCurrentState.active_legacy.h = args.h;
- mCurrentState.flags = layerFlags;
- mCurrentState.active_legacy.transform.set(0, 0);
- mCurrentState.crop_legacy.makeInvalid();
- mCurrentState.requestedCrop_legacy = mCurrentState.crop_legacy;
- mCurrentState.z = 0;
- mCurrentState.color.a = 1.0f;
- mCurrentState.layerStack = 0;
- mCurrentState.sequence = 0;
- mCurrentState.requested_legacy = mCurrentState.active_legacy;
- mCurrentState.appId = 0;
- mCurrentState.type = 0;
- mCurrentState.active.w = 0;
- mCurrentState.active.h = 0;
- mCurrentState.active.transform.set(0, 0);
- mCurrentState.transform = 0;
- mCurrentState.transformToDisplayInverse = false;
- mCurrentState.crop.makeInvalid();
- mCurrentState.acquireFence = new Fence(-1);
- mCurrentState.dataspace = ui::Dataspace::UNKNOWN;
- mCurrentState.hdrMetadata.validTypes = 0;
- mCurrentState.surfaceDamageRegion.clear();
- mCurrentState.cornerRadius = 0.0f;
- mCurrentState.api = -1;
- mCurrentState.hasColorTransform = false;
+ mState.current.active_legacy.w = args.w;
+ mState.current.active_legacy.h = args.h;
+ mState.current.flags = layerFlags;
+ mState.current.active_legacy.transform.set(0, 0);
+ mState.current.crop_legacy.makeInvalid();
+ mState.current.requestedCrop_legacy = mState.current.crop_legacy;
+ mState.current.z = 0;
+ mState.current.color.a = 1.0f;
+ mState.current.layerStack = 0;
+ mState.current.sequence = 0;
+ mState.current.requested_legacy = mState.current.active_legacy;
+ mState.current.appId = 0;
+ mState.current.type = 0;
+ mState.current.active.w = UINT32_MAX;
+ mState.current.active.h = UINT32_MAX;
+ mState.current.active.transform.set(0, 0);
+ mState.current.transform = 0;
+ mState.current.transformToDisplayInverse = false;
+ mState.current.crop.makeInvalid();
+ mState.current.acquireFence = new Fence(-1);
+ mState.current.dataspace = ui::Dataspace::UNKNOWN;
+ mState.current.hdrMetadata.validTypes = 0;
+ mState.current.surfaceDamageRegion.clear();
+ mState.current.cornerRadius = 0.0f;
+ mState.current.api = -1;
+ mState.current.hasColorTransform = false;
// drawing state & current state are identical
- mDrawingState = mCurrentState;
+ mState.drawing = mState.current;
CompositorTiming compositorTiming;
args.flinger->getCompositorTiming(&compositorTiming);
@@ -144,14 +148,17 @@
void Layer::onRemovedFromCurrentState() {
mRemovedFromCurrentState = true;
- // the layer is removed from SF mCurrentState to mLayersPendingRemoval
- if (mCurrentState.zOrderRelativeOf != nullptr) {
- sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
- if (strongRelative != nullptr) {
- strongRelative->removeZOrderRelative(this);
- mFlinger->setTransactionFlags(eTraversalNeeded);
+ {
+ Mutex::Autolock lock(mStateMutex);
+ // the layer is removed from SF mState.current to mLayersPendingRemoval
+ if (mState.current.zOrderRelativeOf != nullptr) {
+ sp<Layer> strongRelative = mState.current.zOrderRelativeOf.promote();
+ if (strongRelative != nullptr) {
+ strongRelative->removeZOrderRelative(this);
+ mFlinger->setTransactionFlags(eTraversalNeeded);
+ }
+ mState.current.zOrderRelativeOf = nullptr;
}
- mCurrentState.zOrderRelativeOf = nullptr;
}
// Since we are no longer reachable from CurrentState SurfaceFlinger
@@ -289,20 +296,33 @@
return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
}
-Rect Layer::computeScreenBounds() const {
- FloatRect bounds = computeBounds();
- ui::Transform t = getTransform();
+Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
+ Mutex::Autolock lock(mStateMutex);
+ const State& s(getDrawingState());
+ Region transparentRegion = reduceTransparentRegion ? getActiveTransparentRegion(s) : Region();
+ FloatRect bounds = computeBoundsLocked(transparentRegion);
+ ui::Transform t = getTransformLocked();
// Transform to screen space.
bounds = t.transform(bounds);
return Rect{bounds};
}
FloatRect Layer::computeBounds() const {
+ Mutex::Autolock lock(mStateMutex);
+ return computeBoundsLocked();
+}
+
+FloatRect Layer::computeBoundsLocked() const {
const State& s(getDrawingState());
- return computeBounds(getActiveTransparentRegion(s));
+ return computeBoundsLocked(getActiveTransparentRegion(s));
}
FloatRect Layer::computeBounds(const Region& activeTransparentRegion) const {
+ Mutex::Autolock lock(mStateMutex);
+ return computeBoundsLocked(activeTransparentRegion);
+}
+
+FloatRect Layer::computeBoundsLocked(const Region& activeTransparentRegion) const {
const State& s(getDrawingState());
Rect bounds = getCroppedBufferSize(s);
FloatRect floatBounds = bounds.toFloatRect();
@@ -355,6 +375,7 @@
// child bounds as well.
ui::Transform t = s.active_legacy.transform;
croppedBounds = t.transform(croppedBounds);
+ Mutex::Autolock lock(p->mStateMutex);
croppedBounds = p->cropChildBounds(croppedBounds);
croppedBounds = t.inverse().transform(croppedBounds);
}
@@ -382,8 +403,8 @@
// if there are no window scaling involved, this operation will map to full
// pixels in the buffer.
- FloatRect activeCropFloat = computeBounds();
- ui::Transform t = getTransform();
+ FloatRect activeCropFloat = computeBoundsLocked();
+ ui::Transform t = getTransformLocked();
// Transform to screen space.
activeCropFloat = t.transform(activeCropFloat);
activeCropFloat = activeCropFloat.intersect(display->getViewport().toFloatRect());
@@ -433,7 +454,7 @@
// which means using the inverse of the current transform set on the
// SurfaceFlingerConsumer.
uint32_t invTransform = mCurrentTransform;
- if (getTransformToDisplayInverse()) {
+ if (getTransformToDisplayInverseLocked()) {
/*
* the code below applies the primary display's inverse transform to the
* buffer
@@ -484,6 +505,7 @@
}
void Layer::setGeometry(const sp<const DisplayDevice>& display, uint32_t z) {
+ Mutex::Autolock lock(mStateMutex);
const auto displayId = display->getId();
LOG_ALWAYS_FATAL_IF(!displayId);
RETURN_IF_NO_HWC_LAYER(*displayId);
@@ -492,7 +514,7 @@
// enable this layer
hwcInfo.forceClientComposition = false;
- if (isSecure() && !display->isSecure()) {
+ if (isSecureLocked() && !display->isSecure()) {
hwcInfo.forceClientComposition = true;
}
@@ -500,10 +522,9 @@
// this gives us only the "orientation" component of the transform
const State& s(getDrawingState());
- const int bufferWidth = getBufferSize(s).getWidth();
- const int bufferHeight = getBufferSize(s).getHeight();
+ const Rect bufferSize = getBufferSize(s);
auto blendMode = HWC2::BlendMode::None;
- if (!isOpaque(s) || getAlpha() != 1.0f) {
+ if (!isOpaque(s) || getAlphaLocked() != 1.0f) {
blendMode =
mPremultipliedAlpha ? HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
}
@@ -518,9 +539,9 @@
// apply the layer's transform, followed by the display's global transform
// here we're guaranteed that the layer's transform preserves rects
Region activeTransparentRegion(getActiveTransparentRegion(s));
- ui::Transform t = getTransform();
+ ui::Transform t = getTransformLocked();
Rect activeCrop = getCrop(s);
- if (!activeCrop.isEmpty()) {
+ if (!activeCrop.isEmpty() && bufferSize.isValid()) {
activeCrop = t.transform(activeCrop);
if (!activeCrop.intersect(display->getViewport(), &activeCrop)) {
activeCrop.clear();
@@ -532,20 +553,21 @@
// transform.inverse().transform(transform.transform(Rect)) != Rect
// in which case we need to make sure the final rect is clipped to the
// display bounds.
- if (!activeCrop.intersect(Rect(bufferWidth, bufferHeight), &activeCrop)) {
+ if (!activeCrop.intersect(bufferSize, &activeCrop)) {
activeCrop.clear();
}
// mark regions outside the crop as transparent
- activeTransparentRegion.orSelf(Rect(0, 0, bufferWidth, activeCrop.top));
- activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom, bufferWidth, bufferHeight));
+ activeTransparentRegion.orSelf(Rect(0, 0, bufferSize.getWidth(), activeCrop.top));
+ activeTransparentRegion.orSelf(
+ Rect(0, activeCrop.bottom, bufferSize.getWidth(), bufferSize.getHeight()));
activeTransparentRegion.orSelf(Rect(0, activeCrop.top, activeCrop.left, activeCrop.bottom));
activeTransparentRegion.orSelf(
- Rect(activeCrop.right, activeCrop.top, bufferWidth, activeCrop.bottom));
+ Rect(activeCrop.right, activeCrop.top, bufferSize.getWidth(), activeCrop.bottom));
}
// computeBounds returns a FloatRect to provide more accuracy during the
// transformation. We then round upon constructing 'frame'.
- Rect frame{t.transform(computeBounds(activeTransparentRegion))};
+ Rect frame{t.transform(computeBoundsLocked(activeTransparentRegion))};
if (!frame.intersect(display->getViewport(), &frame)) {
frame.clear();
}
@@ -573,7 +595,7 @@
}
getBE().compositionInfo.hwc.sourceCrop = sourceCrop;
- float alpha = static_cast<float>(getAlpha());
+ float alpha = static_cast<float>(getAlphaLocked());
error = hwcLayer->setPlaneAlpha(alpha);
ALOGE_IF(error != HWC2::Error::None,
"[%s] Failed to set plane alpha %.3f: "
@@ -590,6 +612,7 @@
int appId = s.appId;
sp<Layer> parent = mDrawingParent.promote();
if (parent.get()) {
+ Mutex::Autolock lock(parent->mStateMutex);
auto& parentState = parent->getDrawingState();
if (parentState.type >= 0 || parentState.appId >= 0) {
type = parentState.type;
@@ -615,7 +638,7 @@
const ui::Transform bufferOrientation(mCurrentTransform);
ui::Transform transform(tr * t * bufferOrientation);
- if (getTransformToDisplayInverse()) {
+ if (getTransformToDisplayInverseLocked()) {
/*
* the code below applies the primary display's inverse transform to the
* buffer
@@ -665,6 +688,7 @@
}
void Layer::updateCursorPosition(const sp<const DisplayDevice>& display) {
+ Mutex::Autolock lock(mStateMutex);
const auto displayId = display->getId();
LOG_ALWAYS_FATAL_IF(!displayId);
if (!hasHwcLayer(*displayId) || getCompositionType(displayId) != HWC2::Composition::Cursor) {
@@ -679,7 +703,7 @@
Rect win = getCroppedBufferSize(s);
// Subtract the transparent region and snap to the bounds
Rect bounds = reduce(win, getActiveTransparentRegion(s));
- Rect frame(getTransform().transform(bounds));
+ Rect frame(getTransformLocked().transform(bounds));
frame.intersect(display->getViewport(), &frame);
auto& displayTransform = display->getTransform();
auto position = displayTransform.transform(frame);
@@ -709,6 +733,7 @@
void Layer::clearWithOpenGL(const RenderArea& renderArea, float red, float green, float blue,
float alpha) const {
auto& engine(mFlinger->getRenderEngine());
+ Mutex::Autolock lock(mStateMutex);
computeGeometry(renderArea, getBE().mMesh, false);
engine.setupFillWithColor(red, green, blue, alpha);
engine.drawMesh(getBE().mMesh);
@@ -793,14 +818,14 @@
renderengine::Mesh& mesh,
bool useIdentityTransform) const {
const ui::Transform renderAreaTransform(renderArea.getTransform());
- FloatRect win = computeBounds();
+ FloatRect win = computeBoundsLocked();
vec2 lt = vec2(win.left, win.top);
vec2 lb = vec2(win.left, win.bottom);
vec2 rb = vec2(win.right, win.bottom);
vec2 rt = vec2(win.right, win.top);
- ui::Transform layerTransform = getTransform();
+ ui::Transform layerTransform = getTransformLocked();
if (!useIdentityTransform) {
lt = layerTransform.transform(lt);
lb = layerTransform.transform(lb);
@@ -816,7 +841,12 @@
}
bool Layer::isSecure() const {
- const State& s(mDrawingState);
+ Mutex::Autolock lock(mStateMutex);
+ return isSecureLocked();
+}
+
+bool Layer::isSecureLocked() const {
+ const State& s(mState.drawing);
return (s.flags & layer_state_t::eLayerSecure);
}
@@ -844,9 +874,13 @@
// ----------------------------------------------------------------------------
// transaction
// ----------------------------------------------------------------------------
-
void Layer::pushPendingState() {
- if (!mCurrentState.modified) {
+ Mutex::Autolock lock(mStateMutex);
+ pushPendingStateLocked();
+}
+
+void Layer::pushPendingStateLocked() {
+ if (!mState.current.modified) {
return;
}
@@ -854,22 +888,22 @@
// point and send it to the remote layer.
// We don't allow installing sync points after we are removed from the current state
// as we won't be able to signal our end.
- if (mCurrentState.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
- sp<Layer> barrierLayer = mCurrentState.barrierLayer_legacy.promote();
+ if (mState.current.barrierLayer_legacy != nullptr && !isRemovedFromCurrentState()) {
+ sp<Layer> barrierLayer = mState.current.barrierLayer_legacy.promote();
if (barrierLayer == nullptr) {
ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
// If we can't promote the layer we are intended to wait on,
// then it is expired or otherwise invalid. Allow this transaction
// to be applied as per normal (no synchronization).
- mCurrentState.barrierLayer_legacy = nullptr;
+ mState.current.barrierLayer_legacy = nullptr;
} else {
- auto syncPoint = std::make_shared<SyncPoint>(mCurrentState.frameNumber_legacy);
+ auto syncPoint = std::make_shared<SyncPoint>(mState.current.frameNumber_legacy);
if (barrierLayer->addSyncPoint(syncPoint)) {
mRemoteSyncPoints.push_back(std::move(syncPoint));
} else {
// We already missed the frame we're supposed to synchronize
// on, so go ahead and apply the state update
- mCurrentState.barrierLayer_legacy = nullptr;
+ mState.current.barrierLayer_legacy = nullptr;
}
}
@@ -877,21 +911,21 @@
setTransactionFlags(eTransactionNeeded);
mFlinger->setTransactionFlags(eTraversalNeeded);
}
- mPendingStates.push_back(mCurrentState);
- ATRACE_INT(mTransactionName.string(), mPendingStates.size());
+ mState.pending.push_back(mState.current);
+ ATRACE_INT(mTransactionName.string(), mState.pending.size());
}
void Layer::popPendingState(State* stateToCommit) {
- *stateToCommit = mPendingStates[0];
+ *stateToCommit = mState.pending[0];
- mPendingStates.removeAt(0);
- ATRACE_INT(mTransactionName.string(), mPendingStates.size());
+ mState.pending.removeAt(0);
+ ATRACE_INT(mTransactionName.string(), mState.pending.size());
}
bool Layer::applyPendingStates(State* stateToCommit) {
bool stateUpdateAvailable = false;
- while (!mPendingStates.empty()) {
- if (mPendingStates[0].barrierLayer_legacy != nullptr) {
+ while (!mState.pending.empty()) {
+ if (mState.pending[0].barrierLayer_legacy != nullptr) {
if (mRemoteSyncPoints.empty()) {
// If we don't have a sync point for this, apply it anyway. It
// will be visually wrong, but it should keep us from getting
@@ -903,7 +937,7 @@
}
if (mRemoteSyncPoints.front()->getFrameNumber() !=
- mPendingStates[0].frameNumber_legacy) {
+ mState.pending[0].frameNumber_legacy) {
ALOGE("[%s] Unexpected sync point frame number found", mName.string());
// Signal our end of the sync point and then dispose of it
@@ -931,12 +965,12 @@
// If we still have pending updates, wake SurfaceFlinger back up and point
// it at this layer so we can process them
- if (!mPendingStates.empty()) {
+ if (!mState.pending.empty()) {
setTransactionFlags(eTransactionNeeded);
mFlinger->setTransactionFlags(eTraversalNeeded);
}
- mCurrentState.modified = false;
+ mState.current.modified = false;
return stateUpdateAvailable;
}
@@ -1033,7 +1067,8 @@
return 0;
}
- pushPendingState();
+ Mutex::Autolock lock(mStateMutex);
+ pushPendingStateLocked();
State c = getCurrentState();
if (!applyPendingStates(&c)) {
return 0;
@@ -1065,49 +1100,60 @@
clearSyncPoints();
}
- if (mCurrentState.inputInfoChanged) {
+ if (mState.current.inputInfoChanged) {
flags |= eInputInfoChanged;
- mCurrentState.inputInfoChanged = false;
+ mState.current.inputInfoChanged = false;
}
// Commit the transaction
commitTransaction(c);
- mCurrentState.callbackHandles = {};
+ mState.current.callbackHandles = {};
return flags;
}
void Layer::commitTransaction(const State& stateToCommit) {
- mDrawingState = stateToCommit;
+ mState.drawing = stateToCommit;
+}
+
+uint32_t Layer::getTransactionFlags() const {
+ Mutex::Autolock lock(mStateMutex);
+ return mState.transactionFlags;
}
uint32_t Layer::getTransactionFlags(uint32_t flags) {
- return mTransactionFlags.fetch_and(~flags) & flags;
+ Mutex::Autolock lock(mStateMutex);
+ uint32_t and_flags = mState.transactionFlags & flags;
+ mState.transactionFlags &= ~flags;
+ return and_flags;
}
uint32_t Layer::setTransactionFlags(uint32_t flags) {
- return mTransactionFlags.fetch_or(flags);
+ uint32_t old_flags = mState.transactionFlags;
+ mState.transactionFlags |= flags;
+ return old_flags;
}
bool Layer::setPosition(float x, float y, bool immediate) {
- if (mCurrentState.requested_legacy.transform.tx() == x &&
- mCurrentState.requested_legacy.transform.ty() == y)
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.requested_legacy.transform.tx() == x &&
+ mState.current.requested_legacy.transform.ty() == y)
return false;
- mCurrentState.sequence++;
+ mState.current.sequence++;
// We update the requested and active position simultaneously because
// we want to apply the position portion of the transform matrix immediately,
// but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
- mCurrentState.requested_legacy.transform.set(x, y);
+ mState.current.requested_legacy.transform.set(x, y);
if (immediate && !mFreezeGeometryUpdates) {
// Here we directly update the active state
// unlike other setters, because we store it within
// the transform, but use different latching rules.
// b/38182305
- mCurrentState.active_legacy.transform.set(x, y);
+ mState.current.active_legacy.transform.set(x, y);
}
mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
- mCurrentState.modified = true;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
@@ -1140,38 +1186,44 @@
}
bool Layer::setLayer(int32_t z) {
- if (mCurrentState.z == z && !usingRelativeZ(LayerVector::StateSet::Current)) return false;
- mCurrentState.sequence++;
- mCurrentState.z = z;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.z == z && !usingRelativeZLocked(LayerVector::StateSet::Current))
+ return false;
+
+ mState.current.sequence++;
+ mState.current.z = z;
+ mState.current.modified = true;
// Discard all relative layering.
- if (mCurrentState.zOrderRelativeOf != nullptr) {
- sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
+ if (mState.current.zOrderRelativeOf != nullptr) {
+ sp<Layer> strongRelative = mState.current.zOrderRelativeOf.promote();
if (strongRelative != nullptr) {
strongRelative->removeZOrderRelative(this);
}
- mCurrentState.zOrderRelativeOf = nullptr;
+ mState.current.zOrderRelativeOf = nullptr;
}
setTransactionFlags(eTransactionNeeded);
return true;
}
void Layer::removeZOrderRelative(const wp<Layer>& relative) {
- mCurrentState.zOrderRelatives.remove(relative);
- mCurrentState.sequence++;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.zOrderRelatives.remove(relative);
+ mState.current.sequence++;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
}
void Layer::addZOrderRelative(const wp<Layer>& relative) {
- mCurrentState.zOrderRelatives.add(relative);
- mCurrentState.modified = true;
- mCurrentState.sequence++;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.zOrderRelatives.add(relative);
+ mState.current.modified = true;
+ mState.current.sequence++;
setTransactionFlags(eTransactionNeeded);
}
bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ) {
+ Mutex::Autolock lock(mStateMutex);
sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
if (handle == nullptr) {
return false;
@@ -1181,20 +1233,20 @@
return false;
}
- if (mCurrentState.z == relativeZ && usingRelativeZ(LayerVector::StateSet::Current) &&
- mCurrentState.zOrderRelativeOf == relative) {
+ if (mState.current.z == relativeZ && usingRelativeZLocked(LayerVector::StateSet::Current) &&
+ mState.current.zOrderRelativeOf == relative) {
return false;
}
- mCurrentState.sequence++;
- mCurrentState.modified = true;
- mCurrentState.z = relativeZ;
+ mState.current.sequence++;
+ mState.current.modified = true;
+ mState.current.z = relativeZ;
- auto oldZOrderRelativeOf = mCurrentState.zOrderRelativeOf.promote();
+ auto oldZOrderRelativeOf = mState.current.zOrderRelativeOf.promote();
if (oldZOrderRelativeOf != nullptr) {
oldZOrderRelativeOf->removeZOrderRelative(this);
}
- mCurrentState.zOrderRelativeOf = relative;
+ mState.current.zOrderRelativeOf = relative;
relative->addZOrderRelative(this);
setTransactionFlags(eTransactionNeeded);
@@ -1203,48 +1255,51 @@
}
bool Layer::setSize(uint32_t w, uint32_t h) {
- if (mCurrentState.requested_legacy.w == w && mCurrentState.requested_legacy.h == h)
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.requested_legacy.w == w && mState.current.requested_legacy.h == h)
return false;
- mCurrentState.requested_legacy.w = w;
- mCurrentState.requested_legacy.h = h;
- mCurrentState.modified = true;
+ mState.current.requested_legacy.w = w;
+ mState.current.requested_legacy.h = h;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
// record the new size, from this point on, when the client request
// a buffer, it'll get the new size.
- setDefaultBufferSize(mCurrentState.requested_legacy.w, mCurrentState.requested_legacy.h);
+ setDefaultBufferSize(mState.current.requested_legacy.w, mState.current.requested_legacy.h);
return true;
}
bool Layer::setAlpha(float alpha) {
- if (mCurrentState.color.a == alpha) return false;
- mCurrentState.sequence++;
- mCurrentState.color.a = alpha;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.color.a == alpha) return false;
+ mState.current.sequence++;
+ mState.current.color.a = alpha;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setColor(const half3& color) {
- if (color.r == mCurrentState.color.r && color.g == mCurrentState.color.g &&
- color.b == mCurrentState.color.b)
+ Mutex::Autolock lock(mStateMutex);
+ if (color.r == mState.current.color.r && color.g == mState.current.color.g &&
+ color.b == mState.current.color.b)
return false;
- mCurrentState.sequence++;
- mCurrentState.color.r = color.r;
- mCurrentState.color.g = color.g;
- mCurrentState.color.b = color.b;
- mCurrentState.modified = true;
+ mState.current.sequence++;
+ mState.current.color.r = color.r;
+ mState.current.color.g = color.g;
+ mState.current.color.b = color.b;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setCornerRadius(float cornerRadius) {
- if (mCurrentState.cornerRadius == cornerRadius)
- return false;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.cornerRadius == cornerRadius) return false;
- mCurrentState.sequence++;
- mCurrentState.cornerRadius = cornerRadius;
- mCurrentState.modified = true;
+ mState.current.sequence++;
+ mState.current.cornerRadius = cornerRadius;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
@@ -1258,45 +1313,50 @@
ALOGW("Attempt to set rotation matrix without permission ACCESS_SURFACE_FLINGER ignored");
return false;
}
- mCurrentState.sequence++;
- mCurrentState.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
- matrix.dsdy);
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.sequence++;
+ mState.current.requested_legacy.transform.set(matrix.dsdx, matrix.dtdy, matrix.dtdx,
+ matrix.dsdy);
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setTransparentRegionHint(const Region& transparent) {
- mCurrentState.requestedTransparentRegion_legacy = transparent;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.requestedTransparentRegion_legacy = transparent;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setFlags(uint8_t flags, uint8_t mask) {
- const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
- if (mCurrentState.flags == newFlags) return false;
- mCurrentState.sequence++;
- mCurrentState.flags = newFlags;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ const uint32_t newFlags = (mState.current.flags & ~mask) | (flags & mask);
+ if (mState.current.flags == newFlags) return false;
+ mState.current.sequence++;
+ mState.current.flags = newFlags;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setCrop_legacy(const Rect& crop, bool immediate) {
- if (mCurrentState.requestedCrop_legacy == crop) return false;
- mCurrentState.sequence++;
- mCurrentState.requestedCrop_legacy = crop;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.requestedCrop_legacy == crop) return false;
+ mState.current.sequence++;
+ mState.current.requestedCrop_legacy = crop;
if (immediate && !mFreezeGeometryUpdates) {
- mCurrentState.crop_legacy = crop;
+ mState.current.crop_legacy = crop;
}
mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
- mCurrentState.modified = true;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
bool Layer::setOverrideScalingMode(int32_t scalingMode) {
+ Mutex::Autolock lock(mStateMutex);
if (scalingMode == mOverrideScalingMode) return false;
mOverrideScalingMode = scalingMode;
setTransactionFlags(eTransactionNeeded);
@@ -1304,22 +1364,29 @@
}
void Layer::setInfo(int32_t type, int32_t appId) {
- mCurrentState.appId = appId;
- mCurrentState.type = type;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.appId = appId;
+ mState.current.type = type;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
}
bool Layer::setLayerStack(uint32_t layerStack) {
- if (mCurrentState.layerStack == layerStack) return false;
- mCurrentState.sequence++;
- mCurrentState.layerStack = layerStack;
- mCurrentState.modified = true;
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.layerStack == layerStack) return false;
+ mState.current.sequence++;
+ mState.current.layerStack = layerStack;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
uint32_t Layer::getLayerStack() const {
+ Mutex::Autolock lock(mStateMutex);
+ return getLayerStackLocked();
+}
+
+uint32_t Layer::getLayerStackLocked() const {
auto p = mDrawingParent.promote();
if (p == nullptr) {
return getDrawingState().layerStack;
@@ -1328,15 +1395,16 @@
}
void Layer::deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber) {
- mCurrentState.barrierLayer_legacy = barrierLayer;
- mCurrentState.frameNumber_legacy = frameNumber;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.barrierLayer_legacy = barrierLayer;
+ mState.current.frameNumber_legacy = frameNumber;
// We don't set eTransactionNeeded, because just receiving a deferral
// request without any other state updates shouldn't actually induce a delay
- mCurrentState.modified = true;
- pushPendingState();
- mCurrentState.barrierLayer_legacy = nullptr;
- mCurrentState.frameNumber_legacy = 0;
- mCurrentState.modified = false;
+ mState.current.modified = true;
+ pushPendingStateLocked();
+ mState.current.barrierLayer_legacy = nullptr;
+ mState.current.frameNumber_legacy = 0;
+ mState.current.modified = false;
}
void Layer::deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle, uint64_t frameNumber) {
@@ -1349,7 +1417,8 @@
// ----------------------------------------------------------------------------
bool Layer::isHiddenByPolicy() const {
- const State& s(mDrawingState);
+ Mutex::Autolock lock(mStateMutex);
+ const State& s(mState.drawing);
const auto& parent = mDrawingParent.promote();
if (parent != nullptr && parent->isHiddenByPolicy()) {
return true;
@@ -1394,16 +1463,17 @@
// TODO(marissaw): add new layer state info to layer debugging
LayerDebugInfo Layer::getLayerDebugInfo() const {
+ Mutex::Autolock lock(mStateMutex);
LayerDebugInfo info;
const State& ds = getDrawingState();
info.mName = getName();
sp<Layer> parent = getParent();
info.mParentName = (parent == nullptr ? std::string("none") : parent->getName().string());
- info.mType = String8(getTypeId());
+ info.mType = std::string(getTypeId());
info.mTransparentRegion = ds.activeTransparentRegion_legacy;
info.mVisibleRegion = visibleRegion;
info.mSurfaceDamageRegion = surfaceDamageRegion;
- info.mLayerStack = getLayerStack();
+ info.mLayerStack = getLayerStackLocked();
info.mX = ds.active_legacy.transform.tx();
info.mY = ds.active_legacy.transform.ty();
info.mZ = ds.z;
@@ -1439,7 +1509,14 @@
return info;
}
-void Layer::miniDumpHeader(String8& result) {
+std::tuple<uint32_t, int32_t> Layer::getLayerStackAndZ(StateSet stateSet) {
+ Mutex::Autolock lock(mStateMutex);
+ const State& state = (stateSet == StateSet::Current) ? mState.current : mState.drawing;
+
+ return {state.layerStack, state.z};
+}
+
+void Layer::miniDumpHeader(std::string& result) {
result.append("-------------------------------");
result.append("-------------------------------");
result.append("-----------------------------\n");
@@ -1454,50 +1531,52 @@
result.append("-----------------------------\n");
}
-void Layer::miniDump(String8& result, DisplayId displayId) const {
+void Layer::miniDump(std::string& result, DisplayId displayId) const {
+ Mutex::Autolock lock(mStateMutex);
if (!hasHwcLayer(displayId)) {
return;
}
- String8 name;
+ std::string name;
if (mName.length() > 77) {
std::string shortened;
shortened.append(mName.string(), 36);
shortened.append("[...]");
shortened.append(mName.string() + (mName.length() - 36), 36);
- name = shortened.c_str();
+ name = shortened;
} else {
- name = mName;
+ name = std::string(mName.string(), mName.size());
}
- result.appendFormat(" %s\n", name.string());
+ StringAppendF(&result, " %s\n", name.c_str());
const State& layerState(getDrawingState());
const LayerBE::HWCInfo& hwcInfo = getBE().mHwcLayers.at(displayId);
if (layerState.zOrderRelativeOf != nullptr || mDrawingParent != nullptr) {
- result.appendFormat(" rel %6d | ", layerState.z);
+ StringAppendF(&result, " rel %6d | ", layerState.z);
} else {
- result.appendFormat(" %10d | ", layerState.z);
+ StringAppendF(&result, " %10d | ", layerState.z);
}
- result.appendFormat("%10s | ", to_string(getCompositionType(displayId)).c_str());
- result.appendFormat("%10s | ", to_string(hwcInfo.transform).c_str());
+ StringAppendF(&result, "%10s | ", to_string(getCompositionType(displayId)).c_str());
+ StringAppendF(&result, "%10s | ", to_string(hwcInfo.transform).c_str());
const Rect& frame = hwcInfo.displayFrame;
- result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
+ StringAppendF(&result, "%4d %4d %4d %4d | ", frame.left, frame.top, frame.right, frame.bottom);
const FloatRect& crop = hwcInfo.sourceCrop;
- result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right, crop.bottom);
+ StringAppendF(&result, "%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, crop.right,
+ crop.bottom);
result.append("- - - - - - - - - - - - - - - -\n");
std::string compositionInfoStr;
getBE().compositionInfo.dump(compositionInfoStr, "compositionInfo");
- result.append(compositionInfoStr.c_str());
+ result.append(compositionInfoStr);
result.append("- - - - - - - - - - - - - - - -");
result.append("- - - - - - - - - - - - - - - -");
result.append("- - - - - - - - - - - - - - -\n");
}
-void Layer::dumpFrameStats(String8& result) const {
+void Layer::dumpFrameStats(std::string& result) const {
mFrameTracker.dumpStats(result);
}
@@ -1513,8 +1592,8 @@
mFrameTracker.getStats(outStats);
}
-void Layer::dumpFrameEvents(String8& result) {
- result.appendFormat("- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
+void Layer::dumpFrameEvents(std::string& result) {
+ StringAppendF(&result, "- Layer %s (%s, %p)\n", getName().string(), getTypeId(), this);
Mutex::Autolock lock(mFrameEventHistoryMutex);
mFrameEventHistory.checkFencesForCompletion();
mFrameEventHistory.dump(result);
@@ -1582,6 +1661,7 @@
}
if (attachChildren()) {
+ Mutex::Autolock lock(mStateMutex);
setTransactionFlags(eTransactionNeeded);
}
for (const sp<Layer>& child : mCurrentChildren) {
@@ -1632,6 +1712,7 @@
client->updateParent(newParent);
}
+ Mutex::Autolock lock(mStateMutex);
if (mLayerDetached) {
mLayerDetached = false;
setTransactionFlags(eTransactionNeeded);
@@ -1675,18 +1756,24 @@
bool Layer::setColorTransform(const mat4& matrix) {
static const mat4 identityMatrix = mat4();
- if (mCurrentState.colorTransform == matrix) {
+ Mutex::Autolock lock(mStateMutex);
+ if (mState.current.colorTransform == matrix) {
return false;
}
- ++mCurrentState.sequence;
- mCurrentState.colorTransform = matrix;
- mCurrentState.hasColorTransform = matrix != identityMatrix;
- mCurrentState.modified = true;
+ ++mState.current.sequence;
+ mState.current.colorTransform = matrix;
+ mState.current.hasColorTransform = matrix != identityMatrix;
+ mState.current.modified = true;
setTransactionFlags(eTransactionNeeded);
return true;
}
mat4 Layer::getColorTransform() const {
+ Mutex::Autolock lock(mStateMutex);
+ return getColorTransformLocked();
+}
+
+mat4 Layer::getColorTransformLocked() const {
mat4 colorTransform = mat4(getDrawingState().colorTransform);
if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
colorTransform = parent->getColorTransform() * colorTransform;
@@ -1695,6 +1782,7 @@
}
bool Layer::hasColorTransform() const {
+ Mutex::Autolock lock(mStateMutex);
bool hasColorTransform = getDrawingState().hasColorTransform;
if (sp<Layer> parent = mDrawingParent.promote(); parent != nullptr) {
hasColorTransform = hasColorTransform || parent->hasColorTransform();
@@ -1725,12 +1813,18 @@
}
int32_t Layer::getZ() const {
- return mDrawingState.z;
+ Mutex::Autolock lock(mStateMutex);
+ return mState.drawing.z;
}
bool Layer::usingRelativeZ(LayerVector::StateSet stateSet) {
+ Mutex::Autolock lock(mStateMutex);
+ return usingRelativeZLocked(stateSet);
+}
+
+bool Layer::usingRelativeZLocked(LayerVector::StateSet stateSet) {
const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
- const State& state = useDrawing ? mDrawingState : mCurrentState;
+ const State& state = useDrawing ? mState.drawing : mState.current;
return state.zOrderRelativeOf != nullptr;
}
@@ -1740,7 +1834,7 @@
"makeTraversalList received invalid stateSet");
const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
- const State& state = useDrawing ? mDrawingState : mCurrentState;
+ const State& state = useDrawing ? mState.drawing : mState.current;
if (state.zOrderRelatives.size() == 0) {
*outSkipRelativeZUsers = true;
@@ -1756,7 +1850,7 @@
}
for (const sp<Layer>& child : children) {
- const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
+ const State& childState = useDrawing ? child->mState.drawing : child->mState.current;
if (childState.zOrderRelativeOf != nullptr) {
continue;
}
@@ -1795,7 +1889,6 @@
visitor(this);
for (; i < list.size(); i++) {
const auto& relative = list[i];
-
if (skipRelativeZUsers && relative->usingRelativeZ(stateSet)) {
continue;
}
@@ -1843,7 +1936,7 @@
"makeTraversalList received invalid stateSet");
const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
- const State& state = useDrawing ? mDrawingState : mCurrentState;
+ const State& state = useDrawing ? mState.drawing : mState.current;
LayerVector traverse(stateSet);
for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
@@ -1856,7 +1949,7 @@
}
for (const sp<Layer>& child : children) {
- const State& childState = useDrawing ? child->mDrawingState : child->mCurrentState;
+ const State& childState = useDrawing ? child->mState.drawing : child->mState.current;
// If a layer has a relativeOf layer, only ignore if the layer it's relative to is a
// descendent of the top most parent of the tree. If it's not a descendent, then just add
// the child here since it won't be added later as a relative.
@@ -1913,10 +2006,16 @@
}
ui::Transform Layer::getTransform() const {
+ Mutex::Autolock lock(mStateMutex);
+ return getTransformLocked();
+}
+
+ui::Transform Layer::getTransformLocked() const {
ui::Transform t;
const auto& p = mDrawingParent.promote();
if (p != nullptr) {
- t = p->getTransform();
+ Mutex::Autolock lock(p->mStateMutex);
+ t = p->getTransformLocked();
// If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
// it isFixedSize) then there may be additional scaling not accounted
@@ -1944,18 +2043,27 @@
}
half Layer::getAlpha() const {
- const auto& p = mDrawingParent.promote();
+ Mutex::Autolock lock(mStateMutex);
+ return getAlphaLocked();
+}
+half Layer::getAlphaLocked() const {
+ const auto& p = mDrawingParent.promote();
half parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0_hf;
return parentAlpha * getDrawingState().color.a;
}
half4 Layer::getColor() const {
const half4 color(getDrawingState().color);
- return half4(color.r, color.g, color.b, getAlpha());
+ return half4(color.r, color.g, color.b, getAlphaLocked());
}
Layer::RoundedCornerState Layer::getRoundedCornerState() const {
+ Mutex::Autolock lock(mStateMutex);
+ return getRoundedCornerStateLocked();
+}
+
+Layer::RoundedCornerState Layer::getRoundedCornerStateLocked() const {
const auto& p = mDrawingParent.promote();
if (p != nullptr) {
RoundedCornerState parentState = p->getRoundedCornerState();
@@ -1972,7 +2080,7 @@
}
}
const float radius = getDrawingState().cornerRadius;
- return radius > 0 ? RoundedCornerState(computeBounds(), radius) : RoundedCornerState();
+ return radius > 0 ? RoundedCornerState(computeBoundsLocked(), radius) : RoundedCornerState();
}
void Layer::commitChildList() {
@@ -1985,19 +2093,21 @@
}
void Layer::setInputInfo(const InputWindowInfo& info) {
- mCurrentState.inputInfo = info;
- mCurrentState.modified = true;
- mCurrentState.inputInfoChanged = true;
+ Mutex::Autolock lock(mStateMutex);
+ mState.current.inputInfo = info;
+ mState.current.modified = true;
+ mState.current.inputInfoChanged = true;
setTransactionFlags(eTransactionNeeded);
}
void Layer::writeToProto(LayerProto* layerInfo, LayerVector::StateSet stateSet) {
+ Mutex::Autolock lock(mStateMutex);
const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
- const State& state = useDrawing ? mDrawingState : mCurrentState;
+ const State& state = useDrawing ? mState.drawing : mState.current;
ui::Transform requestedTransform = state.active_legacy.transform;
- ui::Transform transform = getTransform();
+ ui::Transform transform = getTransformLocked();
layerInfo->set_id(sequence);
layerInfo->set_name(getName().c_str());
@@ -2019,7 +2129,7 @@
LayerProtoHelper::writeToProto(visibleRegion, layerInfo->mutable_visible_region());
LayerProtoHelper::writeToProto(surfaceDamageRegion, layerInfo->mutable_damage_region());
- layerInfo->set_layer_stack(getLayerStack());
+ layerInfo->set_layer_stack(getLayerStackLocked());
layerInfo->set_z(state.z);
PositionProto* position = layerInfo->mutable_position();
@@ -2035,7 +2145,7 @@
size->set_h(state.active_legacy.h);
LayerProtoHelper::writeToProto(state.crop_legacy, layerInfo->mutable_crop());
- layerInfo->set_corner_radius(getRoundedCornerState().radius);
+ layerInfo->set_corner_radius(getRoundedCornerStateLocked().radius);
layerInfo->set_is_opaque(isOpaque(state));
layerInfo->set_invalidate(contentDirty);
@@ -2076,7 +2186,7 @@
layerInfo->set_curr_frame(mCurrentFrameNumber);
layerInfo->set_effective_scaling_mode(getEffectiveScalingMode());
- for (const auto& pendingState : mPendingStates) {
+ for (const auto& pendingState : mState.pending) {
auto barrierLayer = pendingState.barrierLayer_legacy.promote();
if (barrierLayer != nullptr) {
BarrierLayerProto* barrierLayerProto = layerInfo->add_barrier_layer();
@@ -2120,19 +2230,25 @@
}
InputWindowInfo Layer::fillInputInfo(const Rect& screenBounds) {
- InputWindowInfo info = mDrawingState.inputInfo;
+ InputWindowInfo info;
+ ui::Transform t;
+ Rect layerBounds;
+ {
+ Mutex::Autolock lock(mStateMutex);
+ info = mState.drawing.inputInfo;
+ t = getTransformLocked();
+ const float xScale = t.sx();
+ const float yScale = t.sy();
+ if (xScale != 1.0f || yScale != 1.0f) {
+ info.windowXScale *= 1.0f / xScale;
+ info.windowYScale *= 1.0f / yScale;
+ info.touchableRegion.scaleSelf(xScale, yScale);
+ }
- ui::Transform t = getTransform();
- const float xScale = t.sx();
- const float yScale = t.sy();
- if (xScale != 1.0f || yScale != 1.0f) {
- info.windowXScale *= 1.0f / xScale;
- info.windowYScale *= 1.0f / yScale;
- info.touchableRegion.scaleSelf(xScale, yScale);
+ // Transform layer size to screen space and inset it by surface insets.
+ layerBounds = getCroppedBufferSize(getDrawingState());
}
- // Transform layer size to screen space and inset it by surface insets.
- Rect layerBounds = getCroppedBufferSize(getDrawingState());
layerBounds = t.transform(layerBounds);
layerBounds.inset(info.surfaceInset, info.surfaceInset, info.surfaceInset, info.surfaceInset);
@@ -2150,13 +2266,13 @@
// Position the touchable region relative to frame screen location and restrict it to frame
// bounds.
info.touchableRegion = info.touchableRegion.translate(info.frameLeft, info.frameTop);
- info.touchableRegion = info.touchableRegion.intersect(frame);
info.visible = isVisible();
return info;
}
bool Layer::hasInput() const {
- return mDrawingState.inputInfo.token != nullptr;
+ Mutex::Autolock lock(mStateMutex);
+ return mState.drawing.inputInfo.token != nullptr;
}
// ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h
index 6ea80c7..fb75e4c 100644
--- a/services/surfaceflinger/Layer.h
+++ b/services/surfaceflinger/Layer.h
@@ -55,6 +55,7 @@
#include "RenderArea.h"
using namespace android::surfaceflinger;
+using StateSet = android::LayerVector::StateSet;
namespace android {
@@ -239,7 +240,7 @@
// also the rendered size of the layer prior to any transformations. Parent
// or local matrix transformations will not affect the size of the buffer,
// but may affect it's on-screen size or clipping.
- virtual bool setSize(uint32_t w, uint32_t h);
+ virtual bool setSize(uint32_t w, uint32_t h) EXCLUDES(mStateMutex);
// Set a 2x2 transformation matrix on the layer. This transform
// will be applied after parent transforms, but before any final
// producer specified transform.
@@ -254,57 +255,76 @@
// setPosition operates in parent buffer space (pre parent-transform) or display
// space for top-level layers.
- virtual bool setPosition(float x, float y, bool immediate);
+ virtual bool setPosition(float x, float y, bool immediate) EXCLUDES(mStateMutex);
// Buffer space
- virtual bool setCrop_legacy(const Rect& crop, bool immediate);
+ virtual bool setCrop_legacy(const Rect& crop, bool immediate) EXCLUDES(mStateMutex);
// TODO(b/38182121): Could we eliminate the various latching modes by
// using the layer hierarchy?
// -----------------------------------------------------------------------
- virtual bool setLayer(int32_t z);
- virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ);
+ virtual bool setLayer(int32_t z) EXCLUDES(mStateMutex);
+ virtual bool setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t relativeZ)
+ EXCLUDES(mStateMutex);
- virtual bool setAlpha(float alpha);
- virtual bool setColor(const half3& color);
+ virtual bool setAlpha(float alpha) EXCLUDES(mStateMutex);
+ virtual bool setColor(const half3& color) EXCLUDES(mStateMutex);
// Set rounded corner radius for this layer and its children.
//
// We only support 1 radius per layer in the hierarchy, where parent layers have precedence.
// The shape of the rounded corner rectangle is specified by the crop rectangle of the layer
// from which we inferred the rounded corner radius.
- virtual bool setCornerRadius(float cornerRadius);
- virtual bool setTransparentRegionHint(const Region& transparent);
- virtual bool setFlags(uint8_t flags, uint8_t mask);
- virtual bool setLayerStack(uint32_t layerStack);
- virtual uint32_t getLayerStack() const;
+ virtual bool setCornerRadius(float cornerRadius) EXCLUDES(mStateMutex);
+ virtual bool setTransparentRegionHint(const Region& transparent) EXCLUDES(mStateMutex);
+ virtual bool setFlags(uint8_t flags, uint8_t mask) EXCLUDES(mStateMutex);
+ virtual bool setLayerStack(uint32_t layerStack) EXCLUDES(mStateMutex);
+ virtual uint32_t getLayerStack() const EXCLUDES(mStateMutex);
virtual void deferTransactionUntil_legacy(const sp<IBinder>& barrierHandle,
uint64_t frameNumber);
- virtual void deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber);
- virtual bool setOverrideScalingMode(int32_t overrideScalingMode);
- virtual void setInfo(int32_t type, int32_t appId);
- virtual bool reparentChildren(const sp<IBinder>& layer);
+ virtual void deferTransactionUntil_legacy(const sp<Layer>& barrierLayer, uint64_t frameNumber)
+ EXCLUDES(mStateMutex);
+ virtual bool setOverrideScalingMode(int32_t overrideScalingMode) EXCLUDES(mStateMutex);
+ virtual void setInfo(int32_t type, int32_t appId) EXCLUDES(mStateMutex);
+ virtual bool reparentChildren(const sp<IBinder>& layer) EXCLUDES(mStateMutex);
virtual void setChildrenDrawingParent(const sp<Layer>& layer);
- virtual bool reparent(const sp<IBinder>& newParentHandle);
+ virtual bool reparent(const sp<IBinder>& newParentHandle) EXCLUDES(mStateMutex);
virtual bool detachChildren();
bool attachChildren();
bool isLayerDetached() const { return mLayerDetached; }
- virtual bool setColorTransform(const mat4& matrix);
- virtual mat4 getColorTransform() const;
- virtual bool hasColorTransform() const;
+ virtual bool setColorTransform(const mat4& matrix) EXCLUDES(mStateMutex);
+ mat4 getColorTransform() const EXCLUDES(mStateMutex);
+ virtual mat4 getColorTransformLocked() const REQUIRES(mStateMutex);
+ virtual bool hasColorTransform() const EXCLUDES(mStateMutex);
+ ;
// Used only to set BufferStateLayer state
- virtual bool setTransform(uint32_t /*transform*/) { return false; };
- virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/) { return false; };
- virtual bool setCrop(const Rect& /*crop*/) { return false; };
- virtual bool setBuffer(const sp<GraphicBuffer>& /*buffer*/) { return false; };
- virtual bool setAcquireFence(const sp<Fence>& /*fence*/) { return false; };
- virtual bool setDataspace(ui::Dataspace /*dataspace*/) { return false; };
- virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) { return false; };
- virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) { return false; };
- virtual bool setApi(int32_t /*api*/) { return false; };
- virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/) { return false; };
+ virtual bool setTransform(uint32_t /*transform*/) EXCLUDES(mStateMutex) { return false; };
+ virtual bool setTransformToDisplayInverse(bool /*transformToDisplayInverse*/)
+ EXCLUDES(mStateMutex) {
+ return false;
+ };
+ virtual bool setCrop(const Rect& /*crop*/) EXCLUDES(mStateMutex) { return false; };
+ virtual bool setFrame(const Rect& /*frame*/) EXCLUDES(mStateMutex) { return false; };
+ virtual bool setBuffer(const sp<GraphicBuffer>& /*buffer*/) EXCLUDES(mStateMutex) {
+ return false;
+ };
+ virtual bool setAcquireFence(const sp<Fence>& /*fence*/) EXCLUDES(mStateMutex) {
+ return false;
+ };
+ virtual bool setDataspace(ui::Dataspace /*dataspace*/) EXCLUDES(mStateMutex) { return false; };
+ virtual bool setHdrMetadata(const HdrMetadata& /*hdrMetadata*/) EXCLUDES(mStateMutex) {
+ return false;
+ };
+ virtual bool setSurfaceDamageRegion(const Region& /*surfaceDamage*/) EXCLUDES(mStateMutex) {
+ return false;
+ };
+ virtual bool setApi(int32_t /*api*/) EXCLUDES(mStateMutex) { return false; };
+ virtual bool setSidebandStream(const sp<NativeHandle>& /*sidebandStream*/)
+ EXCLUDES(mStateMutex) {
+ return false;
+ };
virtual bool setTransactionCompletedListeners(
- const std::vector<sp<CallbackHandle>>& /*handles*/) {
+ const std::vector<sp<CallbackHandle>>& /*handles*/) EXCLUDES(mStateMutex) {
return false;
};
@@ -323,18 +343,21 @@
virtual void useSurfaceDamage() {}
virtual void useEmptyDamage() {}
- uint32_t getTransactionFlags() const { return mTransactionFlags; }
- uint32_t getTransactionFlags(uint32_t flags);
- uint32_t setTransactionFlags(uint32_t flags);
+ uint32_t getTransactionFlags() const EXCLUDES(mStateMutex);
+ uint32_t getTransactionFlags(uint32_t flags) EXCLUDES(mStateMutex);
+ uint32_t setTransactionFlags(uint32_t flags) REQUIRES(mStateMutex);
- bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const {
+ bool belongsToDisplay(uint32_t layerStack, bool isPrimaryDisplay) const EXCLUDES(mStateMutex) {
return getLayerStack() == layerStack && (!mPrimaryDisplayOnly || isPrimaryDisplay);
}
void computeGeometry(const RenderArea& renderArea, renderengine::Mesh& mesh,
- bool useIdentityTransform) const;
- FloatRect computeBounds(const Region& activeTransparentRegion) const;
- FloatRect computeBounds() const;
+ bool useIdentityTransform) const REQUIRES(mStateMutex);
+ FloatRect computeBounds(const Region& activeTransparentRegion) const EXCLUDES(mStateMutex);
+ FloatRect computeBoundsLocked(const Region& activeTransparentRegion) const
+ REQUIRES(mStateMutex);
+ FloatRect computeBounds() const EXCLUDES(mStateMutex);
+ FloatRect computeBoundsLocked() const REQUIRES(mStateMutex);
int32_t getSequence() const { return sequence; }
@@ -351,16 +374,21 @@
*/
virtual bool isOpaque(const Layer::State&) const { return false; }
+ virtual bool isDrawingOpaque() const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return isOpaque(mState.drawing);
+ }
+
/*
* isSecure - true if this surface is secure, that is if it prevents
* screenshots or VNC servers.
*/
- bool isSecure() const;
+ bool isSecure() const EXCLUDES(mStateMutex);
/*
* isVisible - true if this layer is visible, false otherwise
*/
- virtual bool isVisible() const = 0;
+ virtual bool isVisible() const EXCLUDES(mStateMutex) = 0;
/*
* isHiddenByPolicy - true if this layer has been forced invisible.
@@ -368,7 +396,13 @@
* For example if this layer has no active buffer, it may not be hidden by
* policy, but it still can not be visible.
*/
- bool isHiddenByPolicy() const;
+ bool isHiddenByPolicy() const EXCLUDES(mStateMutex);
+
+ /*
+ * isProtected - true if the layer may contain protected content in the
+ * GRALLOC_USAGE_PROTECTED sense.
+ */
+ virtual bool isProtected() const { return false; }
/*
* isFixedSize - true if content has a fixed size
@@ -383,7 +417,8 @@
bool isRemovedFromCurrentState() const;
void writeToProto(LayerProto* layerInfo,
- LayerVector::StateSet stateSet = LayerVector::StateSet::Drawing);
+ LayerVector::StateSet stateSet = LayerVector::StateSet::Drawing)
+ EXCLUDES(mStateMutex);
void writeToProto(LayerProto* layerInfo, DisplayId displayId);
@@ -396,25 +431,32 @@
virtual Region getActiveTransparentRegion(const Layer::State& s) const {
return s.activeTransparentRegion_legacy;
}
+
+ virtual Region getDrawingActiveTransparentRegion() const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return getActiveTransparentRegion(mState.drawing);
+ }
+
virtual Rect getCrop(const Layer::State& s) const { return s.crop_legacy; }
protected:
/*
* onDraw - draws the surface.
*/
- virtual void onDraw(const RenderArea& renderArea, const Region& clip,
- bool useIdentityTransform) = 0;
+ virtual void onDraw(const RenderArea& renderArea, const Region& clip, bool useIdentityTransform)
+ EXCLUDES(mStateMutex) = 0;
public:
virtual void setDefaultBufferSize(uint32_t /*w*/, uint32_t /*h*/) {}
virtual bool isHdrY410() const { return false; }
- void setGeometry(const sp<const DisplayDevice>& display, uint32_t z);
+ void setGeometry(const sp<const DisplayDevice>& display, uint32_t z) EXCLUDES(mStateMutex);
void forceClientComposition(DisplayId displayId);
bool getForceClientComposition(DisplayId displayId);
virtual void setPerFrameData(DisplayId displayId, const ui::Transform& transform,
- const Rect& viewport, int32_t supportedPerFrameMetadata) = 0;
+ const Rect& viewport, int32_t supportedPerFrameMetadata)
+ EXCLUDES(mStateMutex) = 0;
// callIntoHwc exists so we can update our local state and call
// acceptDisplayChanges without unnecessarily updating the device's state
@@ -422,7 +464,7 @@
HWC2::Composition getCompositionType(const std::optional<DisplayId>& displayId) const;
void setClearClientTarget(DisplayId displayId, bool clear);
bool getClearClientTarget(DisplayId displayId) const;
- void updateCursorPosition(const sp<const DisplayDevice>& display);
+ void updateCursorPosition(const sp<const DisplayDevice>& display) EXCLUDES(mStateMutex);
/*
* called after page-flip
@@ -445,7 +487,8 @@
virtual bool onPostComposition(const std::optional<DisplayId>& /*displayId*/,
const std::shared_ptr<FenceTime>& /*glDoneFence*/,
const std::shared_ptr<FenceTime>& /*presentFence*/,
- const CompositorTiming& /*compositorTiming*/) {
+ const CompositorTiming& /*compositorTiming*/)
+ EXCLUDES(mStateMutex) {
return false;
}
@@ -457,14 +500,14 @@
* draw - performs some global clipping optimizations
* and calls onDraw().
*/
- void draw(const RenderArea& renderArea, const Region& clip);
- void draw(const RenderArea& renderArea, bool useIdentityTransform);
+ void draw(const RenderArea& renderArea, const Region& clip) EXCLUDES(mStateMutex);
+ void draw(const RenderArea& renderArea, bool useIdentityTransform) EXCLUDES(mStateMutex);
/*
* doTransaction - process the transaction. This is a good place to figure
* out which attributes of the surface have changed.
*/
- uint32_t doTransaction(uint32_t transactionFlags);
+ uint32_t doTransaction(uint32_t transactionFlags) EXCLUDES(mStateMutex);
/*
* setVisibleRegion - called to set the new visible region. This gives
@@ -497,17 +540,17 @@
* to figure out if the content or size of a surface has changed.
*/
virtual Region latchBuffer(bool& /*recomputeVisibleRegions*/, nsecs_t /*latchTime*/,
- const sp<Fence>& /*releaseFence*/) {
+ const sp<Fence>& /*releaseFence*/) EXCLUDES(mStateMutex) {
return {};
}
virtual bool isBufferLatched() const { return false; }
/*
- * called with the state lock from a binder thread when the layer is
+ * called with SurfaceFlinger mStateLock a binder thread when the layer is
* removed from the current list to the pending removal list
*/
- void onRemovedFromCurrentState();
+ void onRemovedFromCurrentState() EXCLUDES(mStateMutex);
/*
* Called when the layer is added back to the current state list.
@@ -527,7 +570,7 @@
/*
* Returns if a frame is ready
*/
- virtual bool hasReadyFrame() const { return false; }
+ virtual bool hasReadyFrame() const EXCLUDES(mStateMutex) { return false; }
virtual int32_t getQueuedFrameCount() const { return 0; }
@@ -556,19 +599,34 @@
}
// -----------------------------------------------------------------------
- void clearWithOpenGL(const RenderArea& renderArea) const;
+ void clearWithOpenGL(const RenderArea& renderArea) const EXCLUDES(mStateMutex);
- inline const State& getDrawingState() const { return mDrawingState; }
- inline const State& getCurrentState() const { return mCurrentState; }
- inline State& getCurrentState() { return mCurrentState; }
+ inline const State& getDrawingState() const REQUIRES(mStateMutex) { return mState.drawing; }
- LayerDebugInfo getLayerDebugInfo() const;
+ inline const State& getCurrentState() const REQUIRES(mStateMutex) { return mState.current; }
+
+ inline State& getCurrentState() REQUIRES(mStateMutex) { return mState.current; }
+
+ std::tuple<uint32_t, int32_t> getLayerStackAndZ(StateSet stateSet) EXCLUDES(mStateMutex);
+ wp<Layer> getZOrderRelativeOf(StateSet stateSet) EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ const State& state = (stateSet == StateSet::Current) ? mState.current : mState.drawing;
+
+ return state.zOrderRelativeOf;
+ }
+
+ uint8_t getCurrentFlags() EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return mState.current.flags;
+ }
+
+ LayerDebugInfo getLayerDebugInfo() const EXCLUDES(mStateMutex);
/* always call base class first */
- static void miniDumpHeader(String8& result);
- void miniDump(String8& result, DisplayId displayId) const;
- void dumpFrameStats(String8& result) const;
- void dumpFrameEvents(String8& result);
+ static void miniDumpHeader(std::string& result);
+ void miniDump(std::string& result, DisplayId displayId) const EXCLUDES(mStateMutex);
+ void dumpFrameStats(std::string& result) const;
+ void dumpFrameEvents(std::string& result);
void clearFrameStats();
void logFrameStats();
void getFrameStats(FrameStats* outStats) const;
@@ -581,22 +639,29 @@
void addAndGetFrameTimestamps(const NewFrameEventsEntry* newEntry,
FrameEventHistoryDelta* outDelta);
- virtual bool getTransformToDisplayInverse() const { return false; }
+ bool getTransformToDisplayInverse() const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ return getTransformToDisplayInverseLocked();
+ }
- ui::Transform getTransform() const;
+ virtual bool getTransformToDisplayInverseLocked() const REQUIRES(mStateMutex) { return false; }
+
+ ui::Transform getTransform() const EXCLUDES(mStateMutex);
+ ui::Transform getTransformLocked() const REQUIRES(mStateMutex);
// Returns the Alpha of the Surface, accounting for the Alpha
// of parent Surfaces in the hierarchy (alpha's will be multiplied
// down the hierarchy).
- half getAlpha() const;
- half4 getColor() const;
+ half getAlpha() const EXCLUDES(mStateMutex);
+ half4 getColor() const REQUIRES(mStateMutex);
// Returns how rounded corners should be drawn for this layer.
// This will traverse the hierarchy until it reaches its root, finding topmost rounded
// corner definition and converting it into current layer's coordinates.
// As of now, only 1 corner radius per display list is supported. Subsequent ones will be
// ignored.
- RoundedCornerState getRoundedCornerState() const;
+ RoundedCornerState getRoundedCornerState() const EXCLUDES(mStateMutex);
+ RoundedCornerState getRoundedCornerStateLocked() const REQUIRES(mStateMutex);
void traverseInReverseZOrder(LayerVector::StateSet stateSet,
const LayerVector::Visitor& visitor);
@@ -616,7 +681,7 @@
ssize_t removeChild(const sp<Layer>& layer);
sp<Layer> getParent() const { return mCurrentParent.promote(); }
bool hasParent() const { return getParent() != nullptr; }
- Rect computeScreenBounds() const;
+ Rect computeScreenBounds(bool reduceTransparentRegion = true) const EXCLUDES(mStateMutex);
bool setChildLayer(const sp<Layer>& childLayer, int32_t z);
bool setChildRelativeLayer(const sp<Layer>& childLayer,
const sp<IBinder>& relativeToHandle, int32_t relativeZ);
@@ -624,14 +689,23 @@
// Copy the current list of children to the drawing state. Called by
// SurfaceFlinger to complete a transaction.
void commitChildList();
- int32_t getZ() const;
- virtual void pushPendingState();
+ int32_t getZ() const EXCLUDES(mStateMutex);
+ void pushPendingState() EXCLUDES(mStateMutex);
+ virtual void pushPendingStateLocked() REQUIRES(mStateMutex);
/**
* Returns active buffer size in the correct orientation. Buffer size is determined by undoing
* any buffer transformations. If the layer has no buffer then return INVALID_RECT.
*/
- virtual Rect getBufferSize(const Layer::State&) const { return Rect::INVALID_RECT; }
+ virtual Rect getBufferSize(const Layer::State&) const REQUIRES(mStateMutex) {
+ return Rect::INVALID_RECT;
+ }
+
+ virtual Rect getBufferSize(StateSet stateSet) const EXCLUDES(mStateMutex) {
+ Mutex::Autolock lock(mStateMutex);
+ const State& state = (stateSet == StateSet::Current) ? mState.current : mState.drawing;
+ return getBufferSize(state);
+ }
protected:
// constant
@@ -660,16 +734,17 @@
// For unit tests
friend class TestableSurfaceFlinger;
- void commitTransaction(const State& stateToCommit);
+ void commitTransaction(const State& stateToCommit) REQUIRES(mStateMutex);
uint32_t getEffectiveUsage(uint32_t usage) const;
- virtual FloatRect computeCrop(const sp<const DisplayDevice>& display) const;
+ virtual FloatRect computeCrop(const sp<const DisplayDevice>& display) const
+ REQUIRES(mStateMutex);
// Compute the initial crop as specified by parent layers and the
// SurfaceControl for this layer. Does not include buffer crop from the
// IGraphicBufferProducer client, as that should not affect child clipping.
// Returns in screen space.
- Rect computeInitialCrop(const sp<const DisplayDevice>& display) const;
+ Rect computeInitialCrop(const sp<const DisplayDevice>& display) const REQUIRES(mStateMutex);
/**
* Setup rounded corners coordinates of this layer, taking into account the layer bounds and
* crop coordinates, transforming them into layer space.
@@ -677,13 +752,13 @@
void setupRoundedCornersCropCoordinates(Rect win, const FloatRect& roundedCornersCrop) const;
// drawing
- void clearWithOpenGL(const RenderArea& renderArea, float r, float g, float b,
- float alpha) const;
+ void clearWithOpenGL(const RenderArea& renderArea, float r, float g, float b, float alpha) const
+ EXCLUDES(mStateMutex);
void setParent(const sp<Layer>& layer);
LayerVector makeTraversalList(LayerVector::StateSet stateSet, bool* outSkipRelativeZUsers);
- void addZOrderRelative(const wp<Layer>& relative);
- void removeZOrderRelative(const wp<Layer>& relative);
+ void addZOrderRelative(const wp<Layer>& relative) EXCLUDES(mStateMutex);
+ void removeZOrderRelative(const wp<Layer>& relative) EXCLUDES(mStateMutex);
class SyncPoint {
public:
@@ -719,9 +794,10 @@
// Returns false if the relevant frame has already been latched
bool addSyncPoint(const std::shared_ptr<SyncPoint>& point);
- void popPendingState(State* stateToCommit);
- virtual bool applyPendingStates(State* stateToCommit);
- virtual uint32_t doTransactionResize(uint32_t flags, Layer::State* stateToCommit);
+ void popPendingState(State* stateToCommit) REQUIRES(mStateMutex);
+ virtual bool applyPendingStates(State* stateToCommit) REQUIRES(mStateMutex);
+ virtual uint32_t doTransactionResize(uint32_t flags, Layer::State* stateToCommit)
+ REQUIRES(mStateMutex);
void clearSyncPoints();
@@ -754,14 +830,15 @@
bool getPremultipledAlpha() const;
bool mPendingHWCDestroy{false};
- void setInputInfo(const InputWindowInfo& info);
+ void setInputInfo(const InputWindowInfo& info) EXCLUDES(mStateMutex);
- InputWindowInfo fillInputInfo(const Rect& screenBounds);
- bool hasInput() const;
+ InputWindowInfo fillInputInfo(const Rect& screenBounds) EXCLUDES(mStateMutex);
+ bool hasInput() const EXCLUDES(mStateMutex);
protected:
// -----------------------------------------------------------------------
- bool usingRelativeZ(LayerVector::StateSet stateSet);
+ bool usingRelativeZ(LayerVector::StateSet stateSet) EXCLUDES(mStateMutex);
+ bool usingRelativeZLocked(LayerVector::StateSet stateSet) REQUIRES(mStateMutex);
bool mPremultipliedAlpha{true};
String8 mName;
@@ -769,14 +846,14 @@
bool mPrimaryDisplayOnly = false;
- // these are protected by an external lock
- State mCurrentState;
- State mDrawingState;
- std::atomic<uint32_t> mTransactionFlags{0};
-
// Accessed from main thread and binder threads
- Mutex mPendingStateMutex;
- Vector<State> mPendingStates;
+ mutable Mutex mStateMutex;
+ struct {
+ State current;
+ State drawing;
+ uint32_t transactionFlags{0};
+ Vector<State> pending;
+ } mState GUARDED_BY(mStateMutex);
// Timestamp history for UIAutomation. Thread safe.
FrameTracker mFrameTracker;
@@ -849,7 +926,7 @@
* The cropped bounds must be transformed back from parent layer space to child layer space by
* applying the inverse of the child's transformation.
*/
- FloatRect cropChildBounds(const FloatRect& childBounds) const;
+ FloatRect cropChildBounds(const FloatRect& childBounds) const REQUIRES(mStateMutex);
/**
* Returns the cropped buffer size or the layer crop if the layer has no buffer. Return
@@ -857,7 +934,12 @@
* A layer with an invalid buffer size and no crop is considered to be boundless. The layer
* bounds are constrained by its parent bounds.
*/
- Rect getCroppedBufferSize(const Layer::State& s) const;
+ Rect getCroppedBufferSize(const Layer::State& s) const REQUIRES(mStateMutex);
+
+ // locked version of public methods
+ bool isSecureLocked() const REQUIRES(mStateMutex);
+ virtual uint32_t getLayerStackLocked() const REQUIRES(mStateMutex);
+ half getAlphaLocked() const REQUIRES(mStateMutex);
};
} // namespace android
diff --git a/services/surfaceflinger/LayerBE.cpp b/services/surfaceflinger/LayerBE.cpp
index 70b00dd..e39babe 100644
--- a/services/surfaceflinger/LayerBE.cpp
+++ b/services/surfaceflinger/LayerBE.cpp
@@ -101,15 +101,8 @@
result += base::StringPrintf("\tsourceCrop=%6.1f %6.1f %6.1f %6.1f\n", hwc.sourceCrop.left,
hwc.sourceCrop.top, hwc.sourceCrop.right, hwc.sourceCrop.bottom);
- {
- //
- // Keep a conversion from std::string to String8 and back until Region can use std::string
- //
- String8 regionString;
- hwc.visibleRegion.dump(regionString, "visibleRegion");
- hwc.surfaceDamage.dump(regionString, "surfaceDamage");
- result += regionString.string();
- }
+ hwc.visibleRegion.dump(result, "visibleRegion");
+ hwc.surfaceDamage.dump(result, "surfaceDamage");
result += base::StringPrintf("\tcolor transform matrix:\n"
"\t\t[%f, %f, %f, %f,\n"
diff --git a/services/surfaceflinger/LayerStats.cpp b/services/surfaceflinger/LayerStats.cpp
index c0174ae..a2d1feb 100644
--- a/services/surfaceflinger/LayerStats.cpp
+++ b/services/surfaceflinger/LayerStats.cpp
@@ -23,11 +23,13 @@
#include <android-base/stringprintf.h>
#include <log/log.h>
-#include <utils/String8.h>
#include <utils/Trace.h>
namespace android {
+using base::StringAppendF;
+using base::StringPrintf;
+
void LayerStats::enable() {
ATRACE_CALL();
std::lock_guard<std::mutex> lock(mMutex);
@@ -64,26 +66,24 @@
if (!layer) continue;
traverseLayerTreeStatsLocked(layer->children, layerGlobal, outLayerShapeVec);
std::string key = "";
- base::StringAppendF(&key, ",%s", layer->type.c_str());
- base::StringAppendF(&key, ",%s", layerCompositionType(layer->hwcCompositionType));
- base::StringAppendF(&key, ",%d", layer->isProtected);
- base::StringAppendF(&key, ",%s", layerTransform(layer->hwcTransform));
- base::StringAppendF(&key, ",%s", layerPixelFormat(layer->activeBuffer.format).c_str());
- base::StringAppendF(&key, ",%s", layer->dataspace.c_str());
- base::StringAppendF(&key, ",%s",
- destinationLocation(layer->hwcFrame.left, layerGlobal.resolution[0],
- true));
- base::StringAppendF(&key, ",%s",
- destinationLocation(layer->hwcFrame.top, layerGlobal.resolution[1],
- false));
- base::StringAppendF(&key, ",%s",
- destinationSize(layer->hwcFrame.right - layer->hwcFrame.left,
- layerGlobal.resolution[0], true));
- base::StringAppendF(&key, ",%s",
- destinationSize(layer->hwcFrame.bottom - layer->hwcFrame.top,
- layerGlobal.resolution[1], false));
- base::StringAppendF(&key, ",%s", scaleRatioWH(layer).c_str());
- base::StringAppendF(&key, ",%s", alpha(static_cast<float>(layer->color.a)));
+ StringAppendF(&key, ",%s", layer->type.c_str());
+ StringAppendF(&key, ",%s", layerCompositionType(layer->hwcCompositionType));
+ StringAppendF(&key, ",%d", layer->isProtected);
+ StringAppendF(&key, ",%s", layerTransform(layer->hwcTransform));
+ StringAppendF(&key, ",%s", layerPixelFormat(layer->activeBuffer.format).c_str());
+ StringAppendF(&key, ",%s", layer->dataspace.c_str());
+ StringAppendF(&key, ",%s",
+ destinationLocation(layer->hwcFrame.left, layerGlobal.resolution[0], true));
+ StringAppendF(&key, ",%s",
+ destinationLocation(layer->hwcFrame.top, layerGlobal.resolution[1], false));
+ StringAppendF(&key, ",%s",
+ destinationSize(layer->hwcFrame.right - layer->hwcFrame.left,
+ layerGlobal.resolution[0], true));
+ StringAppendF(&key, ",%s",
+ destinationSize(layer->hwcFrame.bottom - layer->hwcFrame.top,
+ layerGlobal.resolution[1], false));
+ StringAppendF(&key, ",%s", scaleRatioWH(layer).c_str());
+ StringAppendF(&key, ",%s", alpha(static_cast<float>(layer->color.a)));
outLayerShapeVec->push_back(key);
ALOGV("%s", key.c_str());
@@ -101,9 +101,9 @@
traverseLayerTreeStatsLocked(layerTree.topLevelLayers, layerGlobal, &layerShapeVec);
std::string layerShapeKey =
- base::StringPrintf("%d,%s,%s,%s", static_cast<int32_t>(layerShapeVec.size()),
- layerGlobal.colorMode.c_str(), layerGlobal.colorTransform.c_str(),
- layerTransform(layerGlobal.globalTransform));
+ StringPrintf("%d,%s,%s,%s", static_cast<int32_t>(layerShapeVec.size()),
+ layerGlobal.colorMode.c_str(), layerGlobal.colorTransform.c_str(),
+ layerTransform(layerGlobal.globalTransform));
ALOGV("%s", layerShapeKey.c_str());
std::sort(layerShapeVec.begin(), layerShapeVec.end(), std::greater<std::string>());
@@ -114,7 +114,7 @@
mLayerShapeStatsMap[layerShapeKey]++;
}
-void LayerStats::dump(String8& result) {
+void LayerStats::dump(std::string& result) {
ATRACE_CALL();
ALOGD("Dumping");
std::lock_guard<std::mutex> lock(mMutex);
@@ -122,7 +122,7 @@
result.append("LayerType,CompositionType,IsProtected,Transform,PixelFormat,Dataspace,");
result.append("DstX,DstY,DstWidth,DstHeight,WScale,HScale,Alpha\n");
for (auto& u : mLayerShapeStatsMap) {
- result.appendFormat("%u,%s\n", u.second, u.first.c_str());
+ StringAppendF(&result, "%u,%s\n", u.second, u.first.c_str());
}
}
diff --git a/services/surfaceflinger/LayerStats.h b/services/surfaceflinger/LayerStats.h
index 9de9cce..62b2688 100644
--- a/services/surfaceflinger/LayerStats.h
+++ b/services/surfaceflinger/LayerStats.h
@@ -24,7 +24,6 @@
using namespace android::surfaceflinger;
namespace android {
-class String8;
class LayerStats {
public:
@@ -33,7 +32,7 @@
void clear();
bool isEnabled();
void logLayerStats(const LayersProto& layersProto);
- void dump(String8& result);
+ void dump(std::string& result);
private:
// Traverse layer tree to get all visible layers' stats
diff --git a/services/surfaceflinger/LayerVector.cpp b/services/surfaceflinger/LayerVector.cpp
index 8494524..a7db23e 100644
--- a/services/surfaceflinger/LayerVector.cpp
+++ b/services/surfaceflinger/LayerVector.cpp
@@ -38,18 +38,12 @@
const auto& l = *reinterpret_cast<const sp<Layer>*>(lhs);
const auto& r = *reinterpret_cast<const sp<Layer>*>(rhs);
- const auto& lState =
- (mStateSet == StateSet::Current) ? l->getCurrentState() : l->getDrawingState();
- const auto& rState =
- (mStateSet == StateSet::Current) ? r->getCurrentState() : r->getDrawingState();
+ const auto& [ls, lz] = l->getLayerStackAndZ(mStateSet);
+ const auto& [rs, rz] = r->getLayerStackAndZ(mStateSet);
- uint32_t ls = lState.layerStack;
- uint32_t rs = rState.layerStack;
if (ls != rs)
return (ls > rs) ? 1 : -1;
- int32_t lz = lState.z;
- int32_t rz = rState.z;
if (lz != rz)
return (lz > rz) ? 1 : -1;
@@ -62,9 +56,8 @@
void LayerVector::traverseInZOrder(StateSet stateSet, const Visitor& visitor) const {
for (size_t i = 0; i < size(); i++) {
const auto& layer = (*this)[i];
- auto& state = (stateSet == StateSet::Current) ? layer->getCurrentState()
- : layer->getDrawingState();
- if (state.zOrderRelativeOf != nullptr) {
+ auto zOrderRelativeOf = layer->getZOrderRelativeOf(stateSet);
+ if (zOrderRelativeOf != nullptr) {
continue;
}
layer->traverseInZOrder(stateSet, visitor);
@@ -74,9 +67,8 @@
void LayerVector::traverseInReverseZOrder(StateSet stateSet, const Visitor& visitor) const {
for (auto i = static_cast<int64_t>(size()) - 1; i >= 0; i--) {
const auto& layer = (*this)[i];
- auto& state = (stateSet == StateSet::Current) ? layer->getCurrentState()
- : layer->getDrawingState();
- if (state.zOrderRelativeOf != nullptr) {
+ auto zOrderRelativeOf = layer->getZOrderRelativeOf(stateSet);
+ if (zOrderRelativeOf != nullptr) {
continue;
}
layer->traverseInReverseZOrder(stateSet, visitor);
diff --git a/services/surfaceflinger/Scheduler/DispSync.cpp b/services/surfaceflinger/Scheduler/DispSync.cpp
index 172c418..b74b901 100644
--- a/services/surfaceflinger/Scheduler/DispSync.cpp
+++ b/services/surfaceflinger/Scheduler/DispSync.cpp
@@ -24,9 +24,9 @@
#include <algorithm>
-#include <log/log.h>
+#include <android-base/stringprintf.h>
#include <cutils/properties.h>
-#include <utils/String8.h>
+#include <log/log.h>
#include <utils/Thread.h>
#include <utils/Trace.h>
@@ -36,6 +36,7 @@
#include "EventLog/EventLog.h"
#include "SurfaceFlinger.h"
+using android::base::StringAppendF;
using std::max;
using std::min;
@@ -667,54 +668,56 @@
}
}
-void DispSync::dump(String8& result) const {
+void DispSync::dump(std::string& result) const {
Mutex::Autolock lock(mMutex);
- result.appendFormat("present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
- result.appendFormat("mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
- 1000000000.0 / mPeriod, mRefreshSkipCount);
- result.appendFormat("mPhase: %" PRId64 " ns\n", mPhase);
- result.appendFormat("mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
- result.appendFormat("mNumResyncSamplesSincePresent: %d (limit %d)\n",
- mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
- result.appendFormat("mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples, MAX_RESYNC_SAMPLES);
+ StringAppendF(&result, "present fences are %s\n", mIgnorePresentFences ? "ignored" : "used");
+ StringAppendF(&result, "mPeriod: %" PRId64 " ns (%.3f fps; skipCount=%d)\n", mPeriod,
+ 1000000000.0 / mPeriod, mRefreshSkipCount);
+ StringAppendF(&result, "mPhase: %" PRId64 " ns\n", mPhase);
+ StringAppendF(&result, "mError: %" PRId64 " ns (sqrt=%.1f)\n", mError, sqrt(mError));
+ StringAppendF(&result, "mNumResyncSamplesSincePresent: %d (limit %d)\n",
+ mNumResyncSamplesSincePresent, MAX_RESYNC_SAMPLES_WITHOUT_PRESENT);
+ StringAppendF(&result, "mNumResyncSamples: %zd (max %d)\n", mNumResyncSamples,
+ MAX_RESYNC_SAMPLES);
- result.appendFormat("mResyncSamples:\n");
+ result.append("mResyncSamples:\n");
nsecs_t previous = -1;
for (size_t i = 0; i < mNumResyncSamples; i++) {
size_t idx = (mFirstResyncSample + i) % MAX_RESYNC_SAMPLES;
nsecs_t sampleTime = mResyncSamples[idx];
if (i == 0) {
- result.appendFormat(" %" PRId64 "\n", sampleTime);
+ StringAppendF(&result, " %" PRId64 "\n", sampleTime);
} else {
- result.appendFormat(" %" PRId64 " (+%" PRId64 ")\n", sampleTime,
- sampleTime - previous);
+ StringAppendF(&result, " %" PRId64 " (+%" PRId64 ")\n", sampleTime,
+ sampleTime - previous);
}
previous = sampleTime;
}
- result.appendFormat("mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
+ StringAppendF(&result, "mPresentFences [%d]:\n", NUM_PRESENT_SAMPLES);
nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
previous = Fence::SIGNAL_TIME_INVALID;
for (size_t i = 0; i < NUM_PRESENT_SAMPLES; i++) {
size_t idx = (i + mPresentSampleOffset) % NUM_PRESENT_SAMPLES;
nsecs_t presentTime = mPresentFences[idx]->getSignalTime();
if (presentTime == Fence::SIGNAL_TIME_PENDING) {
- result.appendFormat(" [unsignaled fence]\n");
+ StringAppendF(&result, " [unsignaled fence]\n");
} else if (presentTime == Fence::SIGNAL_TIME_INVALID) {
- result.appendFormat(" [invalid fence]\n");
+ StringAppendF(&result, " [invalid fence]\n");
} else if (previous == Fence::SIGNAL_TIME_PENDING ||
previous == Fence::SIGNAL_TIME_INVALID) {
- result.appendFormat(" %" PRId64 " (%.3f ms ago)\n", presentTime,
- (now - presentTime) / 1000000.0);
+ StringAppendF(&result, " %" PRId64 " (%.3f ms ago)\n", presentTime,
+ (now - presentTime) / 1000000.0);
} else {
- result.appendFormat(" %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n", presentTime,
- presentTime - previous, (presentTime - previous) / (double)mPeriod,
- (now - presentTime) / 1000000.0);
+ StringAppendF(&result, " %" PRId64 " (+%" PRId64 " / %.3f) (%.3f ms ago)\n",
+ presentTime, presentTime - previous,
+ (presentTime - previous) / (double)mPeriod,
+ (now - presentTime) / 1000000.0);
}
previous = presentTime;
}
- result.appendFormat("current monotonic time: %" PRId64 "\n", now);
+ StringAppendF(&result, "current monotonic time: %" PRId64 "\n", now);
}
// TODO(b/113612090): Figure out how much of this is still relevant.
diff --git a/services/surfaceflinger/Scheduler/DispSync.h b/services/surfaceflinger/Scheduler/DispSync.h
index 5d19093..4a90f10 100644
--- a/services/surfaceflinger/Scheduler/DispSync.h
+++ b/services/surfaceflinger/Scheduler/DispSync.h
@@ -29,7 +29,6 @@
namespace android {
-class String8;
class FenceTime;
class DispSync {
@@ -57,7 +56,7 @@
virtual void setIgnorePresentFences(bool ignore) = 0;
virtual nsecs_t expectedPresentTime() = 0;
- virtual void dump(String8& result) const = 0;
+ virtual void dump(std::string& result) const = 0;
};
namespace impl {
@@ -161,7 +160,7 @@
nsecs_t expectedPresentTime();
// dump appends human-readable debug info to the result string.
- void dump(String8& result) const override;
+ void dump(std::string& result) const override;
private:
void updateModelLocked();
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index 9bee9a3..1f08f4e 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -22,18 +22,20 @@
#include <chrono>
#include <cstdint>
+#include <android-base/stringprintf.h>
+
#include <cutils/compiler.h>
#include <cutils/sched_policy.h>
#include <gui/DisplayEventReceiver.h>
#include <utils/Errors.h>
-#include <utils/String8.h>
#include <utils/Trace.h>
#include "EventThread.h"
using namespace std::chrono_literals;
+using android::base::StringAppendF;
// ---------------------------------------------------------------------------
@@ -46,10 +48,14 @@
namespace impl {
EventThread::EventThread(std::unique_ptr<VSyncSource> src,
- ResyncWithRateLimitCallback resyncWithRateLimitCallback,
- InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
+ const ResyncWithRateLimitCallback& resyncWithRateLimitCallback,
+ const InterceptVSyncsCallback& interceptVSyncsCallback,
+ const ResetIdleTimerCallback& resetIdleTimerCallback,
+ const char* threadName)
: EventThread(nullptr, std::move(src), resyncWithRateLimitCallback, interceptVSyncsCallback,
- threadName) {}
+ threadName) {
+ mResetIdleTimer = resetIdleTimerCallback;
+}
EventThread::EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
@@ -148,6 +154,9 @@
void EventThread::requestNextVsync(const sp<EventThread::Connection>& connection) {
std::lock_guard<std::mutex> lock(mMutex);
+ if (mResetIdleTimer) {
+ mResetIdleTimer();
+ }
if (mResyncWithRateLimitCallback) {
mResyncWithRateLimitCallback();
@@ -384,18 +393,18 @@
}
}
-void EventThread::dump(String8& result) const {
+void EventThread::dump(std::string& result) const {
std::lock_guard<std::mutex> lock(mMutex);
- result.appendFormat("VSYNC state: %s\n", mDebugVsyncEnabled ? "enabled" : "disabled");
- result.appendFormat(" soft-vsync: %s\n", mUseSoftwareVSync ? "enabled" : "disabled");
- result.appendFormat(" numListeners=%zu,\n events-delivered: %u\n",
- mDisplayEventConnections.size(), mVSyncEvent[0].vsync.count);
+ StringAppendF(&result, "VSYNC state: %s\n", mDebugVsyncEnabled ? "enabled" : "disabled");
+ StringAppendF(&result, " soft-vsync: %s\n", mUseSoftwareVSync ? "enabled" : "disabled");
+ StringAppendF(&result, " numListeners=%zu,\n events-delivered: %u\n",
+ mDisplayEventConnections.size(), mVSyncEvent[0].vsync.count);
for (const wp<Connection>& weak : mDisplayEventConnections) {
sp<Connection> connection = weak.promote();
- result.appendFormat(" %p: count=%d\n", connection.get(),
- connection != nullptr ? connection->count : 0);
+ StringAppendF(&result, " %p: count=%d\n", connection.get(),
+ connection != nullptr ? connection->count : 0);
}
- result.appendFormat(" other-events-pending: %zu\n", mPendingEvents.size());
+ StringAppendF(&result, " other-events-pending: %zu\n", mPendingEvents.size());
}
// ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h
index 5e7ed13..0773c05 100644
--- a/services/surfaceflinger/Scheduler/EventThread.h
+++ b/services/surfaceflinger/Scheduler/EventThread.h
@@ -40,7 +40,6 @@
class EventThreadTest;
class SurfaceFlinger;
-class String8;
// ---------------------------------------------------------------------------
@@ -76,7 +75,7 @@
// called when receiving a hotplug event
virtual void onHotplugReceived(DisplayType displayType, bool connected) = 0;
- virtual void dump(String8& result) const = 0;
+ virtual void dump(std::string& result) const = 0;
virtual void setPhaseOffset(nsecs_t phaseOffset) = 0;
};
@@ -108,13 +107,15 @@
public:
using ResyncWithRateLimitCallback = std::function<void()>;
using InterceptVSyncsCallback = std::function<void(nsecs_t)>;
+ using ResetIdleTimerCallback = std::function<void()>;
// TODO(b/113612090): Once the Scheduler is complete this constructor will become obsolete.
EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
EventThread(std::unique_ptr<VSyncSource> src,
- ResyncWithRateLimitCallback resyncWithRateLimitCallback,
- InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
+ const ResyncWithRateLimitCallback& resyncWithRateLimitCallback,
+ const InterceptVSyncsCallback& interceptVSyncsCallback,
+ const ResetIdleTimerCallback& resetIdleTimerCallback, const char* threadName);
~EventThread();
sp<BnDisplayEventConnection> createEventConnection() const override;
@@ -131,7 +132,7 @@
// called when receiving a hotplug event
void onHotplugReceived(DisplayType displayType, bool connected) override;
- void dump(String8& result) const override;
+ void dump(std::string& result) const override;
void setPhaseOffset(nsecs_t phaseOffset) override;
@@ -178,6 +179,9 @@
// for debugging
bool mDebugVsyncEnabled GUARDED_BY(mMutex) = false;
+
+ // Callback that resets the idle timer when the next vsync is received.
+ ResetIdleTimerCallback mResetIdleTimer;
};
// ---------------------------------------------------------------------------
diff --git a/services/surfaceflinger/Scheduler/IdleTimer.cpp b/services/surfaceflinger/Scheduler/IdleTimer.cpp
new file mode 100644
index 0000000..5a76dbc
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/IdleTimer.cpp
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2018 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 "IdleTimer.h"
+
+#include <chrono>
+#include <thread>
+
+namespace android {
+namespace scheduler {
+
+IdleTimer::IdleTimer(const Interval& interval, const TimeoutCallback& timeoutCallback)
+ : mInterval(interval), mTimeoutCallback(timeoutCallback) {}
+
+IdleTimer::~IdleTimer() {
+ stop();
+}
+
+void IdleTimer::start() {
+ {
+ std::lock_guard<std::mutex> lock(mMutex);
+ mState = TimerState::RESET;
+ }
+ mThread = std::thread(&IdleTimer::loop, this);
+}
+
+void IdleTimer::stop() {
+ {
+ std::lock_guard<std::mutex> lock(mMutex);
+ mState = TimerState::STOPPED;
+ }
+ mCondition.notify_all();
+ if (mThread.joinable()) {
+ mThread.join();
+ }
+}
+
+void IdleTimer::loop() {
+ std::lock_guard<std::mutex> lock(mMutex);
+ while (mState != TimerState::STOPPED) {
+ if (mState == TimerState::IDLE) {
+ mCondition.wait(mMutex);
+ } else if (mState == TimerState::RESET) {
+ mState = TimerState::WAITING;
+ if (mCondition.wait_for(mMutex, mInterval) == std::cv_status::timeout) {
+ if (mTimeoutCallback) {
+ mTimeoutCallback();
+ }
+ }
+ if (mState == TimerState::WAITING) {
+ mState = TimerState::IDLE;
+ }
+ }
+ }
+}
+
+void IdleTimer::reset() {
+ {
+ std::lock_guard<std::mutex> lock(mMutex);
+ mState = TimerState::RESET;
+ }
+ mCondition.notify_all();
+}
+
+} // namespace scheduler
+} // namespace android
diff --git a/services/surfaceflinger/Scheduler/IdleTimer.h b/services/surfaceflinger/Scheduler/IdleTimer.h
new file mode 100644
index 0000000..aee3fa3
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/IdleTimer.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2018 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 <chrono>
+#include <condition_variable>
+#include <thread>
+
+#include <android-base/thread_annotations.h>
+
+namespace android {
+namespace scheduler {
+
+/*
+ * Class that sets off a timer for a given interval, and fires a callback when the
+ * interval expires.
+ */
+class IdleTimer {
+public:
+ using Interval = std::chrono::milliseconds;
+ using TimeoutCallback = std::function<void()>;
+
+ IdleTimer(const Interval& interval, const TimeoutCallback& timeoutCallback);
+ ~IdleTimer();
+
+ void start();
+ void stop();
+ void reset();
+
+private:
+ // Enum to track in what state is the timer.
+ enum class TimerState { STOPPED = 0, RESET = 1, WAITING = 2, IDLE = 3 };
+
+ // Function that loops until the condition for stopping is met.
+ void loop();
+
+ // Thread waiting for timer to expire.
+ std::thread mThread;
+
+ // Condition used to notify mThread.
+ std::condition_variable_any mCondition;
+
+ // Lock used for synchronizing the waiting thread with the application thread.
+ std::mutex mMutex;
+
+ TimerState mState GUARDED_BY(mMutex) = TimerState::RESET;
+
+ // Interval after which timer expires.
+ const Interval mInterval;
+
+ // Callback that happens when timer expires.
+ const TimeoutCallback mTimeoutCallback;
+};
+
+} // namespace scheduler
+} // namespace android
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
index 4457f72..fad56e6 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.cpp
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -29,6 +29,7 @@
#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
#include <configstore/Utils.h>
+#include <cutils/properties.h>
#include <gui/ISurfaceComposer.h>
#include <ui/DisplayStatInfo.h>
#include <utils/Timers.h>
@@ -38,6 +39,7 @@
#include "DispSyncSource.h"
#include "EventControlThread.h"
#include "EventThread.h"
+#include "IdleTimer.h"
#include "InjectVSyncSource.h"
#include "SchedulerUtils.h"
@@ -68,6 +70,17 @@
primaryDispSync->init(mHasSyncFramework, mDispSyncPresentTimeOffset);
mPrimaryDispSync = std::move(primaryDispSync);
mEventControlThread = std::make_unique<impl::EventControlThread>(function);
+
+ char value[PROPERTY_VALUE_MAX];
+ property_get("debug.sf.set_idle_timer_ms", value, "0");
+ mSetIdleTimerMs = atoi(value);
+
+ if (mSetIdleTimerMs > 0) {
+ mIdleTimer =
+ std::make_unique<scheduler::IdleTimer>(std::chrono::milliseconds(mSetIdleTimerMs),
+ [this] { expiredTimerCallback(); });
+ mIdleTimer->start();
+ }
}
Scheduler::~Scheduler() = default;
@@ -98,7 +111,8 @@
std::make_unique<DispSyncSource>(dispSync, phaseOffsetNs, true, sourceName.c_str());
const std::string threadName = connectionName + "Thread";
return std::make_unique<impl::EventThread>(std::move(eventThreadSource), resyncCallback,
- interceptCallback, threadName.c_str());
+ interceptCallback, [this] { resetIdleTimer(); },
+ threadName.c_str());
}
sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
@@ -133,7 +147,7 @@
mConnections[handle->id]->thread->onScreenReleased();
}
-void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, String8& result) const {
+void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, std::string& result) const {
RETURN_IF_INVALID();
mConnections.at(handle->id)->thread->dump(result);
}
@@ -309,4 +323,18 @@
}
}
+void Scheduler::resetIdleTimer() {
+ if (mIdleTimer) {
+ mIdleTimer->reset();
+ ATRACE_INT("ExpiredIdleTimer", 0);
+ }
+}
+
+void Scheduler::expiredTimerCallback() {
+ // TODO(b/113612090): Each time a timer expired, we should record the information into
+ // a circular buffer. Once this has happened a given amount (TBD) of times, we can comfortably
+ // say that the device is sitting in idle.
+ ATRACE_INT("ExpiredIdleTimer", 1);
+}
+
} // namespace android
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index 764ad00..8d4514b 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -25,6 +25,7 @@
#include "DispSync.h"
#include "EventControlThread.h"
#include "EventThread.h"
+#include "IdleTimer.h"
#include "InjectVSyncSource.h"
#include "LayerHistory.h"
#include "SchedulerUtils.h"
@@ -91,7 +92,7 @@
void onScreenReleased(const sp<ConnectionHandle>& handle);
// Should be called when dumpsys command is received.
- void dump(const sp<ConnectionHandle>& handle, String8& result) const;
+ void dump(const sp<ConnectionHandle>& handle, std::string& result) const;
// Offers ability to modify phase offset in the event thread.
void setPhaseOffset(const sp<ConnectionHandle>& handle, nsecs_t phaseOffset);
@@ -126,6 +127,10 @@
// Collects the average difference between timestamps for each frame regardless
// of which layer the timestamp came from.
void determineTimestampAverage(bool isAutoTimestamp, const nsecs_t framePresentTime);
+ // Function that resets the idle timer.
+ void resetIdleTimer();
+ // Function that is called when the timer expires.
+ void expiredTimerCallback();
// TODO(b/113612090): Instead of letting BufferQueueLayer to access mDispSync directly, it
// should make request to Scheduler to compute next refresh.
@@ -163,6 +168,11 @@
size_t mCounter = 0;
LayerHistory mLayerHistory;
+
+ // Timer that records time between requests for next vsync. If the time is higher than a given
+ // interval, a callback is fired. Set this variable to >0 to use this feature.
+ int64_t mSetIdleTimerMs = 0;
+ std::unique_ptr<scheduler::IdleTimer> mIdleTimer;
};
} // namespace android
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 0bda020..4a93be6 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -113,6 +113,7 @@
using namespace android::hardware::configstore;
using namespace android::hardware::configstore::V1_0;
+using base::StringAppendF;
using ui::ColorMode;
using ui::Dataspace;
using ui::Hdr;
@@ -378,7 +379,7 @@
mUseHwcVirtualDisplays = atoi(value);
ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
- property_get("ro.sf.disable_triple_buffer", value, "1");
+ property_get("ro.sf.disable_triple_buffer", value, "0");
mLayerTripleBufferingDisabled = atoi(value);
ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
@@ -733,24 +734,6 @@
ALOGE("Run StartPropertySetThread failed!");
}
- // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
- // is used to saturate legacy sRGB content. However, to make sure the same color under
- // Display P3 will be saturated to the same color, we intentionally break the API spec
- // and apply this saturation matrix on Display P3 content. Unless the risk of applying
- // such saturation matrix on Display P3 is understood fully, the API should always return
- // identify matrix.
- mEnhancedSaturationMatrix =
- getHwComposer().getDataspaceSaturationMatrix(*display->getId(), Dataspace::SRGB_LINEAR);
-
- // we will apply this on Display P3.
- if (mEnhancedSaturationMatrix != mat4()) {
- ColorSpace srgb(ColorSpace::sRGB());
- ColorSpace displayP3(ColorSpace::DisplayP3());
- mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
- mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
- mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
- }
-
ALOGV("Done initializing");
}
@@ -1145,6 +1128,19 @@
componentMask, maxFrames);
}
+status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
+ uint64_t maxFrames, uint64_t timestamp,
+ DisplayedFrameStats* outStats) const {
+ const auto display = getDisplayDevice(displayToken);
+ if (!display || !display->getId()) {
+ ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
+ return BAD_VALUE;
+ }
+
+ return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
+ outStats);
+}
+
status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
postMessageSync(new LambdaMessage([&] {
Mutex::Autolock _l(mStateLock);
@@ -1498,7 +1494,7 @@
// Re-enable default display.
display = getDefaultDisplayDeviceLocked();
LOG_ALWAYS_FATAL_IF(!display);
- setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
+ setPowerModeInternal(display, currentDisplayPowerMode);
// Reset the timing values to account for the period of the swapped in HWC
const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
@@ -2092,7 +2088,7 @@
// - Dataspace::BT2020_PQ
Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
Dataspace* outHdrDataSpace) const {
- Dataspace bestDataSpace = Dataspace::SRGB;
+ Dataspace bestDataSpace = Dataspace::V0_SRGB;
*outHdrDataSpace = Dataspace::UNKNOWN;
for (const auto& layer : display->getVisibleLayersSortedByZ()) {
@@ -2362,6 +2358,7 @@
const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
const sp<IGraphicBufferProducer>& producer) {
DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
+ creationArgs.sequenceId = state.sequenceId;
creationArgs.isVirtual = state.isVirtual();
creationArgs.isSecure = state.isSecure;
creationArgs.displaySurface = dispSurface;
@@ -2417,7 +2414,7 @@
Dataspace defaultDataSpace = Dataspace::UNKNOWN;
if (display->hasWideColorGamut()) {
defaultColorMode = ColorMode::SRGB;
- defaultDataSpace = Dataspace::SRGB;
+ defaultDataSpace = Dataspace::V0_SRGB;
}
setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
RenderIntent::COLORIMETRIC);
@@ -2739,7 +2736,7 @@
commitTransaction();
- if ((inputChanged || mVisibleRegionsDirty) && mInputFlinger) {
+ if (inputChanged || mVisibleRegionsDirty) {
updateInputWindows();
}
@@ -2749,11 +2746,18 @@
void SurfaceFlinger::updateInputWindows() {
ATRACE_CALL();
+ if (mInputFlinger == nullptr) {
+ return;
+ }
+
Vector<InputWindowInfo> inputHandles;
mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
if (layer->hasInput()) {
- inputHandles.add(layer->fillInputInfo(layer->computeScreenBounds()));
+ // When calculating the screen bounds we ignore the transparent region since it may
+ // result in an unwanted offset.
+ inputHandles.add(layer->fillInputInfo(
+ layer->computeScreenBounds(false /* reduceTransparentRegion */)));
}
});
mInputFlinger->setInputWindows(inputHandles);
@@ -2833,9 +2837,6 @@
outDirtyRegion.clear();
mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
- // start with the whole surface at its current location
- const Layer::State& s(layer->getDrawingState());
-
// only consider the layers on the given layer stack
if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
return;
@@ -2873,7 +2874,7 @@
// handle hidden surfaces by setting the visible region to empty
if (CC_LIKELY(layer->isVisible())) {
- const bool translucent = !layer->isOpaque(s);
+ const bool translucent = !layer->isDrawingOpaque();
Rect bounds(layer->computeScreenBounds());
visibleRegion.set(bounds);
@@ -2883,7 +2884,8 @@
if (translucent) {
if (tr.preserveRects()) {
// transform the transparent region
- transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
+ transparentRegion =
+ tr.transform(layer->getDrawingActiveTransparentRegion());
} else {
// transformation too complex, can't do the
// transparent region optimization.
@@ -3017,6 +3019,11 @@
mVisibleRegionsDirty |= visibleRegions;
+ if (visibleRegions) {
+ // Update input window info if the layer receives its first buffer.
+ updateInputWindows();
+ }
+
// If we will need to wake up at some time in the future to deal with a
// queued frame that shouldn't be displayed during this vsync period, wake
// up during the next vsync period to check again.
@@ -3068,7 +3075,6 @@
mat4 colorMatrix;
bool applyColorMatrix = false;
- bool needsEnhancedColorMatrix = false;
// Framebuffer will live in this scope for GPU composition.
std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
@@ -3115,16 +3121,6 @@
colorMatrix = mDrawingState.colorMatrix;
}
- // The current enhanced saturation matrix is designed to enhance Display P3,
- // thus we only apply this matrix when the render intent is not colorimetric
- // and the output color space is Display P3.
- needsEnhancedColorMatrix =
- (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
- outputDataspace == Dataspace::DISPLAY_P3);
- if (needsEnhancedColorMatrix) {
- colorMatrix *= mEnhancedSaturationMatrix;
- }
-
display->setViewportAndProjection();
// Never touch the framebuffer if we don't have any framebuffer layers
@@ -3182,9 +3178,8 @@
case HWC2::Composition::Sideband:
case HWC2::Composition::SolidColor: {
LOG_ALWAYS_FATAL_IF(!displayId);
- const Layer::State& state(layer->getDrawingState());
if (layer->getClearClientTarget(*displayId) && !firstLayer &&
- layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
+ layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
// never clear the very first layer since we're
// guaranteed the FB is already cleared
@@ -3199,9 +3194,6 @@
tmpMatrix = mDrawingState.colorMatrix;
}
tmpMatrix *= layer->getColorTransform();
- if (needsEnhancedColorMatrix) {
- tmpMatrix *= mEnhancedSaturationMatrix;
- }
getRenderEngine().setColorTransform(tmpMatrix);
} else {
getRenderEngine().setColorTransform(colorMatrix);
@@ -3505,7 +3497,7 @@
uint32_t flags = 0;
- const uint32_t what = s.what;
+ const uint64_t what = s.what;
bool geometryAppliesWithResize =
what & layer_state_t::eGeometryAppliesWithResize;
@@ -3677,6 +3669,9 @@
if (what & layer_state_t::eCropChanged) {
if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
}
+ if (what & layer_state_t::eFrameChanged) {
+ if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
+ }
if (what & layer_state_t::eBufferChanged) {
if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
}
@@ -3916,10 +3911,11 @@
setTransactionFlags(eTransactionNeeded);
}
-void SurfaceFlinger::onHandleDestroyed(const sp<Layer>& layer)
+void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
{
Mutex::Autolock lock(mStateLock);
markLayerPendingRemovalLocked(mStateLock, layer);
+ layer.clear();
}
// ---------------------------------------------------------------------------
@@ -3947,7 +3943,7 @@
const auto display = getDisplayDevice(displayToken);
if (!display) return;
- setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
+ setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
const nsecs_t period = activeConfig->getVsyncPeriod();
@@ -3964,8 +3960,7 @@
postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
}
-void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
- bool stateLockHeld) {
+void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
if (display->isVirtual()) {
ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
return;
@@ -3984,13 +3979,7 @@
display->setPowerMode(mode);
if (mInterceptor->isEnabled()) {
- ConditionalLock lock(mStateLock, !stateLockHeld);
- ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
- if (idx < 0) {
- ALOGW("Surface Interceptor SavePowerMode: invalid display token");
- return;
- }
- mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
+ mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
}
if (currentMode == HWC_POWER_MODE_OFF) {
@@ -4085,7 +4074,7 @@
} else if (display->isVirtual()) {
ALOGW("Attempt to set power mode %d for virtual display", mode);
} else {
- setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
+ setPowerModeInternal(display, mode);
}
}));
}
@@ -4094,7 +4083,7 @@
status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
NO_THREAD_SAFETY_ANALYSIS {
- String8 result;
+ std::string result;
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
@@ -4102,8 +4091,8 @@
if ((uid != AID_SHELL) &&
!PermissionCache::checkPermission(sDump, pid, uid)) {
- result.appendFormat("Permission Denial: "
- "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
+ StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
+ pid, uid);
} else {
// Try to get the main lock, but give up after one second
// (this would indicate SF is stuck, but we want to be able to
@@ -4111,9 +4100,10 @@
status_t err = mStateLock.timedLock(s2ns(1));
bool locked = (err == NO_ERROR);
if (!locked) {
- result.appendFormat(
- "SurfaceFlinger appears to be unresponsive (%s [%d]), "
- "dumping anyways (no locks held)\n", strerror(-err), err);
+ StringAppendF(&result,
+ "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
+ "(no locks held)\n",
+ strerror(-err), err);
}
bool dumpAll = true;
@@ -4231,21 +4221,18 @@
mStateLock.unlock();
}
}
- write(fd, result.string(), result.size());
+ write(fd, result.c_str(), result.size());
return NO_ERROR;
}
-void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
- size_t& /* index */, String8& result) const
-{
- mCurrentState.traverseInZOrder([&](Layer* layer) {
- result.appendFormat("%s\n", layer->getName().string());
- });
+void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
+ std::string& result) const {
+ mCurrentState.traverseInZOrder(
+ [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
}
void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
- String8& result) const
-{
+ std::string& result) const {
String8 name;
if (index < args.size()) {
name = String8(args[index]);
@@ -4256,7 +4243,7 @@
displayId && getHwComposer().isConnected(*displayId)) {
const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
const nsecs_t period = activeConfig->getVsyncPeriod();
- result.appendFormat("%" PRId64 "\n", period);
+ StringAppendF(&result, "%" PRId64 "\n", period);
}
if (name.isEmpty()) {
@@ -4271,8 +4258,7 @@
}
void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
- String8& /* result */)
-{
+ std::string& /* result */) {
String8 name;
if (index < args.size()) {
name = String8(args[index]);
@@ -4298,37 +4284,34 @@
mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
}
-void SurfaceFlinger::appendSfConfigString(String8& result) const
-{
+void SurfaceFlinger::appendSfConfigString(std::string& result) const {
result.append(" [sf");
if (isLayerTripleBufferingDisabled())
result.append(" DISABLE_TRIPLE_BUFFERING");
- result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
- result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
- result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
- result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
- result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
- maxFrameBufferAcquiredBuffers);
+ StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
+ StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
+ StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
+ StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
+ StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
+ maxFrameBufferAcquiredBuffers);
result.append("]");
}
-void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
-{
- result.appendFormat("Static screen stats:\n");
+void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
+ result.append("Static screen stats:\n");
for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
float percent = 100.0f *
static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
- result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
- b + 1, bucketTimeSec, percent);
+ StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
}
float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
float percent = 100.0f *
static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
- result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
- SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
+ StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
+ bucketTimeSec, percent);
}
void SurfaceFlinger::recordBufferingStats(const char* layerName,
@@ -4349,8 +4332,8 @@
}
}
-void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
- result.appendFormat("Layer frame timestamps:\n");
+void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
+ result.append("Layer frame timestamps:\n");
const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
const size_t count = currentLayers.size();
@@ -4359,7 +4342,7 @@
}
}
-void SurfaceFlinger::dumpBufferingStats(String8& result) const {
+void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
result.append("Buffering stats:\n");
result.append(" [Layer name] <Active time> <Two buffer> "
"<Double buffered> <Triple buffered>\n");
@@ -4385,15 +4368,13 @@
for (const auto& sortedPair : sorted) {
float activeTime = sortedPair.first;
const BufferTuple& values = sortedPair.second;
- result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
- std::get<0>(values).c_str(), activeTime,
- std::get<1>(values), std::get<2>(values),
- std::get<3>(values));
+ StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
+ activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
}
result.append("\n");
}
-void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
+void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
for (const auto& [token, display] : mDisplays) {
const auto displayId = display->getId();
if (!displayId) {
@@ -4404,8 +4385,9 @@
continue;
}
- result.appendFormat("Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
- *hwcDisplayId);
+ StringAppendF(&result,
+ "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
+ *hwcDisplayId);
uint8_t port;
DisplayIdentificationData data;
if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
@@ -4416,7 +4398,7 @@
if (!isEdid(data)) {
result.append("unknown identification data: ");
for (uint8_t byte : data) {
- result.appendFormat("%x ", byte);
+ StringAppendF(&result, "%x ", byte);
}
result.append("\n");
continue;
@@ -4426,23 +4408,23 @@
if (!edid) {
result.append("invalid EDID: ");
for (uint8_t byte : data) {
- result.appendFormat("%x ", byte);
+ StringAppendF(&result, "%x ", byte);
}
result.append("\n");
continue;
}
- result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
+ StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
result.append(edid->displayName.data(), edid->displayName.length());
result.append("\"\n");
}
}
-void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
- result.appendFormat("Device has wide color display: %d\n", hasWideColorDisplay);
- result.appendFormat("Device uses color management: %d\n", useColorManagement);
- result.appendFormat("DisplayColorSetting: %s\n",
- decodeDisplayColorSetting(mDisplayColorSetting).c_str());
+void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
+ StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
+ StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
+ StringAppendF(&result, "DisplayColorSetting: %s\n",
+ decodeDisplayColorSetting(mDisplayColorSetting).c_str());
// TODO: print out if wide-color mode is active or not
@@ -4452,22 +4434,20 @@
continue;
}
- result.appendFormat("Display %s color modes:\n", to_string(*displayId).c_str());
+ StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
for (auto&& mode : modes) {
- result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
+ StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
}
ColorMode currentMode = display->getActiveColorMode();
- result.appendFormat(" Current color mode: %s (%d)\n",
- decodeColorMode(currentMode).c_str(), currentMode);
+ StringAppendF(&result, " Current color mode: %s (%d)\n",
+ decodeColorMode(currentMode).c_str(), currentMode);
}
result.append("\n");
}
-void SurfaceFlinger::dumpFrameCompositionInfo(String8& result) const {
- std::string stringResult;
-
+void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
for (const auto& [token, display] : mDisplays) {
const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
if (it == getBE().mEndOfFrameCompositionInfo.end()) {
@@ -4475,15 +4455,13 @@
}
const auto& compositionInfoList = it->second;
- stringResult += base::StringPrintf("%s\n", display->getDebugName().c_str());
- stringResult += base::StringPrintf("numComponents: %zu\n", compositionInfoList.size());
+ StringAppendF(&result, "%s\n", display->getDebugName().c_str());
+ StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
for (const auto& compositionInfo : compositionInfoList) {
- compositionInfo.dump(stringResult, nullptr);
- stringResult += base::StringPrintf("\n");
+ compositionInfo.dump(result, nullptr);
+ result.append("\n");
}
}
-
- result.append(stringResult.c_str());
}
LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
@@ -4522,8 +4500,7 @@
}
void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
- String8& result) const
-{
+ std::string& result) const {
bool colorize = false;
if (index < args.size()
&& (args[index] == String16("--color"))) {
@@ -4571,16 +4548,17 @@
if (const auto displayId = getInternalDisplayId();
displayId && getHwComposer().isConnected(*displayId)) {
const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
- result.appendFormat("Display %s: app phase %" PRId64 " ns, "
- "sf phase %" PRId64 " ns, "
- "early app phase %" PRId64 " ns, "
- "early sf phase %" PRId64 " ns, "
- "early app gl phase %" PRId64 " ns, "
- "early sf gl phase %" PRId64 " ns, "
- "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
- to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
- appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
- dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
+ StringAppendF(&result,
+ "Display %s: app phase %" PRId64 " ns, "
+ "sf phase %" PRId64 " ns, "
+ "early app phase %" PRId64 " ns, "
+ "early sf phase %" PRId64 " ns, "
+ "early app gl phase %" PRId64 " ns, "
+ "early sf gl phase %" PRId64 " ns, "
+ "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
+ to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
+ appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
+ dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
}
result.append("\n");
@@ -4589,7 +4567,7 @@
dumpStaticScreenStats(result);
result.append("\n");
- result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
+ StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
dumpBufferingStats(result);
@@ -4597,15 +4575,15 @@
* Dump the visible layer list
*/
colorizer.bold(result);
- result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
- result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
- mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
+ StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
+ StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
+ mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
colorizer.reset(result);
{
LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
- result.append(LayerProtoParser::layerTreeToString(layerTree).c_str());
+ result.append(LayerProtoParser::layerTreeToString(layerTree));
result.append("\n");
}
@@ -4618,7 +4596,7 @@
*/
colorizer.bold(result);
- result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
+ StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
colorizer.reset(result);
for (const auto& [token, display] : mDisplays) {
display->dump(result);
@@ -4637,27 +4615,28 @@
if (const auto display = getDefaultDisplayDeviceLocked()) {
display->undefinedRegion.dump(result, "undefinedRegion");
- result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
- display->isPoweredOn());
+ StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
+ display->isPoweredOn());
}
- result.appendFormat(" transaction-flags : %08x\n"
- " gpu_to_cpu_unsupported : %d\n",
- mTransactionFlags.load(), !mGpuToCpuSupported);
+ StringAppendF(&result,
+ " transaction-flags : %08x\n"
+ " gpu_to_cpu_unsupported : %d\n",
+ mTransactionFlags.load(), !mGpuToCpuSupported);
if (const auto displayId = getInternalDisplayId();
displayId && getHwComposer().isConnected(*displayId)) {
const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
- result.appendFormat(" refresh-rate : %f fps\n"
- " x-dpi : %f\n"
- " y-dpi : %f\n",
- 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
- activeConfig->getDpiY());
+ StringAppendF(&result,
+ " refresh-rate : %f fps\n"
+ " x-dpi : %f\n"
+ " y-dpi : %f\n",
+ 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
+ activeConfig->getDpiY());
}
- result.appendFormat(" transaction time: %f us\n",
- inTransactionDuration/1000.0);
+ StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
- result.appendFormat(" use Scheduler: %s\n", mUseScheduler ? "true" : "false");
+ StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
/*
* VSYNC state
*/
@@ -4683,7 +4662,7 @@
continue;
}
- result.appendFormat("Display %s HWC layers:\n", to_string(*displayId).c_str());
+ StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Layer::miniDumpHeader(result);
mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
result.append("\n");
@@ -4696,8 +4675,7 @@
result.append("h/w composer state:\n");
colorizer.reset(result);
bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
- result.appendFormat(" h/w composer %s\n",
- hwcDisabled ? "disabled" : "enabled");
+ StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
getHwComposer().dump(result);
/*
@@ -4711,7 +4689,7 @@
*/
if (mVrFlingerRequestsDisplay && mVrFlinger) {
result.append("VrFlinger state:\n");
- result.append(mVrFlinger->Dump().c_str());
+ result.append(mVrFlinger->Dump());
result.append("\n");
}
}
@@ -4791,7 +4769,8 @@
case INJECT_VSYNC:
case SET_POWER_MODE:
case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
- case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: {
+ case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
+ case GET_DISPLAYED_CONTENT_SAMPLE: {
if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
IPCThreadState* ipc = IPCThreadState::self();
ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
@@ -5225,15 +5204,12 @@
mFlinger(flinger),
mChildrenOnly(childrenOnly) {}
const ui::Transform& getTransform() const override { return mTransform; }
- Rect getBounds() const override {
- const Layer::State& layerState(mLayer->getDrawingState());
- return mLayer->getBufferSize(layerState);
- }
+ Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
int getHeight() const override {
- return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
+ return mLayer->getBufferSize(StateSet::Drawing).getHeight();
}
int getWidth() const override {
- return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
+ return mLayer->getBufferSize(StateSet::Drawing).getWidth();
}
bool isSecure() const override { return false; }
bool needsFiltering() const override { return mNeedsFiltering; }
@@ -5300,7 +5276,7 @@
const int uid = IPCThreadState::self()->getCallingUid();
const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
- if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
+ if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
return PERMISSION_DENIED;
}
@@ -5308,12 +5284,12 @@
Rect crop(sourceCrop);
if (sourceCrop.width() <= 0) {
crop.left = 0;
- crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
+ crop.right = parent->getBufferSize(StateSet::Current).getWidth();
}
if (sourceCrop.height() <= 0) {
crop.top = 0;
- crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
+ crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
}
int32_t reqWidth = crop.width() * frameScale;
@@ -5473,10 +5449,11 @@
ALOGW("FB is protected: PERMISSION_DENIED");
return PERMISSION_DENIED;
}
+ auto& engine(getRenderEngine());
// this binds the given EGLImage as a framebuffer for the
// duration of this scope.
- renderengine::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
+ renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
if (bufferBond.getStatus() != NO_ERROR) {
ALOGE("got ANWB binding error while taking screenshot");
return INVALID_OPERATION;
@@ -5488,9 +5465,9 @@
// dependent on the context's EGLConfig.
renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
- base::unique_fd syncFd = getRenderEngine().flush();
+ base::unique_fd syncFd = engine.flush();
if (syncFd < 0) {
- getRenderEngine().finish();
+ engine.finish();
}
*outSyncFd = syncFd.release();
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index fe2f1c26..b1bfb3a 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -486,6 +486,9 @@
virtual status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
uint8_t componentMask,
uint64_t maxFrames) const override;
+ virtual status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
+ uint64_t timestamp,
+ DisplayedFrameStats* outStats) const override;
/* ------------------------------------------------------------------------
* DeathRecipient interface
@@ -521,7 +524,7 @@
// called on the main thread in response to setActiveConfig()
void setActiveConfigInternal(const sp<DisplayDevice>& display, int mode);
// called on the main thread in response to setPowerMode()
- void setPowerModeInternal(const sp<DisplayDevice>& display, int mode, bool stateLockHeld);
+ void setPowerModeInternal(const sp<DisplayDevice>& display, int mode);
// Called on the main thread in response to setActiveColorMode()
void setActiveColorModeInternal(const sp<DisplayDevice>& display, ui::ColorMode colorMode,
@@ -598,7 +601,7 @@
// called when all clients have released all their references to
// this layer meaning it is entirely safe to destroy all
// resources associated to this layer.
- void onHandleDestroyed(const sp<Layer>& layer);
+ void onHandleDestroyed(sp<Layer>& layer);
// remove a layer from SurfaceFlinger immediately
status_t removeLayer(const sp<Layer>& layer);
@@ -806,25 +809,25 @@
return hwcDisplayId ? getHwComposer().toPhysicalDisplayId(*hwcDisplayId) : std::nullopt;
}
- void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
- void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
- void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
- void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
+ void listLayersLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
+ void dumpStatsLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
+ void clearStatsLocked(const Vector<String16>& args, size_t& index, std::string& result);
+ void dumpAllLocked(const Vector<String16>& args, size_t& index, std::string& result) const;
bool startDdmConnection();
- void appendSfConfigString(String8& result) const;
+ void appendSfConfigString(std::string& result) const;
void logFrameStats();
- void dumpStaticScreenStats(String8& result) const;
+ void dumpStaticScreenStats(std::string& result) const;
// Not const because each Layer needs to query Fences and cache timestamps.
- void dumpFrameEventsLocked(String8& result);
+ void dumpFrameEventsLocked(std::string& result);
void recordBufferingStats(const char* layerName,
std::vector<OccupancyTracker::Segment>&& history);
- void dumpBufferingStats(String8& result) const;
- void dumpDisplayIdentificationData(String8& result) const;
- void dumpWideColorInfo(String8& result) const;
- void dumpFrameCompositionInfo(String8& result) const;
+ void dumpBufferingStats(std::string& result) const;
+ void dumpDisplayIdentificationData(std::string& result) const;
+ void dumpWideColorInfo(std::string& result) const;
+ void dumpFrameCompositionInfo(std::string& result) const;
LayersProto dumpProtoInfo(LayerVector::StateSet stateSet) const;
LayersProto dumpVisibleLayersProtoInfo(const DisplayDevice& display) const;
@@ -983,8 +986,6 @@
std::thread::id mMainThreadId;
DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::ENHANCED;
- // Applied on Display P3 layers when the render intent is non-colorimetric.
- mat4 mEnhancedSaturationMatrix;
ui::Dataspace mDefaultCompositionDataspace;
ui::Dataspace mWideColorGamutCompositionDataspace;
diff --git a/services/surfaceflinger/SurfaceInterceptor.cpp b/services/surfaceflinger/SurfaceInterceptor.cpp
index 7bfe033..a6dcb7e 100644
--- a/services/surfaceflinger/SurfaceInterceptor.cpp
+++ b/services/surfaceflinger/SurfaceInterceptor.cpp
@@ -101,22 +101,23 @@
transaction->set_animation(layerFlags & BnSurfaceComposer::eAnimation);
const int32_t layerId(getLayerId(layer));
- addPositionLocked(transaction, layerId, layer->mCurrentState.active_legacy.transform.tx(),
- layer->mCurrentState.active_legacy.transform.ty());
- addDepthLocked(transaction, layerId, layer->mCurrentState.z);
- addAlphaLocked(transaction, layerId, layer->mCurrentState.color.a);
+ Mutex::Autolock lock(layer->mStateMutex);
+ addPositionLocked(transaction, layerId, layer->mState.current.active_legacy.transform.tx(),
+ layer->mState.current.active_legacy.transform.ty());
+ addDepthLocked(transaction, layerId, layer->mState.current.z);
+ addAlphaLocked(transaction, layerId, layer->mState.current.color.a);
addTransparentRegionLocked(transaction, layerId,
- layer->mCurrentState.activeTransparentRegion_legacy);
- addLayerStackLocked(transaction, layerId, layer->mCurrentState.layerStack);
- addCropLocked(transaction, layerId, layer->mCurrentState.crop_legacy);
- addCornerRadiusLocked(transaction, layerId, layer->mCurrentState.cornerRadius);
- if (layer->mCurrentState.barrierLayer_legacy != nullptr) {
+ layer->mState.current.activeTransparentRegion_legacy);
+ addLayerStackLocked(transaction, layerId, layer->mState.current.layerStack);
+ addCropLocked(transaction, layerId, layer->mState.current.crop_legacy);
+ addCornerRadiusLocked(transaction, layerId, layer->mState.current.cornerRadius);
+ if (layer->mState.current.barrierLayer_legacy != nullptr) {
addDeferTransactionLocked(transaction, layerId,
- layer->mCurrentState.barrierLayer_legacy.promote(),
- layer->mCurrentState.frameNumber_legacy);
+ layer->mState.current.barrierLayer_legacy.promote(),
+ layer->mState.current.frameNumber_legacy);
}
addOverrideScalingModeLocked(transaction, layerId, layer->getEffectiveScalingMode());
- addFlagsLocked(transaction, layerId, layer->mCurrentState.flags);
+ addFlagsLocked(transaction, layerId, layer->mState.current.flags);
}
void SurfaceInterceptor::addInitialDisplayStateLocked(Increment* increment,
@@ -426,8 +427,9 @@
SurfaceCreation* creation(increment->mutable_surface_creation());
creation->set_id(getLayerId(layer));
creation->set_name(getLayerName(layer));
- creation->set_w(layer->mCurrentState.active_legacy.w);
- creation->set_h(layer->mCurrentState.active_legacy.h);
+ Mutex::Autolock lock(layer->mStateMutex);
+ creation->set_w(layer->mState.current.active_legacy.w);
+ creation->set_h(layer->mState.current.active_legacy.h);
}
void SurfaceInterceptor::addSurfaceDeletionLocked(Increment* increment,
diff --git a/services/surfaceflinger/SurfaceTracing.cpp b/services/surfaceflinger/SurfaceTracing.cpp
index 1835929..b7e9a91 100644
--- a/services/surfaceflinger/SurfaceTracing.cpp
+++ b/services/surfaceflinger/SurfaceTracing.cpp
@@ -20,6 +20,7 @@
#include "SurfaceTracing.h"
#include <android-base/file.h>
+#include <android-base/stringprintf.h>
#include <log/log.h>
#include <utils/SystemClock.h>
#include <utils/Trace.h>
@@ -120,12 +121,13 @@
return NO_ERROR;
}
-void SurfaceTracing::dump(String8& result) const {
+void SurfaceTracing::dump(std::string& result) const {
std::lock_guard<std::mutex> protoGuard(mTraceMutex);
- result.appendFormat("Tracing state: %s\n", mEnabled ? "enabled" : "disabled");
- result.appendFormat(" number of entries: %zu (%.2fMB / %.2fMB)\n", mBuffer.frameCount(),
- float(mBuffer.used()) / float(1_MB), float(mBuffer.size()) / float(1_MB));
+ base::StringAppendF(&result, "Tracing state: %s\n", mEnabled ? "enabled" : "disabled");
+ base::StringAppendF(&result, " number of entries: %zu (%.2fMB / %.2fMB)\n",
+ mBuffer.frameCount(), float(mBuffer.used()) / float(1_MB),
+ float(mBuffer.size()) / float(1_MB));
}
} // namespace android
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index ec01be7..fd919af 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -18,7 +18,6 @@
#include <layerproto/LayerProtoHeader.h>
#include <utils/Errors.h>
-#include <utils/String8.h>
#include <memory>
#include <mutex>
@@ -43,7 +42,7 @@
void traceLayers(const char* where, LayersProto);
bool isEnabled() const;
- void dump(String8& result) const;
+ void dump(std::string& result) const;
private:
static constexpr auto kDefaultBufferCapInByte = 100_MB;
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index 2b9f5c8..6a5488a 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -33,7 +33,7 @@
namespace android {
void TimeStats::parseArgs(bool asProto, const Vector<String16>& args, size_t& index,
- String8& result) {
+ std::string& result) {
ATRACE_CALL();
if (args.size() > index + 10) {
@@ -564,7 +564,7 @@
return mEnabled.load();
}
-void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, String8& result) {
+void TimeStats::dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result) {
ATRACE_CALL();
std::lock_guard<std::mutex> lock(mMutex);
@@ -582,7 +582,7 @@
result.append(timeStatsProto.SerializeAsString().c_str(), timeStatsProto.ByteSize());
} else {
ALOGD("Dumping TimeStats as text");
- result.append(mTimeStats.toString(maxLayers).c_str());
+ result.append(mTimeStats.toString(maxLayers));
result.append("\n");
}
}
diff --git a/services/surfaceflinger/TimeStats/TimeStats.h b/services/surfaceflinger/TimeStats/TimeStats.h
index 0b24c46..71c3ed7 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.h
+++ b/services/surfaceflinger/TimeStats/TimeStats.h
@@ -24,7 +24,6 @@
#include <ui/FenceTime.h>
#include <utils/String16.h>
-#include <utils/String8.h>
#include <utils/Vector.h>
#include <deque>
@@ -35,7 +34,6 @@
using namespace android::surfaceflinger;
namespace android {
-class String8;
class TimeStats {
struct FrameTime {
@@ -79,7 +77,7 @@
TimeStats() = default;
~TimeStats() = default;
- void parseArgs(bool asProto, const Vector<String16>& args, size_t& index, String8& result);
+ void parseArgs(bool asProto, const Vector<String16>& args, size_t& index, std::string& result);
bool isEnabled();
void incrementTotalFrames();
@@ -117,7 +115,7 @@
void enable();
void disable();
void clear();
- void dump(bool asProto, std::optional<uint32_t> maxLayers, String8& result);
+ void dump(bool asProto, std::optional<uint32_t> maxLayers, std::string& result);
std::atomic<bool> mEnabled = false;
std::mutex mMutex;
diff --git a/services/surfaceflinger/TransactionCompletedThread.cpp b/services/surfaceflinger/TransactionCompletedThread.cpp
index 389118a..a1a8692 100644
--- a/services/surfaceflinger/TransactionCompletedThread.cpp
+++ b/services/surfaceflinger/TransactionCompletedThread.cpp
@@ -151,18 +151,6 @@
while (mKeepRunning) {
mConditionVariable.wait(mMutex);
- // Present fence should fire almost immediately. If the fence has not signaled in 100ms,
- // there is a major problem and it will probably never fire.
- nsecs_t presentTime = -1;
- if (mPresentFence) {
- status_t status = mPresentFence->wait(100);
- if (status == NO_ERROR) {
- presentTime = mPresentFence->getSignalTime();
- } else {
- ALOGE("present fence has not signaled, err %d", status);
- }
- }
-
// We should never hit this case. The release fences from the previous frame should have
// signaled long before the current frame is presented.
for (const auto& fence : mPreviousReleaseFences) {
@@ -188,17 +176,11 @@
// If the transaction has been latched
if (transactionStats.latchTime >= 0) {
- // If the present time is < 0, this transaction has been latched but not
- // presented. Skip it for now. This can happen when a new transaction comes
- // in between the latch and present steps. sendCallbacks is called by
- // SurfaceFlinger when the transaction is received to ensure that if the
- // transaction that didn't update state it still got a callback.
- if (presentTime < 0) {
+ if (!mPresentFence) {
sendCallback = false;
break;
}
-
- transactionStats.presentTime = presentTime;
+ transactionStats.presentFence = mPresentFence;
}
}
// If the listener has no pending transactions and all latched transactions have been
diff --git a/services/surfaceflinger/tests/Transaction_test.cpp b/services/surfaceflinger/tests/Transaction_test.cpp
index b0360a2..e62fc6e 100644
--- a/services/surfaceflinger/tests/Transaction_test.cpp
+++ b/services/surfaceflinger/tests/Transaction_test.cpp
@@ -396,7 +396,7 @@
BufferUsage::COMPOSER_OVERLAY,
"test");
fillGraphicBufferColor(buffer, Rect(0, 0, bufferWidth, bufferHeight), color);
- Transaction().setBuffer(layer, buffer).setSize(layer, bufferWidth, bufferHeight).apply();
+ Transaction().setBuffer(layer, buffer).apply();
}
void fillLayerColor(uint32_t mLayerType, const sp<SurfaceControl>& layer, const Color& color,
@@ -484,13 +484,14 @@
uint32_t mDisplayWidth;
uint32_t mDisplayHeight;
uint32_t mDisplayLayerStack;
+ Rect mDisplayRect = Rect::INVALID_RECT;
// leave room for ~256 layers
const int32_t mLayerZBase = std::numeric_limits<int32_t>::max() - 256;
- void setPositionWithResizeHelper(uint32_t layerType);
- void setSizeBasicHelper(uint32_t layerType);
- void setMatrixWithResizeHelper(uint32_t layerType);
+ void setRelativeZBasicHelper(uint32_t layerType);
+ void setRelativeZGroupHelper(uint32_t layerType);
+ void setAlphaBasicHelper(uint32_t layerType);
sp<SurfaceControl> mBlackBgSurface;
bool mColorManagementUsed;
@@ -505,6 +506,8 @@
SurfaceComposerClient::getDisplayInfo(mDisplay, &info);
mDisplayWidth = info.w;
mDisplayHeight = info.h;
+ mDisplayRect =
+ Rect(static_cast<int32_t>(mDisplayWidth), static_cast<int32_t>(mDisplayHeight));
// After a new buffer is queued, SurfaceFlinger is notified and will
// latch the new buffer on next vsync. Let's heuristically wait for 3
@@ -575,31 +578,33 @@
::testing::Values(static_cast<uint32_t>(ISurfaceComposerClient::eFXSurfaceBufferQueue),
static_cast<uint32_t>(ISurfaceComposerClient::eFXSurfaceBufferState)));
-TEST_P(LayerTypeTransactionTest, SetPositionBasic) {
+TEST_F(LayerTransactionTest, SetPositionBasic_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
{
SCOPED_TRACE("default position");
+ const Rect rect(0, 0, 32, 32);
auto shot = screenshot();
- shot->expectColor(Rect(0, 0, 32, 32), Color::RED);
- shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
+ shot->expectColor(rect, Color::RED);
+ shot->expectBorder(rect, Color::BLACK);
}
Transaction().setPosition(layer, 5, 10).apply();
{
SCOPED_TRACE("new position");
+ const Rect rect(5, 10, 37, 42);
auto shot = screenshot();
- shot->expectColor(Rect(5, 10, 37, 42), Color::RED);
- shot->expectBorder(Rect(5, 10, 37, 42), Color::BLACK);
+ shot->expectColor(rect, Color::RED);
+ shot->expectBorder(rect, Color::BLACK);
}
}
-TEST_P(LayerTypeTransactionTest, SetPositionRounding) {
+TEST_F(LayerTransactionTest, SetPositionRounding_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// GLES requires only 4 bits of subpixel precision during rasterization
// XXX GLES composition does not match HWC composition due to precision
@@ -618,28 +623,28 @@
}
}
-TEST_P(LayerTypeTransactionTest, SetPositionOutOfBounds) {
+TEST_F(LayerTransactionTest, SetPositionOutOfBounds_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
Transaction().setPosition(layer, -32, -32).apply();
{
SCOPED_TRACE("negative coordinates");
- screenshot()->expectColor(Rect(0, 0, mDisplayWidth, mDisplayHeight), Color::BLACK);
+ screenshot()->expectColor(mDisplayRect, Color::BLACK);
}
Transaction().setPosition(layer, mDisplayWidth, mDisplayHeight).apply();
{
SCOPED_TRACE("positive coordinates");
- screenshot()->expectColor(Rect(0, 0, mDisplayWidth, mDisplayHeight), Color::BLACK);
+ screenshot()->expectColor(mDisplayRect, Color::BLACK);
}
}
-TEST_P(LayerTypeTransactionTest, SetPositionPartiallyOutOfBounds) {
+TEST_F(LayerTransactionTest, SetPositionPartiallyOutOfBounds_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// partially out of bounds
Transaction().setPosition(layer, -30, -30).apply();
@@ -657,10 +662,10 @@
}
}
-void LayerTransactionTest::setPositionWithResizeHelper(uint32_t layerType) {
+TEST_F(LayerTransactionTest, SetPositionWithResize_BufferQueue) {
sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32, layerType));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// setPosition is applied immediately by default, with or without resize
// pending
@@ -668,39 +673,18 @@
{
SCOPED_TRACE("resize pending");
auto shot = screenshot();
- Rect rect;
- switch (layerType) {
- case ISurfaceComposerClient::eFXSurfaceBufferQueue:
- rect = {5, 10, 37, 42};
- break;
- case ISurfaceComposerClient::eFXSurfaceBufferState:
- rect = {5, 10, 69, 74};
- break;
- default:
- ASSERT_FALSE(true) << "Unsupported layer type";
- }
-
+ const Rect rect(5, 10, 37, 42);
shot->expectColor(rect, Color::RED);
shot->expectBorder(rect, Color::BLACK);
}
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 64, 64));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 64, 64));
{
SCOPED_TRACE("resize applied");
screenshot()->expectColor(Rect(5, 10, 69, 74), Color::RED);
}
}
-TEST_F(LayerTransactionTest, SetPositionWithResize_BufferQueue) {
- ASSERT_NO_FATAL_FAILURE(
- setPositionWithResizeHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue));
-}
-
-TEST_F(LayerTransactionTest, SetPositionWithResize_BufferState) {
- ASSERT_NO_FATAL_FAILURE(
- setPositionWithResizeHelper(ISurfaceComposerClient::eFXSurfaceBufferState));
-}
-
TEST_F(LayerTransactionTest, SetPositionWithNextResize_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
@@ -757,55 +741,38 @@
}
}
-void LayerTransactionTest::setSizeBasicHelper(uint32_t layerType) {
+TEST_F(LayerTransactionTest, SetSizeBasic_BufferQueue) {
sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32, layerType));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
Transaction().setSize(layer, 64, 64).apply();
{
SCOPED_TRACE("resize pending");
auto shot = screenshot();
- Rect rect;
- switch (layerType) {
- case ISurfaceComposerClient::eFXSurfaceBufferQueue:
- rect = {0, 0, 32, 32};
- break;
- case ISurfaceComposerClient::eFXSurfaceBufferState:
- rect = {0, 0, 64, 64};
- break;
- default:
- ASSERT_FALSE(true) << "Unsupported layer type";
- }
+ const Rect rect(0, 0, 32, 32);
shot->expectColor(rect, Color::RED);
shot->expectBorder(rect, Color::BLACK);
}
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 64, 64));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 64, 64));
{
SCOPED_TRACE("resize applied");
auto shot = screenshot();
- shot->expectColor(Rect(0, 0, 64, 64), Color::RED);
- shot->expectBorder(Rect(0, 0, 64, 64), Color::BLACK);
+ const Rect rect(0, 0, 64, 64);
+ shot->expectColor(rect, Color::RED);
+ shot->expectBorder(rect, Color::BLACK);
}
}
-TEST_F(LayerTransactionTest, SetSizeBasic_BufferQueue) {
- setSizeBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue);
-}
-
-TEST_F(LayerTransactionTest, SetSizeBasic_BufferState) {
- setSizeBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferState);
-}
-
TEST_P(LayerTypeTransactionTest, SetSizeInvalid) {
// cannot test robustness against invalid sizes (zero or really huge)
}
-TEST_P(LayerTypeTransactionTest, SetSizeWithScaleToWindow) {
+TEST_F(LayerTransactionTest, SetSizeWithScaleToWindow_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// setSize is immediate with SCALE_TO_WINDOW, unlike setPosition
Transaction()
@@ -867,18 +834,31 @@
}
}
-TEST_P(LayerTypeTransactionTest, SetRelativeZBasic) {
+void LayerTransactionTest::setRelativeZBasicHelper(uint32_t layerType) {
sp<SurfaceControl> layerR;
sp<SurfaceControl> layerG;
- ASSERT_NO_FATAL_FAILURE(layerR = createLayer("test R", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerR, Color::RED, 32, 32));
- ASSERT_NO_FATAL_FAILURE(layerG = createLayer("test G", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerG, Color::GREEN, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layerR = createLayer("test R", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layerR, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layerG = createLayer("test G", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layerG, Color::GREEN, 32, 32));
- Transaction()
- .setPosition(layerG, 16, 16)
- .setRelativeLayer(layerG, layerR->getHandle(), 1)
- .apply();
+ switch (layerType) {
+ case ISurfaceComposerClient::eFXSurfaceBufferQueue:
+ Transaction()
+ .setPosition(layerG, 16, 16)
+ .setRelativeLayer(layerG, layerR->getHandle(), 1)
+ .apply();
+ break;
+ case ISurfaceComposerClient::eFXSurfaceBufferState:
+ Transaction()
+ .setFrame(layerR, Rect(0, 0, 32, 32))
+ .setFrame(layerG, Rect(16, 16, 48, 48))
+ .setRelativeLayer(layerG, layerR->getHandle(), 1)
+ .apply();
+ break;
+ default:
+ ASSERT_FALSE(true) << "Unsupported layer type";
+ }
{
SCOPED_TRACE("layerG above");
auto shot = screenshot();
@@ -895,6 +875,14 @@
}
}
+TEST_F(LayerTransactionTest, SetRelativeZBasic_BufferQueue) {
+ ASSERT_NO_FATAL_FAILURE(setRelativeZBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue));
+}
+
+TEST_F(LayerTransactionTest, SetRelativeZBasic_BufferState) {
+ ASSERT_NO_FATAL_FAILURE(setRelativeZBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferState));
+}
+
TEST_P(LayerTypeTransactionTest, SetRelativeZNegative) {
sp<SurfaceControl> parent =
LayerTransactionTest::createLayer("Parent", 0 /* buffer width */, 0 /* buffer height */,
@@ -920,28 +908,44 @@
std::unique_ptr<ScreenCapture> screenshot;
// only layerB is in this range
sp<IBinder> parentHandle = parent->getHandle();
- ScreenCapture::captureLayers(&screenshot, parentHandle);
+ ScreenCapture::captureLayers(&screenshot, parentHandle, Rect(0, 0, 32, 32));
screenshot->expectColor(Rect(0, 0, 32, 32), Color::BLUE);
}
-TEST_P(LayerTypeTransactionTest, SetRelativeZGroup) {
+void LayerTransactionTest::setRelativeZGroupHelper(uint32_t layerType) {
sp<SurfaceControl> layerR;
sp<SurfaceControl> layerG;
sp<SurfaceControl> layerB;
- ASSERT_NO_FATAL_FAILURE(layerR = createLayer("test R", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerR, Color::RED, 32, 32));
- ASSERT_NO_FATAL_FAILURE(layerG = createLayer("test G", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerG, Color::GREEN, 32, 32));
- ASSERT_NO_FATAL_FAILURE(layerB = createLayer("test B", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerB, Color::BLUE, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layerR = createLayer("test", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layerR, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layerG = createLayer("test", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layerG, Color::GREEN, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layerB = createLayer("test", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layerB, Color::BLUE, 32, 32));
// layerR = 0, layerG = layerR + 3, layerB = 2
- Transaction()
- .setPosition(layerG, 8, 8)
- .setRelativeLayer(layerG, layerR->getHandle(), 3)
- .setPosition(layerB, 16, 16)
- .setLayer(layerB, mLayerZBase + 2)
- .apply();
+ switch (layerType) {
+ case ISurfaceComposerClient::eFXSurfaceBufferQueue:
+ Transaction()
+ .setPosition(layerG, 8, 8)
+ .setRelativeLayer(layerG, layerR->getHandle(), 3)
+ .setPosition(layerB, 16, 16)
+ .setLayer(layerB, mLayerZBase + 2)
+ .apply();
+ break;
+ case ISurfaceComposerClient::eFXSurfaceBufferState:
+ Transaction()
+ .setFrame(layerR, Rect(0, 0, 32, 32))
+ .setFrame(layerG, Rect(8, 8, 40, 40))
+ .setRelativeLayer(layerG, layerR->getHandle(), 3)
+ .setFrame(layerB, Rect(16, 16, 48, 48))
+ .setLayer(layerB, mLayerZBase + 2)
+ .apply();
+ break;
+ default:
+ ASSERT_FALSE(true) << "Unsupported layer type";
+ }
+
{
SCOPED_TRACE("(layerR < layerG) < layerB");
auto shot = screenshot();
@@ -991,6 +995,14 @@
}
}
+TEST_F(LayerTransactionTest, SetRelativeZGroup_BufferQueue) {
+ ASSERT_NO_FATAL_FAILURE(setRelativeZGroupHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue));
+}
+
+TEST_F(LayerTransactionTest, SetRelativeZGroup_BufferState) {
+ ASSERT_NO_FATAL_FAILURE(setRelativeZGroupHelper(ISurfaceComposerClient::eFXSurfaceBufferState));
+}
+
TEST_P(LayerTypeTransactionTest, SetRelativeZBug64572777) {
sp<SurfaceControl> layerR;
sp<SurfaceControl> layerG;
@@ -1018,7 +1030,7 @@
Transaction().setFlags(layer, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden).apply();
{
SCOPED_TRACE("layer hidden");
- screenshot()->expectColor(Rect(0, 0, mDisplayWidth, mDisplayHeight), Color::BLACK);
+ screenshot()->expectColor(mDisplayRect, Color::BLACK);
}
Transaction().setFlags(layer, 0, layer_state_t::eLayerHidden).apply();
@@ -1130,7 +1142,7 @@
Transaction()
.setTransparentRegionHint(layer, Region(top))
.setBuffer(layer, buffer)
- .setSize(layer, 32, 32)
+ .setFrame(layer, Rect(0, 0, 32, 32))
.apply();
{
SCOPED_TRACE("top transparent");
@@ -1154,7 +1166,7 @@
ASSERT_NO_FATAL_FAILURE(fillGraphicBufferColor(buffer, top, Color::RED));
ASSERT_NO_FATAL_FAILURE(fillGraphicBufferColor(buffer, bottom, Color::TRANSPARENT));
- Transaction().setBuffer(layer, buffer).setSize(layer, 32, 32).apply();
+ Transaction().setBuffer(layer, buffer).apply();
{
SCOPED_TRACE("bottom transparent");
auto shot = screenshot();
@@ -1163,7 +1175,7 @@
}
}
-TEST_P(LayerTypeTransactionTest, SetTransparentRegionHintOutOfBounds) {
+TEST_F(LayerTransactionTest, SetTransparentRegionHintOutOfBounds_BufferQueue) {
sp<SurfaceControl> layerTransparent;
sp<SurfaceControl> layerR;
ASSERT_NO_FATAL_FAILURE(layerTransparent = createLayer("test transparent", 32, 32));
@@ -1171,30 +1183,64 @@
// check that transparent region hint is bound by the layer size
Transaction()
- .setTransparentRegionHint(layerTransparent,
- Region(Rect(0, 0, mDisplayWidth, mDisplayHeight)))
+ .setTransparentRegionHint(layerTransparent, Region(mDisplayRect))
.setPosition(layerR, 16, 16)
.setLayer(layerR, mLayerZBase + 1)
.apply();
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerTransparent, Color::TRANSPARENT, 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerR, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(
+ fillBufferQueueLayerColor(layerTransparent, Color::TRANSPARENT, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layerR, Color::RED, 32, 32));
screenshot()->expectColor(Rect(16, 16, 48, 48), Color::RED);
}
-TEST_P(LayerTypeTransactionTest, SetAlphaBasic) {
+TEST_F(LayerTransactionTest, SetTransparentRegionHintOutOfBounds_BufferState) {
+ sp<SurfaceControl> layerTransparent;
+ sp<SurfaceControl> layerR;
+ ASSERT_NO_FATAL_FAILURE(layerTransparent = createLayer("test transparent", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(
+ layerR = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+
+ // check that transparent region hint is bound by the layer size
+ Transaction()
+ .setTransparentRegionHint(layerTransparent, Region(mDisplayRect))
+ .setFrame(layerR, Rect(16, 16, 48, 48))
+ .setLayer(layerR, mLayerZBase + 1)
+ .apply();
+ ASSERT_NO_FATAL_FAILURE(
+ fillBufferQueueLayerColor(layerTransparent, Color::TRANSPARENT, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layerR, Color::RED, 32, 32));
+ screenshot()->expectColor(Rect(16, 16, 48, 48), Color::RED);
+}
+
+void LayerTransactionTest::setAlphaBasicHelper(uint32_t layerType) {
sp<SurfaceControl> layer1;
sp<SurfaceControl> layer2;
- ASSERT_NO_FATAL_FAILURE(layer1 = createLayer("test 1", 32, 32));
- ASSERT_NO_FATAL_FAILURE(layer2 = createLayer("test 2", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer1, {64, 0, 0, 255}, 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer2, {0, 64, 0, 255}, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layer1 = createLayer("test 1", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(layer2 = createLayer("test 2", 32, 32, layerType));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer1, {64, 0, 0, 255}, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer2, {0, 64, 0, 255}, 32, 32));
- Transaction()
- .setAlpha(layer1, 0.25f)
- .setAlpha(layer2, 0.75f)
- .setPosition(layer2, 16, 0)
- .setLayer(layer2, mLayerZBase + 1)
- .apply();
+ switch (layerType) {
+ case ISurfaceComposerClient::eFXSurfaceBufferQueue:
+ Transaction()
+ .setAlpha(layer1, 0.25f)
+ .setAlpha(layer2, 0.75f)
+ .setPosition(layer2, 16, 0)
+ .setLayer(layer2, mLayerZBase + 1)
+ .apply();
+ break;
+ case ISurfaceComposerClient::eFXSurfaceBufferState:
+ Transaction()
+ .setAlpha(layer1, 0.25f)
+ .setAlpha(layer2, 0.75f)
+ .setFrame(layer1, Rect(0, 0, 32, 32))
+ .setFrame(layer2, Rect(16, 0, 48, 32))
+ .setLayer(layer2, mLayerZBase + 1)
+ .apply();
+ break;
+ default:
+ ASSERT_FALSE(true) << "Unsupported layer type";
+ }
{
auto shot = screenshot();
uint8_t r = 16; // 64 * 0.25f
@@ -1207,6 +1253,14 @@
}
}
+TEST_F(LayerTransactionTest, SetAlphaBasic_BufferQueue) {
+ ASSERT_NO_FATAL_FAILURE(setAlphaBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue));
+}
+
+TEST_F(LayerTransactionTest, SetAlphaBasic_BufferState) {
+ ASSERT_NO_FATAL_FAILURE(setAlphaBasicHelper(ISurfaceComposerClient::eFXSurfaceBufferState));
+}
+
TEST_P(LayerTypeTransactionTest, SetAlphaClamped) {
const Color color = {64, 0, 0, 255};
sp<SurfaceControl> layer;
@@ -1230,7 +1284,7 @@
sp<SurfaceControl> layer;
const uint8_t size = 64;
const uint8_t testArea = 4;
- const float cornerRadius = 16.0f;
+ const float cornerRadius = 20.0f;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", size, size));
ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, size, size));
@@ -1238,13 +1292,43 @@
.setCornerRadius(layer, cornerRadius)
.apply();
{
+ const uint8_t bottom = size - 1;
+ const uint8_t right = size - 1;
auto shot = screenshot();
// Transparent corners
shot->expectColor(Rect(0, 0, testArea, testArea), Color::BLACK);
- shot->expectColor(Rect(0, size - testArea, testArea, testArea), Color::BLACK);
- shot->expectColor(Rect(size - testArea, 0, testArea, testArea), Color::BLACK);
- shot->expectColor(Rect(size - testArea, size - testArea, testArea, testArea),
- Color::BLACK);
+ shot->expectColor(Rect(size - testArea, 0, right, testArea), Color::BLACK);
+ shot->expectColor(Rect(0, bottom - testArea, testArea, bottom), Color::BLACK);
+ shot->expectColor(Rect(size - testArea, bottom - testArea, right, bottom), Color::BLACK);
+ }
+}
+
+TEST_P(LayerTypeTransactionTest, SetCornerRadiusChildCrop) {
+ sp<SurfaceControl> parent;
+ sp<SurfaceControl> child;
+ const uint8_t size = 64;
+ const uint8_t testArea = 4;
+ const float cornerRadius = 20.0f;
+ ASSERT_NO_FATAL_FAILURE(parent = createLayer("parent", size, size));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(parent, Color::RED, size, size));
+ ASSERT_NO_FATAL_FAILURE(child = createLayer("child", size, size / 2));
+ ASSERT_NO_FATAL_FAILURE(fillLayerColor(child, Color::GREEN, size, size / 2));
+
+ Transaction()
+ .setCornerRadius(parent, cornerRadius)
+ .reparent(child, parent->getHandle())
+ .setPosition(child, 0, size / 2)
+ .apply();
+ {
+ const uint8_t bottom = size - 1;
+ const uint8_t right = size - 1;
+ auto shot = screenshot();
+ // Top edge of child should not have rounded corners because it's translated in the parent
+ shot->expectColor(Rect(0, size / 2, right, static_cast<int>(bottom - cornerRadius)),
+ Color::GREEN);
+ // But bottom edges should have been clipped according to parent bounds
+ shot->expectColor(Rect(0, bottom - testArea, testArea, bottom), Color::BLACK);
+ shot->expectColor(Rect(right - testArea, bottom - testArea, right, bottom), Color::BLACK);
}
}
@@ -1362,7 +1446,7 @@
Transaction().setLayerStack(layer, mDisplayLayerStack + 1).apply();
{
SCOPED_TRACE("non-existing layer stack");
- screenshot()->expectColor(Rect(0, 0, mDisplayWidth, mDisplayHeight), Color::BLACK);
+ screenshot()->expectColor(mDisplayRect, Color::BLACK);
}
Transaction().setLayerStack(layer, mDisplayLayerStack).apply();
@@ -1372,11 +1456,11 @@
}
}
-TEST_P(LayerTypeTransactionTest, SetMatrixBasic) {
+TEST_F(LayerTransactionTest, SetMatrixBasic_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(
- fillLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN, Color::BLUE, Color::WHITE));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
+ Color::BLUE, Color::WHITE));
Transaction().setMatrix(layer, 1.0f, 0.0f, 0.0f, 1.0f).setPosition(layer, 0, 0).apply();
{
@@ -1414,11 +1498,57 @@
}
}
-TEST_P(LayerTypeTransactionTest, SetMatrixRot45) {
+TEST_F(LayerTransactionTest, SetMatrixBasic_BufferState) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(
+ layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
+ Color::BLUE, Color::WHITE));
+
+ Transaction()
+ .setMatrix(layer, 1.0f, 0.0f, 0.0f, 1.0f)
+ .setFrame(layer, Rect(0, 0, 32, 32))
+ .apply();
+ {
+ SCOPED_TRACE("IDENTITY");
+ screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::RED, Color::GREEN, Color::BLUE,
+ Color::WHITE);
+ }
+
+ Transaction().setMatrix(layer, -1.0f, 0.0f, 0.0f, 1.0f).apply();
+ {
+ SCOPED_TRACE("FLIP_H");
+ screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::RED, Color::GREEN, Color::BLUE,
+ Color::WHITE);
+ }
+
+ Transaction().setMatrix(layer, 1.0f, 0.0f, 0.0f, -1.0f).apply();
+ {
+ SCOPED_TRACE("FLIP_V");
+ screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::RED, Color::GREEN, Color::BLUE,
+ Color::WHITE);
+ }
+
+ Transaction().setMatrix(layer, 0.0f, 1.0f, -1.0f, 0.0f).apply();
+ {
+ SCOPED_TRACE("ROT_90");
+ screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::RED, Color::GREEN, Color::BLUE,
+ Color::WHITE);
+ }
+
+ Transaction().setMatrix(layer, 2.0f, 0.0f, 0.0f, 2.0f).apply();
+ {
+ SCOPED_TRACE("SCALE");
+ screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::RED, Color::GREEN, Color::BLUE,
+ Color::WHITE);
+ }
+}
+
+TEST_F(LayerTransactionTest, SetMatrixRot45_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(
- fillLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN, Color::BLUE, Color::WHITE));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
+ Color::BLUE, Color::WHITE));
const float rot = M_SQRT1_2; // 45 degrees
const float trans = M_SQRT2 * 16.0f;
@@ -1437,52 +1567,33 @@
shot->expectColor(get8x8Rect(2 * unit, 3 * unit), Color::WHITE);
}
-void LayerTransactionTest::setMatrixWithResizeHelper(uint32_t layerType) {
+TEST_F(LayerTransactionTest, SetMatrixWithResize_BufferQueue) {
sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32, layerType));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// setMatrix is applied after any pending resize, unlike setPosition
Transaction().setMatrix(layer, 2.0f, 0.0f, 0.0f, 2.0f).setSize(layer, 64, 64).apply();
{
SCOPED_TRACE("resize pending");
auto shot = screenshot();
- Rect rect;
- switch (layerType) {
- case ISurfaceComposerClient::eFXSurfaceBufferQueue:
- rect = {0, 0, 32, 32};
- break;
- case ISurfaceComposerClient::eFXSurfaceBufferState:
- rect = {0, 0, 128, 128};
- break;
- default:
- ASSERT_FALSE(true) << "Unsupported layer type";
- }
+ const Rect rect(0, 0, 32, 32);
shot->expectColor(rect, Color::RED);
shot->expectBorder(rect, Color::BLACK);
}
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layerType, layer, Color::RED, 64, 64));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 64, 64));
{
SCOPED_TRACE("resize applied");
- screenshot()->expectColor(Rect(0, 0, 128, 128), Color::RED);
+ const Rect rect(0, 0, 128, 128);
+ screenshot()->expectColor(rect, Color::RED);
}
}
-TEST_F(LayerTransactionTest, SetMatrixWithResize_BufferQueue) {
- ASSERT_NO_FATAL_FAILURE(
- setMatrixWithResizeHelper(ISurfaceComposerClient::eFXSurfaceBufferQueue));
-}
-
-TEST_F(LayerTransactionTest, SetMatrixWithResize_BufferState) {
- ASSERT_NO_FATAL_FAILURE(
- setMatrixWithResizeHelper(ISurfaceComposerClient::eFXSurfaceBufferState));
-}
-
-TEST_P(LayerTypeTransactionTest, SetMatrixWithScaleToWindow) {
+TEST_F(LayerTransactionTest, SetMatrixWithScaleToWindow_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(fillLayerColor(layer, Color::RED, 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
// setMatrix is immediate with SCALE_TO_WINDOW, unlike setPosition
Transaction()
@@ -1493,11 +1604,11 @@
screenshot()->expectColor(Rect(0, 0, 128, 128), Color::RED);
}
-TEST_P(LayerTypeTransactionTest, SetOverrideScalingModeBasic) {
+TEST_F(LayerTransactionTest, SetOverrideScalingModeBasic_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
- ASSERT_NO_FATAL_FAILURE(
- fillLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN, Color::BLUE, Color::WHITE));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
+ Color::BLUE, Color::WHITE));
// XXX SCALE_CROP is not respected; calling setSize and
// setOverrideScalingMode in separate transactions does not work
@@ -1547,8 +1658,8 @@
Transaction().setCrop(layer, crop).apply();
auto shot = screenshot();
- shot->expectColor(crop, Color::RED);
- shot->expectBorder(crop, Color::BLACK);
+ shot->expectColor(Rect(0, 0, 32, 32), Color::RED);
+ shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
}
TEST_F(LayerTransactionTest, SetCropEmpty_BufferQueue) {
@@ -1599,18 +1710,22 @@
shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
}
-TEST_F(LayerTransactionTest, SetCropOutOfBounds_BufferState) {
- sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(
- layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
-
- Transaction().setCrop(layer, Rect(-128, -64, 128, 64)).apply();
- auto shot = screenshot();
- shot->expectColor(Rect(0, 0, 32, 32), Color::RED);
- shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
-}
-
+// TODO (marissaw): change Layer to make crop to be in bounds instead of passing a bad crop to hwc
+// TEST_F(LayerTransactionTest, SetCropOutOfBounds_BufferState) {
+// sp<SurfaceControl> layer;
+// ASSERT_NO_FATAL_FAILURE(
+// layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+// ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
+//
+// Transaction()
+// .setCrop(layer, Rect(-128, -64, 128, 64))
+// .setFrame(layer, Rect(0, 0, 32, 32))
+// .apply();
+// auto shot = screenshot();
+// shot->expectColor(Rect(0, 0, 32, 32), Color::RED);
+// shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
+//}
+//
TEST_F(LayerTransactionTest, SetCropWithTranslation_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
@@ -1630,12 +1745,12 @@
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
- const Point position(32, 32);
+ const Rect frame(32, 32, 64, 64);
const Rect crop(8, 8, 24, 24);
- Transaction().setPosition(layer, position.x, position.y).setCrop(layer, crop).apply();
+ Transaction().setFrame(layer, frame).setCrop(layer, crop).apply();
auto shot = screenshot();
- shot->expectColor(crop + position, Color::RED);
- shot->expectBorder(crop + position, Color::BLACK);
+ shot->expectColor(frame, Color::RED);
+ shot->expectBorder(frame, Color::BLACK);
}
TEST_F(LayerTransactionTest, SetCropWithScale_BufferQueue) {
@@ -1643,7 +1758,7 @@
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(layer, Color::RED, 32, 32));
- // crop is affected by matrix
+ // crop_legacy is affected by matrix
Transaction()
.setMatrix(layer, 2.0f, 0.0f, 0.0f, 2.0f)
.setCrop_legacy(layer, Rect(8, 8, 24, 24))
@@ -1653,22 +1768,6 @@
shot->expectBorder(Rect(16, 16, 48, 48), Color::BLACK);
}
-TEST_F(LayerTransactionTest, SetCropWithScale_BufferState) {
- sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(
- layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
-
- // crop is affected by matrix
- Transaction()
- .setMatrix(layer, 2.0f, 0.0f, 0.0f, 2.0f)
- .setCrop(layer, Rect(8, 8, 24, 24))
- .apply();
- auto shot = screenshot();
- shot->expectColor(Rect(16, 16, 48, 48), Color::RED);
- shot->expectBorder(Rect(16, 16, 48, 48), Color::BLACK);
-}
-
TEST_F(LayerTransactionTest, SetCropWithResize_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
@@ -1692,30 +1791,6 @@
}
}
-TEST_F(LayerTransactionTest, SetCropWithResize_BufferState) {
- sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(
- layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
-
- // setCrop_legacy is applied immediately by default, with or without resize pending
- Transaction().setCrop(layer, Rect(8, 8, 24, 24)).setSize(layer, 16, 16).apply();
- {
- SCOPED_TRACE("new buffer pending");
- auto shot = screenshot();
- shot->expectColor(Rect(8, 8, 16, 16), Color::RED);
- shot->expectBorder(Rect(8, 8, 16, 16), Color::BLACK);
- }
-
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 16, 16));
- {
- SCOPED_TRACE("new buffer");
- auto shot = screenshot();
- shot->expectColor(Rect(8, 8, 16, 16), Color::RED);
- shot->expectBorder(Rect(8, 8, 16, 16), Color::BLACK);
- }
-}
-
TEST_F(LayerTransactionTest, SetCropWithNextResize_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
@@ -1753,41 +1828,6 @@
}
}
-TEST_F(LayerTransactionTest, SetCropWithNextResize_BufferState) {
- sp<SurfaceControl> layer;
- ASSERT_NO_FATAL_FAILURE(
- layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
-
- // request setCrop_legacy to be applied with the next resize
- Transaction().setCrop(layer, Rect(8, 8, 24, 24)).setGeometryAppliesWithResize(layer).apply();
- {
- SCOPED_TRACE("set crop 1");
- screenshot()->expectColor(Rect(8, 8, 24, 24), Color::RED);
- }
-
- Transaction().setCrop(layer, Rect(4, 4, 12, 12)).apply();
- {
- SCOPED_TRACE("set crop 2");
- screenshot()->expectColor(Rect(4, 4, 12, 12), Color::RED);
- }
-
- Transaction().setSize(layer, 16, 16).apply();
- {
- SCOPED_TRACE("resize");
- screenshot()->expectColor(Rect(4, 4, 12, 12), Color::RED);
- }
-
- // finally resize
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 16, 16));
- {
- SCOPED_TRACE("new buffer");
- auto shot = screenshot();
- shot->expectColor(Rect(4, 4, 12, 12), Color::RED);
- shot->expectBorder(Rect(4, 4, 12, 12), Color::BLACK);
- }
-}
-
TEST_F(LayerTransactionTest, SetCropWithNextResizeScaleToWindow_BufferQueue) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(layer = createLayer("test", 32, 32));
@@ -1819,37 +1859,122 @@
}
}
-TEST_F(LayerTransactionTest, SetCropWithNextResizeScaleToWindow_BufferState) {
+TEST_F(LayerTransactionTest, SetFrameBasic_BufferState) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(
+ layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
+ const Rect frame(8, 8, 24, 24);
+
+ Transaction().setFrame(layer, frame).apply();
+ auto shot = screenshot();
+ shot->expectColor(frame, Color::RED);
+ shot->expectBorder(frame, Color::BLACK);
+}
+
+TEST_F(LayerTransactionTest, SetFrameEmpty_BufferState) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(
layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
- // all properties are applied immediate so setGeometryAppliesWithResize has no effect
- Transaction()
- .setCrop(layer, Rect(4, 4, 12, 12))
- .setSize(layer, 16, 16)
- .setOverrideScalingMode(layer, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW)
- .setGeometryAppliesWithResize(layer)
- .apply();
{
- SCOPED_TRACE("new crop pending");
- auto shot = screenshot();
- shot->expectColor(Rect(4, 4, 12, 12), Color::RED);
- shot->expectBorder(Rect(4, 4, 12, 12), Color::BLACK);
+ SCOPED_TRACE("empty rect");
+ Transaction().setFrame(layer, Rect(8, 8, 8, 8)).apply();
+ screenshot()->expectColor(Rect(0, 0, 32, 32), Color::BLACK);
}
- Transaction().setPosition(layer, 1, 0).setGeometryAppliesWithResize(layer).apply();
- ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 16, 16));
- Transaction().setPosition(layer, 0, 0).apply();
{
- SCOPED_TRACE("new crop applied");
- auto shot = screenshot();
- shot->expectColor(Rect(4, 4, 12, 12), Color::RED);
- shot->expectBorder(Rect(4, 4, 12, 12), Color::BLACK);
+ SCOPED_TRACE("negative rect");
+ Transaction().setFrame(layer, Rect(8, 8, 0, 0)).apply();
+ screenshot()->expectColor(Rect(0, 0, 32, 32), Color::BLACK);
}
}
+TEST_F(LayerTransactionTest, SetFrameDefaultParentless_BufferState) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(
+ layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 10, 10));
+
+ // A parentless layer will default to a frame with the same size as the buffer
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, 10, 10), Color::RED);
+ shot->expectBorder(Rect(0, 0, 10, 10), Color::BLACK);
+}
+
+TEST_F(LayerTransactionTest, SetFrameDefaultBSParent_BufferState) {
+ sp<SurfaceControl> parent, child;
+ ASSERT_NO_FATAL_FAILURE(
+ parent = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(parent, Color::RED, 32, 32));
+ Transaction().setFrame(parent, Rect(0, 0, 32, 32)).apply();
+
+ ASSERT_NO_FATAL_FAILURE(
+ child = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(child, Color::BLUE, 10, 10));
+
+ Transaction().reparent(child, parent->getHandle()).apply();
+
+ // A layer will default to the frame of its parent
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, 32, 32), Color::BLUE);
+ shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
+}
+
+TEST_F(LayerTransactionTest, SetFrameDefaultBQParent_BufferState) {
+ sp<SurfaceControl> parent, child;
+ ASSERT_NO_FATAL_FAILURE(parent = createLayer("test", 32, 32));
+ ASSERT_NO_FATAL_FAILURE(fillBufferQueueLayerColor(parent, Color::RED, 32, 32));
+
+ ASSERT_NO_FATAL_FAILURE(
+ child = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(child, Color::BLUE, 10, 10));
+
+ Transaction().reparent(child, parent->getHandle()).apply();
+
+ // A layer will default to the frame of its parent
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, 32, 32), Color::BLUE);
+ shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
+}
+
+TEST_F(LayerTransactionTest, SetFrameUpdate_BufferState) {
+ sp<SurfaceControl> layer;
+ ASSERT_NO_FATAL_FAILURE(
+ layer = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer, Color::RED, 32, 32));
+ Transaction().setFrame(layer, Rect(0, 0, 32, 32)).apply();
+
+ std::this_thread::sleep_for(500ms);
+
+ Transaction().setFrame(layer, Rect(16, 16, 48, 48)).apply();
+
+ auto shot = screenshot();
+ shot->expectColor(Rect(16, 16, 48, 48), Color::RED);
+ shot->expectBorder(Rect(16, 16, 48, 48), Color::BLACK);
+}
+
+TEST_F(LayerTransactionTest, SetFrameOutsideBounds_BufferState) {
+ sp<SurfaceControl> parent, child;
+ ASSERT_NO_FATAL_FAILURE(
+ parent = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ ASSERT_NO_FATAL_FAILURE(
+ child = createLayer("test", 32, 32, ISurfaceComposerClient::eFXSurfaceBufferState));
+ Transaction().reparent(child, parent->getHandle()).apply();
+
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(parent, Color::RED, 32, 32));
+ Transaction().setFrame(parent, Rect(0, 0, 32, 32)).apply();
+
+ ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(child, Color::BLUE, 10, 10));
+ Transaction().setFrame(child, Rect(0, 16, 32, 32)).apply();
+
+ auto shot = screenshot();
+ shot->expectColor(Rect(0, 0, 32, 16), Color::RED);
+ shot->expectColor(Rect(0, 16, 32, 32), Color::BLUE);
+ shot->expectBorder(Rect(0, 0, 32, 32), Color::BLACK);
+}
+
TEST_F(LayerTransactionTest, SetBufferBasic_BufferState) {
sp<SurfaceControl> layer;
ASSERT_NO_FATAL_FAILURE(
@@ -1906,6 +2031,7 @@
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer1, Color::RED, 64, 64));
+ Transaction().setFrame(layer1, Rect(0, 0, 64, 64)).apply();
{
SCOPED_TRACE("set layer 1 buffer red");
auto shot = screenshot();
@@ -1914,6 +2040,7 @@
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerColor(layer2, Color::BLUE, 32, 32));
+ Transaction().setFrame(layer2, Rect(0, 0, 32, 32)).apply();
{
SCOPED_TRACE("set layer 2 buffer blue");
auto shot = screenshot();
@@ -1950,7 +2077,10 @@
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
Color::BLUE, Color::WHITE));
- Transaction().setTransform(layer, NATIVE_WINDOW_TRANSFORM_ROT_90).apply();
+ Transaction()
+ .setFrame(layer, Rect(0, 0, 32, 32))
+ .setTransform(layer, NATIVE_WINDOW_TRANSFORM_ROT_90)
+ .apply();
screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::BLUE, Color::RED, Color::WHITE,
Color::GREEN, true /* filtered */);
@@ -1964,7 +2094,10 @@
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
Color::BLUE, Color::WHITE));
- Transaction().setTransform(layer, NATIVE_WINDOW_TRANSFORM_FLIP_H).apply();
+ Transaction()
+ .setFrame(layer, Rect(0, 0, 32, 32))
+ .setTransform(layer, NATIVE_WINDOW_TRANSFORM_FLIP_H)
+ .apply();
screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::GREEN, Color::RED, Color::WHITE,
Color::BLUE, true /* filtered */);
@@ -1978,7 +2111,10 @@
ASSERT_NO_FATAL_FAILURE(fillBufferStateLayerQuadrant(layer, 32, 32, Color::RED, Color::GREEN,
Color::BLUE, Color::WHITE));
- Transaction().setTransform(layer, NATIVE_WINDOW_TRANSFORM_FLIP_V).apply();
+ Transaction()
+ .setFrame(layer, Rect(0, 0, 32, 32))
+ .setTransform(layer, NATIVE_WINDOW_TRANSFORM_FLIP_V)
+ .apply();
screenshot()->expectQuadrant(Rect(0, 0, 32, 32), Color::BLUE, Color::WHITE, Color::RED,
Color::GREEN, true /* filtered */);
@@ -2013,7 +2149,6 @@
Transaction()
.setBuffer(layer, buffer)
.setAcquireFence(layer, fence)
- .setSize(layer, 32, 32)
.apply();
auto shot = screenshot();
@@ -2036,7 +2171,6 @@
Transaction()
.setBuffer(layer, buffer)
.setDataspace(layer, ui::Dataspace::UNKNOWN)
- .setSize(layer, 32, 32)
.apply();
auto shot = screenshot();
@@ -2061,7 +2195,6 @@
Transaction()
.setBuffer(layer, buffer)
.setHdrMetadata(layer, hdrMetadata)
- .setSize(layer, 32, 32)
.apply();
auto shot = screenshot();
@@ -2086,7 +2219,6 @@
Transaction()
.setBuffer(layer, buffer)
.setSurfaceDamageRegion(layer, region)
- .setSize(layer, 32, 32)
.apply();
auto shot = screenshot();
@@ -2109,7 +2241,6 @@
Transaction()
.setBuffer(layer, buffer)
.setApi(layer, NATIVE_WINDOW_API_CPU)
- .setSize(layer, 32, 32)
.apply();
auto shot = screenshot();
@@ -2371,12 +2502,12 @@
}
void verifyTransactionStats(const TransactionStats& transactionStats) const {
- const auto& [latchTime, presentTime, surfaceStats] = transactionStats;
+ const auto& [latchTime, presentFence, surfaceStats] = transactionStats;
if (mTransactionResult == ExpectedResult::Transaction::PRESENTED) {
ASSERT_GE(latchTime, 0) << "bad latch time";
- ASSERT_GE(presentTime, 0) << "bad present time";
+ ASSERT_NE(presentFence, nullptr);
} else {
- ASSERT_EQ(presentTime, -1) << "transaction shouldn't have been presented";
+ ASSERT_EQ(presentFence, nullptr) << "transaction shouldn't have been presented";
ASSERT_EQ(latchTime, -1) << "unpresented transactions shouldn't be latched";
}
@@ -2465,36 +2596,33 @@
};
class LayerCallbackTest : public LayerTransactionTest {
-protected:
+public:
virtual sp<SurfaceControl> createBufferStateLayer() {
- return createLayer(mClient, "test", mWidth, mHeight,
- ISurfaceComposerClient::eFXSurfaceBufferState);
+ return createLayer(mClient, "test", 0, 0, ISurfaceComposerClient::eFXSurfaceBufferState);
}
- virtual void fillTransaction(Transaction& transaction, CallbackHelper* callbackHelper,
- const sp<SurfaceControl>& layer = nullptr) {
+ static void fillTransaction(Transaction& transaction, CallbackHelper* callbackHelper,
+ const sp<SurfaceControl>& layer = nullptr) {
if (layer) {
sp<GraphicBuffer> buffer =
- new GraphicBuffer(mWidth, mHeight, PIXEL_FORMAT_RGBA_8888, 1,
+ new GraphicBuffer(32, 32, PIXEL_FORMAT_RGBA_8888, 1,
BufferUsage::CPU_READ_OFTEN | BufferUsage::CPU_WRITE_OFTEN |
BufferUsage::COMPOSER_OVERLAY |
BufferUsage::GPU_TEXTURE,
"test");
- fillGraphicBufferColor(buffer, Rect(0, 0, mWidth, mHeight), Color::RED);
+ fillGraphicBufferColor(buffer, Rect(0, 0, 32, 32), Color::RED);
sp<Fence> fence = new Fence(-1);
- transaction.setBuffer(layer, buffer)
- .setAcquireFence(layer, fence)
- .setSize(layer, mWidth, mHeight);
+ transaction.setBuffer(layer, buffer).setAcquireFence(layer, fence);
}
transaction.addTransactionCompletedCallback(callbackHelper->function,
callbackHelper->getContext());
}
- void waitForCallback(CallbackHelper& helper, const ExpectedResult& expectedResult,
- bool finalState = false) {
+ static void waitForCallback(CallbackHelper& helper, const ExpectedResult& expectedResult,
+ bool finalState = false) {
TransactionStats transactionStats;
ASSERT_NO_FATAL_FAILURE(helper.getTransactionStats(&transactionStats));
EXPECT_NO_FATAL_FAILURE(expectedResult.verifyTransactionStats(transactionStats));
@@ -2504,9 +2632,9 @@
}
}
- void waitForCallbacks(CallbackHelper& helper,
- const std::vector<ExpectedResult>& expectedResults,
- bool finalState = false) {
+ static void waitForCallbacks(CallbackHelper& helper,
+ const std::vector<ExpectedResult>& expectedResults,
+ bool finalState = false) {
for (const auto& expectedResult : expectedResults) {
waitForCallback(helper, expectedResult);
}
@@ -2514,9 +2642,6 @@
ASSERT_NO_FATAL_FAILURE(helper.verifyFinalState());
}
}
-
- uint32_t mWidth = 32;
- uint32_t mHeight = 32;
};
TEST_F(LayerCallbackTest, Basic) {
@@ -2542,7 +2667,7 @@
CallbackHelper callback;
fillTransaction(transaction, &callback);
- transaction.setPosition(layer, mWidth, mHeight).apply();
+ transaction.setFrame(layer, Rect(0, 0, 32, 32)).apply();
ExpectedResult expected;
expected.addSurface(ExpectedResult::Transaction::NOT_PRESENTED, layer);
@@ -2568,7 +2693,7 @@
CallbackHelper callback;
fillTransaction(transaction, &callback, layer);
- transaction.setPosition(layer, -100, -100).apply();
+ transaction.setFrame(layer, Rect(-100, -100, 100, 100)).apply();
ExpectedResult expected;
expected.addSurface(ExpectedResult::Transaction::PRESENTED, layer);
@@ -2585,7 +2710,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2});
@@ -2638,7 +2764,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2});
@@ -2654,9 +2781,9 @@
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
sp<SurfaceControl> layer1, layer2;
- ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
Transaction transaction1, transaction2;
@@ -2664,7 +2791,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2});
@@ -2729,7 +2857,7 @@
fillTransaction(transaction, &callback);
}
- transaction.setPosition(layer, mWidth, mHeight).apply();
+ transaction.setFrame(layer, Rect(0, 0, 32, 32)).apply();
ExpectedResult expected;
expected.addSurface((i == 0) ? ExpectedResult::Transaction::PRESENTED
@@ -2751,7 +2879,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2},
@@ -2772,9 +2901,9 @@
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
sp<SurfaceControl> layer1, layer2;
- ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
Transaction transaction1, transaction2;
@@ -2783,7 +2912,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2},
@@ -2804,9 +2934,9 @@
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
sp<SurfaceControl> layer1, layer2;
- ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
Transaction transaction1, transaction2;
@@ -2816,7 +2946,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2});
@@ -2842,9 +2973,9 @@
ASSERT_EQ(NO_ERROR, client2->initCheck()) << "failed to create SurfaceComposerClient";
sp<SurfaceControl> layer1, layer2;
- ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer1 = createLayer(client1, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
- ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", mWidth, mHeight,
+ ASSERT_NO_FATAL_FAILURE(layer2 = createLayer(client2, "test", 0, 0,
ISurfaceComposerClient::eFXSurfaceBufferState));
Transaction transaction1, transaction2;
@@ -2854,7 +2985,8 @@
fillTransaction(transaction1, &callback1, layer1);
fillTransaction(transaction2, &callback2, layer2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction1.setFrame(layer1, Rect(0, 0, 32, 32));
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
ExpectedResult expected;
expected.addSurfaces(ExpectedResult::Transaction::PRESENTED, {layer1, layer2});
@@ -2866,7 +2998,7 @@
fillTransaction(transaction1, &callback1);
fillTransaction(transaction2, &callback2);
- transaction2.setPosition(layer2, mWidth, mHeight).merge(std::move(transaction1)).apply();
+ transaction2.setFrame(layer2, Rect(32, 32, 64, 64)).merge(std::move(transaction1)).apply();
expected.addSurface(ExpectedResult::Transaction::NOT_PRESENTED, layer2);
EXPECT_NO_FATAL_FAILURE(waitForCallback(callback1, expected, true));
@@ -2930,7 +3062,7 @@
CallbackHelper callback;
fillTransaction(transaction, &callback, layer);
- transaction.setPosition(layer, mWidth, mHeight).apply();
+ transaction.setFrame(layer, Rect(0, 0, 32, 32)).apply();
ExpectedResult expectedResult;
expectedResult.addSurface(ExpectedResult::Transaction::PRESENTED, layer);
@@ -2944,7 +3076,7 @@
fillTransaction(transaction, &callback);
- transaction.setPosition(layer, mWidth, mHeight).apply();
+ transaction.setFrame(layer, Rect(0, 0, 32, 32)).apply();
std::this_thread::sleep_for(200ms);
}
@@ -4245,7 +4377,7 @@
// red area to the right of the blue area
mCapture->expectColor(Rect(30, 0, 59, 59), Color::RED);
- Rect crop = Rect(0, 0, 30, 30);
+ const Rect crop = Rect(0, 0, 30, 30);
ScreenCapture::captureLayers(&mCapture, redLayerHandle, crop);
// Capturing the cropped screen, cropping out the shown red area, should leave only the blue
// area visible.
diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp
index 42b7146..2f35ae5 100644
--- a/services/surfaceflinger/tests/unittests/Android.bp
+++ b/services/surfaceflinger/tests/unittests/Android.bp
@@ -24,11 +24,13 @@
},
srcs: [
":libsurfaceflinger_sources",
+ "libsurfaceflinger_unittest_main.cpp",
"CompositionTest.cpp",
"DisplayIdentificationTest.cpp",
"DisplayTransactionTest.cpp",
"EventControlThreadTest.cpp",
"EventThreadTest.cpp",
+ "IdleTimerTest.cpp",
"LayerHistoryTest.cpp",
"SchedulerTest.cpp",
"SchedulerUtilsTest.cpp",
diff --git a/services/surfaceflinger/tests/unittests/CompositionTest.cpp b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
index 5a6aa92..b7c09ed 100644
--- a/services/surfaceflinger/tests/unittests/CompositionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/CompositionTest.cpp
@@ -286,8 +286,10 @@
static void setupCommonScreensCaptureCallExpectations(CompositionTest* test) {
// Called once with a non-null value to set a framebuffer, and then
// again with nullptr to clear it.
- EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(NotNull())).WillOnce(Return(true));
- EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(IsNull())).WillOnce(Return(true));
+ EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(NotNull(), false))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(IsNull(), false))
+ .WillOnce(Return(true));
EXPECT_CALL(*test->mRenderEngine, checkErrors()).WillRepeatedly(Return());
EXPECT_CALL(*test->mRenderEngine, createFramebuffer())
@@ -344,8 +346,10 @@
Rect(DEFAULT_DISPLAY_WIDTH, DEFAULT_DISPLAY_HEIGHT),
ui::Transform::ROT_0))
.Times(1);
- EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(NotNull())).WillOnce(Return(true));
- EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(IsNull())).WillOnce(Return(true));
+ EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(NotNull(), false))
+ .WillOnce(Return(true));
+ EXPECT_CALL(*test->mReFrameBuffer, setNativeWindowBuffer(IsNull(), false))
+ .WillOnce(Return(true));
EXPECT_CALL(*test->mRenderEngine, createFramebuffer())
.WillOnce(Return(
ByMove(std::unique_ptr<renderengine::Framebuffer>(test->mReFrameBuffer))));
diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
index 34cee3e..02aa5ce 100644
--- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp
@@ -1144,7 +1144,7 @@
getBestColorMode();
- ASSERT_EQ(ui::Dataspace::SRGB, mOutDataspace);
+ ASSERT_EQ(ui::Dataspace::V0_SRGB, mOutDataspace);
ASSERT_EQ(ui::ColorMode::SRGB, mOutColorMode);
ASSERT_EQ(ui::RenderIntent::COLORIMETRIC, mOutRenderIntent);
}
diff --git a/services/surfaceflinger/tests/unittests/IdleTimerTest.cpp b/services/surfaceflinger/tests/unittests/IdleTimerTest.cpp
new file mode 100644
index 0000000..9fe9a18
--- /dev/null
+++ b/services/surfaceflinger/tests/unittests/IdleTimerTest.cpp
@@ -0,0 +1,126 @@
+/*
+ * Copyright 2018 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.
+ */
+
+#undef LOG_TAG
+#define LOG_TAG "SchedulerUnittests"
+
+#include <gmock/gmock.h>
+#include <gtest/gtest.h>
+#include <utils/Log.h>
+
+#include "AsyncCallRecorder.h"
+#include "Scheduler/IdleTimer.h"
+
+using namespace std::chrono_literals;
+
+namespace android {
+namespace scheduler {
+
+class IdleTimerTest : public testing::Test {
+protected:
+ IdleTimerTest() = default;
+ ~IdleTimerTest() override = default;
+
+ AsyncCallRecorder<void (*)()> mExpiredTimerCallback;
+
+ std::unique_ptr<IdleTimer> mIdleTimer;
+};
+
+namespace {
+TEST_F(IdleTimerTest, createAndDestroyTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(30ms, [] {});
+}
+
+TEST_F(IdleTimerTest, startStopTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(30ms, mExpiredTimerCallback.getInvocable());
+ mIdleTimer->start();
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ // The timer expires after 30 ms, so the call to the callback should not happen.
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall().has_value());
+ mIdleTimer->stop();
+}
+
+TEST_F(IdleTimerTest, resetTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(20ms, mExpiredTimerCallback.getInvocable());
+ mIdleTimer->start();
+ std::this_thread::sleep_for(std::chrono::milliseconds(10));
+ // The timer expires after 30 ms, so the call to the callback should not happen.
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ mIdleTimer->reset();
+ // The timer was reset, so the call to the callback should not happen.
+ std::this_thread::sleep_for(std::chrono::milliseconds(15));
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ mIdleTimer->stop();
+}
+
+TEST_F(IdleTimerTest, startNotCalledTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(3ms, mExpiredTimerCallback.getInvocable());
+ std::this_thread::sleep_for(6ms);
+ // The start hasn't happened, so the callback does not happen.
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ mIdleTimer->stop();
+}
+
+TEST_F(IdleTimerTest, idleTimerIdlesTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(3ms, mExpiredTimerCallback.getInvocable());
+ mIdleTimer->start();
+ std::this_thread::sleep_for(6ms);
+ // The timer expires after 3 ms, so the call to the callback happens.
+ EXPECT_TRUE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ std::this_thread::sleep_for(6ms);
+ // Timer can be idle.
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ // Timer can be reset.
+ mIdleTimer->reset();
+ std::this_thread::sleep_for(6ms);
+ // Timer fires again.
+ EXPECT_TRUE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ mIdleTimer->stop();
+}
+
+TEST_F(IdleTimerTest, timeoutCallbackExecutionTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(3ms, mExpiredTimerCallback.getInvocable());
+
+ mIdleTimer->start();
+ std::this_thread::sleep_for(6ms);
+ // The timer expires after 3 ms, so the call to the callback should happen.
+ EXPECT_TRUE(mExpiredTimerCallback.waitForCall(1us).has_value());
+ mIdleTimer->stop();
+}
+
+TEST_F(IdleTimerTest, noCallbacksAfterStopAndResetTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(3ms, mExpiredTimerCallback.getInvocable());
+ mIdleTimer->start();
+ std::this_thread::sleep_for(6ms);
+ EXPECT_TRUE(mExpiredTimerCallback.waitForCall().has_value());
+ mIdleTimer->stop();
+ mIdleTimer->reset();
+ std::this_thread::sleep_for(6ms);
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall().has_value());
+}
+
+TEST_F(IdleTimerTest, noCallbacksAfterStopTest) {
+ mIdleTimer = std::make_unique<scheduler::IdleTimer>(3ms, mExpiredTimerCallback.getInvocable());
+ mIdleTimer->start();
+ std::this_thread::sleep_for(1ms);
+ mIdleTimer->stop();
+ std::this_thread::sleep_for(3ms);
+ EXPECT_FALSE(mExpiredTimerCallback.waitForCall(1us).has_value());
+}
+
+} // namespace
+} // namespace scheduler
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
index d0cf1b7..35f30d7 100644
--- a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
+++ b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp
@@ -117,7 +117,7 @@
mScheduler->hotplugReceived(nullptr, EventThread::DisplayType::Primary, false));
ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenAcquired(nullptr));
ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(nullptr));
- String8 testString;
+ std::string testString;
ASSERT_NO_FATAL_FAILURE(mScheduler->dump(nullptr, testString));
EXPECT_TRUE(testString == "");
ASSERT_NO_FATAL_FAILURE(mScheduler->setPhaseOffset(nullptr, 10));
@@ -146,7 +146,7 @@
EXPECT_CALL(*mEventThread, onScreenReleased()).Times(0);
ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(connectionHandle));
- String8 testString;
+ std::string testString;
EXPECT_CALL(*mEventThread, dump(_)).Times(0);
ASSERT_NO_FATAL_FAILURE(mScheduler->dump(connectionHandle, testString));
EXPECT_TRUE(testString == "");
@@ -176,7 +176,7 @@
EXPECT_CALL(*mEventThread, onScreenReleased()).Times(1);
ASSERT_NO_FATAL_FAILURE(mScheduler->onScreenReleased(mConnectionHandle));
- String8 testString("dump");
+ std::string testString("dump");
EXPECT_CALL(*mEventThread, dump(testString)).Times(1);
ASSERT_NO_FATAL_FAILURE(mScheduler->dump(mConnectionHandle, testString));
EXPECT_TRUE(testString != "");
diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
index 6d4f7ef..4da08b8 100644
--- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
+++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h
@@ -178,11 +178,12 @@
using HotplugEvent = SurfaceFlinger::HotplugEvent;
- auto& mutableLayerCurrentState(sp<Layer> layer) { return layer->mCurrentState; }
- auto& mutableLayerDrawingState(sp<Layer> layer) { return layer->mDrawingState; }
+ auto& mutableLayerCurrentState(sp<Layer> layer) { return layer->mState.current; }
+ auto& mutableLayerDrawingState(sp<Layer> layer) { return layer->mState.drawing; }
void setLayerSidebandStream(sp<Layer> layer, sp<NativeHandle> sidebandStream) {
- layer->mDrawingState.sidebandStream = sidebandStream;
+ Mutex::Autolock lock(layer->mStateMutex);
+ layer->mState.drawing.sidebandStream = sidebandStream;
layer->getBE().compositionInfo.hwc.sidebandStream = sidebandStream;
}
@@ -226,9 +227,8 @@
auto onInitializeDisplays() { return mFlinger->onInitializeDisplays(); }
- auto setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
- bool stateLockHeld = false) {
- return mFlinger->setPowerModeInternal(display, mode, stateLockHeld);
+ auto setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
+ return mFlinger->setPowerModeInternal(display, mode);
}
auto onMessageReceived(int32_t what) { return mFlinger->onMessageReceived(what); }
diff --git a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
index 186ed79..86f1a39 100644
--- a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
@@ -21,13 +21,14 @@
#include <log/log.h>
#include <utils/String16.h>
-#include <utils/String8.h>
#include <utils/Vector.h>
#include <random>
#include "TimeStats/TimeStats.h"
+#include "libsurfaceflinger_unittest_main.h"
+
using namespace android::surfaceflinger;
using namespace google::protobuf;
@@ -131,7 +132,7 @@
std::string TimeStatsTest::inputCommand(InputCommand cmd, bool useProto) {
size_t index = 0;
- String8 result;
+ std::string result;
Vector<String16> args;
switch (cmd) {
@@ -162,7 +163,7 @@
}
EXPECT_NO_FATAL_FAILURE(mTimeStats->parseArgs(useProto, args, index, result));
- return std::string(result.string(), result.size());
+ return result;
}
static std::string genLayerName(int32_t layerID) {
@@ -487,6 +488,10 @@
}
TEST_F(TimeStatsTest, canSurviveMonkey) {
+ if (g_noSlowTests) {
+ GTEST_SKIP();
+ }
+
EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
for (size_t i = 0; i < 10000000; ++i) {
diff --git a/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.cpp b/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.cpp
new file mode 100644
index 0000000..bc1f00d
--- /dev/null
+++ b/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.cpp
@@ -0,0 +1,49 @@
+/*
+ * Copyright 2018 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 <gtest/gtest.h>
+
+#include "libsurfaceflinger_unittest_main.h"
+
+// ------------------------------------------------------------------------
+// To pass extra command line arguments to the Google Test executable from
+// atest, you have to use this somewhat verbose syntax:
+//
+// clang-format off
+//
+// atest libsurfaceflinger_unittest -- --module-arg libsurfaceflinger_unittest:native-test-flag:<--flag>[:<value>]
+//
+// For example:
+//
+// atest libsurfaceflinger_unittest -- --module-arg libsurfaceflinger_unittest:native-test-flag:--no-slow
+//
+// clang-format on
+// ------------------------------------------------------------------------
+
+// Set to true if "--no-slow" is passed to the test.
+bool g_noSlowTests = false;
+
+int main(int argc, char **argv) {
+ ::testing::InitGoogleTest(&argc, argv);
+
+ for (int i = 1; i < argc; i++) {
+ if (strcmp(argv[i], "--no-slow") == 0) {
+ g_noSlowTests = true;
+ }
+ }
+
+ return RUN_ALL_TESTS();
+}
\ No newline at end of file
diff --git a/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.h b/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.h
new file mode 100644
index 0000000..e742c50
--- /dev/null
+++ b/services/surfaceflinger/tests/unittests/libsurfaceflinger_unittest_main.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2018 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
+
+// Set to true if "--no-slow" is passed to the test.
+extern bool g_noSlowTests;
diff --git a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
index 68fd8b4..dfdda09 100644
--- a/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
+++ b/services/surfaceflinger/tests/unittests/mock/DisplayHardware/MockComposer.h
@@ -116,6 +116,8 @@
MOCK_METHOD4(getDisplayedContentSamplingAttributes,
Error(Display, PixelFormat*, Dataspace*, uint8_t*));
MOCK_METHOD4(setDisplayContentSamplingEnabled, Error(Display, bool, uint8_t, uint64_t));
+ MOCK_METHOD4(getDisplayedContentSample,
+ Error(Display, uint64_t, uint64_t, DisplayedFrameStats*));
MOCK_METHOD2(getDisplayCapabilities, Error(Display, std::vector<DisplayCapability>*));
};
diff --git a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
index 34e71cb..9213ae5 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockDispSync.h
@@ -18,7 +18,6 @@
#include <gmock/gmock.h>
-#include <utils/String8.h>
#include "Scheduler/DispSync.h"
namespace android {
@@ -44,7 +43,7 @@
MOCK_METHOD1(setIgnorePresentFences, void(bool));
MOCK_METHOD0(expectedPresentTime, nsecs_t());
- MOCK_CONST_METHOD1(dump, void(String8&));
+ MOCK_CONST_METHOD1(dump, void(std::string&));
};
} // namespace mock
diff --git a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
index ad2463d..0a1c827 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h
@@ -32,7 +32,7 @@
MOCK_METHOD0(onScreenReleased, void());
MOCK_METHOD0(onScreenAcquired, void());
MOCK_METHOD2(onHotplugReceived, void(DisplayType, bool));
- MOCK_CONST_METHOD1(dump, void(String8&));
+ MOCK_CONST_METHOD1(dump, void(std::string&));
MOCK_METHOD1(setPhaseOffset, void(nsecs_t phaseOffset));
};
diff --git a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
index a416808..1bee271 100644
--- a/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
+++ b/services/surfaceflinger/tests/unittests/mock/RenderEngine/MockRenderEngine.h
@@ -38,7 +38,7 @@
MOCK_METHOD0(createFramebuffer, std::unique_ptr<Framebuffer>());
MOCK_METHOD0(createImage, std::unique_ptr<renderengine::Image>());
MOCK_CONST_METHOD0(primeCache, void());
- MOCK_METHOD1(dump, void(String8&));
+ MOCK_METHOD1(dump, void(std::string&));
MOCK_CONST_METHOD0(useNativeFenceSync, bool());
MOCK_CONST_METHOD0(useWaitSync, bool());
MOCK_CONST_METHOD0(isCurrent, bool());
@@ -74,6 +74,9 @@
MOCK_METHOD1(drawMesh, void(const Mesh&));
MOCK_CONST_METHOD0(getMaxTextureSize, size_t());
MOCK_CONST_METHOD0(getMaxViewportDims, size_t());
+ MOCK_CONST_METHOD0(isProtected, bool());
+ MOCK_CONST_METHOD0(supportsProtectedContent, bool());
+ MOCK_METHOD1(useProtectedContext, bool(bool));
MOCK_CONST_METHOD4(drawLayers,
status_t(const DisplaySettings&, const std::vector<LayerSettings>&,
ANativeWindowBuffer* const, base::unique_fd*));
@@ -84,8 +87,7 @@
Image();
~Image() override;
- MOCK_METHOD2(setNativeWindowBuffer,
- bool(ANativeWindowBuffer* buffer, bool isProtected));
+ MOCK_METHOD2(setNativeWindowBuffer, bool(ANativeWindowBuffer*, bool));
};
class Framebuffer : public renderengine::Framebuffer {
@@ -93,7 +95,7 @@
Framebuffer();
~Framebuffer() override;
- MOCK_METHOD1(setNativeWindowBuffer, bool(ANativeWindowBuffer*));
+ MOCK_METHOD2(setNativeWindowBuffer, bool(ANativeWindowBuffer*, bool));
};
} // namespace mock
diff --git a/services/utils/tests/PriorityDumper_test.cpp b/services/utils/tests/PriorityDumper_test.cpp
index 90cc6de..2320a90 100644
--- a/services/utils/tests/PriorityDumper_test.cpp
+++ b/services/utils/tests/PriorityDumper_test.cpp
@@ -54,7 +54,7 @@
};
static void addAll(Vector<String16>& av, const std::vector<std::string>& v) {
- for (auto element : v) {
+ for (const auto& element : v) {
av.add(String16(element.c_str()));
}
}
diff --git a/services/vr/bufferhubd/Android.bp b/services/vr/bufferhubd/Android.bp
index 0a59f29..7a7e437 100644
--- a/services/vr/bufferhubd/Android.bp
+++ b/services/vr/bufferhubd/Android.bp
@@ -14,7 +14,6 @@
sharedLibraries = [
"libbase",
- "libbinder",
"libbufferhubservice",
"libcutils",
"libgtest_prod",
@@ -30,12 +29,9 @@
name: "libbufferhubd",
srcs: [
"buffer_channel.cpp",
- "buffer_client.cpp",
"buffer_hub.cpp",
- "buffer_hub_binder.cpp",
"consumer_channel.cpp",
"consumer_queue_channel.cpp",
- "IBufferHub.cpp",
"producer_channel.cpp",
"producer_queue_channel.cpp",
],
@@ -45,10 +41,7 @@
"-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
],
export_include_dirs: ["include"],
- header_libs: [
- "libdvr_headers",
- "libnativewindow_headers",
- ],
+ header_libs: ["libdvr_headers"],
shared_libs: sharedLibraries,
static_libs: [
"libbufferhub",
diff --git a/services/vr/bufferhubd/IBufferHub.cpp b/services/vr/bufferhubd/IBufferHub.cpp
deleted file mode 100644
index 5980873..0000000
--- a/services/vr/bufferhubd/IBufferHub.cpp
+++ /dev/null
@@ -1,110 +0,0 @@
-#include <log/log.h>
-#include <private/dvr/IBufferHub.h>
-
-namespace android {
-namespace dvr {
-
-class BpBufferHub : public BpInterface<IBufferHub> {
- public:
- explicit BpBufferHub(const sp<IBinder>& impl)
- : BpInterface<IBufferHub>(impl) {}
-
- sp<IBufferClient> createBuffer(uint32_t width, uint32_t height,
- uint32_t layer_count, uint32_t format,
- uint64_t usage,
- uint64_t user_metadata_size) override;
-
- status_t importBuffer(uint64_t token, sp<IBufferClient>* outClient) override;
-};
-
-IMPLEMENT_META_INTERFACE(BufferHub, "android.dvr.IBufferHub");
-
-// Transaction code
-enum {
- CREATE_BUFFER = IBinder::FIRST_CALL_TRANSACTION,
- IMPORT_BUFFER,
-};
-
-sp<IBufferClient> BpBufferHub::createBuffer(uint32_t width, uint32_t height,
- uint32_t layer_count,
- uint32_t format, uint64_t usage,
- uint64_t user_metadata_size) {
- Parcel data, reply;
- status_t ret = OK;
- ret |= data.writeInterfaceToken(IBufferHub::getInterfaceDescriptor());
- ret |= data.writeUint32(width);
- ret |= data.writeUint32(height);
- ret |= data.writeUint32(layer_count);
- ret |= data.writeUint32(format);
- ret |= data.writeUint64(usage);
- ret |= data.writeUint64(user_metadata_size);
-
- if (ret != OK) {
- ALOGE("BpBufferHub::createBuffer: failed to write into parcel");
- return nullptr;
- }
-
- ret = remote()->transact(CREATE_BUFFER, data, &reply);
- if (ret == OK) {
- return interface_cast<IBufferClient>(reply.readStrongBinder());
- } else {
- ALOGE("BpBufferHub::createBuffer: failed to transact; errno=%d", ret);
- return nullptr;
- }
-}
-
-status_t BpBufferHub::importBuffer(uint64_t token,
- sp<IBufferClient>* outClient) {
- Parcel data, reply;
- status_t ret = OK;
- ret |= data.writeInterfaceToken(IBufferHub::getInterfaceDescriptor());
- ret |= data.writeUint64(token);
- if (ret != OK) {
- ALOGE("BpBufferHub::importBuffer: failed to write into parcel");
- return ret;
- }
-
- ret = remote()->transact(IMPORT_BUFFER, data, &reply);
- if (ret == OK) {
- *outClient = interface_cast<IBufferClient>(reply.readStrongBinder());
- return OK;
- } else {
- ALOGE("BpBufferHub::importBuffer: failed to transact; errno=%d", ret);
- return ret;
- }
-}
-
-status_t BnBufferHub::onTransact(uint32_t code, const Parcel& data,
- Parcel* reply, uint32_t flags) {
- switch (code) {
- case CREATE_BUFFER: {
- CHECK_INTERFACE(IBufferHub, data, reply);
- uint32_t width = data.readUint32();
- uint32_t height = data.readUint32();
- uint32_t layer_count = data.readUint32();
- uint32_t format = data.readUint32();
- uint64_t usage = data.readUint64();
- uint64_t user_metadata_size = data.readUint64();
- sp<IBufferClient> ret = createBuffer(width, height, layer_count, format,
- usage, user_metadata_size);
- return reply->writeStrongBinder(IInterface::asBinder(ret));
- }
- case IMPORT_BUFFER: {
- CHECK_INTERFACE(IBufferHub, data, reply);
- uint64_t token = data.readUint64();
- sp<IBufferClient> client;
- status_t ret = importBuffer(token, &client);
- if (ret == OK) {
- return reply->writeStrongBinder(IInterface::asBinder(client));
- } else {
- return ret;
- }
- }
- default:
- // Should not reach except binder defined transactions such as dumpsys
- return BBinder::onTransact(code, data, reply, flags);
- }
-}
-
-} // namespace dvr
-} // namespace android
\ No newline at end of file
diff --git a/services/vr/bufferhubd/buffer_channel.cpp b/services/vr/bufferhubd/buffer_channel.cpp
index cf072b6..695396c 100644
--- a/services/vr/bufferhubd/buffer_channel.cpp
+++ b/services/vr/bufferhubd/buffer_channel.cpp
@@ -32,7 +32,7 @@
: BufferHubChannel(service, buffer_id, channel_id, kDetachedBufferType),
buffer_node_(buffer_node) {
client_state_mask_ = buffer_node_->AddNewActiveClientsBitToMask();
- if (client_state_mask_ == 0ULL) {
+ if (client_state_mask_ == 0U) {
ALOGE("BufferChannel::BufferChannel: %s", strerror(errno));
buffer_node_ = nullptr;
}
@@ -41,7 +41,7 @@
BufferChannel::~BufferChannel() {
ALOGD_IF(TRACE, "BufferChannel::~BufferChannel: channel_id=%d buffer_id=%d.",
channel_id(), buffer_id());
- if (client_state_mask_ != 0ULL) {
+ if (client_state_mask_ != 0U) {
buffer_node_->RemoveClientsBitFromMask(client_state_mask_);
}
Hangup();
diff --git a/services/vr/bufferhubd/buffer_client.cpp b/services/vr/bufferhubd/buffer_client.cpp
deleted file mode 100644
index f14faf7..0000000
--- a/services/vr/bufferhubd/buffer_client.cpp
+++ /dev/null
@@ -1,18 +0,0 @@
-#include <private/dvr/buffer_client.h>
-#include <private/dvr/buffer_hub_binder.h>
-
-namespace android {
-namespace dvr {
-
-status_t BufferClient::duplicate(uint64_t* outToken) {
- if (!buffer_node_) {
- // Should never happen
- ALOGE("BufferClient::duplicate: node is missing.");
- return UNEXPECTED_NULL;
- }
- return service_->registerToken(std::weak_ptr<BufferNode>(buffer_node_),
- outToken);
-}
-
-} // namespace dvr
-} // namespace android
\ No newline at end of file
diff --git a/services/vr/bufferhubd/buffer_hub_binder.cpp b/services/vr/bufferhubd/buffer_hub_binder.cpp
deleted file mode 100644
index 580433e..0000000
--- a/services/vr/bufferhubd/buffer_hub_binder.cpp
+++ /dev/null
@@ -1,129 +0,0 @@
-#include <stdio.h>
-
-#include <binder/IPCThreadState.h>
-#include <binder/IServiceManager.h>
-#include <binder/ProcessState.h>
-#include <log/log.h>
-#include <private/dvr/buffer_hub_binder.h>
-#include <private/dvr/buffer_node.h>
-
-namespace android {
-namespace dvr {
-
-status_t BufferHubBinderService::start(
- const std::shared_ptr<BufferHubService>& pdx_service) {
- IPCThreadState::self()->disableBackgroundScheduling(true);
-
- sp<BufferHubBinderService> service = new BufferHubBinderService();
- service->pdx_service_ = pdx_service;
-
- // Not using BinderService::publish because need to get an instance of this
- // class (above). Following code is the same as
- // BinderService::publishAndJoinThreadPool
- sp<IServiceManager> sm = defaultServiceManager();
- status_t result = sm->addService(
- String16(getServiceName()), service,
- /*allowIsolated =*/false,
- /*dump flags =*/IServiceManager::DUMP_FLAG_PRIORITY_DEFAULT);
- if (result != OK) {
- ALOGE("Publishing bufferhubd failed with error %d", result);
- return result;
- }
-
- sp<ProcessState> process_self(ProcessState::self());
- process_self->startThreadPool();
-
- return result;
-}
-
-status_t BufferHubBinderService::dump(int fd, const Vector<String16>& args) {
- FILE* out = fdopen(dup(fd), "w");
-
- // Currently not supporting args, so notify the user.
- if (!args.isEmpty()) {
- fprintf(out,
- "Note: dumpsys bufferhubd currently does not support args."
- "Input arguments are ignored.\n");
- }
-
- fprintf(out, "Binder service:\n");
- // Active buffers
- fprintf(out, "Active BufferClients: %zu\n", client_list_.size());
- // TODO(b/117790952): print buffer information after BufferNode has it
- // TODO(b/116526156): print more information once we have them
-
- if (pdx_service_) {
- fprintf(out, "\nPDX service:\n");
- // BufferHubService::Dumpstate(size_t) is not actually using the param
- // So just using 0 as the length
- fprintf(out, "%s", pdx_service_->DumpState(0).c_str());
- } else {
- fprintf(out, "PDX service not registered or died.\n");
- }
-
- fclose(out);
- return OK;
-}
-
-status_t BufferHubBinderService::registerToken(
- const std::weak_ptr<BufferNode> node, uint64_t* outToken) {
- do {
- *outToken = token_engine_();
- } while (token_map_.find(*outToken) != token_map_.end());
-
- token_map_.emplace(*outToken, node);
- return OK;
-}
-
-sp<IBufferClient> BufferHubBinderService::createBuffer(
- uint32_t width, uint32_t height, uint32_t layer_count, uint32_t format,
- uint64_t usage, uint64_t user_metadata_size) {
- std::shared_ptr<BufferNode> node = std::make_shared<BufferNode>(
- width, height, layer_count, format, usage, user_metadata_size);
-
- sp<BufferClient> client = new BufferClient(node, this);
- // Add it to list for bookkeeping and dumpsys.
- client_list_.push_back(client);
-
- return client;
-}
-
-status_t BufferHubBinderService::importBuffer(uint64_t token,
- sp<IBufferClient>* outClient) {
- auto iter = token_map_.find(token);
-
- if (iter == token_map_.end()) { // Not found
- ALOGE("BufferHubBinderService::importBuffer: token %" PRIu64
- "does not exist.",
- token);
- return PERMISSION_DENIED;
- }
-
- if (iter->second.expired()) { // Gone
- ALOGW(
- "BufferHubBinderService::importBuffer: the original node of token "
- "%" PRIu64 "has gone.",
- token);
- token_map_.erase(iter);
- return DEAD_OBJECT;
- }
-
- // Promote the weak_ptr
- std::shared_ptr<BufferNode> node(iter->second);
- if (!node) {
- ALOGE("BufferHubBinderService::importBuffer: promote weak_ptr failed.");
- token_map_.erase(iter);
- return DEAD_OBJECT;
- }
-
- sp<BufferClient> client = new BufferClient(node, this);
- *outClient = client;
-
- token_map_.erase(iter);
- client_list_.push_back(client);
-
- return OK;
-}
-
-} // namespace dvr
-} // namespace android
diff --git a/services/vr/bufferhubd/bufferhubd.cpp b/services/vr/bufferhubd/bufferhubd.cpp
index e44cc2a..50cb3b7 100644
--- a/services/vr/bufferhubd/bufferhubd.cpp
+++ b/services/vr/bufferhubd/bufferhubd.cpp
@@ -6,7 +6,6 @@
#include <log/log.h>
#include <pdx/service_dispatcher.h>
#include <private/dvr/buffer_hub.h>
-#include <private/dvr/buffer_hub_binder.h>
int main(int, char**) {
int ret = -1;
@@ -40,10 +39,6 @@
CHECK_ERROR(!pdx_service, error, "Failed to create bufferhub pdx service\n");
dispatcher->AddService(pdx_service);
- ret = android::dvr::BufferHubBinderService::start(pdx_service);
- CHECK_ERROR(ret != android::OK, error,
- "Failed to create bufferhub binder service\n");
-
ret = dvrSetSchedulerClass(0, "graphics");
CHECK_ERROR(ret < 0, error, "Failed to set thread priority");
diff --git a/services/vr/bufferhubd/consumer_channel.cpp b/services/vr/bufferhubd/consumer_channel.cpp
index f936e95..c7695bc 100644
--- a/services/vr/bufferhubd/consumer_channel.cpp
+++ b/services/vr/bufferhubd/consumer_channel.cpp
@@ -17,7 +17,7 @@
namespace dvr {
ConsumerChannel::ConsumerChannel(BufferHubService* service, int buffer_id,
- int channel_id, uint64_t client_state_mask,
+ int channel_id, uint32_t client_state_mask,
const std::shared_ptr<Channel> producer)
: BufferHubChannel(service, buffer_id, channel_id, kConsumerType),
client_state_mask_(client_state_mask),
@@ -153,6 +153,17 @@
}
}
+void ConsumerChannel::OnProducerGained() {
+ // Clear the signal if exist. There is a possiblity that the signal still
+ // exist in consumer client when producer gains the buffer, e.g. newly added
+ // consumer fail to acquire the previous posted buffer in time. Then, when
+ // producer gains back the buffer, posts the buffer again and signal the
+ // consumer later, there won't be an signal change in eventfd, and thus,
+ // consumer will miss the posted buffer later. Thus, we need to clear the
+ // signal in consumer clients if the signal exist.
+ ClearAvailable();
+}
+
void ConsumerChannel::OnProducerPosted() {
acquired_ = false;
released_ = false;
diff --git a/services/vr/bufferhubd/include/private/dvr/IBufferHub.h b/services/vr/bufferhubd/include/private/dvr/IBufferHub.h
deleted file mode 100644
index 502c6d6..0000000
--- a/services/vr/bufferhubd/include/private/dvr/IBufferHub.h
+++ /dev/null
@@ -1,34 +0,0 @@
-#ifndef ANDROID_DVR_IBUFFERHUB_H
-#define ANDROID_DVR_IBUFFERHUB_H
-
-#include <binder/IInterface.h>
-#include <binder/Parcel.h>
-#include <private/dvr/IBufferClient.h>
-
-namespace android {
-namespace dvr {
-
-class IBufferHub : public IInterface {
- public:
- DECLARE_META_INTERFACE(BufferHub);
-
- static const char* getServiceName() { return "bufferhubd"; }
- virtual sp<IBufferClient> createBuffer(uint32_t width, uint32_t height,
- uint32_t layer_count, uint32_t format,
- uint64_t usage,
- uint64_t user_metadata_size) = 0;
-
- virtual status_t importBuffer(uint64_t token,
- sp<IBufferClient>* outClient) = 0;
-};
-
-class BnBufferHub : public BnInterface<IBufferHub> {
- public:
- virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply,
- uint32_t flags = 0);
-};
-
-} // namespace dvr
-} // namespace android
-
-#endif // ANDROID_DVR_IBUFFERHUB_H
\ No newline at end of file
diff --git a/services/vr/bufferhubd/include/private/dvr/buffer_channel.h b/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
index 744c095..9888db6 100644
--- a/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
+++ b/services/vr/bufferhubd/include/private/dvr/buffer_channel.h
@@ -51,8 +51,8 @@
// The concrete implementation of the Buffer object.
std::shared_ptr<BufferNode> buffer_node_ = nullptr;
- // The state bit of this buffer. Must be one the lower 63 bits.
- uint64_t client_state_mask_ = 0ULL;
+ // The state bit of this buffer.
+ uint32_t client_state_mask_ = 0U;
};
} // namespace dvr
diff --git a/services/vr/bufferhubd/include/private/dvr/buffer_client.h b/services/vr/bufferhubd/include/private/dvr/buffer_client.h
deleted file mode 100644
index d79ec0a..0000000
--- a/services/vr/bufferhubd/include/private/dvr/buffer_client.h
+++ /dev/null
@@ -1,41 +0,0 @@
-#ifndef ANDROID_DVR_BUFFERCLIENT_H
-#define ANDROID_DVR_BUFFERCLIENT_H
-
-#include <private/dvr/IBufferClient.h>
-#include <private/dvr/buffer_node.h>
-
-namespace android {
-namespace dvr {
-
-// Forward declaration to avoid circular dependency
-class BufferHubBinderService;
-
-class BufferClient : public BnBufferClient {
- public:
- // Creates a server-side buffer client from an existing BufferNode. Note that
- // this funciton takes ownership of the shared_ptr.
- explicit BufferClient(std::shared_ptr<BufferNode> node,
- BufferHubBinderService* service)
- : service_(service), buffer_node_(std::move(node)){};
-
- // Binder IPC functions
- bool isValid() override {
- return buffer_node_ ? buffer_node_->IsValid() : false;
- };
-
- status_t duplicate(uint64_t* outToken) override;
-
- private:
- // Hold a pointer to the service to bypass binder interface, as BufferClient
- // and the service will be in the same process. Also, since service owns
- // Client, if service dead the clients will be destroyed, so this pointer is
- // guaranteed to be valid.
- BufferHubBinderService* service_;
-
- std::shared_ptr<BufferNode> buffer_node_;
-};
-
-} // namespace dvr
-} // namespace android
-
-#endif // ANDROID_DVR_IBUFFERCLIENT_H
\ No newline at end of file
diff --git a/services/vr/bufferhubd/include/private/dvr/buffer_hub_binder.h b/services/vr/bufferhubd/include/private/dvr/buffer_hub_binder.h
deleted file mode 100644
index cf6124b..0000000
--- a/services/vr/bufferhubd/include/private/dvr/buffer_hub_binder.h
+++ /dev/null
@@ -1,53 +0,0 @@
-#ifndef ANDROID_DVR_BUFFER_HUB_BINDER_H
-#define ANDROID_DVR_BUFFER_HUB_BINDER_H
-
-#include <random>
-#include <unordered_map>
-#include <vector>
-
-#include <binder/BinderService.h>
-#include <private/dvr/IBufferHub.h>
-#include <private/dvr/buffer_client.h>
-#include <private/dvr/buffer_hub.h>
-#include <private/dvr/buffer_node.h>
-
-namespace android {
-namespace dvr {
-
-class BufferHubBinderService : public BinderService<BufferHubBinderService>,
- public BnBufferHub {
- public:
- static status_t start(const std::shared_ptr<BufferHubService>& pdx_service);
- // Dumps bufferhub related information to given fd (usually stdout)
- // usage: adb shell dumpsys bufferhubd
- virtual status_t dump(int fd, const Vector<String16>& args) override;
-
- // Marks a BufferNode to be duplicated.
- // TODO(b/116681016): add importToken(int64_t)
- status_t registerToken(const std::weak_ptr<BufferNode> node,
- uint64_t* outToken);
-
- // Binder IPC functions
- sp<IBufferClient> createBuffer(uint32_t width, uint32_t height,
- uint32_t layer_count, uint32_t format,
- uint64_t usage,
- uint64_t user_metadata_size) override;
-
- status_t importBuffer(uint64_t token, sp<IBufferClient>* outClient) override;
-
- private:
- std::shared_ptr<BufferHubService> pdx_service_;
-
- std::vector<sp<BufferClient>> client_list_;
-
- // TODO(b/118180214): use a more secure implementation
- std::mt19937_64 token_engine_;
- // The mapping from token to a specific node. This is a many-to-one mapping.
- // One node could be refered by 0 to multiple tokens.
- std::unordered_map<uint64_t, std::weak_ptr<BufferNode>> token_map_;
-};
-
-} // namespace dvr
-} // namespace android
-
-#endif // ANDROID_DVR_BUFFER_HUB_BINDER_H
diff --git a/services/vr/bufferhubd/include/private/dvr/consumer_channel.h b/services/vr/bufferhubd/include/private/dvr/consumer_channel.h
index de0f23c..5ee551f 100644
--- a/services/vr/bufferhubd/include/private/dvr/consumer_channel.h
+++ b/services/vr/bufferhubd/include/private/dvr/consumer_channel.h
@@ -16,16 +16,17 @@
using Message = pdx::Message;
ConsumerChannel(BufferHubService* service, int buffer_id, int channel_id,
- uint64_t client_state_mask,
+ uint32_t client_state_mask,
const std::shared_ptr<Channel> producer);
~ConsumerChannel() override;
bool HandleMessage(Message& message) override;
void HandleImpulse(Message& message) override;
- uint64_t client_state_mask() const { return client_state_mask_; }
+ uint32_t client_state_mask() const { return client_state_mask_; }
BufferInfo GetBufferInfo() const override;
+ void OnProducerGained();
void OnProducerPosted();
void OnProducerClosed();
@@ -38,7 +39,7 @@
pdx::Status<void> OnConsumerRelease(Message& message,
LocalFence release_fence);
- uint64_t client_state_mask_{0};
+ uint32_t client_state_mask_{0U};
bool acquired_{false};
bool released_{true};
std::weak_ptr<Channel> producer_;
diff --git a/services/vr/bufferhubd/include/private/dvr/producer_channel.h b/services/vr/bufferhubd/include/private/dvr/producer_channel.h
index 4734439..96ef1a2 100644
--- a/services/vr/bufferhubd/include/private/dvr/producer_channel.h
+++ b/services/vr/bufferhubd/include/private/dvr/producer_channel.h
@@ -42,7 +42,7 @@
~ProducerChannel() override;
- uint64_t buffer_state() const {
+ uint32_t buffer_state() const {
return buffer_state_->load(std::memory_order_acquire);
}
@@ -51,18 +51,18 @@
BufferInfo GetBufferInfo() const override;
- BufferDescription<BorrowedHandle> GetBuffer(uint64_t client_state_mask);
+ BufferDescription<BorrowedHandle> GetBuffer(uint32_t client_state_mask);
pdx::Status<RemoteChannelHandle> CreateConsumer(Message& message,
- uint64_t consumer_state_mask);
- pdx::Status<uint64_t> CreateConsumerStateMask();
+ uint32_t consumer_state_mask);
+ pdx::Status<uint32_t> CreateConsumerStateMask();
pdx::Status<RemoteChannelHandle> OnNewConsumer(Message& message);
pdx::Status<LocalFence> OnConsumerAcquire(Message& message);
pdx::Status<void> OnConsumerRelease(Message& message,
LocalFence release_fence);
- void OnConsumerOrphaned(const uint64_t& consumer_state_mask);
+ void OnConsumerOrphaned(const uint32_t& consumer_state_mask);
void AddConsumer(ConsumerChannel* channel);
void RemoveConsumer(ConsumerChannel* channel);
@@ -79,13 +79,13 @@
// IonBuffer that is shared between bufferhubd, producer, and consumers.
IonBuffer metadata_buffer_;
BufferHubDefs::MetadataHeader* metadata_header_ = nullptr;
- std::atomic<uint64_t>* buffer_state_ = nullptr;
- std::atomic<uint64_t>* fence_state_ = nullptr;
- std::atomic<uint64_t>* active_clients_bit_mask_ = nullptr;
+ std::atomic<uint32_t>* buffer_state_ = nullptr;
+ std::atomic<uint32_t>* fence_state_ = nullptr;
+ std::atomic<uint32_t>* active_clients_bit_mask_ = nullptr;
// All orphaned consumer bits. Valid bits are the lower 63 bits, while the
// highest bit is reserved for the producer and should not be set.
- uint64_t orphaned_consumer_bit_mask_{0ULL};
+ uint32_t orphaned_consumer_bit_mask_{0U};
LocalFence post_fence_;
LocalFence returned_fence_;
@@ -110,7 +110,7 @@
// Remove consumer from atomics in shared memory based on consumer_state_mask.
// This function is used for clean up for failures in CreateConsumer method.
- void RemoveConsumerClientMask(uint64_t consumer_state_mask);
+ void RemoveConsumerClientMask(uint32_t consumer_state_mask);
ProducerChannel(const ProducerChannel&) = delete;
void operator=(const ProducerChannel&) = delete;
diff --git a/services/vr/bufferhubd/producer_channel.cpp b/services/vr/bufferhubd/producer_channel.cpp
index ab1d94c..1682bfe 100644
--- a/services/vr/bufferhubd/producer_channel.cpp
+++ b/services/vr/bufferhubd/producer_channel.cpp
@@ -93,10 +93,10 @@
// Using placement new here to reuse shared memory instead of new allocation
// and also initialize the value to zero.
buffer_state_ =
- new (&metadata_header_->buffer_state) std::atomic<uint64_t>(0);
- fence_state_ = new (&metadata_header_->fence_state) std::atomic<uint64_t>(0);
+ new (&metadata_header_->buffer_state) std::atomic<uint32_t>(0);
+ fence_state_ = new (&metadata_header_->fence_state) std::atomic<uint32_t>(0);
active_clients_bit_mask_ =
- new (&metadata_header_->active_clients_bit_mask) std::atomic<uint64_t>(0);
+ new (&metadata_header_->active_clients_bit_mask) std::atomic<uint32_t>(0);
// Producer channel is never created after consumer channel, and one buffer
// only have one fixed producer for now. Thus, it is correct to assume
@@ -119,7 +119,7 @@
epoll_event event;
event.events = 0;
- event.data.u64 = 0ULL;
+ event.data.u32 = 0U;
if (epoll_ctl(release_fence_fd_.Get(), EPOLL_CTL_ADD, dummy_fence_fd_.Get(),
&event) < 0) {
ALOGE(
@@ -164,7 +164,7 @@
ProducerChannel::~ProducerChannel() {
ALOGD_IF(TRACE,
"ProducerChannel::~ProducerChannel: channel_id=%d buffer_id=%d "
- "state=%" PRIx64 ".",
+ "state=%" PRIx32 ".",
channel_id(), buffer_id(),
buffer_state_->load(std::memory_order_acquire));
for (auto consumer : consumer_channels_) {
@@ -175,7 +175,7 @@
BufferHubChannel::BufferInfo ProducerChannel::GetBufferInfo() const {
// Derive the mask of signaled buffers in this producer / consumer set.
- uint64_t signaled_mask = signaled() ? BufferHubDefs::kFirstClientBitMask : 0;
+ uint32_t signaled_mask = signaled() ? BufferHubDefs::kFirstClientBitMask : 0;
for (const ConsumerChannel* consumer : consumer_channels_) {
signaled_mask |= consumer->signaled() ? consumer->client_state_mask() : 0;
}
@@ -228,7 +228,7 @@
}
BufferDescription<BorrowedHandle> ProducerChannel::GetBuffer(
- uint64_t client_state_mask) {
+ uint32_t client_state_mask) {
return {buffer_,
metadata_buffer_,
buffer_id(),
@@ -241,27 +241,27 @@
Status<BufferDescription<BorrowedHandle>> ProducerChannel::OnGetBuffer(
Message& /*message*/) {
ATRACE_NAME("ProducerChannel::OnGetBuffer");
- ALOGD_IF(TRACE, "ProducerChannel::OnGetBuffer: buffer=%d, state=%" PRIx64 ".",
+ ALOGD_IF(TRACE, "ProducerChannel::OnGetBuffer: buffer=%d, state=%" PRIx32 ".",
buffer_id(), buffer_state_->load(std::memory_order_acquire));
return {GetBuffer(BufferHubDefs::kFirstClientBitMask)};
}
-Status<uint64_t> ProducerChannel::CreateConsumerStateMask() {
+Status<uint32_t> ProducerChannel::CreateConsumerStateMask() {
// Try find the next consumer state bit which has not been claimed by any
// consumer yet.
// memory_order_acquire is chosen here because all writes in other threads
// that release active_clients_bit_mask_ need to be visible here.
- uint64_t current_active_clients_bit_mask =
+ uint32_t current_active_clients_bit_mask =
active_clients_bit_mask_->load(std::memory_order_acquire);
- uint64_t consumer_state_mask =
+ uint32_t consumer_state_mask =
BufferHubDefs::FindNextAvailableClientStateMask(
current_active_clients_bit_mask | orphaned_consumer_bit_mask_);
- if (consumer_state_mask == 0ULL) {
+ if (consumer_state_mask == 0U) {
ALOGE("%s: reached the maximum mumber of consumers per producer: 63.",
__FUNCTION__);
return ErrorStatus(E2BIG);
}
- uint64_t updated_active_clients_bit_mask =
+ uint32_t updated_active_clients_bit_mask =
current_active_clients_bit_mask | consumer_state_mask;
// Set the updated value only if the current value stays the same as what was
// read before. If the comparison succeeds, update the value without
@@ -274,15 +274,15 @@
while (!active_clients_bit_mask_->compare_exchange_weak(
current_active_clients_bit_mask, updated_active_clients_bit_mask,
std::memory_order_acq_rel, std::memory_order_acquire)) {
- ALOGE("%s: Current active clients bit mask is changed to %" PRIx64
- ", which was expected to be %" PRIx64
+ ALOGE("%s: Current active clients bit mask is changed to %" PRIx32
+ ", which was expected to be %" PRIx32
". Trying to generate a new client state mask to resolve race "
"condition.",
__FUNCTION__, updated_active_clients_bit_mask,
current_active_clients_bit_mask);
consumer_state_mask = BufferHubDefs::FindNextAvailableClientStateMask(
current_active_clients_bit_mask | orphaned_consumer_bit_mask_);
- if (consumer_state_mask == 0ULL) {
+ if (consumer_state_mask == 0U) {
ALOGE("%s: reached the maximum mumber of consumers per producer: %d.",
__FUNCTION__, (BufferHubDefs::kMaxNumberOfClients - 1));
return ErrorStatus(E2BIG);
@@ -294,7 +294,7 @@
return {consumer_state_mask};
}
-void ProducerChannel::RemoveConsumerClientMask(uint64_t consumer_state_mask) {
+void ProducerChannel::RemoveConsumerClientMask(uint32_t consumer_state_mask) {
// Clear up the buffer state and fence state in case there is already
// something there due to possible race condition between producer post and
// consumer failed to create channel.
@@ -308,7 +308,7 @@
}
Status<RemoteChannelHandle> ProducerChannel::CreateConsumer(
- Message& message, uint64_t consumer_state_mask) {
+ Message& message, uint32_t consumer_state_mask) {
ATRACE_NAME(__FUNCTION__);
ALOGD_IF(TRACE, "%s: buffer_id=%d", __FUNCTION__, buffer_id());
@@ -332,7 +332,7 @@
return ErrorStatus(ENOMEM);
}
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
if (BufferHubDefs::IsBufferReleased(current_buffer_state) ||
BufferHubDefs::AnyClientGained(current_buffer_state)) {
@@ -343,7 +343,7 @@
bool update_buffer_state = true;
if (!BufferHubDefs::IsClientPosted(current_buffer_state,
consumer_state_mask)) {
- uint64_t updated_buffer_state =
+ uint32_t updated_buffer_state =
current_buffer_state ^
(consumer_state_mask & BufferHubDefs::kHighBitsMask);
while (!buffer_state_->compare_exchange_weak(
@@ -351,15 +351,15 @@
std::memory_order_acquire)) {
ALOGI(
"%s: Failed to post to the new consumer. "
- "Current buffer state was changed to %" PRIx64
+ "Current buffer state was changed to %" PRIx32
" when trying to acquire the buffer and modify the buffer state to "
- "%" PRIx64
+ "%" PRIx32
". About to try again if the buffer is still not gained nor fully "
"released.",
__FUNCTION__, current_buffer_state, updated_buffer_state);
if (BufferHubDefs::IsBufferReleased(current_buffer_state) ||
BufferHubDefs::AnyClientGained(current_buffer_state)) {
- ALOGI("%s: buffer is gained or fully released, state=%" PRIx64 ".",
+ ALOGI("%s: buffer is gained or fully released, state=%" PRIx32 ".",
__FUNCTION__, current_buffer_state);
update_buffer_state = false;
break;
@@ -393,7 +393,7 @@
epoll_event event;
event.events = 0;
- event.data.u64 = 0ULL;
+ event.data.u32 = 0U;
int ret = epoll_ctl(release_fence_fd_.Get(), EPOLL_CTL_MOD,
dummy_fence_fd_.Get(), &event);
ALOGE_IF(ret < 0,
@@ -401,7 +401,7 @@
"release fence to include the dummy fence: %s",
strerror(errno));
- eventfd_t dummy_fence_count = 0ULL;
+ eventfd_t dummy_fence_count = 0U;
if (eventfd_read(dummy_fence_fd_.Get(), &dummy_fence_count) < 0) {
const int error = errno;
if (error != EAGAIN) {
@@ -424,7 +424,7 @@
// Signal any interested consumers. If there are none, the buffer will stay
// in posted state until a consumer comes online. This behavior guarantees
// that no frame is silently dropped.
- for (auto consumer : consumer_channels_) {
+ for (auto& consumer : consumer_channels_) {
consumer->OnProducerPosted();
}
@@ -437,6 +437,9 @@
ClearAvailable();
post_fence_.close();
+ for (auto& consumer : consumer_channels_) {
+ consumer->OnProducerGained();
+ }
return {std::move(returned_fence_)};
}
@@ -448,13 +451,13 @@
ALOGD_IF(TRACE, "ProducerChannel::OnProducerDetach: buffer_id=%d",
buffer_id());
- uint64_t buffer_state = buffer_state_->load(std::memory_order_acquire);
+ uint32_t buffer_state = buffer_state_->load(std::memory_order_acquire);
if (!BufferHubDefs::IsClientGained(
buffer_state, BufferHubDefs::kFirstClientStateMask)) {
// Can only detach a BufferProducer when it's in gained state.
ALOGW(
"ProducerChannel::OnProducerDetach: The buffer (id=%d, state=%"
- PRIx64
+ PRIx32
") is not in gained state.",
buffer_id(), buffer_state);
return {};
@@ -531,15 +534,15 @@
}
}
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
- if (BufferHubDefs::IsClientReleased(current_buffer_state,
+ if (BufferHubDefs::IsBufferReleased(current_buffer_state &
~orphaned_consumer_bit_mask_)) {
SignalAvailable();
if (orphaned_consumer_bit_mask_) {
ALOGW(
"%s: orphaned buffer detected during the this acquire/release cycle: "
- "id=%d orphaned=0x%" PRIx64 " queue_index=%" PRIx64 ".",
+ "id=%d orphaned=0x%" PRIx32 " queue_index=%" PRIx64 ".",
__FUNCTION__, buffer_id(), orphaned_consumer_bit_mask_,
metadata_header_->queue_index);
orphaned_consumer_bit_mask_ = 0;
@@ -549,18 +552,18 @@
return {};
}
-void ProducerChannel::OnConsumerOrphaned(const uint64_t& consumer_state_mask) {
+void ProducerChannel::OnConsumerOrphaned(const uint32_t& consumer_state_mask) {
// Remember the ignored consumer so that newly added consumer won't be
// taking the same state mask as this orphaned consumer.
ALOGE_IF(orphaned_consumer_bit_mask_ & consumer_state_mask,
- "%s: Consumer (consumer_state_mask=%" PRIx64
+ "%s: Consumer (consumer_state_mask=%" PRIx32
") is already orphaned.",
__FUNCTION__, consumer_state_mask);
orphaned_consumer_bit_mask_ |= consumer_state_mask;
- uint64_t current_buffer_state =
+ uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
- if (BufferHubDefs::IsClientReleased(current_buffer_state,
+ if (BufferHubDefs::IsBufferReleased(current_buffer_state &
~orphaned_consumer_bit_mask_)) {
SignalAvailable();
}
@@ -574,8 +577,8 @@
ALOGW(
"%s: detected new orphaned consumer buffer_id=%d "
- "consumer_state_mask=%" PRIx64 " queue_index=%" PRIx64
- " buffer_state=%" PRIx64 " fence_state=%" PRIx64 ".",
+ "consumer_state_mask=%" PRIx32 " queue_index=%" PRIx64
+ " buffer_state=%" PRIx32 " fence_state=%" PRIx32 ".",
__FUNCTION__, buffer_id(), consumer_state_mask,
metadata_header_->queue_index,
buffer_state_->load(std::memory_order_acquire),
@@ -591,18 +594,18 @@
std::find(consumer_channels_.begin(), consumer_channels_.end(), channel));
// Restore the consumer state bit and make it visible in other threads that
// acquire the active_clients_bit_mask_.
- uint64_t consumer_state_mask = channel->client_state_mask();
- uint64_t current_active_clients_bit_mask =
+ uint32_t consumer_state_mask = channel->client_state_mask();
+ uint32_t current_active_clients_bit_mask =
active_clients_bit_mask_->load(std::memory_order_acquire);
- uint64_t updated_active_clients_bit_mask =
+ uint32_t updated_active_clients_bit_mask =
current_active_clients_bit_mask & (~consumer_state_mask);
while (!active_clients_bit_mask_->compare_exchange_weak(
current_active_clients_bit_mask, updated_active_clients_bit_mask,
std::memory_order_acq_rel, std::memory_order_acquire)) {
ALOGI(
"%s: Failed to remove consumer state mask. Current active clients bit "
- "mask is changed to %" PRIu64
- " when trying to acquire and modify it to %" PRIu64
+ "mask is changed to %" PRIx32
+ " when trying to acquire and modify it to %" PRIx32
". About to try again.",
__FUNCTION__, current_active_clients_bit_mask,
updated_active_clients_bit_mask);
@@ -610,7 +613,7 @@
current_active_clients_bit_mask & (~consumer_state_mask);
}
- const uint64_t current_buffer_state =
+ const uint32_t current_buffer_state =
buffer_state_->load(std::memory_order_acquire);
if (BufferHubDefs::IsClientPosted(current_buffer_state,
consumer_state_mask) ||
@@ -631,7 +634,7 @@
if (fence_state_->load(std::memory_order_acquire) & consumer_state_mask) {
epoll_event event;
event.events = EPOLLIN;
- event.data.u64 = consumer_state_mask;
+ event.data.u32 = consumer_state_mask;
if (epoll_ctl(release_fence_fd_.Get(), EPOLL_CTL_MOD,
dummy_fence_fd_.Get(), &event) < 0) {
ALOGE(
diff --git a/services/vr/bufferhubd/tests/Android.bp b/services/vr/bufferhubd/tests/Android.bp
deleted file mode 100644
index a611268..0000000
--- a/services/vr/bufferhubd/tests/Android.bp
+++ /dev/null
@@ -1,26 +0,0 @@
-cc_test {
- name: "buffer_hub_binder_service-test",
- srcs: ["buffer_hub_binder_service-test.cpp"],
- cflags: [
- "-DLOG_TAG=\"buffer_hub_binder_service-test\"",
- "-DTRACE=0",
- "-DATRACE_TAG=ATRACE_TAG_GRAPHICS",
- ],
- header_libs: ["libdvr_headers"],
- static_libs: [
- "libbufferhub",
- "libbufferhubd",
- "libgmock",
- ],
- shared_libs: [
- "libbase",
- "libbinder",
- "liblog",
- "libpdx_default_transport",
- "libui",
- "libutils",
- ],
-
- // TODO(b/117568153): Temporarily opt out using libcrt.
- no_libcrt: true,
-}
diff --git a/services/vr/bufferhubd/tests/buffer_hub_binder_service-test.cpp b/services/vr/bufferhubd/tests/buffer_hub_binder_service-test.cpp
deleted file mode 100644
index 94b422a..0000000
--- a/services/vr/bufferhubd/tests/buffer_hub_binder_service-test.cpp
+++ /dev/null
@@ -1,85 +0,0 @@
-#include <binder/IServiceManager.h>
-#include <gmock/gmock.h>
-#include <gtest/gtest.h>
-#include <private/dvr/IBufferClient.h>
-#include <private/dvr/IBufferHub.h>
-#include <ui/PixelFormat.h>
-
-namespace android {
-namespace dvr {
-
-namespace {
-
-using testing::IsNull;
-using testing::NotNull;
-
-const int kWidth = 640;
-const int kHeight = 480;
-const int kLayerCount = 1;
-const int kFormat = HAL_PIXEL_FORMAT_RGBA_8888;
-const int kUsage = 0;
-const size_t kUserMetadataSize = 0;
-
-class BufferHubBinderServiceTest : public ::testing::Test {
- protected:
- void SetUp() override {
- status_t ret = getService<IBufferHub>(
- String16(IBufferHub::getServiceName()), &service);
- ASSERT_EQ(ret, OK);
- ASSERT_THAT(service, NotNull());
- }
-
- sp<IBufferHub> service;
-};
-
-TEST_F(BufferHubBinderServiceTest, TestCreateBuffer) {
- sp<IBufferClient> bufferClient = service->createBuffer(
- kWidth, kHeight, kLayerCount, kFormat, kUsage, kUserMetadataSize);
- ASSERT_THAT(bufferClient, NotNull());
- EXPECT_TRUE(bufferClient->isValid());
-}
-
-TEST_F(BufferHubBinderServiceTest, TestDuplicateAndImportBuffer) {
- sp<IBufferClient> bufferClient = service->createBuffer(
- kWidth, kHeight, kLayerCount, kFormat, kUsage, kUserMetadataSize);
- ASSERT_THAT(bufferClient, NotNull());
- EXPECT_TRUE(bufferClient->isValid());
-
- uint64_t token1 = 0ULL;
- status_t ret = bufferClient->duplicate(&token1);
- EXPECT_EQ(ret, OK);
-
- // Tokens should be unique even corresponding to the same buffer
- uint64_t token2 = 0ULL;
- ret = bufferClient->duplicate(&token2);
- EXPECT_EQ(ret, OK);
- EXPECT_NE(token2, token1);
-
- sp<IBufferClient> bufferClient1;
- ret = service->importBuffer(token1, &bufferClient1);
- EXPECT_EQ(ret, OK);
- ASSERT_THAT(bufferClient1, NotNull());
- EXPECT_TRUE(bufferClient1->isValid());
-
- // Consumes the token to keep the service clean
- sp<IBufferClient> bufferClient2;
- ret = service->importBuffer(token2, &bufferClient2);
- EXPECT_EQ(ret, OK);
- ASSERT_THAT(bufferClient2, NotNull());
- EXPECT_TRUE(bufferClient2->isValid());
-}
-
-TEST_F(BufferHubBinderServiceTest, TestImportUnexistingToken) {
- // There is very little chance that this test fails if there is a token = 0
- // in the service.
- uint64_t unexistingToken = 0ULL;
- sp<IBufferClient> bufferClient;
- status_t ret = service->importBuffer(unexistingToken, &bufferClient);
- EXPECT_EQ(ret, PERMISSION_DENIED);
- EXPECT_THAT(bufferClient, IsNull());
-}
-
-} // namespace
-
-} // namespace dvr
-} // namespace android
\ No newline at end of file
diff --git a/vulkan/api/vulkan.api b/vulkan/api/vulkan.api
index e4c50d5..6c971be 100644
--- a/vulkan/api/vulkan.api
+++ b/vulkan/api/vulkan.api
@@ -28,7 +28,7 @@
// API version (major.minor.patch)
define VERSION_MAJOR 1
define VERSION_MINOR 1
-define VERSION_PATCH 93
+define VERSION_PATCH 94
// API limits
define VK_MAX_PHYSICAL_DEVICE_NAME_SIZE 256
@@ -524,8 +524,8 @@
@extension("VK_NV_shading_rate_image") define VK_NV_SHADING_RATE_IMAGE_EXTENSION_NAME "VK_NV_shading_rate_image"
// 166
-@extension("VK_NV_raytracing") define VK_NV_RAYTRACING_SPEC_VERSION 2
-@extension("VK_NV_raytracing") define VK_NV_RAYTRACING_EXTENSION_NAME "VK_NV_raytracing"
+@extension("VK_NV_ray_tracing") define VK_NV_RAY_TRACING_SPEC_VERSION 3
+@extension("VK_NV_ray_tracing") define VK_NV_RAY_TRACING_EXTENSION_NAME "VK_NV_ray_tracing"
// 167
@extension("VK_NV_representative_fragment_test") define VK_NV_REPRESENTATIVE_FRAGMENT_TEST_SPEC_VERSION 1
@@ -579,6 +579,10 @@
@extension("VK_NV_shader_subgroup_partitioned") define VK_NV_SHADER_SUBGROUP_PARTITIONED_SPEC_VERSION 1
@extension("VK_NV_shader_subgroup_partitioned") define VK_NV_SHADER_SUBGROUP_PARTITIONED_EXTENSION_NAME "VK_NV_shader_subgroup_partitioned"
+// 201
+@extension("VK_KHR_swapchain_mutable_format") define VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_SPEC_VERSION 1
+@extension("VK_KHR_swapchain_mutable_format") define VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME "VK_KHR_swapchain_mutable_format"
+
// 202
@extension("VK_NV_compute_shader_derivatives") define VK_NV_COMPUTE_SHADER_DERIVATIVES_SPEC_VERSION 1
@extension("VK_NV_compute_shader_derivatives") define VK_NV_COMPUTE_SHADER_DERIVATIVES_EXTENSION_NAME "VK_NV_compute_shader_derivatives"
@@ -615,6 +619,10 @@
@extension("VK_FUCHSIA_imagepipe_surface") define VK_FUCHSIA_IMAGEPIPE_SURFACE_SPEC_VERSION 1
@extension("VK_FUCHSIA_imagepipe_surface") define VK_FUCHSIA_IMAGEPIPE_SURFACE_EXTENSION_NAME "VK_FUCHSIA_imagepipe_surface"
+// 219
+@extension("VK_EXT_fragment_density_map") define VK_EXT_FRAGMENT_DENSITY_MAP_SPEC_VERSION 1
+@extension("VK_EXT_fragment_density_map") define VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME "VK_EXT_fragment_density_map"
+
// 222
@extension("VK_EXT_scalar_block_layout") define VK_EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION 1
@extension("VK_EXT_scalar_block_layout") define VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME "VK_EXT_scalar_block_layout"
@@ -703,7 +711,7 @@
@extension("VK_EXT_validation_cache") @nonDispatchHandle type u64 VkValidationCacheEXT
// 166
-@extension("VK_NV_raytracing") @nonDispatchHandle type u64 VkAccelerationStructureNV
+@extension("VK_NV_ray_tracing") @nonDispatchHandle type u64 VkAccelerationStructureNV
/////////////
// Enums //
@@ -736,6 +744,9 @@
//@extension("VK_NV_shading_rate_image") // 165
VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV = 1000164003,
+
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000,
}
enum VkAttachmentLoadOp {
@@ -804,7 +815,7 @@
//@extension("VK_EXT_inline_uniform_block") // 139
VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT = 1000138000,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_NV = 1000165000,
}
@@ -816,7 +827,7 @@
//@extension("VK_EXT_transform_feedback") // 29
VK_QUERY_TYPE_TRANSFORM_FEEDBACK_STREAM_EXT = 1000028004,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_QUERY_TYPE_ACCELERATION_STRUCTURE_COMPACTED_SIZE_NV = 1000165000,
}
@@ -833,7 +844,7 @@
VK_PIPELINE_BIND_POINT_GRAPHICS = 0x00000000,
VK_PIPELINE_BIND_POINT_COMPUTE = 0x00000001,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_PIPELINE_BIND_POINT_RAY_TRACING_NV = 1000165000,
}
@@ -860,7 +871,7 @@
VK_INDEX_TYPE_UINT16 = 0x00000000,
VK_INDEX_TYPE_UINT32 = 0x00000001,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_INDEX_TYPE_NONE_NV = 1000165000,
}
@@ -1796,7 +1807,7 @@
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADING_RATE_IMAGE_PROPERTIES_NV = 1000164002,
VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_COARSE_SAMPLE_ORDER_STATE_CREATE_INFO_NV = 1000164005,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_STRUCTURE_TYPE_RAY_TRACING_PIPELINE_CREATE_INFO_NV = 1000165000,
VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_NV = 1000165001,
VK_STRUCTURE_TYPE_GEOMETRY_NV = 1000165003,
@@ -1861,6 +1872,11 @@
//@extension("VK_FUCHSIA_imagepipe_surface") // 215
VK_STRUCTURE_TYPE_IMAGEPIPE_SURFACE_CREATE_INFO_FUCHSIA = 1000214000,
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT = 1000218000,
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_PROPERTIES_EXT = 1000218001,
+ VK_STRUCTURE_TYPE_RENDER_PASS_FRAGMENT_DENSITY_MAP_CREATE_INFO_EXT = 1000218002,
+
//@extension("VK_EXT_scalar_block_layout")
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT = 1000221000,
@@ -2030,7 +2046,7 @@
//@extension("VK_EXT_validation_cache") // 161
VK_OBJECT_TYPE_VALIDATION_CACHE_EXT = 1000160000,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV = 1000165000,
}
@@ -2154,7 +2170,7 @@
//@extension("VK_KHR_sampler_ycbcr_conversion") // 157
VK_DEBUG_REPORT_OBJECT_TYPE_SAMPLER_YCBCR_CONVERSION_KHR_EXT = 1000156000,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_DEBUG_REPORT_OBJECT_TYPE_ACCELERATION_STRUCTURE_NV_EXT = 1000165000,
}
@@ -2330,32 +2346,32 @@
VK_COARSE_SAMPLE_ORDER_TYPE_SAMPLE_MAJOR_NV = 3,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
enum VkRayTracingShaderGroupTypeNV {
VK_RAY_TRACING_SHADER_GROUP_TYPE_GENERAL_NV = 0,
VK_RAY_TRACING_SHADER_GROUP_TYPE_TRIANGLES_HIT_GROUP_NV = 1,
VK_RAY_TRACING_SHADER_GROUP_TYPE_PROCEDURAL_HIT_GROUP_NV = 2,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
enum VkGeometryTypeNV {
VK_GEOMETRY_TYPE_TRIANGLES_NV = 0,
VK_GEOMETRY_TYPE_AABBS_NV = 1,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
enum VkAccelerationStructureTypeNV {
VK_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL_NV = 0,
VK_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL_NV = 1,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
enum VkCopyAccelerationStructureModeNV {
VK_COPY_ACCELERATION_STRUCTURE_MODE_CLONE_NV = 0,
VK_COPY_ACCELERATION_STRUCTURE_MODE_COMPACT_NV = 1,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
enum VkAccelerationStructureMemoryRequirementsTypeNV {
VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_OBJECT_NV = 0,
VK_ACCELERATION_STRUCTURE_MEMORY_REQUIREMENTS_TYPE_BUILD_SCRATCH_NV = 1,
@@ -2474,10 +2490,13 @@
//@extension("VK_NV_shading_rate_image") // 165
VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV = 0x00800000,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV = 0x00200000,
VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV = 0x00400000,
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT = 0x01000000,
+
//@extension("VK_EXT_transform_feedback") // 29
VK_ACCESS_TRANSFORM_FEEDBACK_WRITE_BIT_EXT = 0x02000000,
VK_ACCESS_TRANSFORM_FEEDBACK_COUNTER_READ_BIT_EXT = 0x04000000,
@@ -2500,7 +2519,7 @@
//@extension("VK_EXT_conditional_rendering") // 82
VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT = 0x00000200,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_BUFFER_USAGE_RAY_TRACING_BIT_NV = 0x00000400,
//@extension("VK_EXT_transform_feedback") // 29
@@ -2532,7 +2551,7 @@
VK_SHADER_STAGE_ALL = 0x7FFFFFFF,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_SHADER_STAGE_RAYGEN_BIT_NV = 0x00000100,
VK_SHADER_STAGE_ANY_HIT_BIT_NV = 0x00000200,
VK_SHADER_STAGE_CLOSEST_HIT_BIT_NV = 0x00000400,
@@ -2573,6 +2592,9 @@
//@extension("VK_NV_shading_rate_image") // 165
VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV = 0x00000100,
+
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT = 0x00000200,
}
/// Image creation flags
@@ -2614,12 +2636,17 @@
//@extension("VK_NV_corner_sampled_image") // 51
VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV = 0x00002000,
+
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT = 0x00004000,
}
/// Image view creation flags
type VkFlags VkImageViewCreateFlags
-//bitfield VkImageViewCreateFlagBits {
-//}
+bitfield VkImageViewCreateFlagBits {
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001,
+}
/// Pipeline creation flags
type VkFlags VkPipelineCreateFlags
@@ -2636,7 +2663,7 @@
VK_PIPELINE_CREATE_VIEW_INDEX_FROM_DEVICE_INDEX_BIT_KHR = 0x00000008,
VK_PIPELINE_CREATE_DISPATCH_BASE_KHR = 0x00000010,
- //@extension("VK_NV_raytracing") // 166
+ //@extension("VK_NV_ray_tracing") // 166
VK_PIPELINE_CREATE_DEFER_COMPILE_BIT_NV = 0x00000020,
}
@@ -2829,19 +2856,24 @@
//@extension("VK_EXT_conditional_rendering") // 82
VK_PIPELINE_STAGE_CONDITIONAL_RENDERING_BIT_EXT = 0x00040000,
- //@extension("VK_NV_shading_rate_image") // 165
- VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV = 0x00400000,
-
- //@extension("VK_NV_raytracing") // 166
- VK_PIPELINE_STAGE_RAY_TRACING_BIT_NV = 0x00200000,
- VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV = 0x02000000,
-
//@extension("VK_NV_mesh_shader") // 203
VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV = 0x00080000,
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV = 0x00100000,
+ //@extension("VK_NV_ray_tracing") // 166
+ VK_PIPELINE_STAGE_RAY_TRACING_BIT_NV = 0x00200000,
+
+ //@extension("VK_NV_shading_rate_image") // 165
+ VK_PIPELINE_STAGE_SHADING_RATE_IMAGE_BIT_NV = 0x00400000,
+
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT = 0x00800000,
+
//@extension("VK_EXT_transform_feedback") // 29
VK_PIPELINE_STAGE_TRANSFORM_FEEDBACK_BIT_EXT = 0x01000000,
+
+ //@extension("VK_NV_ray_tracing") // 166
+ VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV = 0x02000000,
}
/// Render pass attachment description flags
@@ -2996,8 +3028,11 @@
/// Sampler creation flags
type VkFlags VkSamplerCreateFlags
-//bitfield VkSamplerCreateFlagBits {
-//}
+bitfield VkSamplerCreateFlagBits {
+ //@extension("VK_EXT_fragment_density_map") // 219
+ VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001,
+ VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002,
+}
/// Render pass creation flags
type VkFlags VkRenderPassCreateFlags
@@ -3182,6 +3217,9 @@
//@vulkan1_1
VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = 0x00000001,
VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = 0x00000002,
+
+ //@extension("VK_KHR_swapchain_mutable_format") // 201
+ VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR = 0x00000004,
}
@vulkan1_1
@@ -3520,17 +3558,17 @@
VK_DESCRIPTOR_BINDING_VARIABLE_DESCRIPTOR_COUNT_BIT_EXT = 0x00000008,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
type VkFlags VkGeometryFlagsNV
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
bitfield VkGeometryFlagBitsNV {
VK_GEOMETRY_OPAQUE_BIT_NV = 0x00000001,
VK_GEOMETRY_NO_DUPLICATE_ANY_HIT_INVOCATION_BIT_NV = 0x00000002,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
type VkFlags VkGeometryInstanceFlagsNV
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
bitfield VkGeometryInstanceFlagBitsNV {
VK_GEOMETRY_INSTANCE_TRIANGLE_CULL_DISABLE_BIT_NV = 0x00000001,
VK_GEOMETRY_INSTANCE_TRIANGLE_FRONT_COUNTERCLOCKWISE_BIT_NV = 0x00000002,
@@ -3538,9 +3576,9 @@
VK_GEOMETRY_INSTANCE_FORCE_NO_OPAQUE_BIT_NV = 0x00000008,
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
type VkFlags VkBuildAccelerationStructureFlagsNV
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
bitfield VkBuildAccelerationStructureFlagBitsNV {
VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_UPDATE_BIT_NV = 0x00000001,
VK_BUILD_ACCELERATION_STRUCTURE_ALLOW_COMPACTION_BIT_NV = 0x00000002,
@@ -5025,7 +5063,7 @@
class VkDescriptorUpdateTemplateCreateInfo {
VkStructureType sType
- void* pNext
+ const void* pNext
VkDescriptorUpdateTemplateCreateFlags flags
u32 descriptorUpdateEntryCount
const VkDescriptorUpdateTemplateEntry* pDescriptorUpdateEntries
@@ -7276,7 +7314,7 @@
const VkCoarseSampleOrderCustomNV* pCustomSampleOrders
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkRayTracingShaderGroupCreateInfoNV {
VkStructureType sType
const void* pNext
@@ -7287,7 +7325,7 @@
u32 intersectionShader
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkRayTracingPipelineCreateInfoNV {
VkStructureType sType
const void* pNext
@@ -7302,7 +7340,7 @@
s32 basePipelineIndex
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkGeometryTrianglesNV {
VkStructureType sType
const void* pNext
@@ -7319,7 +7357,7 @@
VkDeviceSize transformOffset
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkGeometryAABBNV {
VkStructureType sType
const void* pNext
@@ -7329,13 +7367,13 @@
VkDeviceSize offset
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkGeometryDataNV {
VkGeometryTrianglesNV triangles
VkGeometryAABBNV aabbs
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkGeometryNV {
VkStructureType sType
const void* pNext
@@ -7344,7 +7382,7 @@
VkGeometryFlagsNV flags
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkAccelerationStructureInfoNV {
VkStructureType sType
const void* pNext
@@ -7355,7 +7393,7 @@
const VkGeometryNV* pGeometries
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkAccelerationStructureCreateInfoNV {
VkStructureType sType
const void* pNext
@@ -7363,7 +7401,7 @@
VkAccelerationStructureInfoNV info
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkBindAccelerationStructureMemoryInfoNV {
VkStructureType sType
const void* pNext
@@ -7374,7 +7412,7 @@
const u32* pDeviceIndices
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkDescriptorAccelerationStructureInfoNV {
VkStructureType sType
const void* pNext
@@ -7382,7 +7420,7 @@
const VkAccelerationStructureNV* pAccelerationStructures
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkAccelerationStructureMemoryRequirementsInfoNV {
VkStructureType sType
const void* pNext
@@ -7390,7 +7428,7 @@
VkAccelerationStructureNV accelerationStructure
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
class VkPhysicalDeviceRaytracingPropertiesNV {
VkStructureType sType
void* pNext
@@ -7671,6 +7709,31 @@
platform.zx_handle_t imagePipeHandle
}
+@extension("VK_EXT_fragment_density_map") // 219
+class VkPhysicalDeviceFragmentDensityMapFeaturesEXT {
+ VkStructureType sType
+ void* pNext
+ VkBool32 fragmentDensityMap
+ VkBool32 fragmentDensityMapDynamic
+ VkBool32 fragmentDensityMapNonSubsampledImages
+}
+
+@extension("VK_EXT_fragment_density_map") // 219
+class VkPhysicalDeviceFragmentDensityMapPropertiesEXT {
+ VkStructureType sType
+ void* pNext
+ VkExtent2D minFragmentDensityTexelSize
+ VkExtent2D maxFragmentDensityTexelSize
+ VkBool32 fragmentDensityInvocations
+}
+
+@extension("VK_EXT_fragment_density_map") // 219
+class VkRenderPassFragmentDensityMapCreateInfoEXT {
+ VkStructureType sType
+ const void* pNext
+ VkAttachmentReference fragmentDensityMapAttachment
+}
+
@extension("VK_EXT_scalar_block_layout") // 222
class VkPhysicalDeviceScalarBlockLayoutFeaturesEXT {
VkStructureType sType
@@ -11502,7 +11565,7 @@
const VkCoarseSampleOrderCustomNV* pCustomSampleOrders) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkCreateAccelerationStructureNV(
VkDevice device,
const VkAccelerationStructureCreateInfoNV* pCreateInfo,
@@ -11511,21 +11574,21 @@
return ?
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkDestroyAccelerationStructureNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
const VkAllocationCallbacks* pAllocator) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkGetAccelerationStructureMemoryRequirementsNV(
VkDevice device,
const VkAccelerationStructureMemoryRequirementsInfoNV* pInfo,
VkMemoryRequirements2KHR* pMemoryRequirements) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkBindAccelerationStructureMemoryNV(
VkDevice device,
u32 bindInfoCount,
@@ -11533,7 +11596,7 @@
return ?
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkCmdBuildAccelerationStructureNV(
VkCommandBuffer commandBuffer,
const VkAccelerationStructureInfoNV* pInfo,
@@ -11546,7 +11609,7 @@
VkDeviceSize scratchOffset) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkCmdCopyAccelerationStructureNV(
VkCommandBuffer commandBuffer,
VkAccelerationStructureNV dst,
@@ -11554,7 +11617,7 @@
VkCopyAccelerationStructureModeNV mode) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkCmdTraceRaysNV(
VkCommandBuffer commandBuffer,
VkBuffer raygenShaderBindingTableBuffer,
@@ -11573,7 +11636,7 @@
u32 depth) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkCreateRaytracingPipelinesNV(
VkDevice device,
VkPipelineCache pipelineCache,
@@ -11584,7 +11647,7 @@
return ?
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkGetRaytracingShaderHandlesNV(
VkDevice device,
VkPipeline pipeline,
@@ -11595,7 +11658,7 @@
return ?
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkGetAccelerationStructureHandleNV(
VkDevice device,
VkAccelerationStructureNV accelerationStructure,
@@ -11604,7 +11667,7 @@
return ?
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd void vkCmdWriteAccelerationStructurePropertiesNV(
VkCommandBuffer commandBuffer,
u32 accelerationStructureCount,
@@ -11614,7 +11677,7 @@
u32 firstQuery) {
}
-@extension("VK_NV_raytracing") // 166
+@extension("VK_NV_ray_tracing") // 166
cmd VkResult vkCompileDeferredNV(
VkDevice device,
VkPipeline pipeline,
diff --git a/vulkan/include/vulkan/vulkan_core.h b/vulkan/include/vulkan/vulkan_core.h
index 35c0664..bdbf800 100644
--- a/vulkan/include/vulkan/vulkan_core.h
+++ b/vulkan/include/vulkan/vulkan_core.h
@@ -43,7 +43,7 @@
#define VK_VERSION_MINOR(version) (((uint32_t)(version) >> 12) & 0x3ff)
#define VK_VERSION_PATCH(version) ((uint32_t)(version) & 0xfff)
// Version of this file
-#define VK_HEADER_VERSION 93
+#define VK_HEADER_VERSION 94
#define VK_NULL_HANDLE 0
@@ -454,6 +454,9 @@
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_VULKAN_MEMORY_MODEL_FEATURES_KHR = 1000211000,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PCI_BUS_INFO_PROPERTIES_EXT = 1000212000,
VK_STRUCTURE_TYPE_IMAGEPIPE_SURFACE_CREATE_INFO_FUCHSIA = 1000214000,
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_FEATURES_EXT = 1000218000,
+ VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_DENSITY_MAP_PROPERTIES_EXT = 1000218001,
+ VK_STRUCTURE_TYPE_RENDER_PASS_FRAGMENT_DENSITY_MAP_CREATE_INFO_EXT = 1000218002,
VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SCALAR_BLOCK_LAYOUT_FEATURES_EXT = 1000221000,
VK_STRUCTURE_TYPE_IMAGE_STENCIL_USAGE_CREATE_INFO_EXT = 1000246000,
VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT = VK_STRUCTURE_TYPE_DEBUG_REPORT_CALLBACK_CREATE_INFO_EXT,
@@ -879,6 +882,7 @@
VK_IMAGE_LAYOUT_PRESENT_SRC_KHR = 1000001002,
VK_IMAGE_LAYOUT_SHARED_PRESENT_KHR = 1000111000,
VK_IMAGE_LAYOUT_SHADING_RATE_OPTIMAL_NV = 1000164003,
+ VK_IMAGE_LAYOUT_FRAGMENT_DENSITY_MAP_OPTIMAL_EXT = 1000218000,
VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL_KHR = VK_IMAGE_LAYOUT_DEPTH_READ_ONLY_STENCIL_ATTACHMENT_OPTIMAL,
VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL_KHR = VK_IMAGE_LAYOUT_DEPTH_ATTACHMENT_STENCIL_READ_ONLY_OPTIMAL,
VK_IMAGE_LAYOUT_BEGIN_RANGE = VK_IMAGE_LAYOUT_UNDEFINED,
@@ -1326,6 +1330,7 @@
VK_FORMAT_FEATURE_COSITED_CHROMA_SAMPLES_BIT = 0x00800000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_CUBIC_BIT_IMG = 0x00002000,
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_MINMAX_BIT_EXT = 0x00010000,
+ VK_FORMAT_FEATURE_FRAGMENT_DENSITY_MAP_BIT_EXT = 0x01000000,
VK_FORMAT_FEATURE_TRANSFER_SRC_BIT_KHR = VK_FORMAT_FEATURE_TRANSFER_SRC_BIT,
VK_FORMAT_FEATURE_TRANSFER_DST_BIT_KHR = VK_FORMAT_FEATURE_TRANSFER_DST_BIT,
VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT_KHR = VK_FORMAT_FEATURE_MIDPOINT_CHROMA_SAMPLES_BIT,
@@ -1349,6 +1354,7 @@
VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT = 0x00000040,
VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT = 0x00000080,
VK_IMAGE_USAGE_SHADING_RATE_IMAGE_BIT_NV = 0x00000100,
+ VK_IMAGE_USAGE_FRAGMENT_DENSITY_MAP_BIT_EXT = 0x00000200,
VK_IMAGE_USAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VkImageUsageFlagBits;
typedef VkFlags VkImageUsageFlags;
@@ -1368,6 +1374,7 @@
VK_IMAGE_CREATE_DISJOINT_BIT = 0x00000200,
VK_IMAGE_CREATE_CORNER_SAMPLED_BIT_NV = 0x00002000,
VK_IMAGE_CREATE_SAMPLE_LOCATIONS_COMPATIBLE_DEPTH_BIT_EXT = 0x00001000,
+ VK_IMAGE_CREATE_SUBSAMPLED_BIT_EXT = 0x00004000,
VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = VK_IMAGE_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT,
VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT_KHR = VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT,
VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT_KHR = VK_IMAGE_CREATE_BLOCK_TEXEL_VIEW_COMPATIBLE_BIT,
@@ -1452,6 +1459,7 @@
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_NV = 0x02000000,
VK_PIPELINE_STAGE_TASK_SHADER_BIT_NV = 0x00080000,
VK_PIPELINE_STAGE_MESH_SHADER_BIT_NV = 0x00100000,
+ VK_PIPELINE_STAGE_FRAGMENT_DENSITY_PROCESS_BIT_EXT = 0x00800000,
VK_PIPELINE_STAGE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VkPipelineStageFlagBits;
typedef VkFlags VkPipelineStageFlags;
@@ -1551,6 +1559,11 @@
} VkBufferUsageFlagBits;
typedef VkFlags VkBufferUsageFlags;
typedef VkFlags VkBufferViewCreateFlags;
+
+typedef enum VkImageViewCreateFlagBits {
+ VK_IMAGE_VIEW_CREATE_FRAGMENT_DENSITY_MAP_DYNAMIC_BIT_EXT = 0x00000001,
+ VK_IMAGE_VIEW_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkImageViewCreateFlagBits;
typedef VkFlags VkImageViewCreateFlags;
typedef VkFlags VkShaderModuleCreateFlags;
typedef VkFlags VkPipelineCacheCreateFlags;
@@ -1617,6 +1630,12 @@
typedef VkFlags VkPipelineDynamicStateCreateFlags;
typedef VkFlags VkPipelineLayoutCreateFlags;
typedef VkFlags VkShaderStageFlags;
+
+typedef enum VkSamplerCreateFlagBits {
+ VK_SAMPLER_CREATE_SUBSAMPLED_BIT_EXT = 0x00000001,
+ VK_SAMPLER_CREATE_SUBSAMPLED_COARSE_RECONSTRUCTION_BIT_EXT = 0x00000002,
+ VK_SAMPLER_CREATE_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
+} VkSamplerCreateFlagBits;
typedef VkFlags VkSamplerCreateFlags;
typedef enum VkDescriptorSetLayoutCreateFlagBits {
@@ -1677,6 +1696,7 @@
VK_ACCESS_SHADING_RATE_IMAGE_READ_BIT_NV = 0x00800000,
VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_NV = 0x00200000,
VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_NV = 0x00400000,
+ VK_ACCESS_FRAGMENT_DENSITY_MAP_READ_BIT_EXT = 0x01000000,
VK_ACCESS_FLAG_BITS_MAX_ENUM = 0x7FFFFFFF
} VkAccessFlagBits;
typedef VkFlags VkAccessFlags;
@@ -4357,7 +4377,7 @@
typedef struct VkDescriptorUpdateTemplateCreateInfo {
VkStructureType sType;
- void* pNext;
+ const void* pNext;
VkDescriptorUpdateTemplateCreateFlags flags;
uint32_t descriptorUpdateEntryCount;
const VkDescriptorUpdateTemplateEntry* pDescriptorUpdateEntries;
@@ -4796,6 +4816,7 @@
typedef enum VkSwapchainCreateFlagBitsKHR {
VK_SWAPCHAIN_CREATE_SPLIT_INSTANCE_BIND_REGIONS_BIT_KHR = 0x00000001,
VK_SWAPCHAIN_CREATE_PROTECTED_BIT_KHR = 0x00000002,
+ VK_SWAPCHAIN_CREATE_MUTABLE_FORMAT_BIT_KHR = 0x00000004,
VK_SWAPCHAIN_CREATE_FLAG_BITS_MAX_ENUM_KHR = 0x7FFFFFFF
} VkSwapchainCreateFlagBitsKHR;
typedef VkFlags VkSwapchainCreateFlagsKHR;
@@ -6128,6 +6149,11 @@
+#define VK_KHR_swapchain_mutable_format 1
+#define VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_SPEC_VERSION 1
+#define VK_KHR_SWAPCHAIN_MUTABLE_FORMAT_EXTENSION_NAME "VK_KHR_swapchain_mutable_format"
+
+
#define VK_KHR_vulkan_memory_model 1
#define VK_KHR_VULKAN_MEMORY_MODEL_SPEC_VERSION 2
#define VK_KHR_VULKAN_MEMORY_MODEL_EXTENSION_NAME "VK_KHR_vulkan_memory_model"
@@ -8117,7 +8143,7 @@
#define VK_NV_ray_tracing 1
VK_DEFINE_NON_DISPATCHABLE_HANDLE(VkAccelerationStructureNV)
-#define VK_NV_RAY_TRACING_SPEC_VERSION 2
+#define VK_NV_RAY_TRACING_SPEC_VERSION 3
#define VK_NV_RAY_TRACING_EXTENSION_NAME "VK_NV_ray_tracing"
#define VK_SHADER_UNUSED_NV (~0U)
@@ -8807,6 +8833,34 @@
+#define VK_EXT_fragment_density_map 1
+#define VK_EXT_FRAGMENT_DENSITY_MAP_SPEC_VERSION 1
+#define VK_EXT_FRAGMENT_DENSITY_MAP_EXTENSION_NAME "VK_EXT_fragment_density_map"
+
+typedef struct VkPhysicalDeviceFragmentDensityMapFeaturesEXT {
+ VkStructureType sType;
+ void* pNext;
+ VkBool32 fragmentDensityMap;
+ VkBool32 fragmentDensityMapDynamic;
+ VkBool32 fragmentDensityMapNonSubsampledImages;
+} VkPhysicalDeviceFragmentDensityMapFeaturesEXT;
+
+typedef struct VkPhysicalDeviceFragmentDensityMapPropertiesEXT {
+ VkStructureType sType;
+ void* pNext;
+ VkExtent2D minFragmentDensityTexelSize;
+ VkExtent2D maxFragmentDensityTexelSize;
+ VkBool32 fragmentDensityInvocations;
+} VkPhysicalDeviceFragmentDensityMapPropertiesEXT;
+
+typedef struct VkRenderPassFragmentDensityMapCreateInfoEXT {
+ VkStructureType sType;
+ const void* pNext;
+ VkAttachmentReference fragmentDensityMapAttachment;
+} VkRenderPassFragmentDensityMapCreateInfoEXT;
+
+
+
#define VK_EXT_scalar_block_layout 1
#define VK_EXT_SCALAR_BLOCK_LAYOUT_SPEC_VERSION 1
#define VK_EXT_SCALAR_BLOCK_LAYOUT_EXTENSION_NAME "VK_EXT_scalar_block_layout"
diff --git a/vulkan/libvulkan/Android.bp b/vulkan/libvulkan/Android.bp
index 7eaf7b2..fed8481 100644
--- a/vulkan/libvulkan/Android.bp
+++ b/vulkan/libvulkan/Android.bp
@@ -39,6 +39,9 @@
"-Wno-switch-enum",
"-Wno-undef",
+ // Have clang emit complete debug_info.
+ "-fstandalone-debug",
+
//"-DLOG_NDEBUG=0",
],