Merge "SF: Include fence returned from renderScreen into layers' release fence" into rvc-dev
diff --git a/cmds/atrace/atrace.cpp b/cmds/atrace/atrace.cpp
index 544e26c..8637a31 100644
--- a/cmds/atrace/atrace.cpp
+++ b/cmds/atrace/atrace.cpp
@@ -233,6 +233,7 @@
{ REQ, "events/filemap/enable" },
} },
{ "memory", "Memory", 0, {
+ { OPT, "events/mm_event/mm_event_record/enable" },
{ OPT, "events/kmem/rss_stat/enable" },
{ OPT, "events/kmem/ion_heap_grow/enable" },
{ OPT, "events/kmem/ion_heap_shrink/enable" },
diff --git a/cmds/atrace/atrace.rc b/cmds/atrace/atrace.rc
index 6e460a0..040ddde 100644
--- a/cmds/atrace/atrace.rc
+++ b/cmds/atrace/atrace.rc
@@ -107,6 +107,8 @@
chmod 0666 /sys/kernel/tracing/events/kmem/ion_heap_grow/enable
chmod 0666 /sys/kernel/debug/tracing/events/kmem/ion_heap_shrink/enable
chmod 0666 /sys/kernel/tracing/events/kmem/ion_heap_shrink/enable
+ chmod 0666 /sys/kernel/debug/tracing/events/mm_event/mm_event_record/enable
+ chmod 0666 /sys/kernel/tracing/events/mm_event/mm_event_record/enable
chmod 0666 /sys/kernel/debug/tracing/events/signal/signal_generate/enable
chmod 0666 /sys/kernel/tracing/events/signal/signal_generate/enable
chmod 0666 /sys/kernel/debug/tracing/events/signal/signal_deliver/enable
diff --git a/cmds/dumpstate/DumpstateService.cpp b/cmds/dumpstate/DumpstateService.cpp
index 1824943..bfcc058 100644
--- a/cmds/dumpstate/DumpstateService.cpp
+++ b/cmds/dumpstate/DumpstateService.cpp
@@ -137,6 +137,8 @@
ds_info->calling_package = calling_package;
pthread_t thread;
+ // Initialize dumpstate
+ ds_->Initialize();
status_t err = pthread_create(&thread, nullptr, dumpstate_thread_main, ds_info);
if (err != 0) {
delete ds_info;
diff --git a/cmds/dumpstate/binder/android/os/IDumpstateListener.aidl b/cmds/dumpstate/binder/android/os/IDumpstateListener.aidl
index e17f18e..8ff4ca6 100644
--- a/cmds/dumpstate/binder/android/os/IDumpstateListener.aidl
+++ b/cmds/dumpstate/binder/android/os/IDumpstateListener.aidl
@@ -32,7 +32,7 @@
*
* @param progress the progress in [0, 100]
*/
- void onProgress(int progress);
+ oneway void onProgress(int progress);
// NOTE: If you add to or change these error codes, please also change the corresponding enums
// in system server, in BugreportManager.java.
@@ -54,16 +54,18 @@
/**
* Called on an error condition with one of the error codes listed above.
+ * This is not an asynchronous method since it can race with dumpstate exiting, thus triggering
+ * death recipient.
*/
void onError(int errorCode);
/**
* Called when taking bugreport finishes successfully.
*/
- void onFinished();
+ oneway void onFinished();
/**
* Called when screenshot is taken.
*/
- void onScreenshotTaken(boolean success);
+ oneway void onScreenshotTaken(boolean success);
}
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 772b9fe..c85c7cf 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -2395,6 +2395,13 @@
options_ = std::move(options);
}
+void Dumpstate::Initialize() {
+ /* gets the sequential id */
+ uint32_t last_id = android::base::GetIntProperty(PROPERTY_LAST_ID, 0);
+ id_ = ++last_id;
+ android::base::SetProperty(PROPERTY_LAST_ID, std::to_string(last_id));
+}
+
Dumpstate::RunStatus Dumpstate::Run(int32_t calling_uid, const std::string& calling_package) {
Dumpstate::RunStatus status = RunInternal(calling_uid, calling_package);
if (listener_ != nullptr) {
@@ -2505,11 +2512,6 @@
: "";
progress_.reset(new Progress(stats_path));
- /* gets the sequential id */
- uint32_t last_id = android::base::GetIntProperty(PROPERTY_LAST_ID, 0);
- id_ = ++last_id;
- android::base::SetProperty(PROPERTY_LAST_ID, std::to_string(last_id));
-
if (acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_NAME) < 0) {
MYLOGE("Failed to acquire wake lock: %s\n", strerror(errno));
} else {
@@ -2675,15 +2677,6 @@
MYLOGI("User denied consent. Returning\n");
return status;
}
- if (options_->do_screenshot &&
- options_->screenshot_fd.get() != -1 &&
- !options_->is_screenshot_copied) {
- bool copy_succeeded = android::os::CopyFileToFd(screenshot_path_,
- options_->screenshot_fd.get());
- if (copy_succeeded) {
- android::os::UnlinkAndLogOnError(screenshot_path_);
- }
- }
if (status == Dumpstate::RunStatus::USER_CONSENT_TIMED_OUT) {
MYLOGI(
"Did not receive user consent yet."
@@ -2813,6 +2806,16 @@
bool copy_succeeded = android::os::CopyFileToFd(path_, options_->bugreport_fd.get());
if (copy_succeeded) {
android::os::UnlinkAndLogOnError(path_);
+ if (options_->do_screenshot &&
+ options_->screenshot_fd.get() != -1 &&
+ !options_->is_screenshot_copied) {
+ copy_succeeded = android::os::CopyFileToFd(screenshot_path_,
+ options_->screenshot_fd.get());
+ options_->is_screenshot_copied = copy_succeeded;
+ if (copy_succeeded) {
+ android::os::UnlinkAndLogOnError(screenshot_path_);
+ }
+ }
}
return copy_succeeded ? Dumpstate::RunStatus::OK : Dumpstate::RunStatus::ERROR;
} else if (consent_result == UserConsentResult::UNAVAILABLE) {
@@ -2837,8 +2840,9 @@
assert(options_->bugreport_fd.get() == -1);
// calling_uid and calling_package are for user consent to share the bugreport with
- // an app; they are irrelvant here because bugreport is only written to a local
- // directory, and not shared.
+ // an app; they are irrelevant here because bugreport is triggered via command line.
+ // Update Last ID before calling Run().
+ Initialize();
status = Run(-1 /* calling_uid */, "" /* calling_package */);
}
return status;
diff --git a/cmds/dumpstate/dumpstate.h b/cmds/dumpstate/dumpstate.h
index 9ce662b..498f338 100644
--- a/cmds/dumpstate/dumpstate.h
+++ b/cmds/dumpstate/dumpstate.h
@@ -216,6 +216,9 @@
/* Checkes whether dumpstate is generating a zipped bugreport. */
bool IsZipping() const;
+ /* Initialize dumpstate fields before starting bugreport generation */
+ void Initialize();
+
/*
* Forks a command, waits for it to finish, and returns its status.
*
@@ -329,7 +332,12 @@
struct DumpOptions;
- /* Main entry point for running a complete bugreport. */
+ /*
+ * Main entry point for running a complete bugreport.
+ *
+ * Initialize() dumpstate before calling this method.
+ *
+ */
RunStatus Run(int32_t calling_uid, const std::string& calling_package);
RunStatus ParseCommandlineAndRun(int argc, char* argv[]);
diff --git a/cmds/installd/dexopt.cpp b/cmds/installd/dexopt.cpp
index 1af6edd..5ee6a9f 100644
--- a/cmds/installd/dexopt.cpp
+++ b/cmds/installd/dexopt.cpp
@@ -374,6 +374,14 @@
bool skip_compilation = vold_decrypt == "trigger_restart_min_framework" ||
vold_decrypt == "1";
+ std::string updatable_bcp_packages =
+ MapPropertyToArg("dalvik.vm.dex2oat-updatable-bcp-packages-file",
+ "--updatable-bcp-packages-file=%s");
+ if (updatable_bcp_packages.empty()) {
+ // Make dex2oat fail by providing non-existent file name.
+ updatable_bcp_packages = "--updatable-bcp-packages-file=/nonx/updatable-bcp-packages.txt";
+ }
+
std::string resolve_startup_string_arg =
MapPropertyToArg("persist.device_config.runtime.dex2oat_resolve_startup_strings",
"--resolve-startup-const-strings=%s");
@@ -520,6 +528,7 @@
AddRuntimeArg(dex2oat_Xms_arg);
AddRuntimeArg(dex2oat_Xmx_arg);
+ AddArg(updatable_bcp_packages);
AddArg(resolve_startup_string_arg);
AddArg(image_block_size_arg);
AddArg(dex2oat_compiler_filter_arg);
diff --git a/libs/binder/IAppOpsCallback.cpp b/libs/binder/IAppOpsCallback.cpp
index 0ce1dd5..b9eb281 100644
--- a/libs/binder/IAppOpsCallback.cpp
+++ b/libs/binder/IAppOpsCallback.cpp
@@ -39,7 +39,7 @@
data.writeInterfaceToken(IAppOpsCallback::getInterfaceDescriptor());
data.writeInt32(op);
data.writeString16(packageName);
- remote()->transact(OP_CHANGED_TRANSACTION, data, &reply);
+ remote()->transact(OP_CHANGED_TRANSACTION, data, &reply, IBinder::FLAG_ONEWAY);
}
};
@@ -58,7 +58,6 @@
String16 packageName;
(void)data.readString16(&packageName);
opChanged(op, packageName);
- reply->writeNoException();
return NO_ERROR;
} break;
default:
diff --git a/libs/binder/tests/Android.bp b/libs/binder/tests/Android.bp
index 3ee8187..c7b7551 100644
--- a/libs/binder/tests/Android.bp
+++ b/libs/binder/tests/Android.bp
@@ -40,7 +40,7 @@
},
srcs: ["binderDriverInterfaceTest.cpp"],
- test_suites: ["device-tests", "vts-core"],
+ test_suites: ["device-tests", "vts"],
}
cc_test {
@@ -69,7 +69,7 @@
"libbinder",
"libutils",
],
- test_suites: ["device-tests", "vts-core"],
+ test_suites: ["device-tests", "vts"],
require_root: true,
}
@@ -131,7 +131,7 @@
"liblog",
"libutils",
],
- test_suites: ["device-tests", "vts-core"],
+ test_suites: ["device-tests", "vts"],
require_root: true,
}
diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp
index 30e1351..a8384ac 100644
--- a/libs/gui/BLASTBufferQueue.cpp
+++ b/libs/gui/BLASTBufferQueue.cpp
@@ -110,7 +110,7 @@
mProducer->setMaxDequeuedBufferCount(2);
}
mBufferItemConsumer =
- new BLASTBufferItemConsumer(mConsumer, AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER, 1, true);
+ new BLASTBufferItemConsumer(mConsumer, GraphicBuffer::USAGE_HW_COMPOSER, 1, true);
static int32_t id = 0;
auto name = std::string("BLAST Consumer") + std::to_string(id);
id++;
@@ -119,7 +119,9 @@
mBufferItemConsumer->setBufferFreedListener(this);
mBufferItemConsumer->setDefaultBufferSize(mWidth, mHeight);
mBufferItemConsumer->setDefaultBufferFormat(PIXEL_FORMAT_RGBA_8888);
+
mTransformHint = mSurfaceControl->getTransformHint();
+ mBufferItemConsumer->setTransformHint(mTransformHint);
mNumAcquired = 0;
mNumFrameAvailable = 0;
@@ -130,9 +132,12 @@
void BLASTBufferQueue::update(const sp<SurfaceControl>& surface, int width, int height) {
std::unique_lock _lock{mMutex};
mSurfaceControl = surface;
- mWidth = width;
- mHeight = height;
- mBufferItemConsumer->setDefaultBufferSize(mWidth, mHeight);
+
+ if (mWidth != width || mHeight != height) {
+ mWidth = width;
+ mHeight = height;
+ mBufferItemConsumer->setDefaultBufferSize(mWidth, mHeight);
+ }
}
static void transactionCallbackThunk(void* context, nsecs_t latchTime,
diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp
index 8d79cf8..bd4d62c 100644
--- a/libs/gui/ISurfaceComposer.cpp
+++ b/libs/gui/ISurfaceComposer.cpp
@@ -1145,6 +1145,42 @@
ALOGE("setFrameRate: failed to transact: %s (%d)", strerror(-err), err);
return err;
}
+
+ return reply.readInt32();
+ }
+
+ virtual status_t acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
+ if (!outToken) return BAD_VALUE;
+
+ Parcel data, reply;
+ status_t err = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor());
+ if (err != NO_ERROR) {
+ ALOGE("acquireFrameRateFlexibilityToken: failed writing interface token: %s (%d)",
+ strerror(-err), -err);
+ return err;
+ }
+
+ err = remote()->transact(BnSurfaceComposer::ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN, data,
+ &reply);
+ if (err != NO_ERROR) {
+ ALOGE("acquireFrameRateFlexibilityToken: failed to transact: %s (%d)", strerror(-err),
+ err);
+ return err;
+ }
+
+ err = reply.readInt32();
+ if (err != NO_ERROR) {
+ ALOGE("acquireFrameRateFlexibilityToken: call failed: %s (%d)", strerror(-err), err);
+ return err;
+ }
+
+ err = reply.readStrongBinder(outToken);
+ if (err != NO_ERROR) {
+ ALOGE("acquireFrameRateFlexibilityToken: failed reading binder token: %s (%d)",
+ strerror(-err), err);
+ return err;
+ }
+
return NO_ERROR;
}
};
@@ -1945,6 +1981,16 @@
reply->writeInt32(result);
return NO_ERROR;
}
+ case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
+ CHECK_INTERFACE(ISurfaceComposer, data, reply);
+ sp<IBinder> token;
+ status_t result = acquireFrameRateFlexibilityToken(&token);
+ reply->writeInt32(result);
+ if (result == NO_ERROR) {
+ reply->writeStrongBinder(token);
+ }
+ return NO_ERROR;
+ }
default: {
return BBinder::onTransact(code, data, reply, flags);
}
diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h
index 09487ea..3cef256 100644
--- a/libs/gui/include/gui/ISurfaceComposer.h
+++ b/libs/gui/include/gui/ISurfaceComposer.h
@@ -508,6 +508,14 @@
*/
virtual status_t setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
int8_t compatibility) = 0;
+
+ /*
+ * Acquire a frame rate flexibility token from SurfaceFlinger. While this token is acquired,
+ * surface flinger will freely switch between frame rates in any way it sees fit, regardless of
+ * the current restrictions applied by DisplayManager. This is useful to get consistent behavior
+ * for tests. Release the token by releasing the returned IBinder reference.
+ */
+ virtual status_t acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) = 0;
};
// ----------------------------------------------------------------------------
@@ -566,6 +574,7 @@
GET_GAME_CONTENT_TYPE_SUPPORT,
SET_GAME_CONTENT_TYPE,
SET_FRAME_RATE,
+ ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN,
// Always append new enum to the end.
};
diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp
index 8c0f8f8..ef1fd02 100644
--- a/libs/gui/tests/Surface_test.cpp
+++ b/libs/gui/tests/Surface_test.cpp
@@ -859,6 +859,8 @@
return NO_ERROR;
}
+ status_t acquireFrameRateFlexibilityToken(sp<IBinder>* /*outToken*/) { return NO_ERROR; }
+
protected:
IBinder* onAsBinder() override { return nullptr; }
diff --git a/libs/renderengine/gl/filters/BlurFilter.cpp b/libs/renderengine/gl/filters/BlurFilter.cpp
index 6ba78dc..724877b 100644
--- a/libs/renderengine/gl/filters/BlurFilter.cpp
+++ b/libs/renderengine/gl/filters/BlurFilter.cpp
@@ -54,13 +54,13 @@
static constexpr auto translation = 1.0f;
const GLfloat vboData[] = {
// Vertex data
- translation-size, -translation-size,
- translation-size, -translation+size,
- translation+size, -translation+size,
+ translation - size, -translation - size,
+ translation - size, -translation + size,
+ translation + size, -translation + size,
// UV data
- 0.0f, 0.0f-translation,
- 0.0f, size-translation,
- size, size-translation
+ 0.0f, 0.0f - translation,
+ 0.0f, size - translation,
+ size, size - translation
};
mMeshBuffer.allocateBuffers(vboData, 12 /* size */);
}
@@ -69,7 +69,10 @@
ATRACE_NAME("BlurFilter::setAsDrawTarget");
mRadius = radius;
- if (!mTexturesAllocated) {
+ if (mDisplayWidth < display.physicalDisplay.width() ||
+ mDisplayHeight < display.physicalDisplay.height()) {
+ ATRACE_NAME("BlurFilter::allocatingTextures");
+
mDisplayWidth = display.physicalDisplay.width();
mDisplayHeight = display.physicalDisplay.height();
mCompositionFbo.allocateBuffers(mDisplayWidth, mDisplayHeight);
@@ -78,7 +81,6 @@
const uint32_t fboHeight = floorf(mDisplayHeight * kFboScale);
mPingFbo.allocateBuffers(fboWidth, fboHeight);
mPongFbo.allocateBuffers(fboWidth, fboHeight);
- mTexturesAllocated = true;
if (mPingFbo.getStatus() != GL_FRAMEBUFFER_COMPLETE) {
ALOGE("Invalid ping buffer");
@@ -120,27 +122,35 @@
status_t BlurFilter::prepare() {
ATRACE_NAME("BlurFilter::prepare");
- blit(mCompositionFbo, mPingFbo);
// Kawase is an approximation of Gaussian, but it behaves differently from it.
// A radius transformation is required for approximating them, and also to introduce
// non-integer steps, necessary to smoothly interpolate large radii.
- auto radius = mRadius / 6.0f;
+ const auto radius = mRadius / 6.0f;
// Calculate how many passes we'll do, based on the radius.
// Too many passes will make the operation expensive.
- auto passes = min(kMaxPasses, (uint32_t)ceil(radius));
+ const auto passes = min(kMaxPasses, (uint32_t)ceil(radius));
- // We'll ping pong between our textures, to accumulate the result of various offsets.
+ const float radiusByPasses = radius / (float)passes;
+ const float stepX = radiusByPasses / (float)mCompositionFbo.getBufferWidth();
+ const float stepY = radiusByPasses / (float)mCompositionFbo.getBufferHeight();
+
+ // Let's start by downsampling and blurring the composited frame simultaneously.
mBlurProgram.useProgram();
- GLFramebuffer* read = &mPingFbo;
- GLFramebuffer* draw = &mPongFbo;
- float stepX = radius / (float)mCompositionFbo.getBufferWidth() / (float)passes;
- float stepY = radius / (float)mCompositionFbo.getBufferHeight() / (float)passes;
- glViewport(0, 0, draw->getBufferWidth(), draw->getBufferHeight());
glActiveTexture(GL_TEXTURE0);
glUniform1i(mBTextureLoc, 0);
- for (auto i = 0; i < passes; i++) {
+ glBindTexture(GL_TEXTURE_2D, mCompositionFbo.getTextureName());
+ glUniform2f(mBOffsetLoc, stepX, stepY);
+ glViewport(0, 0, mPingFbo.getBufferWidth(), mPingFbo.getBufferHeight());
+ mPingFbo.bind();
+ drawMesh(mBUvLoc, mBPosLoc);
+
+ // And now we'll ping pong between our textures, to accumulate the result of various offsets.
+ GLFramebuffer* read = &mPingFbo;
+ GLFramebuffer* draw = &mPongFbo;
+ glViewport(0, 0, draw->getBufferWidth(), draw->getBufferHeight());
+ for (auto i = 1; i < passes; i++) {
ATRACE_NAME("BlurFilter::renderPass");
draw->bind();
@@ -156,9 +166,6 @@
}
mLastDrawTarget = read;
- // Cleanup
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
-
return NO_ERROR;
}
@@ -177,7 +184,6 @@
glBlitFramebuffer(0, 0, mLastDrawTarget->getBufferWidth(),
mLastDrawTarget->getBufferHeight(), 0, 0, mDisplayWidth, mDisplayHeight,
GL_COLOR_BUFFER_BIT, GL_LINEAR);
- glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
return NO_ERROR;
}
@@ -256,12 +262,12 @@
}
void BlurFilter::blit(GLFramebuffer& read, GLFramebuffer& draw) const {
+ ATRACE_NAME("BlurFilter::blit");
read.bindAsReadBuffer();
draw.bindAsDrawBuffer();
glBlitFramebuffer(0, 0, read.getBufferWidth(), read.getBufferHeight(), 0, 0,
draw.getBufferWidth(), draw.getBufferHeight(), GL_COLOR_BUFFER_BIT,
GL_LINEAR);
- glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
} // namespace gl
diff --git a/libs/renderengine/gl/filters/BlurFilter.h b/libs/renderengine/gl/filters/BlurFilter.h
index 3eb5c96..36e5a77 100644
--- a/libs/renderengine/gl/filters/BlurFilter.h
+++ b/libs/renderengine/gl/filters/BlurFilter.h
@@ -67,11 +67,10 @@
// Frame buffers holding the blur passes.
GLFramebuffer mPingFbo;
GLFramebuffer mPongFbo;
- uint32_t mDisplayWidth;
- uint32_t mDisplayHeight;
+ uint32_t mDisplayWidth = 0;
+ uint32_t mDisplayHeight = 0;
// Buffer holding the final blur pass.
GLFramebuffer* mLastDrawTarget;
- bool mTexturesAllocated = false;
// VBO containing vertex and uv data of a fullscreen triangle.
GLVertexBuffer mMeshBuffer;
diff --git a/services/inputflinger/InputManager.cpp b/services/inputflinger/InputManager.cpp
index fc771a2..e68946d 100644
--- a/services/inputflinger/InputManager.cpp
+++ b/services/inputflinger/InputManager.cpp
@@ -111,8 +111,10 @@
handlesPerDisplay.emplace(info.displayId, std::vector<sp<InputWindowHandle>>());
handlesPerDisplay[info.displayId].push_back(new BinderWindowHandle(info));
}
- for (auto const& i : handlesPerDisplay) {
- mDispatcher->setInputWindows(i.second, i.first, setInputWindowsListener);
+ mDispatcher->setInputWindows(handlesPerDisplay);
+
+ if (setInputWindowsListener) {
+ setInputWindowsListener->onSetInputWindowsFinished();
}
}
diff --git a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
index 3b18813..7c5c9c5 100644
--- a/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
+++ b/services/inputflinger/benchmarks/InputDispatcher_benchmarks.cpp
@@ -252,7 +252,7 @@
sp<FakeApplicationHandle> application = new FakeApplicationHandle();
sp<FakeWindowHandle> window = new FakeWindowHandle(application, dispatcher, "Fake Window");
- dispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ dispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
NotifyMotionArgs motionArgs = generateMotionArgs();
@@ -288,7 +288,7 @@
sp<FakeApplicationHandle> application = new FakeApplicationHandle();
sp<FakeWindowHandle> window = new FakeWindowHandle(application, dispatcher, "Fake Window");
- dispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ dispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
for (auto _ : state) {
MotionEvent event = generateMotionEvent();
diff --git a/services/inputflinger/dispatcher/InputDispatcher.cpp b/services/inputflinger/dispatcher/InputDispatcher.cpp
index 308d19b..4ec61b0 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.cpp
+++ b/services/inputflinger/dispatcher/InputDispatcher.cpp
@@ -3621,6 +3621,18 @@
mWindowHandlesByDisplay[displayId] = newHandles;
}
+void InputDispatcher::setInputWindows(
+ const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>& handlesPerDisplay) {
+ { // acquire lock
+ std::scoped_lock _l(mLock);
+ for (auto const& i : handlesPerDisplay) {
+ setInputWindowsLocked(i.second, i.first);
+ }
+ }
+ // Wake up poll loop since it may need to make new input dispatching choices.
+ mLooper->wake();
+}
+
/**
* Called from InputManagerService, update window handle list by displayId that can receive input.
* A window handle contains information about InputChannel, Touch Region, Types, Focused,...
@@ -3628,9 +3640,8 @@
* For focused handle, check if need to change and send a cancel event to previous one.
* For removed handle, check if need to send a cancel event if already in touch.
*/
-void InputDispatcher::setInputWindows(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
- int32_t displayId,
- const sp<ISetInputWindowsListener>& setInputWindowsListener) {
+void InputDispatcher::setInputWindowsLocked(
+ const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId) {
if (DEBUG_FOCUS) {
std::string windowList;
for (const sp<InputWindowHandle>& iwh : inputWindowHandles) {
@@ -3638,109 +3649,97 @@
}
ALOGD("setInputWindows displayId=%" PRId32 " %s", displayId, windowList.c_str());
}
- { // acquire lock
- std::scoped_lock _l(mLock);
- // Copy old handles for release if they are no longer present.
- const std::vector<sp<InputWindowHandle>> oldWindowHandles =
- getWindowHandlesLocked(displayId);
+ // Copy old handles for release if they are no longer present.
+ const std::vector<sp<InputWindowHandle>> oldWindowHandles = getWindowHandlesLocked(displayId);
- updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
+ updateWindowHandlesForDisplayLocked(inputWindowHandles, displayId);
- sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
- bool foundHoveredWindow = false;
- for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
- // Set newFocusedWindowHandle to the top most focused window instead of the last one
- if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
- windowHandle->getInfo()->visible) {
- newFocusedWindowHandle = windowHandle;
+ sp<InputWindowHandle> newFocusedWindowHandle = nullptr;
+ bool foundHoveredWindow = false;
+ for (const sp<InputWindowHandle>& windowHandle : getWindowHandlesLocked(displayId)) {
+ // Set newFocusedWindowHandle to the top most focused window instead of the last one
+ if (!newFocusedWindowHandle && windowHandle->getInfo()->hasFocus &&
+ windowHandle->getInfo()->visible) {
+ newFocusedWindowHandle = windowHandle;
+ }
+ if (windowHandle == mLastHoverWindowHandle) {
+ foundHoveredWindow = true;
+ }
+ }
+
+ if (!foundHoveredWindow) {
+ mLastHoverWindowHandle = nullptr;
+ }
+
+ sp<InputWindowHandle> oldFocusedWindowHandle =
+ getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
+
+ if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
+ if (oldFocusedWindowHandle != nullptr) {
+ if (DEBUG_FOCUS) {
+ ALOGD("Focus left window: %s in display %" PRId32,
+ oldFocusedWindowHandle->getName().c_str(), displayId);
}
- if (windowHandle == mLastHoverWindowHandle) {
- foundHoveredWindow = true;
+ sp<InputChannel> focusedInputChannel =
+ getInputChannelLocked(oldFocusedWindowHandle->getToken());
+ if (focusedInputChannel != nullptr) {
+ CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
+ "focus left window");
+ synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
+ enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
}
+ mFocusedWindowHandlesByDisplay.erase(displayId);
+ }
+ if (newFocusedWindowHandle != nullptr) {
+ if (DEBUG_FOCUS) {
+ ALOGD("Focus entered window: %s in display %" PRId32,
+ newFocusedWindowHandle->getName().c_str(), displayId);
+ }
+ mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
+ enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
}
- if (!foundHoveredWindow) {
- mLastHoverWindowHandle = nullptr;
+ if (mFocusedDisplayId == displayId) {
+ onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
}
+ }
- sp<InputWindowHandle> oldFocusedWindowHandle =
- getValueByKey(mFocusedWindowHandlesByDisplay, displayId);
-
- if (!haveSameToken(oldFocusedWindowHandle, newFocusedWindowHandle)) {
- if (oldFocusedWindowHandle != nullptr) {
+ ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
+ if (stateIndex >= 0) {
+ TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
+ for (size_t i = 0; i < state.windows.size();) {
+ TouchedWindow& touchedWindow = state.windows[i];
+ if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
if (DEBUG_FOCUS) {
- ALOGD("Focus left window: %s in display %" PRId32,
- oldFocusedWindowHandle->getName().c_str(), displayId);
+ ALOGD("Touched window was removed: %s in display %" PRId32,
+ touchedWindow.windowHandle->getName().c_str(), displayId);
}
- sp<InputChannel> focusedInputChannel =
- getInputChannelLocked(oldFocusedWindowHandle->getToken());
- if (focusedInputChannel != nullptr) {
- CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,
- "focus left window");
- synthesizeCancelationEventsForInputChannelLocked(focusedInputChannel, options);
- enqueueFocusEventLocked(*oldFocusedWindowHandle, false /*hasFocus*/);
+ sp<InputChannel> touchedInputChannel =
+ getInputChannelLocked(touchedWindow.windowHandle->getToken());
+ if (touchedInputChannel != nullptr) {
+ CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
+ "touched window was removed");
+ synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel, options);
}
- mFocusedWindowHandlesByDisplay.erase(displayId);
- }
- if (newFocusedWindowHandle != nullptr) {
- if (DEBUG_FOCUS) {
- ALOGD("Focus entered window: %s in display %" PRId32,
- newFocusedWindowHandle->getName().c_str(), displayId);
- }
- mFocusedWindowHandlesByDisplay[displayId] = newFocusedWindowHandle;
- enqueueFocusEventLocked(*newFocusedWindowHandle, true /*hasFocus*/);
- }
-
- if (mFocusedDisplayId == displayId) {
- onFocusChangedLocked(oldFocusedWindowHandle, newFocusedWindowHandle);
+ state.windows.erase(state.windows.begin() + i);
+ } else {
+ ++i;
}
}
+ }
- ssize_t stateIndex = mTouchStatesByDisplay.indexOfKey(displayId);
- if (stateIndex >= 0) {
- TouchState& state = mTouchStatesByDisplay.editValueAt(stateIndex);
- for (size_t i = 0; i < state.windows.size();) {
- TouchedWindow& touchedWindow = state.windows[i];
- if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {
- if (DEBUG_FOCUS) {
- ALOGD("Touched window was removed: %s in display %" PRId32,
- touchedWindow.windowHandle->getName().c_str(), displayId);
- }
- sp<InputChannel> touchedInputChannel =
- getInputChannelLocked(touchedWindow.windowHandle->getToken());
- if (touchedInputChannel != nullptr) {
- CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,
- "touched window was removed");
- synthesizeCancelationEventsForInputChannelLocked(touchedInputChannel,
- options);
- }
- state.windows.erase(state.windows.begin() + i);
- } else {
- ++i;
- }
+ // Release information for windows that are no longer present.
+ // This ensures that unused input channels are released promptly.
+ // Otherwise, they might stick around until the window handle is destroyed
+ // which might not happen until the next GC.
+ for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
+ if (!hasWindowHandleLocked(oldWindowHandle)) {
+ if (DEBUG_FOCUS) {
+ ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
}
+ oldWindowHandle->releaseChannel();
}
-
- // Release information for windows that are no longer present.
- // This ensures that unused input channels are released promptly.
- // Otherwise, they might stick around until the window handle is destroyed
- // which might not happen until the next GC.
- for (const sp<InputWindowHandle>& oldWindowHandle : oldWindowHandles) {
- if (!hasWindowHandleLocked(oldWindowHandle)) {
- if (DEBUG_FOCUS) {
- ALOGD("Window went away: %s", oldWindowHandle->getName().c_str());
- }
- oldWindowHandle->releaseChannel();
- }
- }
- } // release lock
-
- // Wake up poll loop since it may need to make new input dispatching choices.
- mLooper->wake();
-
- if (setInputWindowsListener) {
- setInputWindowsListener->onSetInputWindowsFinished();
}
}
diff --git a/services/inputflinger/dispatcher/InputDispatcher.h b/services/inputflinger/dispatcher/InputDispatcher.h
index 4aa47f8..cbba7e1 100644
--- a/services/inputflinger/dispatcher/InputDispatcher.h
+++ b/services/inputflinger/dispatcher/InputDispatcher.h
@@ -109,8 +109,8 @@
virtual std::unique_ptr<VerifiedInputEvent> verifyInputEvent(const InputEvent& event) override;
virtual void setInputWindows(
- const std::vector<sp<InputWindowHandle>>& inputWindowHandles, int32_t displayId,
- const sp<ISetInputWindowsListener>& setInputWindowsListener = nullptr) override;
+ const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>&
+ handlesPerDisplay) override;
virtual void setFocusedApplication(
int32_t displayId, const sp<InputApplicationHandle>& inputApplicationHandle) override;
virtual void setFocusedDisplay(int32_t displayId) override;
@@ -278,6 +278,8 @@
std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>> mWindowHandlesByDisplay
GUARDED_BY(mLock);
+ void setInputWindowsLocked(const std::vector<sp<InputWindowHandle>>& inputWindowHandles,
+ int32_t displayId) REQUIRES(mLock);
// Get window handles by display, return an empty vector if not found.
std::vector<sp<InputWindowHandle>> getWindowHandlesLocked(int32_t displayId) const
REQUIRES(mLock);
diff --git a/services/inputflinger/dispatcher/include/InputDispatcherInterface.h b/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
index 6e98676..09dc92c 100644
--- a/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
+++ b/services/inputflinger/dispatcher/include/InputDispatcherInterface.h
@@ -19,6 +19,7 @@
#include <InputListener.h>
#include <input/ISetInputWindowsListener.h>
+#include <unordered_map>
namespace android {
@@ -99,13 +100,13 @@
*/
virtual std::unique_ptr<VerifiedInputEvent> verifyInputEvent(const InputEvent& event) = 0;
- /* Sets the list of input windows.
+ /* Sets the list of input windows per display.
*
* This method may be called on any thread (usually by the input manager).
*/
virtual void setInputWindows(
- const std::vector<sp<InputWindowHandle> >& inputWindowHandles, int32_t displayId,
- const sp<ISetInputWindowsListener>& setInputWindowsListener = nullptr) = 0;
+ const std::unordered_map<int32_t, std::vector<sp<InputWindowHandle>>>&
+ handlesPerDisplay) = 0;
/* Sets the focused application on the given display.
*
diff --git a/services/inputflinger/tests/EventHub_test.cpp b/services/inputflinger/tests/EventHub_test.cpp
index be2e19e..71731b0 100644
--- a/services/inputflinger/tests/EventHub_test.cpp
+++ b/services/inputflinger/tests/EventHub_test.cpp
@@ -34,6 +34,7 @@
using android::sp;
using android::UinputHomeKey;
using std::chrono_literals::operator""ms;
+using std::chrono_literals::operator""s;
static constexpr bool DEBUG = false;
@@ -70,11 +71,12 @@
mEventHub = std::make_unique<EventHub>();
consumeInitialDeviceAddedEvents();
mKeyboard = createUinputDevice<UinputHomeKey>();
- mDeviceId = waitForDeviceCreation();
+ ASSERT_NO_FATAL_FAILURE(mDeviceId = waitForDeviceCreation());
}
virtual void TearDown() override {
mKeyboard.reset();
waitForDeviceClose(mDeviceId);
+ assertNoMoreEvents();
}
/**
@@ -83,21 +85,38 @@
int32_t waitForDeviceCreation();
void waitForDeviceClose(int32_t deviceId);
void consumeInitialDeviceAddedEvents();
- std::vector<RawEvent> getEvents(std::chrono::milliseconds timeout = 5ms);
+ void assertNoMoreEvents();
+ /**
+ * Read events from the EventHub.
+ *
+ * If expectedEvents is set, wait for a significant period of time to try and ensure that
+ * the expected number of events has been read. The number of returned events
+ * may be smaller (if timeout has been reached) or larger than expectedEvents.
+ *
+ * If expectedEvents is not set, return all of the immediately available events.
+ */
+ std::vector<RawEvent> getEvents(std::optional<size_t> expectedEvents = std::nullopt);
};
-std::vector<RawEvent> EventHubTest::getEvents(std::chrono::milliseconds timeout) {
+std::vector<RawEvent> EventHubTest::getEvents(std::optional<size_t> expectedEvents) {
static constexpr size_t EVENT_BUFFER_SIZE = 256;
std::array<RawEvent, EVENT_BUFFER_SIZE> eventBuffer;
std::vector<RawEvent> events;
while (true) {
- size_t count =
+ std::chrono::milliseconds timeout = 0s;
+ if (expectedEvents) {
+ timeout = 2s;
+ }
+ const size_t count =
mEventHub->getEvents(timeout.count(), eventBuffer.data(), eventBuffer.size());
if (count == 0) {
break;
}
events.insert(events.end(), eventBuffer.begin(), eventBuffer.begin() + count);
+ if (expectedEvents && events.size() >= *expectedEvents) {
+ break;
+ }
}
if (DEBUG) {
dumpEvents(events);
@@ -111,7 +130,7 @@
* it will return a lot of "device added" type of events.
*/
void EventHubTest::consumeInitialDeviceAddedEvents() {
- std::vector<RawEvent> events = getEvents(0ms);
+ std::vector<RawEvent> events = getEvents();
std::set<int32_t /*deviceId*/> existingDevices;
// All of the events should be DEVICE_ADDED type, except the last one.
for (size_t i = 0; i < events.size() - 1; i++) {
@@ -128,8 +147,11 @@
int32_t EventHubTest::waitForDeviceCreation() {
// Wait a little longer than usual, to ensure input device has time to be created
- std::vector<RawEvent> events = getEvents(20ms);
- EXPECT_EQ(2U, events.size()); // Using "expect" because the function is non-void.
+ std::vector<RawEvent> events = getEvents(2);
+ if (events.size() != 2) {
+ ADD_FAILURE() << "Instead of 2 events, received " << events.size();
+ return 0; // this value is unused
+ }
const RawEvent& deviceAddedEvent = events[0];
EXPECT_EQ(static_cast<int32_t>(EventHubInterface::DEVICE_ADDED), deviceAddedEvent.type);
InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceAddedEvent.deviceId);
@@ -142,7 +164,7 @@
}
void EventHubTest::waitForDeviceClose(int32_t deviceId) {
- std::vector<RawEvent> events = getEvents(20ms);
+ std::vector<RawEvent> events = getEvents(2);
ASSERT_EQ(2U, events.size());
const RawEvent& deviceRemovedEvent = events[0];
EXPECT_EQ(static_cast<int32_t>(EventHubInterface::DEVICE_REMOVED), deviceRemovedEvent.type);
@@ -152,6 +174,11 @@
finishedDeviceScanEvent.type);
}
+void EventHubTest::assertNoMoreEvents() {
+ std::vector<RawEvent> events = getEvents();
+ ASSERT_TRUE(events.empty());
+}
+
/**
* Ensure that input_events are generated with monotonic clock.
* That means input_event should receive a timestamp that is in the future of the time
@@ -162,7 +189,7 @@
nsecs_t lastEventTime = systemTime(SYSTEM_TIME_MONOTONIC);
ASSERT_NO_FATAL_FAILURE(mKeyboard->pressAndReleaseHomeKey());
- std::vector<RawEvent> events = getEvents();
+ std::vector<RawEvent> events = getEvents(4);
ASSERT_EQ(4U, events.size()) << "Expected to receive 2 keys and 2 syncs, total of 4 events";
for (const RawEvent& event : events) {
// Cannot use strict comparison because the events may happen too quickly
diff --git a/services/inputflinger/tests/InputDispatcher_test.cpp b/services/inputflinger/tests/InputDispatcher_test.cpp
index 1f283b1..29f3dac 100644
--- a/services/inputflinger/tests/InputDispatcher_test.cpp
+++ b/services/inputflinger/tests/InputDispatcher_test.cpp
@@ -871,7 +871,7 @@
sp<FakeWindowHandle> window = new FakeWindowHandle(application, mDispatcher, "Fake Window",
ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
<< "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
@@ -888,7 +888,7 @@
sp<FakeWindowHandle> windowSecond = new FakeWindowHandle(application, mDispatcher, "Second",
ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({windowTop, windowSecond}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectMotionDown(mDispatcher,
AINPUT_SOURCE_TOUCHSCREEN, ADISPLAY_ID_DEFAULT))
<< "Inject motion event should return INPUT_EVENT_INJECTION_SUCCEEDED";
@@ -910,7 +910,7 @@
// Display should have only one focused window
windowSecond->setFocus(true);
- mDispatcher->setInputWindows({windowTop, windowSecond}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
windowSecond->consumeFocusEvent(true);
ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
@@ -935,7 +935,7 @@
windowTop->setFocus(true);
windowSecond->setFocus(true);
- mDispatcher->setInputWindows({windowTop, windowSecond}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
windowTop->consumeFocusEvent(true);
ASSERT_EQ(INPUT_EVENT_INJECTION_SUCCEEDED, injectKeyDown(mDispatcher))
<< "Inject key event should return INPUT_EVENT_INJECTION_SUCCEEDED";
@@ -960,7 +960,7 @@
windowSecond->setFocus(true);
// Release channel for window is no longer valid.
windowTop->releaseChannel();
- mDispatcher->setInputWindows({windowTop, windowSecond}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowTop, windowSecond}}});
windowSecond->consumeFocusEvent(true);
// Test inject a key down, should dispatch to a valid window.
@@ -986,7 +986,7 @@
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
- mDispatcher->setInputWindows({windowLeft, windowRight}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowLeft, windowRight}}});
// Inject an event with coordinate in the area of right window, with mouse cursor in the area of
// left window. This event should be dispatched to the left window.
@@ -1003,7 +1003,7 @@
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true);
NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
@@ -1025,7 +1025,7 @@
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
NotifyMotionArgs motionArgs =
generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
@@ -1053,7 +1053,7 @@
"Second Window", ADISPLAY_ID_DEFAULT);
// Add the windows to the dispatcher
- mDispatcher->setInputWindows({firstWindow, secondWindow}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
// Send down to the first window
NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
@@ -1090,7 +1090,7 @@
"Second Window", ADISPLAY_ID_DEFAULT);
// Add the windows to the dispatcher
- mDispatcher->setInputWindows({firstWindow, secondWindow}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
// Send down to the first window
NotifyMotionArgs downMotionArgs = generateMotionArgs(AMOTION_EVENT_ACTION_DOWN,
@@ -1152,7 +1152,7 @@
| InputWindowInfo::FLAG_SPLIT_TOUCH);
// Add the windows to the dispatcher
- mDispatcher->setInputWindows({firstWindow, secondWindow}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {firstWindow, secondWindow}}});
PointF pointInFirst = {300, 200};
PointF pointInSecond = {300, 600};
@@ -1204,7 +1204,7 @@
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true);
@@ -1220,7 +1220,7 @@
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
mDispatcher->notifyKey(&keyArgs);
@@ -1235,7 +1235,7 @@
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
// Send key
NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN, ADISPLAY_ID_DEFAULT);
@@ -1289,7 +1289,7 @@
sp<FakeApplicationHandle> application = new FakeApplicationHandle();
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
true /*isGestureMonitor*/);
@@ -1309,7 +1309,7 @@
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true);
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
@@ -1325,7 +1325,7 @@
sp<FakeApplicationHandle> application = new FakeApplicationHandle();
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
FakeMonitorReceiver monitor = FakeMonitorReceiver(mDispatcher, "GM_1", ADISPLAY_ID_DEFAULT,
true /*isGestureMonitor*/);
@@ -1351,7 +1351,7 @@
sp<FakeWindowHandle> window =
new FakeWindowHandle(application, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
NotifyMotionArgs motionArgs =
generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
@@ -1387,29 +1387,29 @@
window->setFocus(true);
SCOPED_TRACE("Check default value of touch mode");
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
SCOPED_TRACE("Remove the window to trigger focus loss");
window->setFocus(false);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(false /*hasFocus*/, true /*inTouchMode*/);
SCOPED_TRACE("Disable touch mode");
mDispatcher->setInTouchMode(false);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true /*hasFocus*/, false /*inTouchMode*/);
SCOPED_TRACE("Remove the window to trigger focus loss");
window->setFocus(false);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(false /*hasFocus*/, false /*inTouchMode*/);
SCOPED_TRACE("Enable touch mode again");
mDispatcher->setInTouchMode(true);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
window->assertNoEvents();
@@ -1423,7 +1423,7 @@
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
window->setFocus(true);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
window->consumeFocusEvent(true /*hasFocus*/, true /*inTouchMode*/);
NotifyKeyArgs keyArgs = generateKeyArgs(AKEY_EVENT_ACTION_DOWN);
@@ -1459,7 +1459,7 @@
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application);
- mDispatcher->setInputWindows({window}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {window}}});
NotifyMotionArgs motionArgs =
generateMotionArgs(AMOTION_EVENT_ACTION_DOWN, AINPUT_SOURCE_TOUCHSCREEN,
@@ -1512,7 +1512,7 @@
mWindow = new FakeWindowHandle(mApp, mDispatcher, "Fake Window", ADISPLAY_ID_DEFAULT);
mWindow->setFocus(true);
- mDispatcher->setInputWindows({mWindow}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow}}});
mWindow->consumeFocusEvent(true);
}
@@ -1602,7 +1602,7 @@
// Set focus window for primary display, but focused display would be second one.
mDispatcher->setFocusedApplication(ADISPLAY_ID_DEFAULT, application1);
windowInPrimary->setFocus(true);
- mDispatcher->setInputWindows({windowInPrimary}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {windowInPrimary}}});
windowInPrimary->consumeFocusEvent(true);
application2 = new FakeApplicationHandle();
@@ -1614,7 +1614,7 @@
// Set focus window for second display.
mDispatcher->setFocusedApplication(SECOND_DISPLAY_ID, application2);
windowInSecondary->setFocus(true);
- mDispatcher->setInputWindows({windowInSecondary}, SECOND_DISPLAY_ID);
+ mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {windowInSecondary}}});
windowInSecondary->consumeFocusEvent(true);
}
@@ -1664,7 +1664,7 @@
windowInSecondary->consumeKeyDown(ADISPLAY_ID_NONE);
// Remove all windows in secondary display.
- mDispatcher->setInputWindows({}, SECOND_DISPLAY_ID);
+ mDispatcher->setInputWindows({{SECOND_DISPLAY_ID, {}}});
// Expect old focus should receive a cancel event.
windowInSecondary->consumeEvent(AINPUT_EVENT_TYPE_KEY, AKEY_EVENT_ACTION_UP, ADISPLAY_ID_NONE,
@@ -1828,7 +1828,7 @@
mFocusedWindow->setFocus(true);
// Expect one focus window exist in display.
- mDispatcher->setInputWindows({mUnfocusedWindow, mFocusedWindow}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mUnfocusedWindow, mFocusedWindow}}});
mFocusedWindow->consumeFocusEvent(true);
}
@@ -1916,7 +1916,7 @@
mWindow2->setId(1);
mWindow2->setFrame(Rect(100, 100, 200, 200));
- mDispatcher->setInputWindows({mWindow1, mWindow2}, ADISPLAY_ID_DEFAULT);
+ mDispatcher->setInputWindows({{ADISPLAY_ID_DEFAULT, {mWindow1, mWindow2}}});
}
protected:
diff --git a/services/inputflinger/tests/UinputDevice.cpp b/services/inputflinger/tests/UinputDevice.cpp
index 99480b7..10e7293 100644
--- a/services/inputflinger/tests/UinputDevice.cpp
+++ b/services/inputflinger/tests/UinputDevice.cpp
@@ -44,9 +44,7 @@
device.id.product = 0x01;
device.id.version = 1;
- // Using EXPECT instead of ASSERT to allow the device creation to continue even when
- // some failures are reported when configuring the device.
- EXPECT_NO_FATAL_FAILURE(configureDevice(mDeviceFd, &device));
+ ASSERT_NO_FATAL_FAILURE(configureDevice(mDeviceFd, &device));
if (write(mDeviceFd, &device, sizeof(device)) < 0) {
FAIL() << "Could not write uinput_user_dev struct into uinput file descriptor: "
@@ -70,7 +68,7 @@
" with value %" PRId32 " : %s",
type, code, value, strerror(errno));
ALOGE("%s", msg.c_str());
- ADD_FAILURE() << msg.c_str();
+ FAIL() << msg.c_str();
}
}
@@ -82,41 +80,41 @@
void UinputKeyboard::configureDevice(int fd, uinput_user_dev* device) {
// enable key press/release event
if (ioctl(fd, UI_SET_EVBIT, EV_KEY)) {
- ADD_FAILURE() << "Error in ioctl : UI_SET_EVBIT : EV_KEY: " << strerror(errno);
+ FAIL() << "Error in ioctl : UI_SET_EVBIT : EV_KEY: " << strerror(errno);
}
// enable set of KEY events
std::for_each(mKeys.begin(), mKeys.end(), [fd](int key) {
if (ioctl(fd, UI_SET_KEYBIT, key)) {
- ADD_FAILURE() << "Error in ioctl : UI_SET_KEYBIT : " << key << " : " << strerror(errno);
+ FAIL() << "Error in ioctl : UI_SET_KEYBIT : " << key << " : " << strerror(errno);
}
});
// enable synchronization event
if (ioctl(fd, UI_SET_EVBIT, EV_SYN)) {
- ADD_FAILURE() << "Error in ioctl : UI_SET_EVBIT : EV_SYN: " << strerror(errno);
+ FAIL() << "Error in ioctl : UI_SET_EVBIT : EV_SYN: " << strerror(errno);
}
}
void UinputKeyboard::pressKey(int key) {
if (mKeys.find(key) == mKeys.end()) {
- ADD_FAILURE() << mName << ": Cannot inject key press: Key not found: " << key;
+ FAIL() << mName << ": Cannot inject key press: Key not found: " << key;
}
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_KEY, key, 1));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_KEY, key, 1);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
void UinputKeyboard::releaseKey(int key) {
if (mKeys.find(key) == mKeys.end()) {
- ADD_FAILURE() << mName << ": Cannot inject key release: Key not found: " << key;
+ FAIL() << mName << ": Cannot inject key release: Key not found: " << key;
}
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_KEY, key, 0));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_KEY, key, 0);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
void UinputKeyboard::pressAndReleaseKey(int key) {
- EXPECT_NO_FATAL_FAILURE(pressKey(key));
- EXPECT_NO_FATAL_FAILURE(releaseKey(key));
+ pressKey(key);
+ releaseKey(key);
}
// --- UinputHomeKey ---
@@ -124,7 +122,7 @@
UinputHomeKey::UinputHomeKey() : UinputKeyboard({KEY_HOME}) {}
void UinputHomeKey::pressAndReleaseHomeKey() {
- EXPECT_NO_FATAL_FAILURE(pressAndReleaseKey(KEY_HOME));
+ pressAndReleaseKey(KEY_HOME);
}
// --- UinputTouchScreen ---
@@ -158,35 +156,35 @@
}
void UinputTouchScreen::sendSlot(int32_t slot) {
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_SLOT, slot));
+ injectEvent(EV_ABS, ABS_MT_SLOT, slot);
}
void UinputTouchScreen::sendTrackingId(int32_t trackingId) {
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_TRACKING_ID, trackingId));
+ injectEvent(EV_ABS, ABS_MT_TRACKING_ID, trackingId);
}
void UinputTouchScreen::sendDown(const Point& point) {
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_KEY, BTN_TOUCH, 1));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_POSITION_X, point.x));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_POSITION_Y, point.y));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_KEY, BTN_TOUCH, 1);
+ injectEvent(EV_ABS, ABS_MT_POSITION_X, point.x);
+ injectEvent(EV_ABS, ABS_MT_POSITION_Y, point.y);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
void UinputTouchScreen::sendMove(const Point& point) {
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_POSITION_X, point.x));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_POSITION_Y, point.y));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_ABS, ABS_MT_POSITION_X, point.x);
+ injectEvent(EV_ABS, ABS_MT_POSITION_Y, point.y);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
void UinputTouchScreen::sendUp() {
sendTrackingId(0xffffffff);
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_KEY, BTN_TOUCH, 0));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_KEY, BTN_TOUCH, 0);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
void UinputTouchScreen::sendToolType(int32_t toolType) {
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_ABS, ABS_MT_TOOL_TYPE, toolType));
- EXPECT_NO_FATAL_FAILURE(injectEvent(EV_SYN, SYN_REPORT, 0));
+ injectEvent(EV_ABS, ABS_MT_TOOL_TYPE, toolType);
+ injectEvent(EV_SYN, SYN_REPORT, 0);
}
// Get the center x, y base on the range definition.
diff --git a/services/sensorservice/SensorDirectConnection.cpp b/services/sensorservice/SensorDirectConnection.cpp
index 106efd6..1622e77 100644
--- a/services/sensorservice/SensorDirectConnection.cpp
+++ b/services/sensorservice/SensorDirectConnection.cpp
@@ -93,6 +93,23 @@
return nullptr;
}
+void SensorService::SensorDirectConnection::updateSensorSubscriptions() {
+ if (!hasSensorAccess()) {
+ stopAll(true /* backupRecord */);
+ } else {
+ recoverAll();
+ }
+}
+
+void SensorService::SensorDirectConnection::setSensorAccess(bool hasAccess) {
+ mHasSensorAccess = hasAccess;
+ updateSensorSubscriptions();
+}
+
+bool SensorService::SensorDirectConnection::hasSensorAccess() const {
+ return mHasSensorAccess && !mService->mSensorPrivacyPolicy->isSensorPrivacyEnabled();
+}
+
status_t SensorService::SensorDirectConnection::enableDisable(
int handle, bool enabled, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs,
int reservedFlags) {
diff --git a/services/sensorservice/SensorDirectConnection.h b/services/sensorservice/SensorDirectConnection.h
index ead08d3..fa88fbc 100644
--- a/services/sensorservice/SensorDirectConnection.h
+++ b/services/sensorservice/SensorDirectConnection.h
@@ -54,6 +54,9 @@
// called by SensorService when return to NORMAL mode.
void recoverAll();
+ void updateSensorSubscriptions();
+
+ void setSensorAccess(bool hasAccess);
protected:
virtual ~SensorDirectConnection();
// ISensorEventConnection functions
@@ -66,6 +69,7 @@
virtual int32_t configureChannel(int handle, int rateLevel);
virtual void destroy();
private:
+ bool hasSensorAccess() const;
const sp<SensorService> mService;
const uid_t mUid;
const sensors_direct_mem_t mMem;
@@ -76,6 +80,8 @@
std::unordered_map<int, int> mActivated;
std::unordered_map<int, int> mActivatedBackup;
+ std::atomic_bool mHasSensorAccess = true;
+
mutable Mutex mDestroyLock;
bool mDestroyed;
};
diff --git a/services/sensorservice/SensorEventConnection.cpp b/services/sensorservice/SensorEventConnection.cpp
index 9a13c00..5be4ccd 100644
--- a/services/sensorservice/SensorEventConnection.cpp
+++ b/services/sensorservice/SensorEventConnection.cpp
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+#include <cinttypes>
#include <sys/socket.h>
#include <utils/threads.h>
@@ -69,17 +70,16 @@
}
bool SensorService::SensorEventConnection::needsWakeLock() {
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
return !mDead && mWakeLockRefCount > 0;
}
void SensorService::SensorEventConnection::resetWakeLockRefCount() {
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
mWakeLockRefCount = 0;
}
void SensorService::SensorEventConnection::dump(String8& result) {
- Mutex::Autolock _l(mConnectionLock);
result.appendFormat("\tOperating Mode: ");
if (!mService->isWhiteListedPackage(getPackageName())) {
result.append("RESTRICTED\n");
@@ -91,11 +91,13 @@
result.appendFormat("\t %s | WakeLockRefCount %d | uid %d | cache size %d | "
"max cache size %d\n", mPackageName.string(), mWakeLockRefCount, mUid, mCacheSize,
mMaxCacheSize);
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
+
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ for (auto& it : mSensorInfo) {
+ const FlushInfo& flushInfo = it.second.flushInfo;
result.appendFormat("\t %s 0x%08x | status: %s | pending flush events %d \n",
- mService->getSensorName(mSensorInfo.keyAt(i)).string(),
- mSensorInfo.keyAt(i),
+ mService->getSensorName(it.first).string(),
+ it.first,
flushInfo.mFirstFlushPending ? "First flush pending" :
"active",
flushInfo.mPendingFlushEventsToSend);
@@ -121,7 +123,7 @@
*/
void SensorService::SensorEventConnection::dump(util::ProtoOutputStream* proto) const {
using namespace service::SensorEventConnectionProto;
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
if (!mService->isWhiteListedPackage(getPackageName())) {
proto->write(OPERATING_MODE, OP_MODE_RESTRICTED);
@@ -135,12 +137,12 @@
proto->write(UID, int32_t(mUid));
proto->write(CACHE_SIZE, int32_t(mCacheSize));
proto->write(MAX_CACHE_SIZE, int32_t(mMaxCacheSize));
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- const FlushInfo& flushInfo = mSensorInfo.valueAt(i);
+ for (auto& it : mSensorInfo) {
+ const FlushInfo& flushInfo = it.second.flushInfo;
const uint64_t token = proto->start(FLUSH_INFOS);
proto->write(FlushInfoProto::SENSOR_NAME,
- std::string(mService->getSensorName(mSensorInfo.keyAt(i))));
- proto->write(FlushInfoProto::SENSOR_HANDLE, mSensorInfo.keyAt(i));
+ std::string(mService->getSensorName(it.first)));
+ proto->write(FlushInfoProto::SENSOR_HANDLE, it.first);
proto->write(FlushInfoProto::FIRST_FLUSH_PENDING, flushInfo.mFirstFlushPending);
proto->write(FlushInfoProto::PENDING_FLUSH_EVENTS_TO_SEND,
flushInfo.mPendingFlushEventsToSend);
@@ -157,40 +159,56 @@
#endif
}
-bool SensorService::SensorEventConnection::addSensor(int32_t handle) {
- Mutex::Autolock _l(mConnectionLock);
+bool SensorService::SensorEventConnection::addSensor(
+ int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags) {
+ std::lock_guard<std::mutex> _l(mConnectionLock);
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
if (si == nullptr ||
!canAccessSensor(si->getSensor(), "Tried adding", mOpPackageName) ||
- mSensorInfo.indexOfKey(handle) >= 0) {
+ mSensorInfo.count(handle) > 0) {
return false;
}
- mSensorInfo.add(handle, FlushInfo());
+
+ SensorRequest request = {
+ .samplingPeriodNs = samplingPeriodNs,
+ .maxBatchReportLatencyNs = maxBatchReportLatencyNs,
+ .reservedFlags = reservedFlags
+ };
+
+ mSensorInfo[handle] = request;
return true;
}
bool SensorService::SensorEventConnection::removeSensor(int32_t handle) {
- Mutex::Autolock _l(mConnectionLock);
- if (mSensorInfo.removeItem(handle) >= 0) {
- return true;
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ return mSensorInfo.erase(handle) > 0;
+}
+
+std::vector<int32_t> SensorService::SensorEventConnection::getActiveSensorHandles() const {
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ std::vector<int32_t> list;
+ for (auto& it : mSensorInfo) {
+ list.push_back(it.first);
}
- return false;
+ return list;
}
bool SensorService::SensorEventConnection::hasSensor(int32_t handle) const {
- Mutex::Autolock _l(mConnectionLock);
- return mSensorInfo.indexOfKey(handle) >= 0;
+ std::lock_guard<std::recursive_mutex> _backlock(mBackupLock);
+ std::lock_guard<std::mutex> _lock(mConnectionLock);
+ return mSensorInfo.count(handle) + mSensorInfoBackup.count(handle) > 0;
}
bool SensorService::SensorEventConnection::hasAnySensor() const {
- Mutex::Autolock _l(mConnectionLock);
- return mSensorInfo.size() ? true : false;
+ std::lock_guard<std::recursive_mutex> _backlock(mBackupLock);
+ std::lock_guard<std::mutex> _lock(mConnectionLock);
+ return mSensorInfo.size() + mSensorInfoBackup.size() ? true : false;
}
bool SensorService::SensorEventConnection::hasOneShotSensors() const {
- Mutex::Autolock _l(mConnectionLock);
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- const int handle = mSensorInfo.keyAt(i);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ for (auto &it : mSensorInfo) {
+ const int handle = it.first;
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
if (si != nullptr && si->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
return true;
@@ -205,16 +223,15 @@
void SensorService::SensorEventConnection::setFirstFlushPending(int32_t handle,
bool value) {
- Mutex::Autolock _l(mConnectionLock);
- ssize_t index = mSensorInfo.indexOfKey(handle);
- if (index >= 0) {
- FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ if (mSensorInfo.count(handle) > 0) {
+ FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
flushInfo.mFirstFlushPending = value;
}
}
void SensorService::SensorEventConnection::updateLooperRegistration(const sp<Looper>& looper) {
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
updateLooperRegistrationLocked(looper);
}
@@ -233,8 +250,8 @@
int looper_flags = 0;
if (mCacheSize > 0) looper_flags |= ALOOPER_EVENT_OUTPUT;
if (mDataInjectionMode) looper_flags |= ALOOPER_EVENT_INPUT;
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- const int handle = mSensorInfo.keyAt(i);
+ for (auto& it : mSensorInfo) {
+ const int handle = it.first;
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
if (si != nullptr && si->getSensor().isWakeUpSensor()) {
looper_flags |= ALOOPER_EVENT_INPUT;
@@ -265,10 +282,9 @@
}
void SensorService::SensorEventConnection::incrementPendingFlushCount(int32_t handle) {
- Mutex::Autolock _l(mConnectionLock);
- ssize_t index = mSensorInfo.indexOfKey(handle);
- if (index >= 0) {
- FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ if (mSensorInfo.count(handle) > 0) {
+ FlushInfo& flushInfo = mSensorInfo[handle].flushInfo;
flushInfo.mPendingFlushEventsToSend++;
}
}
@@ -282,7 +298,7 @@
std::unique_ptr<sensors_event_t[]> sanitizedBuffer;
int count = 0;
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
if (scratch) {
size_t i=0;
while (i<numEvents) {
@@ -296,15 +312,14 @@
sensor_handle = buffer[i].meta_data.sensor;
}
- ssize_t index = mSensorInfo.indexOfKey(sensor_handle);
// Check if this connection has registered for this sensor. If not continue to the
// next sensor_event.
- if (index < 0) {
+ if (mSensorInfo.count(sensor_handle) == 0) {
++i;
continue;
}
- FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
+ FlushInfo& flushInfo = mSensorInfo[sensor_handle].flushInfo;
// Check if there is a pending flush_complete event for this sensor on this connection.
if (buffer[i].type == SENSOR_TYPE_META_DATA && flushInfo.mFirstFlushPending == true &&
mapFlushEventsToConnections[i] == this) {
@@ -425,9 +440,62 @@
return size < 0 ? status_t(size) : status_t(NO_ERROR);
}
+void SensorService::SensorEventConnection::updateSensorSubscriptions() {
+ if (!hasSensorAccess()) {
+ stopAll();
+ } else {
+ recoverAll();
+ }
+}
+
void SensorService::SensorEventConnection::setSensorAccess(const bool hasAccess) {
- Mutex::Autolock _l(mConnectionLock);
- mHasSensorAccess = hasAccess;
+ if (mHasSensorAccess != hasAccess) {
+ mHasSensorAccess = hasAccess;
+ updateSensorSubscriptions();
+ }
+}
+
+void SensorService::SensorEventConnection::stopAll() {
+ bool backupPerformed = false;
+ std::lock_guard<std::recursive_mutex> _backlock(mBackupLock);
+ {
+ std::lock_guard<std::mutex> _lock(mConnectionLock);
+ if (!mSensorInfo.empty()) {
+ mSensorInfoBackup = mSensorInfo;
+ mSensorInfo.clear();
+ backupPerformed = true;
+ }
+ }
+
+ if (backupPerformed) {
+ for (auto& it : mSensorInfoBackup) {
+ int32_t handle = it.first;
+
+ status_t err = mService->disable(this, handle);
+
+ if (err != NO_ERROR) {
+ ALOGE("Error disabling sensor %d", handle);
+ }
+ }
+ }
+}
+
+void SensorService::SensorEventConnection::recoverAll() {
+ std::lock_guard<std::recursive_mutex> _l(mBackupLock);
+ for (auto& it : mSensorInfoBackup) {
+ int32_t handle = it.first;
+ SensorRequest &request = it.second;
+
+ status_t err = mService->enable(
+ this, handle, request.samplingPeriodNs, request.maxBatchReportLatencyNs,
+ request.reservedFlags, mOpPackageName);
+
+ if (err != NO_ERROR) {
+ ALOGE("Error recovering sensor %d", handle);
+ }
+ }
+
+ mSensorInfoBackup.clear();
}
bool SensorService::SensorEventConnection::hasSensorAccess() {
@@ -522,14 +590,14 @@
flushCompleteEvent.type = SENSOR_TYPE_META_DATA;
// Loop through all the sensors for this connection and check if there are any pending
// flush complete events to be sent.
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- const int handle = mSensorInfo.keyAt(i);
+ for (auto& it : mSensorInfo) {
+ const int handle = it.first;
sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(handle);
if (si == nullptr) {
continue;
}
- FlushInfo& flushInfo = mSensorInfo.editValueAt(i);
+ FlushInfo& flushInfo = it.second.flushInfo;
while (flushInfo.mPendingFlushEventsToSend > 0) {
flushCompleteEvent.meta_data.sensor = handle;
bool wakeUpSensor = si->getSensor().isWakeUpSensor();
@@ -554,7 +622,7 @@
// half the size of the socket buffer allocated in BitTube whichever is smaller.
const int maxWriteSize = helpers::min(SensorEventQueue::MAX_RECEIVE_BUFFER_EVENT_COUNT/2,
int(mService->mSocketBufferSize/(sizeof(sensors_event_t)*2)));
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
// Send pending flush complete events (if any)
sendPendingFlushEventsLocked();
for (int numEventsSent = 0; numEventsSent < mCacheSize;) {
@@ -615,14 +683,13 @@
// separately before the next batch of events.
for (int j = 0; j < numEventsDropped; ++j) {
if (scratch[j].type == SENSOR_TYPE_META_DATA) {
- ssize_t index = mSensorInfo.indexOfKey(scratch[j].meta_data.sensor);
- if (index < 0) {
+ if (mSensorInfo.count(scratch[j].meta_data.sensor) == 0) {
ALOGW("%s: sensor 0x%x is not found in connection",
__func__, scratch[j].meta_data.sensor);
continue;
}
- FlushInfo& flushInfo = mSensorInfo.editValueAt(index);
+ FlushInfo& flushInfo = mSensorInfo[scratch[j].meta_data.sensor].flushInfo;
flushInfo.mPendingFlushEventsToSend++;
ALOGD_IF(DEBUG_CONNECTIONS, "increment pendingFlushCount %d",
flushInfo.mPendingFlushEventsToSend);
@@ -658,13 +725,21 @@
} else {
err = mService->disable(this, handle);
}
+
return err;
}
status_t SensorService::SensorEventConnection::setEventRate(
int handle, nsecs_t samplingPeriodNs)
{
- return mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
+ status_t err = mService->setEventRate(this, handle, samplingPeriodNs, mOpPackageName);
+
+ std::lock_guard<std::mutex> _l(mConnectionLock);
+ if (err == NO_ERROR && mSensorInfo.count(handle) > 0) {
+ mSensorInfo[handle].samplingPeriodNs = samplingPeriodNs;
+ }
+
+ return err;
}
status_t SensorService::SensorEventConnection::flush() {
@@ -685,7 +760,7 @@
// and remove the fd from Looper. Call checkWakeLockState to know if SensorService
// can release the wake-lock.
ALOGD_IF(DEBUG_CONNECTIONS, "%p Looper error %d", this, fd);
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
mDead = true;
mWakeLockRefCount = 0;
updateLooperRegistrationLocked(mService->getLooper());
@@ -704,7 +779,7 @@
unsigned char buf[sizeof(sensors_event_t)];
ssize_t numBytesRead = ::recv(fd, buf, sizeof(buf), MSG_DONTWAIT);
{
- Mutex::Autolock _l(mConnectionLock);
+ std::lock_guard<std::mutex> _l(mConnectionLock);
if (numBytesRead == sizeof(sensors_event_t)) {
if (!mDataInjectionMode) {
ALOGE("Data injected in normal mode, dropping event"
@@ -764,8 +839,8 @@
int SensorService::SensorEventConnection::computeMaxCacheSizeLocked() const {
size_t fifoWakeUpSensors = 0;
size_t fifoNonWakeUpSensors = 0;
- for (size_t i = 0; i < mSensorInfo.size(); ++i) {
- sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(mSensorInfo.keyAt(i));
+ for (auto& it : mSensorInfo) {
+ sp<SensorInterface> si = mService->getSensorInterfaceFromHandle(it.first);
if (si == nullptr) {
continue;
}
diff --git a/services/sensorservice/SensorEventConnection.h b/services/sensorservice/SensorEventConnection.h
index caf5d7c..80e7431 100644
--- a/services/sensorservice/SensorEventConnection.h
+++ b/services/sensorservice/SensorEventConnection.h
@@ -23,7 +23,6 @@
#include <utils/Vector.h>
#include <utils/SortedVector.h>
-#include <utils/KeyedVector.h>
#include <utils/threads.h>
#include <utils/AndroidThreads.h>
#include <utils/RefBase.h>
@@ -58,8 +57,10 @@
bool hasSensor(int32_t handle) const;
bool hasAnySensor() const;
bool hasOneShotSensors() const;
- bool addSensor(int32_t handle);
+ bool addSensor(
+ int32_t handle, nsecs_t samplingPeriodNs, nsecs_t maxBatchReportLatencyNs, int reservedFlags);
bool removeSensor(int32_t handle);
+ std::vector<int32_t> getActiveSensorHandles() const;
void setFirstFlushPending(int32_t handle, bool value);
void dump(String8& result);
void dump(util::ProtoOutputStream* proto) const;
@@ -70,7 +71,7 @@
uid_t getUid() const { return mUid; }
void setSensorAccess(const bool hasAccess);
-
+ void updateSensorSubscriptions();
private:
virtual ~SensorEventConnection();
virtual void onFirstRef();
@@ -136,13 +137,22 @@
// privacy not being enabled.
bool hasSensorAccess();
+ void stopAll();
+ void recoverAll();
+
// Call noteOp for the sensor if the sensor requires a permission
bool noteOpIfRequired(const sensors_event_t& event);
sp<SensorService> const mService;
sp<BitTube> mChannel;
uid_t mUid;
- mutable Mutex mConnectionLock;
+
+ // A lock that should be used when modifying mSensorInfo
+ mutable std::mutex mConnectionLock;
+
+ // A lock that should be used when modifying mSensorInfoBackup
+ mutable std::recursive_mutex mBackupLock;
+
// Number of events from wake up sensors which are still pending and haven't been delivered to
// the corresponding application. It is incremented by one unit for each write to the socket.
uint32_t mWakeLockRefCount;
@@ -169,8 +179,17 @@
FlushInfo() : mPendingFlushEventsToSend(0), mFirstFlushPending(false) {}
};
- // protected by SensorService::mLock. Key for this vector is the sensor handle.
- KeyedVector<int, FlushInfo> mSensorInfo;
+
+ struct SensorRequest {
+ nsecs_t samplingPeriodNs;
+ nsecs_t maxBatchReportLatencyNs;
+ int reservedFlags;
+ FlushInfo flushInfo;
+ };
+
+ // protected by SensorService::mLock. Key for this map is the sensor handle.
+ std::unordered_map<int32_t, SensorRequest> mSensorInfo;
+ std::unordered_map<int32_t, SensorRequest> mSensorInfoBackup;
sensors_event_t *mEventCache;
int mCacheSize, mMaxCacheSize;
@@ -185,7 +204,7 @@
mutable Mutex mDestroyLock;
bool mDestroyed;
- bool mHasSensorAccess;
+ std::atomic_bool mHasSensorAccess;
// Store a mapping of sensor handles to required AppOp for a sensor. This map only contains a
// valid mapping for sensors that require a permission in order to reduce the lookup time.
diff --git a/services/sensorservice/SensorService.cpp b/services/sensorservice/SensorService.cpp
index 22a15c6..29df825 100644
--- a/services/sensorservice/SensorService.cpp
+++ b/services/sensorservice/SensorService.cpp
@@ -301,11 +301,24 @@
void SensorService::setSensorAccess(uid_t uid, bool hasAccess) {
ConnectionSafeAutolock connLock = mConnectionHolder.lock(mLock);
- for (const sp<SensorEventConnection>& conn : connLock.getActiveConnections()) {
+ const auto& connections = connLock.getActiveConnections();
+ const auto& directConnections = connLock.getDirectConnections();
+
+ mLock.unlock();
+ for (const sp<SensorEventConnection>& conn : connections) {
if (conn->getUid() == uid) {
conn->setSensorAccess(hasAccess);
}
}
+
+ for (const sp<SensorDirectConnection>& conn : directConnections) {
+ if (conn->getUid() == uid) {
+ conn->setSensorAccess(hasAccess);
+ }
+ }
+
+ // Lock the mutex again for clean shutdown
+ mLock.lock();
}
const Sensor& SensorService::registerSensor(SensorInterface* s, bool isDebug, bool isVirtual) {
@@ -638,8 +651,11 @@
void SensorService::disableAllSensorsLocked(ConnectionSafeAutolock* connLock) {
SensorDevice& dev(SensorDevice::getInstance());
+ for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
+ connection->updateSensorSubscriptions();
+ }
for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
- connection->stopAll(true /* backupRecord */);
+ connection->updateSensorSubscriptions();
}
dev.disableAllSensors();
// Clear all pending flush connections for all active sensors. If one of the active
@@ -666,8 +682,11 @@
}
SensorDevice& dev(SensorDevice::getInstance());
dev.enableAllSensors();
+ for (const sp<SensorEventConnection>& connection : connLock->getActiveConnections()) {
+ connection->updateSensorSubscriptions();
+ }
for (const sp<SensorDirectConnection>& connection : connLock->getDirectConnections()) {
- connection->recoverAll();
+ connection->updateSensorSubscriptions();
}
}
@@ -1589,7 +1608,7 @@
}
}
- if (connection->addSensor(handle)) {
+ if (connection->addSensor(handle, samplingPeriodNs, maxBatchReportLatencyNs, reservedFlags)) {
BatteryService::enableSensor(connection->getUid(), handle);
// the sensor was added (which means it wasn't already there)
// so, see if this connection becomes active
@@ -1739,18 +1758,22 @@
const int halVersion = dev.getHalDeviceVersion();
status_t err(NO_ERROR);
Mutex::Autolock _l(mLock);
+
+ size_t numSensors = 0;
// Loop through all sensors for this connection and call flush on each of them.
- for (size_t i = 0; i < connection->mSensorInfo.size(); ++i) {
- const int handle = connection->mSensorInfo.keyAt(i);
+ for (int handle : connection->getActiveSensorHandles()) {
sp<SensorInterface> sensor = getSensorInterfaceFromHandle(handle);
if (sensor == nullptr) {
continue;
}
+ numSensors++;
+
if (sensor->getSensor().getReportingMode() == AREPORTING_MODE_ONE_SHOT) {
ALOGE("flush called on a one-shot sensor");
err = INVALID_OPERATION;
continue;
}
+
if (halVersion <= SENSORS_DEVICE_API_VERSION_1_0 || isVirtualSensor(handle)) {
// For older devices just increment pending flush count which will send a trivial
// flush complete event.
@@ -1768,7 +1791,8 @@
err = (err_flush != NO_ERROR) ? err_flush : err;
}
}
- return err;
+
+ return (numSensors == 0) ? INVALID_OPERATION : err;
}
bool SensorService::canAccessSensor(const Sensor& sensor, const char* operation,
diff --git a/services/surfaceflinger/DisplayHardware/DisplayIdentification.cpp b/services/surfaceflinger/DisplayHardware/DisplayIdentification.cpp
index f24f314..b6d904f 100644
--- a/services/surfaceflinger/DisplayHardware/DisplayIdentification.cpp
+++ b/services/surfaceflinger/DisplayHardware/DisplayIdentification.cpp
@@ -35,6 +35,7 @@
using byte_view = std::basic_string_view<uint8_t>;
+constexpr size_t kEdidBlockSize = 128;
constexpr size_t kEdidHeaderLength = 5;
constexpr uint16_t kFallbackEdidManufacturerId = 0;
@@ -98,6 +99,57 @@
return info;
}
+Cea861ExtensionBlock parseCea861Block(const byte_view& block) {
+ Cea861ExtensionBlock cea861Block;
+
+ constexpr size_t kRevisionNumberOffset = 1;
+ cea861Block.revisionNumber = block[kRevisionNumberOffset];
+
+ constexpr size_t kDetailedTimingDescriptorsOffset = 2;
+ const size_t dtdStart =
+ std::min(kEdidBlockSize, static_cast<size_t>(block[kDetailedTimingDescriptorsOffset]));
+
+ // Parse data blocks.
+ for (size_t dataBlockOffset = 4; dataBlockOffset < dtdStart;) {
+ const uint8_t header = block[dataBlockOffset];
+ const uint8_t tag = header >> 5;
+ const size_t bodyLength = header & 0b11111;
+ constexpr size_t kDataBlockHeaderSize = 1;
+ const size_t dataBlockSize = bodyLength + kDataBlockHeaderSize;
+
+ if (block.size() < dataBlockOffset + dataBlockSize) {
+ ALOGW("Invalid EDID: CEA 861 data block is truncated.");
+ break;
+ }
+
+ const byte_view dataBlock(block.data() + dataBlockOffset, dataBlockSize);
+ constexpr uint8_t kVendorSpecificDataBlockTag = 0x3;
+
+ if (tag == kVendorSpecificDataBlockTag) {
+ const uint32_t ieeeRegistrationId =
+ dataBlock[1] | (dataBlock[2] << 8) | (dataBlock[3] << 16);
+ constexpr uint32_t kHdmiIeeeRegistrationId = 0xc03;
+
+ if (ieeeRegistrationId == kHdmiIeeeRegistrationId) {
+ const uint8_t a = dataBlock[4] >> 4;
+ const uint8_t b = dataBlock[4] & 0b1111;
+ const uint8_t c = dataBlock[5] >> 4;
+ const uint8_t d = dataBlock[5] & 0b1111;
+ cea861Block.hdmiVendorDataBlock =
+ HdmiVendorDataBlock{.physicalAddress = HdmiPhysicalAddress{a, b, c, d}};
+ } else {
+ ALOGV("Ignoring vendor specific data block for vendor with IEEE OUI %x",
+ ieeeRegistrationId);
+ }
+ } else {
+ ALOGV("Ignoring CEA-861 data block with tag %x", tag);
+ }
+ dataBlockOffset += bodyLength + kDataBlockHeaderSize;
+ }
+
+ return cea861Block;
+}
+
} // namespace
uint16_t DisplayId::manufacturerId() const {
@@ -115,13 +167,12 @@
}
std::optional<Edid> parseEdid(const DisplayIdentificationData& edid) {
- constexpr size_t kMinLength = 128;
- if (edid.size() < kMinLength) {
+ if (edid.size() < kEdidBlockSize) {
ALOGW("Invalid EDID: structure is truncated.");
// Attempt parsing even if EDID is malformed.
} else {
- ALOGW_IF(edid[126] != 0, "EDID extensions are currently unsupported.");
- ALOGW_IF(std::accumulate(edid.begin(), edid.begin() + kMinLength, static_cast<uint8_t>(0)),
+ ALOGW_IF(std::accumulate(edid.begin(), edid.begin() + kEdidBlockSize,
+ static_cast<uint8_t>(0)),
"Invalid EDID: structure does not checksum.");
}
@@ -227,13 +278,43 @@
// have been observed to change on some displays with multiple inputs.
const auto modelHash = static_cast<uint32_t>(std::hash<std::string_view>()(modelString));
+ // Parse extension blocks.
+ std::optional<Cea861ExtensionBlock> cea861Block;
+ if (edid.size() < kEdidBlockSize) {
+ ALOGW("Invalid EDID: block 0 is truncated.");
+ } else {
+ constexpr size_t kNumExtensionsOffset = 126;
+ const size_t numExtensions = edid[kNumExtensionsOffset];
+ view = byte_view(edid.data(), edid.size());
+ for (size_t blockNumber = 1; blockNumber <= numExtensions; blockNumber++) {
+ view.remove_prefix(kEdidBlockSize);
+ if (view.size() < kEdidBlockSize) {
+ ALOGW("Invalid EDID: block %zu is truncated.", blockNumber);
+ break;
+ }
+
+ const byte_view block(view.data(), kEdidBlockSize);
+ ALOGW_IF(std::accumulate(block.begin(), block.end(), static_cast<uint8_t>(0)),
+ "Invalid EDID: block %zu does not checksum.", blockNumber);
+ const uint8_t tag = block[0];
+
+ constexpr uint8_t kCea861BlockTag = 0x2;
+ if (tag == kCea861BlockTag) {
+ cea861Block = parseCea861Block(block);
+ } else {
+ ALOGV("Ignoring block number %zu with tag %x.", blockNumber, tag);
+ }
+ }
+ }
+
return Edid{.manufacturerId = manufacturerId,
.productId = productId,
.pnpId = *pnpId,
.modelHash = modelHash,
.displayName = displayName,
+ .manufactureOrModelYear = manufactureOrModelYear,
.manufactureWeek = manufactureWeek,
- .manufactureOrModelYear = manufactureOrModelYear};
+ .cea861Block = cea861Block};
}
std::optional<PnpId> getPnpId(uint16_t manufacturerId) {
diff --git a/services/surfaceflinger/DisplayHardware/DisplayIdentification.h b/services/surfaceflinger/DisplayHardware/DisplayIdentification.h
index d91b957..fc2f72e 100644
--- a/services/surfaceflinger/DisplayHardware/DisplayIdentification.h
+++ b/services/surfaceflinger/DisplayHardware/DisplayIdentification.h
@@ -57,6 +57,26 @@
std::optional<DeviceProductInfo> deviceProductInfo;
};
+struct ExtensionBlock {
+ uint8_t tag;
+ uint8_t revisionNumber;
+};
+
+struct HdmiPhysicalAddress {
+ // The address describes the path from the display sink in the network of connected HDMI
+ // devices. The format of the address is "a.b.c.d". For example, address 2.1.0.0 means we are
+ // connected to port 1 of a device which is connected to port 2 of the sink.
+ uint8_t a, b, c, d;
+};
+
+struct HdmiVendorDataBlock {
+ std::optional<HdmiPhysicalAddress> physicalAddress;
+};
+
+struct Cea861ExtensionBlock : ExtensionBlock {
+ std::optional<HdmiVendorDataBlock> hdmiVendorDataBlock;
+};
+
struct Edid {
uint16_t manufacturerId;
uint16_t productId;
@@ -65,6 +85,7 @@
std::string_view displayName;
uint8_t manufactureOrModelYear;
uint8_t manufactureWeek;
+ std::optional<Cea861ExtensionBlock> cea861Block;
};
bool isEdid(const DisplayIdentificationData&);
diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp
index 3d67a6b..5039761 100644
--- a/services/surfaceflinger/Layer.cpp
+++ b/services/surfaceflinger/Layer.cpp
@@ -2134,10 +2134,12 @@
writeToProtoDrawingState(layerProto, traceFlags);
writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
- // Only populate for the primary display.
- if (device) {
- const Hwc2::IComposerClient::Composition compositionType = getCompositionType(device);
- layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
+ if (traceFlags & SurfaceTracing::TRACE_COMPOSITION) {
+ // Only populate for the primary display.
+ if (device) {
+ const Hwc2::IComposerClient::Composition compositionType = getCompositionType(device);
+ layerProto->set_hwc_composition_type(static_cast<HwcCompositionType>(compositionType));
+ }
}
for (const sp<Layer>& layer : mDrawingChildren) {
@@ -2180,8 +2182,10 @@
LayerProtoHelper::writePositionToProto(transform.tx(), transform.ty(),
[&]() { return layerInfo->mutable_position(); });
LayerProtoHelper::writeToProto(mBounds, [&]() { return layerInfo->mutable_bounds(); });
- LayerProtoHelper::writeToProto(debugGetVisibleRegionOnDefaultDisplay(),
- [&]() { return layerInfo->mutable_visible_region(); });
+ if (traceFlags & SurfaceTracing::TRACE_COMPOSITION) {
+ LayerProtoHelper::writeToProto(debugGetVisibleRegionOnDefaultDisplay(),
+ [&]() { return layerInfo->mutable_visible_region(); });
+ }
LayerProtoHelper::writeToProto(surfaceDamageRegion,
[&]() { return layerInfo->mutable_damage_region(); });
@@ -2191,15 +2195,13 @@
}
}
- if (traceFlags & SurfaceTracing::TRACE_EXTRA) {
- LayerProtoHelper::writeToProto(mSourceBounds,
- [&]() { return layerInfo->mutable_source_bounds(); });
- LayerProtoHelper::writeToProto(mScreenBounds,
- [&]() { return layerInfo->mutable_screen_bounds(); });
- LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
- [&]() { return layerInfo->mutable_corner_radius_crop(); });
- layerInfo->set_shadow_radius(mEffectiveShadowRadius);
- }
+ LayerProtoHelper::writeToProto(mSourceBounds,
+ [&]() { return layerInfo->mutable_source_bounds(); });
+ LayerProtoHelper::writeToProto(mScreenBounds,
+ [&]() { return layerInfo->mutable_screen_bounds(); });
+ LayerProtoHelper::writeToProto(getRoundedCornerState().cropRect,
+ [&]() { return layerInfo->mutable_corner_radius_crop(); });
+ layerInfo->set_shadow_radius(mEffectiveShadowRadius);
}
void Layer::writeToProtoCommonState(LayerProto* layerInfo, LayerVector::StateSet stateSet,
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
index 02d0b53..14ef733 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.cpp
@@ -301,7 +301,7 @@
mCurrentRefreshRate) != mAvailableRefreshRates.end()) {
return *mCurrentRefreshRate;
}
- return *mRefreshRates.at(mDefaultConfig);
+ return *mRefreshRates.at(getCurrentPolicyLocked()->defaultConfig);
}
void RefreshRateConfigs::setCurrentConfigId(HwcConfigIndexType configId) {
@@ -326,38 +326,59 @@
init(inputConfigs, currentConfigId);
}
-status_t RefreshRateConfigs::setPolicy(HwcConfigIndexType defaultConfigId, float minRefreshRate,
- float maxRefreshRate, bool* outPolicyChanged) {
+bool RefreshRateConfigs::isPolicyValid(const Policy& policy) {
+ // defaultConfig must be a valid config, and within the given refresh rate range.
+ auto iter = mRefreshRates.find(policy.defaultConfig);
+ if (iter == mRefreshRates.end()) {
+ return false;
+ }
+ const RefreshRate& refreshRate = *iter->second;
+ if (!refreshRate.inPolicy(policy.minRefreshRate, policy.maxRefreshRate)) {
+ return false;
+ }
+ return true;
+}
+
+status_t RefreshRateConfigs::setDisplayManagerPolicy(const Policy& policy) {
std::lock_guard lock(mLock);
- bool policyChanged = defaultConfigId != mDefaultConfig ||
- minRefreshRate != mMinRefreshRateFps || maxRefreshRate != mMaxRefreshRateFps;
- if (outPolicyChanged) {
- *outPolicyChanged = policyChanged;
- }
- if (!policyChanged) {
- return NO_ERROR;
- }
- // defaultConfigId must be a valid config ID, and within the given refresh rate range.
- if (mRefreshRates.count(defaultConfigId) == 0) {
+ if (!isPolicyValid(policy)) {
return BAD_VALUE;
}
- const RefreshRate& refreshRate = *mRefreshRates.at(defaultConfigId);
- if (!refreshRate.inPolicy(minRefreshRate, maxRefreshRate)) {
- return BAD_VALUE;
+ Policy previousPolicy = *getCurrentPolicyLocked();
+ mDisplayManagerPolicy = policy;
+ if (*getCurrentPolicyLocked() == previousPolicy) {
+ return CURRENT_POLICY_UNCHANGED;
}
- mDefaultConfig = defaultConfigId;
- mMinRefreshRateFps = minRefreshRate;
- mMaxRefreshRateFps = maxRefreshRate;
constructAvailableRefreshRates();
return NO_ERROR;
}
-void RefreshRateConfigs::getPolicy(HwcConfigIndexType* defaultConfigId, float* minRefreshRate,
- float* maxRefreshRate) const {
+status_t RefreshRateConfigs::setOverridePolicy(const std::optional<Policy>& policy) {
std::lock_guard lock(mLock);
- *defaultConfigId = mDefaultConfig;
- *minRefreshRate = mMinRefreshRateFps;
- *maxRefreshRate = mMaxRefreshRateFps;
+ if (policy && !isPolicyValid(*policy)) {
+ return BAD_VALUE;
+ }
+ Policy previousPolicy = *getCurrentPolicyLocked();
+ mOverridePolicy = policy;
+ if (*getCurrentPolicyLocked() == previousPolicy) {
+ return CURRENT_POLICY_UNCHANGED;
+ }
+ constructAvailableRefreshRates();
+ return NO_ERROR;
+}
+
+const RefreshRateConfigs::Policy* RefreshRateConfigs::getCurrentPolicyLocked() const {
+ return mOverridePolicy ? &mOverridePolicy.value() : &mDisplayManagerPolicy;
+}
+
+RefreshRateConfigs::Policy RefreshRateConfigs::getCurrentPolicy() const {
+ std::lock_guard lock(mLock);
+ return *getCurrentPolicyLocked();
+}
+
+RefreshRateConfigs::Policy RefreshRateConfigs::getDisplayManagerPolicy() const {
+ std::lock_guard lock(mLock);
+ return mDisplayManagerPolicy;
}
bool RefreshRateConfigs::isConfigAllowed(HwcConfigIndexType config) const {
@@ -385,19 +406,25 @@
std::sort(outRefreshRates->begin(), outRefreshRates->end(),
[](const auto refreshRate1, const auto refreshRate2) {
- return refreshRate1->vsyncPeriod > refreshRate2->vsyncPeriod;
+ if (refreshRate1->vsyncPeriod != refreshRate2->vsyncPeriod) {
+ return refreshRate1->vsyncPeriod > refreshRate2->vsyncPeriod;
+ } else {
+ return refreshRate1->configGroup > refreshRate2->configGroup;
+ }
});
}
void RefreshRateConfigs::constructAvailableRefreshRates() {
// Filter configs based on current policy and sort based on vsync period
- HwcConfigGroupType group = mRefreshRates.at(mDefaultConfig)->configGroup;
+ const Policy* policy = getCurrentPolicyLocked();
+ HwcConfigGroupType group = mRefreshRates.at(policy->defaultConfig)->configGroup;
ALOGV("constructAvailableRefreshRates: default %d group %d min %.2f max %.2f",
- mDefaultConfig.value(), group.value(), mMinRefreshRateFps, mMaxRefreshRateFps);
+ policy->defaultConfig.value(), group.value(), policy->minRefreshRate,
+ policy->maxRefreshRate);
getSortedRefreshRateList(
[&](const RefreshRate& refreshRate) REQUIRES(mLock) {
- return refreshRate.configGroup == group &&
- refreshRate.inPolicy(mMinRefreshRateFps, mMaxRefreshRateFps);
+ return (policy->allowGroupSwitching || refreshRate.configGroup == group) &&
+ refreshRate.inPolicy(policy->minRefreshRate, policy->maxRefreshRate);
},
&mAvailableRefreshRates);
@@ -409,7 +436,8 @@
ALOGV("Available refresh rates: %s", availableRefreshRates.c_str());
LOG_ALWAYS_FATAL_IF(mAvailableRefreshRates.empty(),
"No compatible display configs for default=%d min=%.0f max=%.0f",
- mDefaultConfig.value(), mMinRefreshRateFps, mMaxRefreshRateFps);
+ policy->defaultConfig.value(), policy->minRefreshRate,
+ policy->maxRefreshRate);
}
// NO_THREAD_SAFETY_ANALYSIS since this is called from the constructor
@@ -432,7 +460,7 @@
std::vector<const RefreshRate*> sortedConfigs;
getSortedRefreshRateList([](const RefreshRate&) { return true; }, &sortedConfigs);
- mDefaultConfig = currentHwcConfig;
+ mDisplayManagerPolicy.defaultConfig = currentHwcConfig;
mMinSupportedRefreshRate = sortedConfigs.front();
mMaxSupportedRefreshRate = sortedConfigs.back();
constructAvailableRefreshRates();
diff --git a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
index 87d4389..e749f8f 100644
--- a/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
+++ b/services/surfaceflinger/Scheduler/RefreshRateConfigs.h
@@ -20,6 +20,7 @@
#include <algorithm>
#include <numeric>
+#include <optional>
#include <type_traits>
#include "DisplayHardware/HWComposer.h"
@@ -90,14 +91,47 @@
using AllRefreshRatesMapType =
std::unordered_map<HwcConfigIndexType, std::unique_ptr<const RefreshRate>>;
- // Sets the current policy to choose refresh rates. Returns NO_ERROR if the requested policy is
- // valid, or a negative error value otherwise. policyChanged, if non-null, will be set to true
- // if the new policy is different from the old policy.
- status_t setPolicy(HwcConfigIndexType defaultConfigId, float minRefreshRate,
- float maxRefreshRate, bool* policyChanged) EXCLUDES(mLock);
- // Gets the current policy.
- void getPolicy(HwcConfigIndexType* defaultConfigId, float* minRefreshRate,
- float* maxRefreshRate) const EXCLUDES(mLock);
+ struct Policy {
+ // The default config, used to ensure we only initiate display config switches within the
+ // same config group as defaultConfigId's group.
+ HwcConfigIndexType defaultConfig;
+ // The min and max FPS allowed by the policy.
+ float minRefreshRate = 0;
+ float maxRefreshRate = std::numeric_limits<float>::max();
+ // Whether or not we switch config groups to get the best frame rate. Only used by tests.
+ bool allowGroupSwitching = false;
+
+ bool operator==(const Policy& other) const {
+ return defaultConfig == other.defaultConfig && minRefreshRate == other.minRefreshRate &&
+ maxRefreshRate == other.maxRefreshRate &&
+ allowGroupSwitching == other.allowGroupSwitching;
+ }
+
+ bool operator!=(const Policy& other) const { return !(*this == other); }
+ };
+
+ // Return code set*Policy() to indicate the current policy is unchanged.
+ static constexpr int CURRENT_POLICY_UNCHANGED = 1;
+
+ // We maintain the display manager policy and the override policy separately. The override
+ // policy is used by CTS tests to get a consistent device state for testing. While the override
+ // policy is set, it takes precedence over the display manager policy. Once the override policy
+ // is cleared, we revert to using the display manager policy.
+
+ // Sets the display manager policy to choose refresh rates. The return value will be:
+ // - A negative value if the policy is invalid or another error occurred.
+ // - NO_ERROR if the policy was successfully updated, and the current policy is different from
+ // what it was before the call.
+ // - CURRENT_POLICY_UNCHANGED if the policy was successfully updated, but the current policy
+ // is the same as it was before the call.
+ status_t setDisplayManagerPolicy(const Policy& policy) EXCLUDES(mLock);
+ // Sets the override policy. See setDisplayManagerPolicy() for the meaning of the return value.
+ status_t setOverridePolicy(const std::optional<Policy>& policy) EXCLUDES(mLock);
+ // Gets the current policy, which will be the override policy if active, and the display manager
+ // policy otherwise.
+ Policy getCurrentPolicy() const EXCLUDES(mLock);
+ // Gets the display manager policy, regardless of whether an override policy is active.
+ Policy getDisplayManagerPolicy() const EXCLUDES(mLock);
// Returns true if config is allowed by the current policy.
bool isConfigAllowed(HwcConfigIndexType config) const EXCLUDES(mLock);
@@ -208,6 +242,9 @@
// the policy.
const RefreshRate& getCurrentRefreshRateByPolicyLocked() const REQUIRES(mLock);
+ const Policy* getCurrentPolicyLocked() const REQUIRES(mLock);
+ bool isPolicyValid(const Policy& policy);
+
// The list of refresh rates, indexed by display config ID. This must not change after this
// object is initialized.
AllRefreshRatesMapType mRefreshRates;
@@ -220,14 +257,10 @@
// the main thread, and read by the Scheduler (and other objects) on other threads.
const RefreshRate* mCurrentRefreshRate GUARDED_BY(mLock);
- // The default config. This will change at runtime. This is set by SurfaceFlinger on
- // the main thread, and read by the Scheduler (and other objects) on other threads.
- HwcConfigIndexType mDefaultConfig GUARDED_BY(mLock);
-
- // The min and max FPS allowed by the policy. This will change at runtime and set by
- // SurfaceFlinger on the main thread.
- float mMinRefreshRateFps GUARDED_BY(mLock) = 0;
- float mMaxRefreshRateFps GUARDED_BY(mLock) = std::numeric_limits<float>::max();
+ // The policy values will change at runtime. They're set by SurfaceFlinger on the main thread,
+ // and read by the Scheduler (and other objects) on other threads.
+ Policy mDisplayManagerPolicy GUARDED_BY(mLock);
+ std::optional<Policy> mOverridePolicy GUARDED_BY(mLock);
// The min and max refresh rates supported by the device.
// This will not change at runtime.
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index aa68726..e22bc61 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -200,6 +200,15 @@
return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
}
+class FrameRateFlexibilityToken : public BBinder {
+public:
+ FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
+ virtual ~FrameRateFlexibilityToken() { mCallback(); }
+
+private:
+ std::function<void()> mCallback;
+};
+
} // namespace anonymous
// ---------------------------------------------------------------------------
@@ -977,8 +986,11 @@
} else {
HwcConfigIndexType config(mode);
const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
- result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
- refreshRate.fps);
+ result = setDesiredDisplayConfigSpecsInternal(display,
+ scheduler::RefreshRateConfigs::
+ Policy{config, refreshRate.fps,
+ refreshRate.fps},
+ /*overridePolicy=*/false);
}
}));
@@ -993,6 +1005,9 @@
return;
}
+ auto& oldRefreshRate =
+ mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
+
std::lock_guard<std::mutex> lock(mActiveConfigLock);
mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
@@ -1000,6 +1015,9 @@
auto& refreshRate =
mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
+ if (refreshRate.vsyncPeriod != oldRefreshRate.vsyncPeriod) {
+ mTimeStats->incrementRefreshRateSwitches();
+ }
mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
@@ -1929,8 +1947,18 @@
// potentially trigger a display handoff.
updateVrFlinger();
- bool refreshNeeded = handleMessageTransaction();
- refreshNeeded |= handleMessageInvalidate();
+ bool refreshNeeded;
+ withTracingLock([&]() {
+ refreshNeeded = handleMessageTransaction();
+ refreshNeeded |= handleMessageInvalidate();
+ if (mTracingEnabled) {
+ mAddCompositionStateToTrace =
+ mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
+ if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
+ mTracing.notifyLocked("visibleRegionsDirty");
+ }
+ }
+ });
// Layers need to get updated (in the previous line) before we can use them for
// choosing the refresh rate.
@@ -2074,7 +2102,7 @@
mLayersWithQueuedFrames.clear();
if (mVisibleRegionsDirty) {
mVisibleRegionsDirty = false;
- if (mTracingEnabled) {
+ if (mTracingEnabled && mAddCompositionStateToTrace) {
mTracing.notify("visibleRegionsDirty");
}
}
@@ -2956,8 +2984,7 @@
void SurfaceFlinger::commitTransaction()
{
- withTracingLock([this]() { commitTransactionLocked(); });
-
+ commitTransactionLocked();
mTransactionPending = false;
mAnimTransactionPending = false;
mTransactionCV.broadcast();
@@ -3490,12 +3517,13 @@
return flags;
}
-bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
+bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
IPCThreadState* ipc = IPCThreadState::self();
const int pid = ipc->getCallingPid();
const int uid = ipc->getCallingUid();
if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
- !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
+ (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
+ : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
return false;
}
return true;
@@ -4367,13 +4395,11 @@
" present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
dispSyncPresentTimeOffset, getVsyncPeriod());
- HwcConfigIndexType defaultConfig;
- float minFps, maxFps;
- mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
+ scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
StringAppendF(&result,
"DesiredDisplayConfigSpecs: default config ID: %d"
", min: %.2f Hz, max: %.2f Hz",
- defaultConfig.value(), minFps, maxFps);
+ policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
StringAppendF(&result, "(config override by backdoor: %s)\n\n",
mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
@@ -4812,8 +4838,12 @@
case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
case GET_DISPLAYED_CONTENT_SAMPLE:
case NOTIFY_POWER_HINT:
- case SET_GLOBAL_SHADOW_SETTINGS: {
- if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
+ case SET_GLOBAL_SHADOW_SETTINGS:
+ case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
+ // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
+ // necessary permission dynamically. Don't use the permission cache for this check.
+ bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
+ if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
IPCThreadState* ipc = IPCThreadState::self();
ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
ipc->getCallingPid(), ipc->getCallingUid());
@@ -5910,12 +5940,15 @@
}
}
-status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
- HwcConfigIndexType defaultConfig,
- float minRefreshRate,
- float maxRefreshRate) {
+status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
+ const sp<DisplayDevice>& display,
+ const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Mutex::Autolock lock(mStateLock);
+ LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
+ "Can only set override policy on the primary display");
+ LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
+
if (!display->isPrimary()) {
// TODO(b/144711714): For non-primary displays we should be able to set an active config
// as well. For now, just call directly to setActiveConfigWithConstraints but ideally
@@ -5929,7 +5962,8 @@
constraints.seamlessRequired = false;
HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
- if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
+ if (getHwComposer().setActiveConfigWithConstraints(*displayId,
+ policy->defaultConfig.value(),
constraints, &timeline) < 0) {
return BAD_VALUE;
}
@@ -5937,11 +5971,12 @@
repaintEverythingForHWC();
}
- display->setActiveConfig(defaultConfig);
- const nsecs_t vsyncPeriod =
- getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
- mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
- vsyncPeriod);
+ display->setActiveConfig(policy->defaultConfig);
+ const nsecs_t vsyncPeriod = getHwComposer()
+ .getConfigs(*displayId)[policy->defaultConfig.value()]
+ ->getVsyncPeriod();
+ mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
+ policy->defaultConfig, vsyncPeriod);
return NO_ERROR;
}
@@ -5950,17 +5985,20 @@
return NO_ERROR;
}
- bool policyChanged;
- if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
- &policyChanged) < 0) {
+ status_t setPolicyResult = overridePolicy
+ ? mRefreshRateConfigs->setOverridePolicy(policy)
+ : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
+ if (setPolicyResult < 0) {
return BAD_VALUE;
}
- if (!policyChanged) {
+ if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
return NO_ERROR;
}
+ scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
- defaultConfig.value(), minRefreshRate, maxRefreshRate);
+ currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
+ currentPolicy.maxRefreshRate);
// TODO(b/140204874): This hack triggers a notification that something has changed, so
// that listeners that care about a change in allowed configs can get the notification.
@@ -5974,7 +6012,7 @@
auto& preferredRefreshRate = configId
? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
// NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
- : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
+ : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
ALOGV("trying to switch to Scheduler preferred config %d (%s)",
preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
@@ -6009,9 +6047,13 @@
result = BAD_VALUE;
ALOGW("Attempt to set desired display configs for virtual display");
} else {
- result =
- setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
- minRefreshRate, maxRefreshRate);
+ result = setDesiredDisplayConfigSpecsInternal(display,
+ scheduler::RefreshRateConfigs::
+ Policy{HwcConfigIndexType(
+ defaultConfig),
+ minRefreshRate,
+ maxRefreshRate},
+ /*overridePolicy=*/false);
}
}));
@@ -6035,9 +6077,11 @@
}
if (display->isPrimary()) {
- HwcConfigIndexType defaultConfig;
- mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
- *outDefaultConfig = defaultConfig.value();
+ scheduler::RefreshRateConfigs::Policy policy =
+ mRefreshRateConfigs->getDisplayManagerPolicy();
+ *outDefaultConfig = policy.defaultConfig.value();
+ *outMinRefreshRate = policy.minRefreshRate;
+ *outMaxRefreshRate = policy.maxRefreshRate;
return NO_ERROR;
} else if (display->isVirtual()) {
return BAD_VALUE;
@@ -6157,6 +6201,68 @@
return NO_ERROR;
}
+status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
+ if (!outToken) {
+ return BAD_VALUE;
+ }
+ status_t result = NO_ERROR;
+ postMessageSync(new LambdaMessage([&]() {
+ if (mFrameRateFlexibilityTokenCount == 0) {
+ // |mStateLock| not needed as we are on the main thread
+ const auto display = getDefaultDisplayDeviceLocked();
+
+ // This is a little racy, but not in a way that hurts anything. As we grab the
+ // defaultConfig from the display manager policy, we could be setting a new display
+ // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
+ // matter for the override policy though, since we set allowGroupSwitching to true, so
+ // it's not a problem.
+ scheduler::RefreshRateConfigs::Policy overridePolicy;
+ overridePolicy.defaultConfig =
+ mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
+ overridePolicy.allowGroupSwitching = true;
+ result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
+ /*overridePolicy=*/true);
+ }
+
+ if (result == NO_ERROR) {
+ mFrameRateFlexibilityTokenCount++;
+ // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
+ // below, is something to consider carefully. The lifetime of the
+ // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
+ // SurfaceFlinger object were to be destroyed while the token still exists, the token
+ // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
+ // in this case, for two reasons:
+ // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
+ // the program exits is via a crash. So we won't have a situation where the
+ // SurfaceFlinger object is dead but the process is still up.
+ // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
+ // if condition 1 were changed, the problem would only show up when running CTS tests,
+ // not on end user devices, so we could spot it and fix it without serious impact.
+ *outToken = new FrameRateFlexibilityToken(
+ [this]() { onFrameRateFlexibilityTokenReleased(); });
+ ALOGD("Frame rate flexibility token acquired. count=%d",
+ mFrameRateFlexibilityTokenCount);
+ }
+ }));
+ return result;
+}
+
+void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
+ postMessageAsync(new LambdaMessage([&]() {
+ LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
+ "Failed tracking frame rate flexibility tokens");
+ mFrameRateFlexibilityTokenCount--;
+ ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
+ if (mFrameRateFlexibilityTokenCount == 0) {
+ // |mStateLock| not needed as we are on the main thread
+ const auto display = getDefaultDisplayDeviceLocked();
+ status_t result =
+ setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
+ LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
+ }
+ }));
+}
+
} // namespace android
#if defined(__gl_h_)
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index 60904f6..12efca1 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -407,7 +407,8 @@
*/
status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override;
status_t dump(int fd, const Vector<String16>& args) override { return priorityDump(fd, args); }
- bool callingThreadHasUnscopedSurfaceFlingerAccess() EXCLUDES(mStateLock);
+ bool callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache = true)
+ EXCLUDES(mStateLock);
/* ------------------------------------------------------------------------
* ISurfaceComposer interface
@@ -503,6 +504,7 @@
float lightPosY, float lightPosZ, float lightRadius) override;
status_t setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
int8_t compatibility) override;
+ status_t acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) override;
/* ------------------------------------------------------------------------
* DeathRecipient interface
*/
@@ -574,9 +576,9 @@
void setPowerModeInternal(const sp<DisplayDevice>& display, int mode) REQUIRES(mStateLock);
// Sets the desired display configs.
- status_t setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
- HwcConfigIndexType defaultConfig,
- float minRefreshRate, float maxRefreshRate)
+ status_t setDesiredDisplayConfigSpecsInternal(
+ const sp<DisplayDevice>& display,
+ const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy)
EXCLUDES(mStateLock);
// called on the main thread in response to setAutoLowLatencyMode()
@@ -968,6 +970,8 @@
return doDump(fd, args, asProto);
}
+ void onFrameRateFlexibilityTokenReleased();
+
/* ------------------------------------------------------------------------
* VrFlinger
*/
@@ -1073,6 +1077,7 @@
std::unique_ptr<SurfaceInterceptor> mInterceptor;
SurfaceTracing mTracing{*this};
bool mTracingEnabled = false;
+ bool mAddCompositionStateToTrace = false;
bool mTracingEnabledChanged GUARDED_BY(mStateLock) = false;
const std::shared_ptr<TimeStats> mTimeStats;
const std::unique_ptr<FrameTracer> mFrameTracer;
@@ -1275,6 +1280,8 @@
std::atomic<bool> mInputDirty = true;
void dirtyInput() { mInputDirty = true; }
bool inputDirty() { return mInputDirty; }
+
+ int mFrameRateFlexibilityTokenCount = 0;
};
} // namespace android
diff --git a/services/surfaceflinger/SurfaceTracing.cpp b/services/surfaceflinger/SurfaceTracing.cpp
index a9c3332..0b1251e 100644
--- a/services/surfaceflinger/SurfaceTracing.cpp
+++ b/services/surfaceflinger/SurfaceTracing.cpp
@@ -60,6 +60,8 @@
mCanStartTrace.wait(lock);
android::base::ScopedLockAssertion assumeLock(mSfLock);
LayersTraceProto entry = traceLayersLocked(mWhere, displayDevice);
+ mTracingInProgress = false;
+ mMissedTraceEntries = 0;
lock.unlock();
return entry;
}
@@ -76,7 +78,15 @@
void SurfaceTracing::notify(const char* where) {
std::scoped_lock lock(mSfLock);
+ notifyLocked(where);
+}
+
+void SurfaceTracing::notifyLocked(const char* where) {
mWhere = where;
+ if (mTracingInProgress) {
+ mMissedTraceEntries++;
+ }
+ mTracingInProgress = true;
mCanStartTrace.notify_one();
}
@@ -175,7 +185,10 @@
entry.set_elapsed_realtime_nanos(elapsedRealtimeNano());
entry.set_where(where);
LayersProto layers(mFlinger.dumpDrawingStateProto(mTraceFlags, displayDevice));
- mFlinger.dumpOffscreenLayersProto(layers);
+
+ if (flagIsSetLocked(SurfaceTracing::TRACE_EXTRA)) {
+ mFlinger.dumpOffscreenLayersProto(layers);
+ }
entry.mutable_layers()->Swap(&layers);
if (mTraceFlags & SurfaceTracing::TRACE_HWC) {
@@ -183,6 +196,10 @@
mFlinger.dumpHwc(hwcDump);
entry.set_hwc_blob(hwcDump);
}
+ if (!flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION)) {
+ entry.set_excludes_composition_state(true);
+ }
+ entry.set_missed_entries(mMissedTraceEntries);
return entry;
}
diff --git a/services/surfaceflinger/SurfaceTracing.h b/services/surfaceflinger/SurfaceTracing.h
index 83872ed..a00e5d6 100644
--- a/services/surfaceflinger/SurfaceTracing.h
+++ b/services/surfaceflinger/SurfaceTracing.h
@@ -49,6 +49,7 @@
status_t writeToFile();
bool isEnabled() const;
void notify(const char* where);
+ void notifyLocked(const char* where) NO_THREAD_SAFETY_ANALYSIS /* REQUIRES(mSfLock) */;
void setBufferSize(size_t bufferSizeInByte);
void writeToFileAsync();
@@ -57,11 +58,15 @@
enum : uint32_t {
TRACE_CRITICAL = 1 << 0,
TRACE_INPUT = 1 << 1,
- TRACE_EXTRA = 1 << 2,
- TRACE_HWC = 1 << 3,
+ TRACE_COMPOSITION = 1 << 2,
+ TRACE_EXTRA = 1 << 3,
+ TRACE_HWC = 1 << 4,
TRACE_ALL = 0xffffffff
};
void setTraceFlags(uint32_t flags);
+ bool flagIsSetLocked(uint32_t flags) NO_THREAD_SAFETY_ANALYSIS /* REQUIRES(mSfLock) */ {
+ return (mTraceFlags & flags) == flags;
+ }
private:
static constexpr auto kDefaultBufferCapInByte = 5_MB;
@@ -103,6 +108,8 @@
std::mutex& mSfLock;
uint32_t mTraceFlags GUARDED_BY(mSfLock) = TRACE_CRITICAL | TRACE_INPUT;
const char* mWhere GUARDED_BY(mSfLock) = "";
+ uint32_t mMissedTraceEntries GUARDED_BY(mSfLock) = 0;
+ bool mTracingInProgress GUARDED_BY(mSfLock) = false;
mutable std::mutex mTraceLock;
LayersTraceBuffer mBuffer GUARDED_BY(mTraceLock);
diff --git a/services/surfaceflinger/TimeStats/TimeStats.cpp b/services/surfaceflinger/TimeStats/TimeStats.cpp
index 4f59bf2..606e137 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.cpp
+++ b/services/surfaceflinger/TimeStats/TimeStats.cpp
@@ -281,6 +281,15 @@
mTimeStats.clientCompositionReusedFrames++;
}
+void TimeStats::incrementRefreshRateSwitches() {
+ if (!mEnabled.load()) return;
+
+ ATRACE_CALL();
+
+ std::lock_guard<std::mutex> lock(mMutex);
+ mTimeStats.refreshRateSwitches++;
+}
+
void TimeStats::recordDisplayEventConnectionCount(int32_t count) {
if (!mEnabled.load()) return;
@@ -834,6 +843,7 @@
mTimeStats.missedFrames = 0;
mTimeStats.clientCompositionFrames = 0;
mTimeStats.clientCompositionReusedFrames = 0;
+ mTimeStats.refreshRateSwitches = 0;
mTimeStats.displayEventConnectionsCount = 0;
mTimeStats.displayOnTime = 0;
mTimeStats.presentToPresent.hist.clear();
diff --git a/services/surfaceflinger/TimeStats/TimeStats.h b/services/surfaceflinger/TimeStats/TimeStats.h
index f9bd90b..806b47e 100644
--- a/services/surfaceflinger/TimeStats/TimeStats.h
+++ b/services/surfaceflinger/TimeStats/TimeStats.h
@@ -52,6 +52,8 @@
virtual void incrementMissedFrames() = 0;
virtual void incrementClientCompositionFrames() = 0;
virtual void incrementClientCompositionReusedFrames() = 0;
+ // Increments the number of times the display refresh rate changed.
+ virtual void incrementRefreshRateSwitches() = 0;
// Records the most up-to-date count of display event connections.
// The stored count will be the maximum ever recoded.
virtual void recordDisplayEventConnectionCount(int32_t count) = 0;
@@ -215,6 +217,7 @@
void incrementMissedFrames() override;
void incrementClientCompositionFrames() override;
void incrementClientCompositionReusedFrames() override;
+ void incrementRefreshRateSwitches() override;
void recordDisplayEventConnectionCount(int32_t count) override;
void recordFrameDuration(nsecs_t startTime, nsecs_t endTime) override;
diff --git a/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp b/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
index e2f85cc..5305de9 100644
--- a/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
+++ b/services/surfaceflinger/TimeStats/timestatsproto/TimeStatsHelper.cpp
@@ -105,6 +105,7 @@
StringAppendF(&result, "missedFrames = %d\n", missedFrames);
StringAppendF(&result, "clientCompositionFrames = %d\n", clientCompositionFrames);
StringAppendF(&result, "clientCompositionReusedFrames = %d\n", clientCompositionReusedFrames);
+ StringAppendF(&result, "refreshRateSwitches = %d\n", refreshRateSwitches);
StringAppendF(&result, "displayOnTime = %" PRId64 " ms\n", displayOnTime);
StringAppendF(&result, "displayConfigStats is as below:\n");
for (const auto& [fps, duration] : refreshRateStats) {
diff --git a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
index 5e7c449..afb98e0 100644
--- a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
+++ b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h
@@ -62,6 +62,7 @@
int32_t missedFrames = 0;
int32_t clientCompositionFrames = 0;
int32_t clientCompositionReusedFrames = 0;
+ int32_t refreshRateSwitches = 0;
int32_t displayEventConnectionsCount = 0;
int64_t displayOnTime = 0;
Histogram presentToPresent;
diff --git a/services/surfaceflinger/layerproto/layerstrace.proto b/services/surfaceflinger/layerproto/layerstrace.proto
index ac33a0e..acf621e 100644
--- a/services/surfaceflinger/layerproto/layerstrace.proto
+++ b/services/surfaceflinger/layerproto/layerstrace.proto
@@ -51,4 +51,10 @@
// Blob for the current HWC information for all layers, reported by dumpsys.
optional string hwc_blob = 4;
+
+ /* Includes state sent during composition like visible region and composition type. */
+ optional bool excludes_composition_state = 5;
+
+ /* Number of missed entries since the last entry was recorded. */
+ optional int32 missed_entries = 6;
}
diff --git a/services/surfaceflinger/tests/unittests/DisplayIdentificationTest.cpp b/services/surfaceflinger/tests/unittests/DisplayIdentificationTest.cpp
index c2ddfce..cc11aa9 100644
--- a/services/surfaceflinger/tests/unittests/DisplayIdentificationTest.cpp
+++ b/services/surfaceflinger/tests/unittests/DisplayIdentificationTest.cpp
@@ -96,7 +96,7 @@
"\x0a\x20\x20\x20\x20\x20\x01\x47\x02\x03\x2d\x71\x50\x90\x05"
"\x04\x03\x07\x02\x06\x01\x1f\x14\x13\x12\x16\x11\x15\x20\x2c"
"\x09\x07\x03\x15\x07\x50\x57\x07\x00\x39\x07\xbb\x66\x03\x0c"
- "\x00\x20\x00\x00\x83\x01\x00\x00\x01\x1d\x00\x72\x51\xd0\x1e"
+ "\x00\x12\x34\x00\x83\x01\x00\x00\x01\x1d\x00\x72\x51\xd0\x1e"
"\x20\x6e\x28\x55\x00\xc4\x8e\x21\x00\x00\x1e\x01\x1d\x80\x18"
"\x71\x1c\x16\x20\x58\x2c\x25\x00\xc4\x8e\x21\x00\x00\x9e\x8c"
"\x0a\xd0\x8a\x20\xe0\x2d\x10\x10\x3e\x96\x00\x13\x8e\x21\x00"
@@ -185,6 +185,7 @@
EXPECT_EQ(12610, edid->productId);
EXPECT_EQ(21, edid->manufactureOrModelYear);
EXPECT_EQ(0, edid->manufactureWeek);
+ EXPECT_FALSE(edid->cea861Block);
edid = parseEdid(getExternalEdid());
ASSERT_TRUE(edid);
@@ -195,6 +196,7 @@
EXPECT_EQ(10348, edid->productId);
EXPECT_EQ(22, edid->manufactureOrModelYear);
EXPECT_EQ(2, edid->manufactureWeek);
+ EXPECT_FALSE(edid->cea861Block);
edid = parseEdid(getExternalEedid());
ASSERT_TRUE(edid);
@@ -205,6 +207,14 @@
EXPECT_EQ(2302, edid->productId);
EXPECT_EQ(21, edid->manufactureOrModelYear);
EXPECT_EQ(41, edid->manufactureWeek);
+ ASSERT_TRUE(edid->cea861Block);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock->physicalAddress);
+ auto physicalAddress = edid->cea861Block->hdmiVendorDataBlock->physicalAddress;
+ EXPECT_EQ(2, physicalAddress->a);
+ EXPECT_EQ(0, physicalAddress->b);
+ EXPECT_EQ(0, physicalAddress->c);
+ EXPECT_EQ(0, physicalAddress->d);
edid = parseEdid(getPanasonicTvEdid());
ASSERT_TRUE(edid);
@@ -215,6 +225,14 @@
EXPECT_EQ(41622, edid->productId);
EXPECT_EQ(29, edid->manufactureOrModelYear);
EXPECT_EQ(0, edid->manufactureWeek);
+ ASSERT_TRUE(edid->cea861Block);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock->physicalAddress);
+ physicalAddress = edid->cea861Block->hdmiVendorDataBlock->physicalAddress;
+ EXPECT_EQ(2, physicalAddress->a);
+ EXPECT_EQ(0, physicalAddress->b);
+ EXPECT_EQ(0, physicalAddress->c);
+ EXPECT_EQ(0, physicalAddress->d);
edid = parseEdid(getHisenseTvEdid());
ASSERT_TRUE(edid);
@@ -225,6 +243,14 @@
EXPECT_EQ(0, edid->productId);
EXPECT_EQ(29, edid->manufactureOrModelYear);
EXPECT_EQ(18, edid->manufactureWeek);
+ ASSERT_TRUE(edid->cea861Block);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock);
+ ASSERT_TRUE(edid->cea861Block->hdmiVendorDataBlock->physicalAddress);
+ physicalAddress = edid->cea861Block->hdmiVendorDataBlock->physicalAddress;
+ EXPECT_EQ(1, physicalAddress->a);
+ EXPECT_EQ(2, physicalAddress->b);
+ EXPECT_EQ(3, physicalAddress->c);
+ EXPECT_EQ(4, physicalAddress->d);
edid = parseEdid(getCtlDisplayEdid());
ASSERT_TRUE(edid);
@@ -235,6 +261,8 @@
EXPECT_EQ(9373, edid->productId);
EXPECT_EQ(23, edid->manufactureOrModelYear);
EXPECT_EQ(0xff, edid->manufactureWeek);
+ ASSERT_TRUE(edid->cea861Block);
+ EXPECT_FALSE(edid->cea861Block->hdmiVendorDataBlock);
}
TEST(DisplayIdentificationTest, parseInvalidEdid) {
diff --git a/services/surfaceflinger/tests/unittests/PhaseOffsetsTest.cpp b/services/surfaceflinger/tests/unittests/PhaseOffsetsTest.cpp
index 8d49201..ce5993a 100644
--- a/services/surfaceflinger/tests/unittests/PhaseOffsetsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/PhaseOffsetsTest.cpp
@@ -45,8 +45,8 @@
class PhaseDurationTest : public testing::Test {
protected:
PhaseDurationTest()
- : mPhaseDurations(60.0f, 10'500'000, 20'500'000, 16'000'000, 33'500'000, 13'500'000,
- 38'000'000) {}
+ : mPhaseDurations(60.0f, 10'500'000, 20'500'000, 16'000'000, 16'500'000, 13'500'000,
+ 21'000'000) {}
~PhaseDurationTest() = default;
@@ -69,11 +69,11 @@
EXPECT_EQ(offsets.early.sf, 666'667);
- EXPECT_EQ(offsets.early.app, 500'001);
+ EXPECT_EQ(offsets.early.app, 833'334);
EXPECT_EQ(offsets.earlyGl.sf, 3'166'667);
- EXPECT_EQ(offsets.earlyGl.app, 15'166'668);
+ EXPECT_EQ(offsets.earlyGl.app, 15'500'001);
}
TEST_F(PhaseDurationTest, getOffsetsForRefreshRate_90Hz) {
@@ -88,11 +88,11 @@
EXPECT_EQ(offsets.early.sf, -4'888'889);
- EXPECT_EQ(offsets.early.app, 6'055'555);
+ EXPECT_EQ(offsets.early.app, 833'333);
EXPECT_EQ(offsets.earlyGl.sf, -2'388'889);
- EXPECT_EQ(offsets.earlyGl.app, 4'055'555);
+ EXPECT_EQ(offsets.earlyGl.app, 9'944'444);
}
TEST_F(PhaseDurationTest, getOffsetsForRefreshRate_DefaultOffsets) {
@@ -134,11 +134,11 @@
EXPECT_EQ(offsets.early.sf, 52'027'208);
- EXPECT_EQ(offsets.early.app, 18'527'208);
+ EXPECT_EQ(offsets.early.app, 35'527'208);
EXPECT_EQ(offsets.earlyGl.sf, 54'527'208);
- EXPECT_EQ(offsets.earlyGl.app, 16'527'208);
+ EXPECT_EQ(offsets.earlyGl.app, 33'527'208);
}
} // namespace
diff --git a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
index dd04076..ce41291 100644
--- a/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/RefreshRateConfigsTest.cpp
@@ -83,8 +83,8 @@
{{HWC_CONFIG_ID_60, HWC_GROUP_ID_0, VSYNC_60}}};
auto refreshRateConfigs =
std::make_unique<RefreshRateConfigs>(configs, /*currentConfigId=*/HWC_CONFIG_ID_60);
- ASSERT_LT(refreshRateConfigs->setPolicy(HwcConfigIndexType(10), 60, 60, nullptr), 0);
- ASSERT_LT(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 20, 40, nullptr), 0);
+ ASSERT_LT(refreshRateConfigs->setDisplayManagerPolicy({HwcConfigIndexType(10), 60, 60}), 0);
+ ASSERT_LT(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 20, 40}), 0);
}
TEST_F(RefreshRateConfigsTest, twoDeviceConfigs_storesFullRefreshRateMap) {
@@ -126,7 +126,7 @@
ASSERT_EQ(expectedDefaultConfig, minRate60);
ASSERT_EQ(expectedDefaultConfig, performanceRate60);
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_90, 60, 90, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_90, 60, 90}), 0);
refreshRateConfigs->setCurrentConfigId(HWC_CONFIG_ID_90);
const auto& minRate90 = refreshRateConfigs->getMinRefreshRateByPolicy();
@@ -155,7 +155,7 @@
90};
ASSERT_EQ(expectedPerformanceConfig, performanceRate);
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 60, 60, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 60, 60}), 0);
auto& minRate60 = refreshRateConfigs->getMinRefreshRateByPolicy();
auto& performanceRate60 = refreshRateConfigs->getMaxRefreshRateByPolicy();
@@ -180,7 +180,7 @@
EXPECT_EQ(current.configId, HWC_CONFIG_ID_90);
}
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_90, 90, 90, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_90, 90, 90}), 0);
{
auto& current = refreshRateConfigs->getCurrentRefreshRate();
EXPECT_EQ(current.configId, HWC_CONFIG_ID_90);
@@ -212,7 +212,7 @@
EXPECT_EQ(expected60Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(24.0f)));
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 60, 60, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 60, 60}), 0);
EXPECT_EQ(expected60Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(90.0f)));
EXPECT_EQ(expected60Config,
@@ -224,7 +224,7 @@
EXPECT_EQ(expected60Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(24.0f)));
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_90, 90, 90, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_90, 90, 90}), 0);
EXPECT_EQ(expected90Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(90.0f)));
EXPECT_EQ(expected90Config,
@@ -235,7 +235,7 @@
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(30.0f)));
EXPECT_EQ(expected90Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(24.0f)));
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 0, 120, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 0, 120}), 0);
EXPECT_EQ(expected90Config,
refreshRateConfigs->getRefreshRateForContent(makeLayerRequirements(90.0f)));
EXPECT_EQ(expected60Config,
@@ -332,7 +332,7 @@
&ignored));
lr.name = "";
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 60, 60, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 60, 60}), 0);
lr.vote = LayerVoteType::Min;
EXPECT_EQ(expected60Config,
@@ -370,7 +370,7 @@
refreshRateConfigs->getRefreshRateForContentV2(layers, /*touchActive*/ false,
&ignored));
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_90, 90, 90, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_90, 90, 90}), 0);
lr.vote = LayerVoteType::Min;
EXPECT_EQ(expected90Config,
@@ -408,7 +408,7 @@
refreshRateConfigs->getRefreshRateForContentV2(layers, /*touchActive*/ false,
&ignored));
- ASSERT_GE(refreshRateConfigs->setPolicy(HWC_CONFIG_ID_60, 0, 120, nullptr), 0);
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy({HWC_CONFIG_ID_60, 0, 120}), 0);
lr.vote = LayerVoteType::Min;
EXPECT_EQ(expected60Config,
refreshRateConfigs->getRefreshRateForContentV2(layers, /*touchActive*/ false,
@@ -1218,6 +1218,33 @@
}
}
+TEST_F(RefreshRateConfigsTest, groupSwitching) {
+ std::vector<RefreshRateConfigs::InputConfig> configs{
+ {{HWC_CONFIG_ID_60, HWC_GROUP_ID_0, VSYNC_60},
+ {HWC_CONFIG_ID_90, HWC_GROUP_ID_1, VSYNC_90}}};
+ auto refreshRateConfigs =
+ std::make_unique<RefreshRateConfigs>(configs, /*currentConfigId=*/HWC_CONFIG_ID_60);
+
+ auto layers = std::vector<LayerRequirement>{LayerRequirement{.weight = 1.0f}};
+ auto& layer = layers[0];
+ layer.vote = LayerVoteType::ExplicitDefault;
+ layer.desiredRefreshRate = 90.0f;
+ layer.name = "90Hz ExplicitDefault";
+
+ bool touchConsidered;
+ ASSERT_EQ(HWC_CONFIG_ID_60,
+ refreshRateConfigs->getRefreshRateForContentV2(layers, false, &touchConsidered)
+ .configId);
+
+ RefreshRateConfigs::Policy policy;
+ policy.defaultConfig = refreshRateConfigs->getCurrentPolicy().defaultConfig;
+ policy.allowGroupSwitching = true;
+ ASSERT_GE(refreshRateConfigs->setDisplayManagerPolicy(policy), 0);
+ ASSERT_EQ(HWC_CONFIG_ID_90,
+ refreshRateConfigs->getRefreshRateForContentV2(layers, false, &touchConsidered)
+ .configId);
+}
+
} // namespace
} // namespace scheduler
} // namespace android
diff --git a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
index 4f65aee..1f04673 100644
--- a/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
+++ b/services/surfaceflinger/tests/unittests/TimeStatsTest.cpp
@@ -362,6 +362,21 @@
EXPECT_THAT(result, HasSubstr(expectedResult));
}
+TEST_F(TimeStatsTest, canIncreaseRefreshRateSwitches) {
+ // this stat is not in the proto so verify by checking the string dump
+ constexpr size_t REFRESH_RATE_SWITCHES = 2;
+
+ EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
+ for (size_t i = 0; i < REFRESH_RATE_SWITCHES; i++) {
+ ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementRefreshRateSwitches());
+ }
+
+ const std::string result(inputCommand(InputCommand::DUMP_ALL, FMT_STRING));
+ const std::string expectedResult =
+ "refreshRateSwitches = " + std::to_string(REFRESH_RATE_SWITCHES);
+ EXPECT_THAT(result, HasSubstr(expectedResult));
+}
+
TEST_F(TimeStatsTest, canAverageFrameDuration) {
EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
mTimeStats->setPowerMode(HWC_POWER_MODE_NORMAL);
@@ -744,6 +759,7 @@
// These stats are not in the proto so verify by checking the string dump.
EXPECT_TRUE(inputCommand(InputCommand::ENABLE, FMT_STRING).empty());
ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementClientCompositionReusedFrames());
+ ASSERT_NO_FATAL_FAILURE(mTimeStats->incrementRefreshRateSwitches());
mTimeStats->setPowerMode(HWC_POWER_MODE_NORMAL);
mTimeStats
->recordFrameDuration(std::chrono::duration_cast<std::chrono::nanoseconds>(1ms).count(),
@@ -759,6 +775,7 @@
const std::string result(inputCommand(InputCommand::DUMP_ALL, FMT_STRING));
EXPECT_THAT(result, HasSubstr("clientCompositionReusedFrames = 0"));
+ EXPECT_THAT(result, HasSubstr("refreshRateSwitches = 0"));
EXPECT_THAT(result, HasSubstr("averageFrameDuration = 0.000 ms"));
EXPECT_THAT(result, HasSubstr("averageRenderEngineTiming = 0.000 ms"));
}
diff --git a/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h b/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
index c45d584..9ea4dd0 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockTimeStats.h
@@ -36,6 +36,7 @@
MOCK_METHOD0(incrementMissedFrames, void());
MOCK_METHOD0(incrementClientCompositionFrames, void());
MOCK_METHOD0(incrementClientCompositionReusedFrames, void());
+ MOCK_METHOD0(incrementRefreshRateSwitches, void());
MOCK_METHOD1(recordDisplayEventConnectionCount, void(int32_t));
MOCK_METHOD2(recordFrameDuration, void(nsecs_t, nsecs_t));
MOCK_METHOD2(recordRenderEngineDuration, void(nsecs_t, nsecs_t));