From f502922b5a4869c399bebd2254039183b58c8a7d Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Thu, 16 Dec 2021 14:33:46 -0800 Subject: Migrate screenshot methods to AIDL Additonal service, named as "SurfaceFlingerAIDL", is added to surfaceflinger during the process of migrating ISurfaceComposer interface to AIDL. New changes are put into namespace, android::gui. Once migration is complete, this service will be deleted. This CL migrates Screenshot methods to AIDL, more will come. Bug: 211037638 Test: screencap Change-Id: Idee91fa2444646639735847b1c76e983af39227f --- libs/gui/ISurfaceComposer.cpp | 62 ++----------------------------------------- 1 file changed, 2 insertions(+), 60 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 75c5e26fb0..5ab0abc561 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -46,9 +46,11 @@ using namespace aidl::android::hardware::graphics; namespace android { +using gui::DisplayCaptureArgs; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; using gui::IWindowInfosListener; +using gui::LayerCaptureArgs; using ui::ColorMode; class BpSurfaceComposer : public BpInterface @@ -118,36 +120,6 @@ public: remote()->transact(BnSurfaceComposer::BOOT_FINISHED, data, &reply); } - status_t captureDisplay(const DisplayCaptureArgs& args, - const sp& captureListener) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(args.write, data); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(captureListener)); - - return remote()->transact(BnSurfaceComposer::CAPTURE_DISPLAY, data, &reply); - } - - status_t captureDisplay(DisplayId displayId, - const sp& captureListener) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeUint64, displayId.value); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(captureListener)); - - return remote()->transact(BnSurfaceComposer::CAPTURE_DISPLAY_BY_ID, data, &reply); - } - - status_t captureLayers(const LayerCaptureArgs& args, - const sp& captureListener) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(args.write, data); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(captureListener)); - - return remote()->transact(BnSurfaceComposer::CAPTURE_LAYERS, data, &reply); - } - bool authenticateSurfaceTexture( const sp& bufferProducer) const override { Parcel data, reply; @@ -1451,36 +1423,6 @@ status_t BnSurfaceComposer::onTransact( bootFinished(); return NO_ERROR; } - case CAPTURE_DISPLAY: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - DisplayCaptureArgs args; - sp captureListener; - SAFE_PARCEL(args.read, data); - SAFE_PARCEL(data.readStrongBinder, &captureListener); - - return captureDisplay(args, captureListener); - } - case CAPTURE_DISPLAY_BY_ID: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - uint64_t value; - SAFE_PARCEL(data.readUint64, &value); - const auto id = DisplayId::fromValue(value); - if (!id) return BAD_VALUE; - - sp captureListener; - SAFE_PARCEL(data.readStrongBinder, &captureListener); - - return captureDisplay(*id, captureListener); - } - case CAPTURE_LAYERS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - LayerCaptureArgs args; - sp captureListener; - SAFE_PARCEL(args.read, data); - SAFE_PARCEL(data.readStrongBinder, &captureListener); - - return captureLayers(args, captureListener); - } case AUTHENTICATE_SURFACE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); sp bufferProducer = -- cgit v1.2.3-59-g8ed1b From 07e723660ca6265844be1ebd8c4696977151eeba Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Mon, 14 Feb 2022 14:26:04 -0800 Subject: Migrate display related methods to AIDL This migrates display related methods from ISurfaceComposer.h to the AIDL interface. Bug: 219574942 Test: manual Change-Id: I11f011ce61bdd6dfbd8e0f1a1af8925820e3de58 --- libs/gui/ISurfaceComposer.cpp | 116 --------------------- libs/gui/Surface.cpp | 5 +- libs/gui/SurfaceComposerClient.cpp | 43 ++++++-- libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 22 ++++ libs/gui/include/gui/ISurfaceComposer.h | 44 +------- libs/gui/include/private/gui/ComposerServiceAIDL.h | 21 ++++ libs/gui/tests/Surface_test.cpp | 10 +- services/surfaceflinger/SurfaceFlinger.cpp | 75 +++++++++++-- services/surfaceflinger/SurfaceFlinger.h | 34 +++++- 9 files changed, 185 insertions(+), 185 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 5ab0abc561..6911d89cdb 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -220,81 +220,6 @@ public: return result; } - sp createDisplay(const String8& displayName, bool secure) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - status_t status = data.writeString8(displayName); - if (status) { - return nullptr; - } - status = data.writeBool(secure); - if (status) { - return nullptr; - } - - status = remote()->transact(BnSurfaceComposer::CREATE_DISPLAY, data, &reply); - if (status) { - return nullptr; - } - sp display; - status = reply.readNullableStrongBinder(&display); - if (status) { - return nullptr; - } - return display; - } - - void destroyDisplay(const sp& display) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - remote()->transact(BnSurfaceComposer::DESTROY_DISPLAY, data, &reply); - } - - std::vector getPhysicalDisplayIds() const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (remote()->transact(BnSurfaceComposer::GET_PHYSICAL_DISPLAY_IDS, data, &reply) == - NO_ERROR) { - std::vector rawIds; - if (reply.readUint64Vector(&rawIds) == NO_ERROR) { - std::vector displayIds; - displayIds.reserve(rawIds.size()); - - for (const uint64_t rawId : rawIds) { - if (const auto id = DisplayId::fromValue(rawId)) { - displayIds.push_back(*id); - } - } - return displayIds; - } - } - - return {}; - } - - status_t getPrimaryPhysicalDisplayId(PhysicalDisplayId* displayId) const override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(remote()->transact, BnSurfaceComposer::GET_PRIMARY_PHYSICAL_DISPLAY_ID, data, - &reply); - uint64_t rawId; - SAFE_PARCEL(reply.readUint64, &rawId); - if (const auto id = DisplayId::fromValue(rawId)) { - *displayId = *id; - return NO_ERROR; - } - return NAME_NOT_FOUND; - } - - sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeUint64(displayId.value); - remote()->transact(BnSurfaceComposer::GET_PHYSICAL_DISPLAY_TOKEN, data, &reply); - return reply.readStrongBinder(); - } - void setPowerMode(const sp& display, int mode) override { Parcel data, reply; data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); @@ -1461,29 +1386,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case CREATE_DISPLAY: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - String8 displayName; - SAFE_PARCEL(data.readString8, &displayName); - bool secure = false; - SAFE_PARCEL(data.readBool, &secure); - sp display = createDisplay(displayName, secure); - SAFE_PARCEL(reply->writeStrongBinder, display); - return NO_ERROR; - } - case DESTROY_DISPLAY: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = data.readStrongBinder(); - destroyDisplay(display); - return NO_ERROR; - } - case GET_PHYSICAL_DISPLAY_TOKEN: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - const auto id = DisplayId::fromValue(data.readUint64()); - if (!id) return BAD_VALUE; - reply->writeStrongBinder(getPhysicalDisplayToken(*id)); - return NO_ERROR; - } case GET_DISPLAY_STATE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); ui::DisplayState state; @@ -1820,24 +1722,6 @@ status_t BnSurfaceComposer::onTransact( } return error; } - case GET_PHYSICAL_DISPLAY_IDS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - std::vector ids = getPhysicalDisplayIds(); - std::vector rawIds(ids.size()); - std::transform(ids.begin(), ids.end(), rawIds.begin(), - [](PhysicalDisplayId id) { return id.value; }); - return reply->writeUint64Vector(rawIds); - } - case GET_PRIMARY_PHYSICAL_DISPLAY_ID: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - PhysicalDisplayId id; - status_t result = getPrimaryPhysicalDisplayId(&id); - if (result != NO_ERROR) { - ALOGE("getPrimaryPhysicalDisplayId: Failed to get id"); - return result; - } - return reply->writeUint64(id.value); - } case ADD_REGION_SAMPLING_LISTENER: { CHECK_INTERFACE(ISurfaceComposer, data, reply); Rect samplingArea; diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index 20c41460d4..82067580a9 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -45,6 +45,7 @@ #include #include #include +#include namespace android { @@ -343,7 +344,7 @@ status_t Surface::getFrameTimestamps(uint64_t frameNumber, status_t Surface::getWideColorSupport(bool* supported) { ATRACE_CALL(); - const sp display = composerService()->getInternalDisplayToken(); + const sp display = ComposerServiceAIDL::getInstance().getInternalDisplayToken(); if (display == nullptr) { return NAME_NOT_FOUND; } @@ -356,7 +357,7 @@ status_t Surface::getWideColorSupport(bool* supported) { status_t Surface::getHdrSupport(bool* supported) { ATRACE_CALL(); - const sp display = composerService()->getInternalDisplayToken(); + const sp display = ComposerServiceAIDL::getInstance().getInternalDisplayToken(); if (display == nullptr) { return NAME_NOT_FOUND; } diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 26ccda580a..52d89657b5 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -1014,32 +1014,59 @@ status_t SurfaceComposerClient::Transaction::apply(bool synchronous) { // --------------------------------------------------------------------------- sp SurfaceComposerClient::createDisplay(const String8& displayName, bool secure) { - return ComposerService::getComposerService()->createDisplay(displayName, - secure); + sp display = nullptr; + binder::Status status = + ComposerServiceAIDL::getComposerService()->createDisplay(std::string( + displayName.string()), + secure, &display); + return status.isOk() ? display : nullptr; } void SurfaceComposerClient::destroyDisplay(const sp& display) { - return ComposerService::getComposerService()->destroyDisplay(display); + ComposerServiceAIDL::getComposerService()->destroyDisplay(display); } std::vector SurfaceComposerClient::getPhysicalDisplayIds() { - return ComposerService::getComposerService()->getPhysicalDisplayIds(); + std::vector displayIds; + std::vector physicalDisplayIds; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getPhysicalDisplayIds(&displayIds); + if (status.isOk()) { + physicalDisplayIds.reserve(displayIds.size()); + for (auto item : displayIds) { + auto id = DisplayId::fromValue(static_cast(item)); + physicalDisplayIds.push_back(*id); + } + } + return physicalDisplayIds; } status_t SurfaceComposerClient::getPrimaryPhysicalDisplayId(PhysicalDisplayId* id) { - return ComposerService::getComposerService()->getPrimaryPhysicalDisplayId(id); + int64_t displayId; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getPrimaryPhysicalDisplayId(&displayId); + if (status.isOk()) { + *id = *DisplayId::fromValue(static_cast(displayId)); + } + return status.transactionError(); } std::optional SurfaceComposerClient::getInternalDisplayId() { - return ComposerService::getComposerService()->getInternalDisplayId(); + ComposerServiceAIDL& instance = ComposerServiceAIDL::getInstance(); + return instance.getInternalDisplayId(); } sp SurfaceComposerClient::getPhysicalDisplayToken(PhysicalDisplayId displayId) { - return ComposerService::getComposerService()->getPhysicalDisplayToken(displayId); + sp display = nullptr; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getPhysicalDisplayToken(displayId.value, + &display); + return status.isOk() ? display : nullptr; } sp SurfaceComposerClient::getInternalDisplayToken() { - return ComposerService::getComposerService()->getInternalDisplayToken(); + ComposerServiceAIDL& instance = ComposerServiceAIDL::getInstance(); + return instance.getInternalDisplayToken(); } void SurfaceComposerClient::Transaction::setAnimationTransaction() { diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 07921a59a5..345c47d5b9 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -22,6 +22,28 @@ import android.gui.IScreenCaptureListener; /** @hide */ interface ISurfaceComposer { + + /* create a virtual display + * requires ACCESS_SURFACE_FLINGER permission. + */ + @nullable IBinder createDisplay(@utf8InCpp String displayName, boolean secure); + + /* destroy a virtual display + * requires ACCESS_SURFACE_FLINGER permission. + */ + void destroyDisplay(IBinder display); + + /* get stable IDs for connected physical displays. + */ + long[] getPhysicalDisplayIds(); + + long getPrimaryPhysicalDisplayId(); + + /* get token for a physical display given its stable ID obtained via getPhysicalDisplayIds or a + * DisplayEventReceiver hotplug event. + */ + @nullable IBinder getPhysicalDisplayToken(long displayId); + /** * Capture the specified screen. This requires READ_FRAME_BUFFER * permission. This function will fail if there is a secure window on diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 4dfc383b57..a2870db2fa 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -137,40 +137,6 @@ public: VsyncSource vsyncSource = eVsyncSourceApp, EventRegistrationFlags eventRegistration = {}) = 0; - /* create a virtual display - * requires ACCESS_SURFACE_FLINGER permission. - */ - virtual sp createDisplay(const String8& displayName, - bool secure) = 0; - - /* destroy a virtual display - * requires ACCESS_SURFACE_FLINGER permission. - */ - virtual void destroyDisplay(const sp& display) = 0; - - /* get stable IDs for connected physical displays. - */ - virtual std::vector getPhysicalDisplayIds() const = 0; - - virtual status_t getPrimaryPhysicalDisplayId(PhysicalDisplayId*) const = 0; - - // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. - std::optional getInternalDisplayId() const { - const auto displayIds = getPhysicalDisplayIds(); - return displayIds.empty() ? std::nullopt : std::make_optional(displayIds.front()); - } - - /* get token for a physical display given its stable ID obtained via getPhysicalDisplayIds or a - * DisplayEventReceiver hotplug event. - */ - virtual sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const = 0; - - // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. - sp getInternalDisplayToken() const { - const auto displayId = getInternalDisplayId(); - return displayId ? getPhysicalDisplayToken(*displayId) : nullptr; - } - /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */ virtual status_t setTransactionState( const FrameTimelineInfo& frameTimelineInfo, const Vector& state, @@ -596,9 +562,9 @@ public: CREATE_CONNECTION, GET_STATIC_DISPLAY_INFO, CREATE_DISPLAY_EVENT_CONNECTION, - CREATE_DISPLAY, - DESTROY_DISPLAY, - GET_PHYSICAL_DISPLAY_TOKEN, + CREATE_DISPLAY, // Deprecated. Autogenerated by .aidl now. + DESTROY_DISPLAY, // Deprecated. Autogenerated by .aidl now. + GET_PHYSICAL_DISPLAY_TOKEN, // Deprecated. Autogenerated by .aidl now. SET_TRANSACTION_STATE, AUTHENTICATE_SURFACE, GET_SUPPORTED_FRAME_TIMESTAMPS, @@ -626,7 +592,7 @@ public: GET_PROTECTED_CONTENT_SUPPORT, IS_WIDE_COLOR_DISPLAY, GET_DISPLAY_NATIVE_PRIMARIES, - GET_PHYSICAL_DISPLAY_IDS, + GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. ADD_REGION_SAMPLING_LISTENER, REMOVE_REGION_SAMPLING_LISTENER, SET_DESIRED_DISPLAY_MODE_SPECS, @@ -658,7 +624,7 @@ public: REMOVE_TUNNEL_MODE_ENABLED_LISTENER, ADD_WINDOW_INFOS_LISTENER, REMOVE_WINDOW_INFOS_LISTENER, - GET_PRIMARY_PHYSICAL_DISPLAY_ID, + GET_PRIMARY_PHYSICAL_DISPLAY_ID, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_DECORATION_SUPPORT, GET_BOOT_DISPLAY_MODE_SUPPORT, SET_BOOT_DISPLAY_MODE, diff --git a/libs/gui/include/private/gui/ComposerServiceAIDL.h b/libs/gui/include/private/gui/ComposerServiceAIDL.h index fee37eefe0..b32cf2a9c2 100644 --- a/libs/gui/include/private/gui/ComposerServiceAIDL.h +++ b/libs/gui/include/private/gui/ComposerServiceAIDL.h @@ -50,6 +50,27 @@ public: // Get a connection to the Composer Service. This will block until // a connection is established. Returns null if permission is denied. static sp getComposerService(); + + // the following two methods are moved from ISurfaceComposer.h + // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. + std::optional getInternalDisplayId() const { + std::vector displayIds; + binder::Status status = mComposerService->getPhysicalDisplayIds(&displayIds); + return (!status.isOk() || displayIds.empty()) + ? std::nullopt + : DisplayId::fromValue( + static_cast(displayIds.front())); + } + + // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. + sp getInternalDisplayToken() const { + const auto displayId = getInternalDisplayId(); + if (!displayId) return nullptr; + sp display; + binder::Status status = + mComposerService->getPhysicalDisplayToken(displayId->value, &display); + return status.isOk() ? display : nullptr; + } }; // --------------------------------------------------------------------------- diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index a885e926a3..07ac2d4065 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -260,9 +260,7 @@ TEST_F(SurfaceTest, ScreenshotsOfProtectedBuffersDontSucceed) { sp anw(mSurface); // Verify the screenshot works with no protected buffers. - sp sf(ComposerService::getComposerService()); - - const sp display = sf->getInternalDisplayToken(); + const sp display = ComposerServiceAIDL::getInstance().getInternalDisplayToken(); ASSERT_FALSE(display == nullptr); DisplayCaptureArgs captureArgs; @@ -696,12 +694,6 @@ public: ISurfaceComposer::VsyncSource, ISurfaceComposer::EventRegistrationFlags) override { return nullptr; } - sp createDisplay(const String8& /*displayName*/, - bool /*secure*/) override { return nullptr; } - void destroyDisplay(const sp& /*display */) override {} - std::vector getPhysicalDisplayIds() const override { return {}; } - status_t getPrimaryPhysicalDisplayId(PhysicalDisplayId*) const override { return NO_ERROR; } - sp getPhysicalDisplayToken(PhysicalDisplayId) const override { return nullptr; } status_t setTransactionState(const FrameTimelineInfo& /*frameTimelineInfo*/, const Vector& /*state*/, const Vector& /*displays*/, uint32_t /*flags*/, diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 815febe53d..d50869ff90 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5396,8 +5396,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // access to SF. case BOOT_FINISHED: case CLEAR_ANIMATION_FRAME_STATS: - case CREATE_DISPLAY: - case DESTROY_DISPLAY: case GET_ANIMATION_FRAME_STATS: case OVERRIDE_HDR_TYPES: case GET_HDR_CAPABILITIES: @@ -5419,7 +5417,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: case NOTIFY_POWER_BOOST: case SET_GLOBAL_SHADOW_SETTINGS: - case GET_PRIMARY_PHYSICAL_DISPLAY_ID: case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: { // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary // permission dynamically. Don't use the permission cache for this check. @@ -5450,8 +5447,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case AUTHENTICATE_SURFACE: case GET_ACTIVE_COLOR_MODE: case GET_ACTIVE_DISPLAY_MODE: - case GET_PHYSICAL_DISPLAY_IDS: - case GET_PHYSICAL_DISPLAY_TOKEN: case GET_DISPLAY_COLOR_MODES: case GET_DISPLAY_NATIVE_PRIMARIES: case GET_STATIC_DISPLAY_INFO: @@ -5537,10 +5532,15 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { } return PERMISSION_DENIED; } + case CREATE_DISPLAY: + case DESTROY_DISPLAY: + case GET_PRIMARY_PHYSICAL_DISPLAY_ID: + case GET_PHYSICAL_DISPLAY_IDS: + case GET_PHYSICAL_DISPLAY_TOKEN: case CAPTURE_LAYERS: case CAPTURE_DISPLAY: case CAPTURE_DISPLAY_BY_ID: - LOG_FATAL("Deprecated opcode: %d", code); + LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code); return PERMISSION_DENIED; } @@ -7192,6 +7192,59 @@ bool SurfaceFlinger::commitCreatedLayers() { } // gui::ISurfaceComposer + +binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure, + sp* outDisplay) { + status_t status = checkAccessPermission(); + if (status == OK) { + String8 displayName8 = String8::format("%s", displayName.c_str()); + *outDisplay = mFlinger->createDisplay(displayName8, secure); + return binder::Status::ok(); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::destroyDisplay(const sp& display) { + status_t status = checkAccessPermission(); + if (status == OK) { + mFlinger->destroyDisplay(display); + return binder::Status::ok(); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector* outDisplayIds) { + std::vector physicalDisplayIds = mFlinger->getPhysicalDisplayIds(); + std::vector displayIds; + displayIds.reserve(physicalDisplayIds.size()); + for (auto item : physicalDisplayIds) { + displayIds.push_back(static_cast(item.value)); + } + *outDisplayIds = displayIds; + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + + PhysicalDisplayId id; + status = mFlinger->getPrimaryPhysicalDisplayId(&id); + if (status == NO_ERROR) { + *outDisplayId = id.value; + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId, + sp* outDisplay) { + const auto id = DisplayId::fromValue(static_cast(displayId)); + *outDisplay = mFlinger->getPhysicalDisplayToken(*id); + return binder::Status::ok(); +} + binder::Status SurfaceComposerAIDL::captureDisplay( const DisplayCaptureArgs& args, const sp& captureListener) { status_t status = mFlinger->captureDisplay(args, captureListener); @@ -7218,6 +7271,16 @@ binder::Status SurfaceComposerAIDL::captureLayers( return binder::Status::fromStatusT(status); } +status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) { + if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) { + IPCThreadState* ipc = IPCThreadState::self(); + ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d", ipc->getCallingPid(), + ipc->getCallingUid()); + return PERMISSION_DENIED; + } + return OK; +} + } // namespace android #if defined(__gl_h_) diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index f09ee5fad0..3670777713 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -517,17 +517,30 @@ private: bool callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache = true) EXCLUDES(mStateLock); + // the following two methods are moved from ISurfaceComposer.h + // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. + std::optional getInternalDisplayId() const { + const auto displayIds = getPhysicalDisplayIds(); + return displayIds.empty() ? std::nullopt : std::make_optional(displayIds.front()); + } + + // TODO(b/74619554): Remove this stopgap once the framework is display-agnostic. + sp getInternalDisplayToken() const { + const auto displayId = getInternalDisplayId(); + return displayId ? getPhysicalDisplayToken(*displayId) : nullptr; + } + // Implements ISurfaceComposer sp createConnection() override; - sp createDisplay(const String8& displayName, bool secure) override; - void destroyDisplay(const sp& displayToken) override; - std::vector getPhysicalDisplayIds() const override EXCLUDES(mStateLock) { + sp createDisplay(const String8& displayName, bool secure); + void destroyDisplay(const sp& displayToken); + std::vector getPhysicalDisplayIds() const EXCLUDES(mStateLock) { Mutex::Autolock lock(mStateLock); return getPhysicalDisplayIdsLocked(); } - status_t getPrimaryPhysicalDisplayId(PhysicalDisplayId*) const override EXCLUDES(mStateLock); + status_t getPrimaryPhysicalDisplayId(PhysicalDisplayId*) const EXCLUDES(mStateLock); - sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const override; + sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const; status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, const Vector& state, const Vector& displays, uint32_t flags, @@ -1414,12 +1427,23 @@ class SurfaceComposerAIDL : public gui::BnSurfaceComposer { public: SurfaceComposerAIDL(sp sf) { mFlinger = sf; } + binder::Status createDisplay(const std::string& displayName, bool secure, + sp* outDisplay) override; + binder::Status destroyDisplay(const sp& display) override; + binder::Status getPhysicalDisplayIds(std::vector* outDisplayIds) override; + binder::Status getPrimaryPhysicalDisplayId(int64_t* outDisplayId) override; + binder::Status getPhysicalDisplayToken(int64_t displayId, sp* outDisplay) override; + binder::Status captureDisplay(const DisplayCaptureArgs&, const sp&) override; binder::Status captureDisplayById(int64_t, const sp&) override; binder::Status captureLayers(const LayerCaptureArgs&, const sp&) override; +private: + static const constexpr bool kUsePermissionCache = true; + status_t checkAccessPermission(bool usePermissionCache = kUsePermissionCache); + private: sp mFlinger; }; -- cgit v1.2.3-59-g8ed1b From 37396db2bf50b039a6942c9fd692ff899bd531de Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 15 Feb 2022 10:43:00 -0800 Subject: Migrate display related methods to AIDL part 2 This migrates more display related methods with simple arguments from ISurfaceComposer.h to the new AIDL interface. Bug: 219574942 Test: atest SurfaceFlinger_test libsurfaceflinger_unittest libgui_test Change-Id: I57f428f6934e784cb234704ad89ef22218e441b4 --- libs/gui/ISurfaceComposer.cpp | 366 --------------------- libs/gui/Surface.cpp | 8 +- libs/gui/SurfaceComposerClient.cpp | 45 ++- libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 106 ++++++ libs/gui/include/gui/ISurfaceComposer.h | 133 +------- libs/gui/include/gui/Surface.h | 5 + libs/gui/include/private/gui/ComposerServiceAIDL.h | 3 +- libs/gui/tests/Surface_test.cpp | 26 -- services/surfaceflinger/SurfaceFlinger.cpp | 152 +++++++-- services/surfaceflinger/SurfaceFlinger.h | 43 ++- .../surfaceflinger/tests/BootDisplayMode_test.cpp | 15 +- 11 files changed, 324 insertions(+), 578 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 6911d89cdb..d7ec9ff1d6 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -220,14 +220,6 @@ public: return result; } - void setPowerMode(const sp& display, int mode) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - data.writeInt32(mode); - remote()->transact(BnSurfaceComposer::SET_POWER_MODE, data, &reply); - } - status_t getDisplayState(const sp& display, ui::DisplayState* state) override { Parcel data, reply; data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); @@ -327,29 +319,6 @@ public: return static_cast(reply.readInt32()); } - // TODO(b/213909104) : Add unit tests to verify surface flinger boot time APIs - status_t getBootDisplayModeSupport(bool* outSupport) const override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("getBootDisplayModeSupport: failed to write interface token: %d", error); - return error; - } - error = remote()->transact(BnSurfaceComposer::GET_BOOT_DISPLAY_MODE_SUPPORT, data, &reply); - if (error != NO_ERROR) { - ALOGE("getBootDisplayModeSupport: failed to transact: %d", error); - return error; - } - bool support; - error = reply.readBool(&support); - if (error != NO_ERROR) { - ALOGE("getBootDisplayModeSupport: failed to read support: %d", error); - return error; - } - *outSupport = support; - return NO_ERROR; - } - status_t setBootDisplayMode(const sp& display, ui::DisplayModeId displayModeId) override { Parcel data, reply; @@ -375,73 +344,6 @@ public: return result; } - status_t clearBootDisplayMode(const sp& display) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("clearBootDisplayMode failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("clearBootDisplayMode failed to writeStrongBinder: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::CLEAR_BOOT_DISPLAY_MODE, data, &reply); - if (result != NO_ERROR) { - ALOGE("clearBootDisplayMode failed to transact: %d", result); - } - return result; - } - - void setAutoLowLatencyMode(const sp& display, bool on) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to writeInterfaceToken: %d", result); - return; - } - - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to writeStrongBinder: %d", result); - return; - } - result = data.writeBool(on); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to writeBool: %d", result); - return; - } - result = remote()->transact(BnSurfaceComposer::SET_AUTO_LOW_LATENCY_MODE, data, &reply); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to transact: %d", result); - return; - } - } - - void setGameContentType(const sp& display, bool on) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to writeInterfaceToken: %d", result); - return; - } - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to writeStrongBinder: %d", result); - return; - } - result = data.writeBool(on); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to writeBool: %d", result); - return; - } - result = remote()->transact(BnSurfaceComposer::SET_GAME_CONTENT_TYPE, data, &reply); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to transact: %d", result); - } - } - status_t clearAnimationFrameStats() override { Parcel data, reply; status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); @@ -716,26 +618,6 @@ public: return error; } - status_t isWideColorDisplay(const sp& token, - bool* outIsWideColorDisplay) const override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - return error; - } - error = data.writeStrongBinder(token); - if (error != NO_ERROR) { - return error; - } - - error = remote()->transact(BnSurfaceComposer::IS_WIDE_COLOR_DISPLAY, data, &reply); - if (error != NO_ERROR) { - return error; - } - error = reply.readBool(outIsWideColorDisplay); - return error; - } - status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, const sp& listener) override { Parcel data, reply; @@ -968,109 +850,6 @@ public: return reply.readInt32(); } - status_t getDisplayBrightnessSupport(const sp& displayToken, - bool* outSupport) const override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("getDisplayBrightnessSupport: failed to write interface token: %d", error); - return error; - } - error = data.writeStrongBinder(displayToken); - if (error != NO_ERROR) { - ALOGE("getDisplayBrightnessSupport: failed to write display token: %d", error); - return error; - } - error = remote()->transact(BnSurfaceComposer::GET_DISPLAY_BRIGHTNESS_SUPPORT, data, &reply); - if (error != NO_ERROR) { - ALOGE("getDisplayBrightnessSupport: failed to transact: %d", error); - return error; - } - bool support; - error = reply.readBool(&support); - if (error != NO_ERROR) { - ALOGE("getDisplayBrightnessSupport: failed to read support: %d", error); - return error; - } - *outSupport = support; - return NO_ERROR; - } - - status_t setDisplayBrightness(const sp& displayToken, - const gui::DisplayBrightness& brightness) override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to write interface token: %d", error); - return error; - } - error = data.writeStrongBinder(displayToken); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to write display token: %d", error); - return error; - } - error = data.writeParcelable(brightness); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to write brightness: %d", error); - return error; - } - error = remote()->transact(BnSurfaceComposer::SET_DISPLAY_BRIGHTNESS, data, &reply); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to transact: %d", error); - return error; - } - return NO_ERROR; - } - - status_t addHdrLayerInfoListener(const sp& displayToken, - const sp& listener) override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, displayToken); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - const status_t error = - remote()->transact(BnSurfaceComposer::ADD_HDR_LAYER_INFO_LISTENER, data, &reply); - if (error != OK) { - ALOGE("addHdrLayerInfoListener: Failed to transact; error = %d", error); - } - return error; - } - - status_t removeHdrLayerInfoListener(const sp& displayToken, - const sp& listener) override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, displayToken); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - const status_t error = - remote()->transact(BnSurfaceComposer::REMOVE_HDR_LAYER_INFO_LISTENER, data, &reply); - if (error != OK) { - ALOGE("removeHdrLayerInfoListener: Failed to transact; error = %d", error); - } - return error; - } - - status_t notifyPowerBoost(int32_t boostId) override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("notifyPowerBoost: failed to write interface token: %d", error); - return error; - } - error = data.writeInt32(boostId); - if (error != NO_ERROR) { - ALOGE("notifyPowerBoost: failed to write boostId: %d", error); - return error; - } - error = remote()->transact(BnSurfaceComposer::NOTIFY_POWER_BOOST, data, &reply, - IBinder::FLAG_ONEWAY); - if (error != NO_ERROR) { - ALOGE("notifyPowerBoost: failed to transact: %d", error); - return error; - } - return NO_ERROR; - } - status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, float lightPosY, float lightPosZ, float lightRadius) override { Parcel data, reply; @@ -1469,15 +1248,6 @@ status_t BnSurfaceComposer::onTransact( result = reply->writeInt32(result); return result; } - case GET_BOOT_DISPLAY_MODE_SUPPORT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - bool support = false; - status_t result = getBootDisplayModeSupport(&support); - if (result == NO_ERROR) { - reply->writeBool(support); - } - return result; - } case SET_BOOT_DISPLAY_MODE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); sp display = nullptr; @@ -1494,50 +1264,6 @@ status_t BnSurfaceComposer::onTransact( } return setBootDisplayMode(display, displayModeId); } - case CLEAR_BOOT_DISPLAY_MODE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("clearBootDisplayMode failed to readStrongBinder: %d", result); - return result; - } - return clearBootDisplayMode(display); - } - case SET_AUTO_LOW_LATENCY_MODE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to readStrongBinder: %d", result); - return result; - } - bool setAllm = false; - result = data.readBool(&setAllm); - if (result != NO_ERROR) { - ALOGE("setAutoLowLatencyMode failed to readBool: %d", result); - return result; - } - setAutoLowLatencyMode(display, setAllm); - return result; - } - case SET_GAME_CONTENT_TYPE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to readStrongBinder: %d", result); - return result; - } - bool setGameContentTypeOn = false; - result = data.readBool(&setGameContentTypeOn); - if (result != NO_ERROR) { - ALOGE("setGameContentType failed to readBool: %d", result); - return result; - } - setGameContentType(display, setGameContentTypeOn); - return result; - } case CLEAR_ANIMATION_FRAME_STATS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); status_t result = clearAnimationFrameStats(); @@ -1552,13 +1278,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeInt32(result); return NO_ERROR; } - case SET_POWER_MODE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = data.readStrongBinder(); - int32_t mode = data.readInt32(); - setPowerMode(display, mode); - return NO_ERROR; - } case ENABLE_VSYNC_INJECTIONS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); bool enable = false; @@ -1708,20 +1427,6 @@ status_t BnSurfaceComposer::onTransact( } return error; } - case IS_WIDE_COLOR_DISPLAY: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t error = data.readStrongBinder(&display); - if (error != NO_ERROR) { - return error; - } - bool result; - error = isWideColorDisplay(display, &result); - if (error == NO_ERROR) { - reply->writeBool(result); - } - return error; - } case ADD_REGION_SAMPLING_LISTENER: { CHECK_INTERFACE(ISurfaceComposer, data, reply); Rect samplingArea; @@ -1919,77 +1624,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeInt32(result); return result; } - case GET_DISPLAY_BRIGHTNESS_SUPPORT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken; - status_t error = data.readNullableStrongBinder(&displayToken); - if (error != NO_ERROR) { - ALOGE("getDisplayBrightnessSupport: failed to read display token: %d", error); - return error; - } - bool support = false; - error = getDisplayBrightnessSupport(displayToken, &support); - reply->writeBool(support); - return error; - } - case SET_DISPLAY_BRIGHTNESS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken; - status_t error = data.readNullableStrongBinder(&displayToken); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to read display token: %d", error); - return error; - } - gui::DisplayBrightness brightness; - error = data.readParcelable(&brightness); - if (error != NO_ERROR) { - ALOGE("setDisplayBrightness: failed to read brightness: %d", error); - return error; - } - return setDisplayBrightness(displayToken, brightness); - } - case ADD_HDR_LAYER_INFO_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken; - status_t error = data.readNullableStrongBinder(&displayToken); - if (error != NO_ERROR) { - ALOGE("addHdrLayerInfoListener: Failed to read display token"); - return error; - } - sp listener; - error = data.readNullableStrongBinder(&listener); - if (error != NO_ERROR) { - ALOGE("addHdrLayerInfoListener: Failed to read listener"); - return error; - } - return addHdrLayerInfoListener(displayToken, listener); - } - case REMOVE_HDR_LAYER_INFO_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken; - status_t error = data.readNullableStrongBinder(&displayToken); - if (error != NO_ERROR) { - ALOGE("removeHdrLayerInfoListener: Failed to read display token"); - return error; - } - sp listener; - error = data.readNullableStrongBinder(&listener); - if (error != NO_ERROR) { - ALOGE("removeHdrLayerInfoListener: Failed to read listener"); - return error; - } - return removeHdrLayerInfoListener(displayToken, listener); - } - case NOTIFY_POWER_BOOST: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int32_t boostId; - status_t error = data.readInt32(&boostId); - if (error != NO_ERROR) { - ALOGE("notifyPowerBoost: failed to read boostId: %d", error); - return error; - } - return notifyPowerBoost(boostId); - } case SET_GLOBAL_SHADOW_SETTINGS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index 82067580a9..ceb517f2ff 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -126,6 +126,10 @@ sp Surface::composerService() const { return ComposerService::getComposerService(); } +sp Surface::composerServiceAIDL() const { + return ComposerServiceAIDL::getComposerService(); +} + nsecs_t Surface::now() const { return systemTime(); } @@ -350,8 +354,8 @@ status_t Surface::getWideColorSupport(bool* supported) { } *supported = false; - status_t error = composerService()->isWideColorDisplay(display, supported); - return error; + binder::Status status = composerServiceAIDL()->isWideColorDisplay(display, supported); + return status.transactionError(); } status_t Surface::getHdrSupport(bool* supported) { diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 52d89657b5..6b2cda19a0 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2158,7 +2158,9 @@ status_t SurfaceComposerClient::setActiveColorMode(const sp& display, } status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) { - return ComposerService::getComposerService()->getBootDisplayModeSupport(support); + binder::Status status = + ComposerServiceAIDL::getComposerService()->getBootDisplayModeSupport(support); + return status.transactionError(); } status_t SurfaceComposerClient::setBootDisplayMode(const sp& display, @@ -2167,7 +2169,9 @@ status_t SurfaceComposerClient::setBootDisplayMode(const sp& display, } status_t SurfaceComposerClient::clearBootDisplayMode(const sp& display) { - return ComposerService::getComposerService()->clearBootDisplayMode(display); + binder::Status status = + ComposerServiceAIDL::getComposerService()->clearBootDisplayMode(display); + return status.transactionError(); } status_t SurfaceComposerClient::setOverrideFrameRate(uid_t uid, float frameRate) { @@ -2175,16 +2179,16 @@ status_t SurfaceComposerClient::setOverrideFrameRate(uid_t uid, float frameRate) } void SurfaceComposerClient::setAutoLowLatencyMode(const sp& display, bool on) { - ComposerService::getComposerService()->setAutoLowLatencyMode(display, on); + ComposerServiceAIDL::getComposerService()->setAutoLowLatencyMode(display, on); } void SurfaceComposerClient::setGameContentType(const sp& display, bool on) { - ComposerService::getComposerService()->setGameContentType(display, on); + ComposerServiceAIDL::getComposerService()->setGameContentType(display, on); } void SurfaceComposerClient::setDisplayPowerMode(const sp& token, int mode) { - ComposerService::getComposerService()->setPowerMode(token, mode); + ComposerServiceAIDL::getComposerService()->setPowerMode(token, mode); } status_t SurfaceComposerClient::getCompositionPreference( @@ -2245,8 +2249,10 @@ status_t SurfaceComposerClient::getDisplayedContentSample(const sp& dis status_t SurfaceComposerClient::isWideColorDisplay(const sp& display, bool* outIsWideColorDisplay) { - return ComposerService::getComposerService()->isWideColorDisplay(display, - outIsWideColorDisplay); + binder::Status status = + ComposerServiceAIDL::getComposerService()->isWideColorDisplay(display, + outIsWideColorDisplay); + return status.transactionError(); } status_t SurfaceComposerClient::addRegionSamplingListener( @@ -2283,28 +2289,39 @@ status_t SurfaceComposerClient::removeTunnelModeEnabledListener( bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp& displayToken) { bool support = false; - ComposerService::getComposerService()->getDisplayBrightnessSupport(displayToken, &support); - return support; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDisplayBrightnessSupport(displayToken, + &support); + return status.isOk() ? support : false; } status_t SurfaceComposerClient::setDisplayBrightness(const sp& displayToken, const gui::DisplayBrightness& brightness) { - return ComposerService::getComposerService()->setDisplayBrightness(displayToken, brightness); + binder::Status status = + ComposerServiceAIDL::getComposerService()->setDisplayBrightness(displayToken, + brightness); + return status.transactionError(); } status_t SurfaceComposerClient::addHdrLayerInfoListener( const sp& displayToken, const sp& listener) { - return ComposerService::getComposerService()->addHdrLayerInfoListener(displayToken, listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->addHdrLayerInfoListener(displayToken, + listener); + return status.transactionError(); } status_t SurfaceComposerClient::removeHdrLayerInfoListener( const sp& displayToken, const sp& listener) { - return ComposerService::getComposerService()->removeHdrLayerInfoListener(displayToken, - listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->removeHdrLayerInfoListener(displayToken, + listener); + return status.transactionError(); } status_t SurfaceComposerClient::notifyPowerBoost(int32_t boostId) { - return ComposerService::getComposerService()->notifyPowerBoost(boostId); + binder::Status status = ComposerServiceAIDL::getComposerService()->notifyPowerBoost(boostId); + return status.transactionError(); } status_t SurfaceComposerClient::setGlobalShadowSettings(const half4& ambientColor, diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 345c47d5b9..526fae8e55 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -17,6 +17,8 @@ package android.gui; import android.gui.DisplayCaptureArgs; +import android.gui.DisplayBrightness; +import android.gui.IHdrLayerInfoListener; import android.gui.LayerCaptureArgs; import android.gui.IScreenCaptureListener; @@ -44,6 +46,47 @@ interface ISurfaceComposer { */ @nullable IBinder getPhysicalDisplayToken(long displayId); + /* set display power mode. depending on the mode, it can either trigger + * screen on, off or low power mode and wait for it to complete. + * requires ACCESS_SURFACE_FLINGER permission. + */ + void setPowerMode(IBinder display, int mode); + + /** + * Clears the user-preferred display mode. The device should now boot in system preferred + * display mode. + */ + void clearBootDisplayMode(IBinder display); + + /** + * Gets whether boot time display mode operations are supported on the device. + * + * outSupport + * An output parameter for whether boot time display mode operations are supported. + * + * Returns NO_ERROR upon success. Otherwise, + * NAME_NOT_FOUND if the display is invalid, or + * BAD_VALUE if the output parameter is invalid. + */ + // TODO(b/213909104) : Add unit tests to verify surface flinger boot time APIs + boolean getBootDisplayModeSupport(); + + /** + * Switches Auto Low Latency Mode on/off on the connected display, if it is + * available. This should only be called if the display supports Auto Low + * Latency Mode as reported in #getDynamicDisplayInfo. + * For more information, see the HDMI 2.1 specification. + */ + void setAutoLowLatencyMode(IBinder display, boolean on); + + /** + * This will start sending infoframes to the connected display with + * ContentType=Game (if on=true). This should only be called if the display + * Game Content Type as reported in #getDynamicDisplayInfo. + * For more information, see the HDMI 1.4 specification. + */ + void setGameContentType(IBinder display, boolean on); + /** * Capture the specified screen. This requires READ_FRAME_BUFFER * permission. This function will fail if there is a secure window on @@ -61,4 +104,67 @@ interface ISurfaceComposer { * is a secure window on screen */ void captureLayers(in LayerCaptureArgs args, IScreenCaptureListener listener); + + /* + * Queries whether the given display is a wide color display. + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + boolean isWideColorDisplay(IBinder token); + + /* + * Gets whether brightness operations are supported on a display. + * + * displayToken + * The token of the display. + * outSupport + * An output parameter for whether brightness operations are supported. + * + * Returns NO_ERROR upon success. Otherwise, + * NAME_NOT_FOUND if the display is invalid, or + * BAD_VALUE if the output parameter is invalid. + */ + boolean getDisplayBrightnessSupport(IBinder displayToken); + + /* + * Sets the brightness of a display. + * + * displayToken + * The token of the display whose brightness is set. + * brightness + * The DisplayBrightness info to set on the desired display. + * + * Returns NO_ERROR upon success. Otherwise, + * NAME_NOT_FOUND if the display is invalid, or + * BAD_VALUE if the brightness is invalid, or + * INVALID_OPERATION if brightness operations are not supported. + */ + void setDisplayBrightness(IBinder displayToken, in DisplayBrightness brightness); + + /* + * Adds a listener that receives HDR layer information. This is used in combination + * with setDisplayBrightness to adjust the display brightness depending on factors such + * as whether or not HDR is in use. + * + * Returns NO_ERROR upon success or NAME_NOT_FOUND if the display is invalid. + */ + void addHdrLayerInfoListener(IBinder displayToken, IHdrLayerInfoListener listener); + + /* + * Removes a listener that was added with addHdrLayerInfoListener. + * + * Returns NO_ERROR upon success, NAME_NOT_FOUND if the display is invalid, and BAD_VALUE if + * the listener wasn't registered. + * + */ + void removeHdrLayerInfoListener(IBinder displayToken, IHdrLayerInfoListener listener); + + /* + * Sends a power boost to the composer. This function is asynchronous. + * + * boostId + * boost id according to android::hardware::power::Boost + * + * Returns NO_ERROR upon success. + */ + void notifyPowerBoost(int boostId); } diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index a2870db2fa..0a2ae35044 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -160,13 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - /* set display power mode. depending on the mode, it can either trigger - * screen on, off or low power mode and wait for it to complete. - * requires ACCESS_SURFACE_FLINGER permission. - */ - virtual void setPowerMode(const sp& display, int mode) = 0; - - /* returns display statistics for a given display * intended to be used by the media framework to properly schedule * video frames */ @@ -198,40 +191,6 @@ public: */ virtual status_t setBootDisplayMode(const sp& display, ui::DisplayModeId) = 0; - /** - * Clears the user-preferred display mode. The device should now boot in system preferred - * display mode. - */ - virtual status_t clearBootDisplayMode(const sp& display) = 0; - - /** - * Gets whether boot time display mode operations are supported on the device. - * - * outSupport - * An output parameter for whether boot time display mode operations are supported. - * - * Returns NO_ERROR upon success. Otherwise, - * NAME_NOT_FOUND if the display is invalid, or - * BAD_VALUE if the output parameter is invalid. - */ - virtual status_t getBootDisplayModeSupport(bool* outSupport) const = 0; - - /** - * Switches Auto Low Latency Mode on/off on the connected display, if it is - * available. This should only be called if the display supports Auto Low - * Latency Mode as reported in #getDynamicDisplayInfo. - * For more information, see the HDMI 2.1 specification. - */ - virtual void setAutoLowLatencyMode(const sp& display, bool on) = 0; - - /** - * This will start sending infoframes to the connected display with - * ContentType=Game (if on=true). This should only be called if the display - * Game Content Type as reported in #getDynamicDisplayInfo. - * For more information, see the HDMI 1.4 specification. - */ - virtual void setGameContentType(const sp& display, bool on) = 0; - /* Clears the frame statistics for animations. * * Requires the ACCESS_SURFACE_FLINGER permission. @@ -310,13 +269,6 @@ public: */ virtual status_t getProtectedContentSupport(bool* outSupported) const = 0; - /* - * Queries whether the given display is a wide color display. - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t isWideColorDisplay(const sp& token, - bool* outIsWideColorDisplay) const = 0; - /* Registers a listener to stream median luma updates from SurfaceFlinger. * * The sampling area is bounded by both samplingArea and the given stopLayerHandle @@ -397,65 +349,6 @@ public: float* outPrimaryRefreshRateMax, float* outAppRequestRefreshRateMin, float* outAppRequestRefreshRateMax) = 0; - /* - * Gets whether brightness operations are supported on a display. - * - * displayToken - * The token of the display. - * outSupport - * An output parameter for whether brightness operations are supported. - * - * Returns NO_ERROR upon success. Otherwise, - * NAME_NOT_FOUND if the display is invalid, or - * BAD_VALUE if the output parameter is invalid. - */ - virtual status_t getDisplayBrightnessSupport(const sp& displayToken, - bool* outSupport) const = 0; - - /* - * Sets the brightness of a display. - * - * displayToken - * The token of the display whose brightness is set. - * brightness - * The DisplayBrightness info to set on the desired display. - * - * Returns NO_ERROR upon success. Otherwise, - * NAME_NOT_FOUND if the display is invalid, or - * BAD_VALUE if the brightness is invalid, or - * INVALID_OPERATION if brightness operations are not supported. - */ - virtual status_t setDisplayBrightness(const sp& displayToken, - const gui::DisplayBrightness& brightness) = 0; - - /* - * Adds a listener that receives HDR layer information. This is used in combination - * with setDisplayBrightness to adjust the display brightness depending on factors such - * as whether or not HDR is in use. - * - * Returns NO_ERROR upon success or NAME_NOT_FOUND if the display is invalid. - */ - virtual status_t addHdrLayerInfoListener(const sp& displayToken, - const sp& listener) = 0; - /* - * Removes a listener that was added with addHdrLayerInfoListener. - * - * Returns NO_ERROR upon success, NAME_NOT_FOUND if the display is invalid, and BAD_VALUE if - * the listener wasn't registered. - * - */ - virtual status_t removeHdrLayerInfoListener(const sp& displayToken, - const sp& listener) = 0; - - /* - * Sends a power boost to the composer. This function is asynchronous. - * - * boostId - * boost id according to android::hardware::power::Boost - * - * Returns NO_ERROR upon success. - */ - virtual status_t notifyPowerBoost(int32_t boostId) = 0; /* * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows @@ -575,7 +468,7 @@ public: CAPTURE_LAYERS, // Deprecated. Autogenerated by .aidl now. CLEAR_ANIMATION_FRAME_STATS, GET_ANIMATION_FRAME_STATS, - SET_POWER_MODE, + SET_POWER_MODE, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_STATS, GET_HDR_CAPABILITIES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_DISPLAY_COLOR_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. @@ -590,22 +483,22 @@ public: SET_DISPLAY_CONTENT_SAMPLING_ENABLED, GET_DISPLAYED_CONTENT_SAMPLE, GET_PROTECTED_CONTENT_SUPPORT, - IS_WIDE_COLOR_DISPLAY, + IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_NATIVE_PRIMARIES, GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. ADD_REGION_SAMPLING_LISTENER, REMOVE_REGION_SAMPLING_LISTENER, SET_DESIRED_DISPLAY_MODE_SPECS, GET_DESIRED_DISPLAY_MODE_SPECS, - GET_DISPLAY_BRIGHTNESS_SUPPORT, - SET_DISPLAY_BRIGHTNESS, - CAPTURE_DISPLAY_BY_ID, // Deprecated. Autogenerated by .aidl now. - NOTIFY_POWER_BOOST, + GET_DISPLAY_BRIGHTNESS_SUPPORT, // Deprecated. Autogenerated by .aidl now. + SET_DISPLAY_BRIGHTNESS, // Deprecated. Autogenerated by .aidl now. + CAPTURE_DISPLAY_BY_ID, // Deprecated. Autogenerated by .aidl now. + NOTIFY_POWER_BOOST, // Deprecated. Autogenerated by .aidl now. SET_GLOBAL_SHADOW_SETTINGS, GET_AUTO_LOW_LATENCY_MODE_SUPPORT, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - SET_AUTO_LOW_LATENCY_MODE, - GET_GAME_CONTENT_TYPE_SUPPORT, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - SET_GAME_CONTENT_TYPE, + SET_AUTO_LOW_LATENCY_MODE, // Deprecated. Autogenerated by .aidl now. + GET_GAME_CONTENT_TYPE_SUPPORT, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + SET_GAME_CONTENT_TYPE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. SET_FRAME_RATE, // Deprecated. Use DisplayManager.setShouldAlwaysRespectAppRequestedMode(true); ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN, @@ -617,8 +510,8 @@ public: ADD_FPS_LISTENER, REMOVE_FPS_LISTENER, OVERRIDE_HDR_TYPES, - ADD_HDR_LAYER_INFO_LISTENER, - REMOVE_HDR_LAYER_INFO_LISTENER, + ADD_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. ON_PULL_ATOM, ADD_TUNNEL_MODE_ENABLED_LISTENER, REMOVE_TUNNEL_MODE_ENABLED_LISTENER, @@ -626,9 +519,9 @@ public: REMOVE_WINDOW_INFOS_LISTENER, GET_PRIMARY_PHYSICAL_DISPLAY_ID, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_DECORATION_SUPPORT, - GET_BOOT_DISPLAY_MODE_SUPPORT, + GET_BOOT_DISPLAY_MODE_SUPPORT, // Deprecated. Autogenerated by .aidl now. SET_BOOT_DISPLAY_MODE, - CLEAR_BOOT_DISPLAY_MODE, + CLEAR_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. SET_OVERRIDE_FRAME_RATE, // Always append new enum to the end. }; diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h index 40d096e1e5..ba9ee6c752 100644 --- a/libs/gui/include/gui/Surface.h +++ b/libs/gui/include/gui/Surface.h @@ -35,6 +35,10 @@ namespace android { +namespace gui { +class ISurfaceComposer; +} // namespace gui + class ISurfaceComposer; /* This is the same as ProducerListener except that onBuffersDiscarded is @@ -196,6 +200,7 @@ protected: // Virtual for testing. virtual sp composerService() const; + virtual sp composerServiceAIDL() const; virtual nsecs_t now() const; private: diff --git a/libs/gui/include/private/gui/ComposerServiceAIDL.h b/libs/gui/include/private/gui/ComposerServiceAIDL.h index b32cf2a9c2..9a96976c0f 100644 --- a/libs/gui/include/private/gui/ComposerServiceAIDL.h +++ b/libs/gui/include/private/gui/ComposerServiceAIDL.h @@ -68,7 +68,8 @@ public: if (!displayId) return nullptr; sp display; binder::Status status = - mComposerService->getPhysicalDisplayToken(displayId->value, &display); + mComposerService->getPhysicalDisplayToken(static_cast(displayId->value), + &display); return status.isOk() ? display : nullptr; } }; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 07ac2d4065..ec9cba56a2 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -732,7 +732,6 @@ public: return NO_ERROR; } - void setPowerMode(const sp& /*display*/, int /*mode*/) override {} status_t getStaticDisplayInfo(const sp& /*display*/, ui::StaticDisplayInfo*) override { return NO_ERROR; } @@ -751,13 +750,9 @@ public: } status_t setActiveColorMode(const sp& /*display*/, ColorMode /*colorMode*/) override { return NO_ERROR; } - status_t getBootDisplayModeSupport(bool* /*outSupport*/) const override { return NO_ERROR; } status_t setBootDisplayMode(const sp& /*display*/, ui::DisplayModeId /*id*/) override { return NO_ERROR; } - status_t clearBootDisplayMode(const sp& /*display*/) override { return NO_ERROR; } - void setAutoLowLatencyMode(const sp& /*display*/, bool /*on*/) override {} - void setGameContentType(const sp& /*display*/, bool /*on*/) override {} status_t clearAnimationFrameStats() override { return NO_ERROR; } status_t getAnimationFrameStats(FrameStats* /*outStats*/) const override { @@ -804,26 +799,6 @@ public: status_t getColorManagement(bool* /*outGetColorManagement*/) const override { return NO_ERROR; } status_t getProtectedContentSupport(bool* /*outSupported*/) const override { return NO_ERROR; } - status_t isWideColorDisplay(const sp&, bool*) const override { return NO_ERROR; } - status_t getDisplayBrightnessSupport(const sp& /*displayToken*/, - bool* /*outSupport*/) const override { - return NO_ERROR; - } - status_t setDisplayBrightness(const sp& /*displayToken*/, - const gui::DisplayBrightness& /*brightness*/) override { - return NO_ERROR; - } - - status_t addHdrLayerInfoListener(const sp&, - const sp&) override { - return NO_ERROR; - } - - status_t removeHdrLayerInfoListener(const sp&, - const sp&) override { - return NO_ERROR; - } - status_t addRegionSamplingListener(const Rect& /*samplingArea*/, const sp& /*stopLayerHandle*/, const sp& /*listener*/) override { @@ -865,7 +840,6 @@ public: float* /*outAppRequestRefreshRateMax*/) override { return NO_ERROR; }; - status_t notifyPowerBoost(int32_t /*boostId*/) override { return NO_ERROR; } status_t setGlobalShadowSettings(const half4& /*ambientColor*/, const half4& /*spotColor*/, float /*lightPosY*/, float /*lightPosZ*/, diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 779344b299..5ff722b11a 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5418,20 +5418,14 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case SET_DESIRED_DISPLAY_MODE_SPECS: case GET_DESIRED_DISPLAY_MODE_SPECS: case SET_ACTIVE_COLOR_MODE: - case GET_BOOT_DISPLAY_MODE_SUPPORT: case SET_BOOT_DISPLAY_MODE: - case CLEAR_BOOT_DISPLAY_MODE: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: - case SET_AUTO_LOW_LATENCY_MODE: case GET_GAME_CONTENT_TYPE_SUPPORT: - case SET_GAME_CONTENT_TYPE: - case SET_POWER_MODE: case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: case GET_DISPLAYED_CONTENT_SAMPLE: case ADD_TUNNEL_MODE_ENABLED_LISTENER: case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: - case NOTIFY_POWER_BOOST: case SET_GLOBAL_SHADOW_SETTINGS: case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: { // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary @@ -5478,11 +5472,9 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_COLOR_MANAGEMENT: case GET_COMPOSITION_PREFERENCE: case GET_PROTECTED_CONTENT_SUPPORT: - case IS_WIDE_COLOR_DISPLAY: // setFrameRate() is deliberately available for apps to call without any // special permissions. case SET_FRAME_RATE: - case GET_DISPLAY_BRIGHTNESS_SUPPORT: case GET_DISPLAY_DECORATION_SUPPORT: case SET_FRAME_TIMELINE_INFO: case GET_GPU_CONTEXT_PRIORITY: @@ -5490,19 +5482,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // This is not sensitive information, so should not require permission control. return OK; } - case SET_DISPLAY_BRIGHTNESS: - case ADD_HDR_LAYER_INFO_LISTENER: - case REMOVE_HDR_LAYER_INFO_LISTENER: { - IPCThreadState* ipc = IPCThreadState::self(); - const int pid = ipc->getCallingPid(); - const int uid = ipc->getCallingUid(); - if ((uid != AID_GRAPHICS) && - !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) { - ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid); - return PERMISSION_DENIED; - } - return OK; - } case ADD_FPS_LISTENER: case REMOVE_FPS_LISTENER: case ADD_REGION_SAMPLING_LISTENER: @@ -5553,9 +5532,20 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_PRIMARY_PHYSICAL_DISPLAY_ID: case GET_PHYSICAL_DISPLAY_IDS: case GET_PHYSICAL_DISPLAY_TOKEN: + case SET_POWER_MODE: + case CLEAR_BOOT_DISPLAY_MODE: + case GET_BOOT_DISPLAY_MODE_SUPPORT: + case SET_AUTO_LOW_LATENCY_MODE: + case SET_GAME_CONTENT_TYPE: case CAPTURE_LAYERS: case CAPTURE_DISPLAY: case CAPTURE_DISPLAY_BY_ID: + case IS_WIDE_COLOR_DISPLAY: + case GET_DISPLAY_BRIGHTNESS_SUPPORT: + case SET_DISPLAY_BRIGHTNESS: + case ADD_HDR_LAYER_INFO_LISTENER: + case REMOVE_HDR_LAYER_INFO_LISTENER: + case NOTIFY_POWER_BOOST: LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code); return PERMISSION_DENIED; } @@ -7212,21 +7202,21 @@ bool SurfaceFlinger::commitCreatedLayers() { binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure, sp* outDisplay) { status_t status = checkAccessPermission(); - if (status == OK) { - String8 displayName8 = String8::format("%s", displayName.c_str()); - *outDisplay = mFlinger->createDisplay(displayName8, secure); - return binder::Status::ok(); + if (status != OK) { + return binder::Status::fromStatusT(status); } - return binder::Status::fromStatusT(status); + String8 displayName8 = String8::format("%s", displayName.c_str()); + *outDisplay = mFlinger->createDisplay(displayName8, secure); + return binder::Status::ok(); } binder::Status SurfaceComposerAIDL::destroyDisplay(const sp& display) { status_t status = checkAccessPermission(); - if (status == OK) { - mFlinger->destroyDisplay(display); - return binder::Status::ok(); + if (status != OK) { + return binder::Status::fromStatusT(status); } - return binder::Status::fromStatusT(status); + mFlinger->destroyDisplay(display); + return binder::Status::ok(); } binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector* outDisplayIds) { @@ -7261,6 +7251,49 @@ binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId, return binder::Status::ok(); } +binder::Status SurfaceComposerAIDL::setPowerMode(const sp& display, int mode) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + mFlinger->setPowerMode(display, mode); + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->clearBootDisplayMode(display); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->getBootDisplayModeSupport(outMode); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp& display, bool on) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + mFlinger->setAutoLowLatencyMode(display, on); + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::setGameContentType(const sp& display, bool on) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + mFlinger->setGameContentType(display, on); + return binder::Status::ok(); +} + binder::Status SurfaceComposerAIDL::captureDisplay( const DisplayCaptureArgs& args, const sp& captureListener) { status_t status = mFlinger->captureDisplay(args, captureListener); @@ -7287,6 +7320,53 @@ binder::Status SurfaceComposerAIDL::captureLayers( return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp& token, + bool* outIsWideColorDisplay) { + status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp& displayToken, + bool* outSupport) { + status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp& displayToken, + const gui::DisplayBrightness& brightness) { + status_t status = checkControlDisplayBrightnessPermission(); + if (status == OK) { + status = mFlinger->setDisplayBrightness(displayToken, brightness); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener( + const sp& displayToken, const sp& listener) { + status_t status = checkControlDisplayBrightnessPermission(); + if (status == OK) { + status = mFlinger->addHdrLayerInfoListener(displayToken, listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener( + const sp& displayToken, const sp& listener) { + status_t status = checkControlDisplayBrightnessPermission(); + if (status == OK) { + status = mFlinger->removeHdrLayerInfoListener(displayToken, listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->notifyPowerBoost(boostId); + } + return binder::Status::fromStatusT(status); +} + status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) { if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) { IPCThreadState* ipc = IPCThreadState::self(); @@ -7297,6 +7377,18 @@ status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) { return OK; } +status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() { + IPCThreadState* ipc = IPCThreadState::self(); + const int pid = ipc->getCallingPid(); + const int uid = ipc->getCallingUid(); + if ((uid != AID_GRAPHICS) && + !PermissionCache::checkPermission(sControlDisplayBrightness, pid, uid)) { + ALOGE("Permission Denial: can't control brightness pid=%d, uid=%d", pid, uid); + return PERMISSION_DENIED; + } + return OK; +} + } // namespace android #if defined(__gl_h_) diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index d7e5207f20..95c07eb054 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -572,12 +572,12 @@ private: status_t getDisplayNativePrimaries(const sp& displayToken, ui::DisplayPrimaries&) override; status_t setActiveColorMode(const sp& displayToken, ui::ColorMode colorMode) override; - status_t getBootDisplayModeSupport(bool* outSupport) const override; + status_t getBootDisplayModeSupport(bool* outSupport) const; status_t setBootDisplayMode(const sp& displayToken, ui::DisplayModeId id) override; - status_t clearBootDisplayMode(const sp& displayToken) override; - void setAutoLowLatencyMode(const sp& displayToken, bool on) override; - void setGameContentType(const sp& displayToken, bool on) override; - void setPowerMode(const sp& displayToken, int mode) override; + status_t clearBootDisplayMode(const sp& displayToken); + void setAutoLowLatencyMode(const sp& displayToken, bool on); + void setGameContentType(const sp& displayToken, bool on); + void setPowerMode(const sp& displayToken, int mode); status_t clearAnimationFrameStats() override; status_t getAnimationFrameStats(FrameStats* outStats) const override; status_t overrideHdrTypes(const sp& displayToken, @@ -600,8 +600,7 @@ private: uint64_t timestamp, DisplayedFrameStats* outStats) const override; status_t getProtectedContentSupport(bool* outSupported) const override; - status_t isWideColorDisplay(const sp& displayToken, - bool* outIsWideColorDisplay) const override; + status_t isWideColorDisplay(const sp& displayToken, bool* outIsWideColorDisplay) const; status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, const sp& listener) override; status_t removeRegionSamplingListener(const sp& listener) override; @@ -623,15 +622,14 @@ private: float* outPrimaryRefreshRateMax, float* outAppRequestRefreshRateMin, float* outAppRequestRefreshRateMax) override; - status_t getDisplayBrightnessSupport(const sp& displayToken, - bool* outSupport) const override; + status_t getDisplayBrightnessSupport(const sp& displayToken, bool* outSupport) const; status_t setDisplayBrightness(const sp& displayToken, - const gui::DisplayBrightness& brightness) override; + const gui::DisplayBrightness& brightness); status_t addHdrLayerInfoListener(const sp& displayToken, - const sp& listener) override; + const sp& listener); status_t removeHdrLayerInfoListener(const sp& displayToken, - const sp& listener) override; - status_t notifyPowerBoost(int32_t boostId) override; + const sp& listener); + status_t notifyPowerBoost(int32_t boostId); status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, float lightPosY, float lightPosZ, float lightRadius) override; status_t getDisplayDecorationSupport( @@ -1439,16 +1437,33 @@ public: binder::Status getPhysicalDisplayIds(std::vector* outDisplayIds) override; binder::Status getPrimaryPhysicalDisplayId(int64_t* outDisplayId) override; binder::Status getPhysicalDisplayToken(int64_t displayId, sp* outDisplay) override; - + binder::Status setPowerMode(const sp& display, int mode) override; + binder::Status clearBootDisplayMode(const sp& display) override; + binder::Status getBootDisplayModeSupport(bool* outMode) override; + binder::Status setAutoLowLatencyMode(const sp& display, bool on) override; + binder::Status setGameContentType(const sp& display, bool on) override; binder::Status captureDisplay(const DisplayCaptureArgs&, const sp&) override; binder::Status captureDisplayById(int64_t, const sp&) override; binder::Status captureLayers(const LayerCaptureArgs&, const sp&) override; + binder::Status isWideColorDisplay(const sp& token, + bool* outIsWideColorDisplay) override; + binder::Status getDisplayBrightnessSupport(const sp& displayToken, + bool* outSupport) override; + binder::Status setDisplayBrightness(const sp& displayToken, + const gui::DisplayBrightness& brightness) override; + binder::Status addHdrLayerInfoListener(const sp& displayToken, + const sp& listener) override; + binder::Status removeHdrLayerInfoListener( + const sp& displayToken, + const sp& listener) override; + binder::Status notifyPowerBoost(int boostId) override; private: static const constexpr bool kUsePermissionCache = true; status_t checkAccessPermission(bool usePermissionCache = kUsePermissionCache); + status_t checkControlDisplayBrightnessPermission(); private: sp mFlinger; diff --git a/services/surfaceflinger/tests/BootDisplayMode_test.cpp b/services/surfaceflinger/tests/BootDisplayMode_test.cpp index abdb16debf..d70908e390 100644 --- a/services/surfaceflinger/tests/BootDisplayMode_test.cpp +++ b/services/surfaceflinger/tests/BootDisplayMode_test.cpp @@ -20,28 +20,33 @@ #include #include +#include #include namespace android { TEST(BootDisplayModeTest, setBootDisplayMode) { sp sf(ComposerService::getComposerService()); + sp sf_aidl(ComposerServiceAIDL::getComposerService()); auto displayToken = SurfaceComposerClient::getInternalDisplayToken(); bool bootModeSupport = false; - ASSERT_NO_FATAL_FAILURE(sf->getBootDisplayModeSupport(&bootModeSupport)); + binder::Status status = sf_aidl->getBootDisplayModeSupport(&bootModeSupport); + ASSERT_NO_FATAL_FAILURE(status.transactionError()); if (bootModeSupport) { ASSERT_EQ(NO_ERROR, sf->setBootDisplayMode(displayToken, 0)); } } TEST(BootDisplayModeTest, clearBootDisplayMode) { - sp sf(ComposerService::getComposerService()); + sp sf(ComposerServiceAIDL::getComposerService()); auto displayToken = SurfaceComposerClient::getInternalDisplayToken(); bool bootModeSupport = false; - ASSERT_NO_FATAL_FAILURE(sf->getBootDisplayModeSupport(&bootModeSupport)); + binder::Status status = sf->getBootDisplayModeSupport(&bootModeSupport); + ASSERT_NO_FATAL_FAILURE(status.transactionError()); if (bootModeSupport) { - ASSERT_EQ(NO_ERROR, sf->clearBootDisplayMode(displayToken)); + status = sf->clearBootDisplayMode(displayToken); + ASSERT_EQ(NO_ERROR, status.transactionError()); } } -} // namespace android \ No newline at end of file +} // namespace android -- cgit v1.2.3-59-g8ed1b From aa7fc2e4495398a717a4fe0ffbfd783e3a887cec Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 15 Feb 2022 10:43:00 -0800 Subject: Migrate display related methods to AIDL part 3 This migrates more display related methods from ISurfaceComposer.h to the new AIDL interface. (1) migrate getDisplaySttas() and getDisplayState() methods (2) add new parcelables, android.gui.DisplayState, anddroid.gui.DisplayStatInfo and other utilities. (3) all parceables are added into libgui, instead of libui, so libui is isolated from binder serialization code,which is cleaner and avoids libbinder linking errors. Bug: 220043617 Bug: 219574942 Test: atest SurfaceFlinger_test libsurfaceflinger_unittest libgui_test Change-Id: Iacdc42dde1608f883c5578aa3d9f9f8ae9f23038 --- libs/gui/ISurfaceComposer.cpp | 50 ----------- libs/gui/Surface.cpp | 10 +-- libs/gui/SurfaceComposerClient.cpp | 13 ++- libs/gui/aidl/android/gui/DisplayStatInfo.aidl | 23 +++++ libs/gui/aidl/android/gui/DisplayState.aidl | 27 ++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 12 +++ libs/gui/aidl/android/gui/Rect.aidl | 35 ++++++++ libs/gui/aidl/android/gui/Rotation.aidl | 26 ++++++ libs/gui/aidl/android/gui/Size.aidl | 23 +++++ libs/gui/include/gui/ISurfaceComposer.h | 11 --- libs/gui/tests/Surface_test.cpp | 114 ++++++++++++++++++++++-- services/surfaceflinger/SurfaceFlinger.cpp | 28 +++++- services/surfaceflinger/SurfaceFlinger.h | 11 ++- 13 files changed, 306 insertions(+), 77 deletions(-) create mode 100644 libs/gui/aidl/android/gui/DisplayStatInfo.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayState.aidl create mode 100644 libs/gui/aidl/android/gui/Rect.aidl create mode 100644 libs/gui/aidl/android/gui/Rotation.aidl create mode 100644 libs/gui/aidl/android/gui/Size.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index d7ec9ff1d6..3c02e21aff 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -220,18 +220,6 @@ public: return result; } - status_t getDisplayState(const sp& display, ui::DisplayState* state) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - remote()->transact(BnSurfaceComposer::GET_DISPLAY_STATE, data, &reply); - const status_t result = reply.readInt32(); - if (result == NO_ERROR) { - memcpy(state, reply.readInplace(sizeof(ui::DisplayState)), sizeof(ui::DisplayState)); - } - return result; - } - status_t getStaticDisplayInfo(const sp& display, ui::StaticDisplayInfo* info) override { Parcel data, reply; @@ -254,20 +242,6 @@ public: return reply.read(*info); } - status_t getDisplayStats(const sp& display, DisplayStatInfo* stats) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - remote()->transact(BnSurfaceComposer::GET_DISPLAY_STATS, data, &reply); - status_t result = reply.readInt32(); - if (result == NO_ERROR) { - memcpy(stats, - reply.readInplace(sizeof(DisplayStatInfo)), - sizeof(DisplayStatInfo)); - } - return result; - } - status_t getDisplayNativePrimaries(const sp& display, ui::DisplayPrimaries& primaries) override { Parcel data, reply; @@ -1165,18 +1139,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case GET_DISPLAY_STATE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - ui::DisplayState state; - const sp display = data.readStrongBinder(); - const status_t result = getDisplayState(display, &state); - reply->writeInt32(result); - if (result == NO_ERROR) { - memcpy(reply->writeInplace(sizeof(ui::DisplayState)), &state, - sizeof(ui::DisplayState)); - } - return NO_ERROR; - } case GET_STATIC_DISPLAY_INFO: { CHECK_INTERFACE(ISurfaceComposer, data, reply); ui::StaticDisplayInfo info; @@ -1197,18 +1159,6 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(reply->write, info); return NO_ERROR; } - case GET_DISPLAY_STATS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - DisplayStatInfo stats; - sp display = data.readStrongBinder(); - status_t result = getDisplayStats(display, &stats); - reply->writeInt32(result); - if (result == NO_ERROR) { - memcpy(reply->writeInplace(sizeof(DisplayStatInfo)), - &stats, sizeof(DisplayStatInfo)); - } - return NO_ERROR; - } case GET_DISPLAY_NATIVE_PRIMARIES: { CHECK_INTERFACE(ISurfaceComposer, data, reply); ui::DisplayPrimaries primaries; diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index ceb517f2ff..0f0a5c8504 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -27,13 +27,13 @@ #include +#include #include #include #include #include -#include #include #include #include @@ -179,10 +179,10 @@ status_t Surface::getLastQueuedBuffer(sp* outBuffer, status_t Surface::getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration) { ATRACE_CALL(); - DisplayStatInfo stats; - status_t result = composerService()->getDisplayStats(nullptr, &stats); - if (result != NO_ERROR) { - return result; + gui::DisplayStatInfo stats; + binder::Status status = composerServiceAIDL()->getDisplayStats(nullptr, &stats); + if (!status.isOk()) { + return status.transactionError(); } *outRefreshDuration = stats.vsyncPeriod; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 6b2cda19a0..447b3ef0ab 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -43,6 +44,7 @@ #include #include #include +#include #include #include @@ -2094,7 +2096,16 @@ status_t SurfaceComposerClient::injectVSync(nsecs_t when) { status_t SurfaceComposerClient::getDisplayState(const sp& display, ui::DisplayState* state) { - return ComposerService::getComposerService()->getDisplayState(display, state); + gui::DisplayState ds; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDisplayState(display, &ds); + if (status.isOk()) { + state->layerStack = ui::LayerStack::fromValue(ds.layerStack); + state->orientation = static_cast(ds.orientation); + state->layerStackSpaceRect = + ui::Size(ds.layerStackSpaceRect.width, ds.layerStackSpaceRect.height); + } + return status.transactionError(); } status_t SurfaceComposerClient::getStaticDisplayInfo(const sp& display, diff --git a/libs/gui/aidl/android/gui/DisplayStatInfo.aidl b/libs/gui/aidl/android/gui/DisplayStatInfo.aidl new file mode 100644 index 0000000000..68f394281e --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayStatInfo.aidl @@ -0,0 +1,23 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable DisplayStatInfo { + long vsyncTime; + long vsyncPeriod; +} diff --git a/libs/gui/aidl/android/gui/DisplayState.aidl b/libs/gui/aidl/android/gui/DisplayState.aidl new file mode 100644 index 0000000000..9589ab6b1a --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayState.aidl @@ -0,0 +1,27 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.Rotation; +import android.gui.Size; + +/** @hide */ +parcelable DisplayState { + int layerStack; + Rotation orientation = Rotation.Rotation0; + Size layerStackSpaceRect; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 526fae8e55..a9977b0f45 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -18,6 +18,8 @@ package android.gui; import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; +import android.gui.DisplayState; +import android.gui.DisplayStatInfo; import android.gui.IHdrLayerInfoListener; import android.gui.LayerCaptureArgs; import android.gui.IScreenCaptureListener; @@ -52,6 +54,16 @@ interface ISurfaceComposer { */ void setPowerMode(IBinder display, int mode); + /* returns display statistics for a given display + * intended to be used by the media framework to properly schedule + * video frames */ + DisplayStatInfo getDisplayStats(IBinder display); + + /** + * Get transactional state of given display. + */ + DisplayState getDisplayState(IBinder display); + /** * Clears the user-preferred display mode. The device should now boot in system preferred * display mode. diff --git a/libs/gui/aidl/android/gui/Rect.aidl b/libs/gui/aidl/android/gui/Rect.aidl new file mode 100644 index 0000000000..1b13761392 --- /dev/null +++ b/libs/gui/aidl/android/gui/Rect.aidl @@ -0,0 +1,35 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// copied from libs/arect/include/android/rect.h +// TODO(b/221473398): +// use hardware/interfaces/graphics/common/aidl/android/hardware/graphics/common/Rect.aidl +/** @hide */ +parcelable Rect { + /// Minimum X coordinate of the rectangle. + int left; + + /// Minimum Y coordinate of the rectangle. + int top; + + /// Maximum X coordinate of the rectangle. + int right; + + /// Maximum Y coordinate of the rectangle. + int bottom; +} diff --git a/libs/gui/aidl/android/gui/Rotation.aidl b/libs/gui/aidl/android/gui/Rotation.aidl new file mode 100644 index 0000000000..451ff45ccf --- /dev/null +++ b/libs/gui/aidl/android/gui/Rotation.aidl @@ -0,0 +1,26 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +@Backing(type="int") +enum Rotation { + Rotation0 = 0, + Rotation90 = 1, + Rotation180 = 2, + Rotation270 = 3 +} diff --git a/libs/gui/aidl/android/gui/Size.aidl b/libs/gui/aidl/android/gui/Size.aidl new file mode 100644 index 0000000000..415fa36fee --- /dev/null +++ b/libs/gui/aidl/android/gui/Size.aidl @@ -0,0 +1,23 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable Size { + int width = -1; + int height = -1; +} diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 0a2ae35044..2e4d6b470c 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -160,17 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - /* returns display statistics for a given display - * intended to be used by the media framework to properly schedule - * video frames */ - virtual status_t getDisplayStats(const sp& display, - DisplayStatInfo* stats) = 0; - - /** - * Get transactional state of given display. - */ - virtual status_t getDisplayState(const sp& display, ui::DisplayState*) = 0; - /** * Gets immutable information about given physical display. */ diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index ec9cba56a2..e0b86e02fb 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -739,11 +740,6 @@ public: ui::DynamicDisplayInfo*) override { return NO_ERROR; } - status_t getDisplayState(const sp& /*display*/, ui::DisplayState*) override { - return NO_ERROR; - } - status_t getDisplayStats(const sp& /*display*/, - DisplayStatInfo* /*stats*/) override { return NO_ERROR; } status_t getDisplayNativePrimaries(const sp& /*display*/, ui::DisplayPrimaries& /*primaries*/) override { return NO_ERROR; @@ -891,6 +887,114 @@ private: bool mSupportsPresent{true}; }; +class FakeSurfaceComposerAIDL : public gui::ISurfaceComposer { +public: + ~FakeSurfaceComposerAIDL() override {} + + void setSupportsPresent(bool supportsPresent) { mSupportsPresent = supportsPresent; } + + binder::Status createDisplay(const std::string& /*displayName*/, bool /*secure*/, + sp* /*outDisplay*/) override { + return binder::Status::ok(); + } + + binder::Status destroyDisplay(const sp& /*display*/) override { + return binder::Status::ok(); + } + + binder::Status getPhysicalDisplayIds(std::vector* /*outDisplayIds*/) override { + return binder::Status::ok(); + } + + binder::Status getPrimaryPhysicalDisplayId(int64_t* /*outDisplayId*/) override { + return binder::Status::ok(); + } + + binder::Status getPhysicalDisplayToken(int64_t /*displayId*/, + sp* /*outDisplay*/) override { + return binder::Status::ok(); + } + + binder::Status setPowerMode(const sp& /*display*/, int /*mode*/) override { + return binder::Status::ok(); + } + + binder::Status getDisplayStats(const sp& /*display*/, + gui::DisplayStatInfo* /*outStatInfo*/) override { + return binder::Status::ok(); + } + + binder::Status getDisplayState(const sp& /*display*/, + gui::DisplayState* /*outState*/) override { + return binder::Status::ok(); + } + + binder::Status clearBootDisplayMode(const sp& /*display*/) override { + return binder::Status::ok(); + } + + binder::Status getBootDisplayModeSupport(bool* /*outMode*/) override { + return binder::Status::ok(); + } + + binder::Status setAutoLowLatencyMode(const sp& /*display*/, bool /*on*/) override { + return binder::Status::ok(); + } + + binder::Status setGameContentType(const sp& /*display*/, bool /*on*/) override { + return binder::Status::ok(); + } + + binder::Status captureDisplay(const DisplayCaptureArgs&, + const sp&) override { + return binder::Status::ok(); + } + + binder::Status captureDisplayById(int64_t, const sp&) override { + return binder::Status::ok(); + } + + binder::Status captureLayers(const LayerCaptureArgs&, + const sp&) override { + return binder::Status::ok(); + } + + binder::Status isWideColorDisplay(const sp& /*token*/, + bool* /*outIsWideColorDisplay*/) override { + return binder::Status::ok(); + } + + binder::Status getDisplayBrightnessSupport(const sp& /*displayToken*/, + bool* /*outSupport*/) override { + return binder::Status::ok(); + } + + binder::Status setDisplayBrightness(const sp& /*displayToken*/, + const gui::DisplayBrightness& /*brightness*/) override { + return binder::Status::ok(); + } + + binder::Status addHdrLayerInfoListener( + const sp& /*displayToken*/, + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status removeHdrLayerInfoListener( + const sp& /*displayToken*/, + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status notifyPowerBoost(int /*boostId*/) override { return binder::Status::ok(); } + +protected: + IBinder* onAsBinder() override { return nullptr; } + +private: + bool mSupportsPresent{true}; +}; + class FakeProducerFrameEventHistory : public ProducerFrameEventHistory { public: explicit FakeProducerFrameEventHistory(FenceToFenceTimeMap* fenceMap) : mFenceMap(fenceMap) {} diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 5ff722b11a..83f3681072 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5462,8 +5462,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_STATIC_DISPLAY_INFO: case GET_DYNAMIC_DISPLAY_INFO: case GET_DISPLAY_MODES: - case GET_DISPLAY_STATE: - case GET_DISPLAY_STATS: case GET_SUPPORTED_FRAME_TIMESTAMPS: // Calling setTransactionState is safe, because you need to have been // granted a reference to Client* and Handle* to do anything with it. @@ -5533,6 +5531,8 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_PHYSICAL_DISPLAY_IDS: case GET_PHYSICAL_DISPLAY_TOKEN: case SET_POWER_MODE: + case GET_DISPLAY_STATE: + case GET_DISPLAY_STATS: case CLEAR_BOOT_DISPLAY_MODE: case GET_BOOT_DISPLAY_MODE_SUPPORT: case SET_AUTO_LOW_LATENCY_MODE: @@ -7260,6 +7260,30 @@ binder::Status SurfaceComposerAIDL::setPowerMode(const sp& display, int return binder::Status::ok(); } +binder::Status SurfaceComposerAIDL::getDisplayStats(const sp& display, + gui::DisplayStatInfo* outStatInfo) { + DisplayStatInfo statInfo; + status_t status = mFlinger->getDisplayStats(display, &statInfo); + if (status == NO_ERROR) { + outStatInfo->vsyncTime = static_cast(statInfo.vsyncTime); + outStatInfo->vsyncPeriod = static_cast(statInfo.vsyncPeriod); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDisplayState(const sp& display, + gui::DisplayState* outState) { + ui::DisplayState state; + status_t status = mFlinger->getDisplayState(display, &state); + if (status == NO_ERROR) { + outState->layerStack = state.layerStack.id; + outState->orientation = static_cast(state.orientation); + outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width; + outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height; + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { status_t status = checkAccessPermission(); if (status == OK) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 95c07eb054..d44acffabc 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -7,7 +7,6 @@ * * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and @@ -24,6 +23,8 @@ #include #include +#include +#include #include #include #include @@ -562,9 +563,9 @@ private: status_t captureDisplay(DisplayId, const sp&); status_t captureLayers(const LayerCaptureArgs&, const sp&); - status_t getDisplayStats(const sp& displayToken, DisplayStatInfo* stats) override; + status_t getDisplayStats(const sp& displayToken, DisplayStatInfo* stats); status_t getDisplayState(const sp& displayToken, ui::DisplayState*) - EXCLUDES(mStateLock) override; + EXCLUDES(mStateLock); status_t getStaticDisplayInfo(const sp& displayToken, ui::StaticDisplayInfo*) EXCLUDES(mStateLock) override; status_t getDynamicDisplayInfo(const sp& displayToken, ui::DynamicDisplayInfo*) @@ -1438,6 +1439,10 @@ public: binder::Status getPrimaryPhysicalDisplayId(int64_t* outDisplayId) override; binder::Status getPhysicalDisplayToken(int64_t displayId, sp* outDisplay) override; binder::Status setPowerMode(const sp& display, int mode) override; + binder::Status getDisplayStats(const sp& display, + gui::DisplayStatInfo* outStatInfo) override; + binder::Status getDisplayState(const sp& display, + gui::DisplayState* outState) override; binder::Status clearBootDisplayMode(const sp& display) override; binder::Status getBootDisplayModeSupport(bool* outMode) override; binder::Status setAutoLowLatencyMode(const sp& display, bool on) override; -- cgit v1.2.3-59-g8ed1b From a79ddf4b1532435b07a8f9ff21fb18dec723a230 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Thu, 17 Feb 2022 00:01:38 -0800 Subject: Convert StaticDisplayInfo to AIDL parcelable And migrate related ISurfaceComposer::getStaticDisplayInfo() method to AIDL. (1) add android::gui::StaticDisplayInfo etc. for serialization (2) remove serialization code from the orignal StaticDisplayInfo and DeviceProductInfo classes (3) convert between ui::StaticDisplayInfo and gui::StaticDisplayInfo Bug: 220073844 Test: atest libgui_test Change-Id: I462e5d4d76f768bc17ea5ca3dd54249b3ee489d9 --- libs/gui/ISurfaceComposer.cpp | 22 -------- libs/gui/SurfaceComposerClient.cpp | 44 +++++++++++++++- libs/gui/aidl/android/gui/DeviceProductInfo.aidl | 58 ++++++++++++++++++++++ .../aidl/android/gui/DisplayConnectionType.aidl | 24 +++++++++ libs/gui/aidl/android/gui/DisplayModelId.aidl | 26 ++++++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 7 ++- libs/gui/aidl/android/gui/StaticDisplayInfo.aidl | 30 +++++++++++ libs/gui/include/gui/ISurfaceComposer.h | 8 +-- libs/gui/include/gui/SurfaceComposerClient.h | 1 + libs/gui/tests/Surface_test.cpp | 8 +-- libs/ui/Android.bp | 1 - libs/ui/DeviceProductInfo.cpp | 30 ----------- libs/ui/StaticDisplayInfo.cpp | 57 --------------------- libs/ui/include/ui/DeviceProductInfo.h | 9 +--- libs/ui/include/ui/StaticDisplayInfo.h | 8 +-- services/surfaceflinger/SurfaceFlinger.cpp | 44 +++++++++++++++- services/surfaceflinger/SurfaceFlinger.h | 4 +- 17 files changed, 241 insertions(+), 140 deletions(-) create mode 100644 libs/gui/aidl/android/gui/DeviceProductInfo.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayConnectionType.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayModelId.aidl create mode 100644 libs/gui/aidl/android/gui/StaticDisplayInfo.aidl delete mode 100644 libs/ui/StaticDisplayInfo.cpp (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 24d39fe86a..c5de09a4bf 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -37,7 +37,6 @@ #include #include #include -#include #include // --------------------------------------------------------------------------- @@ -226,17 +225,6 @@ public: return result; } - status_t getStaticDisplayInfo(const sp& display, - ui::StaticDisplayInfo* info) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - remote()->transact(BnSurfaceComposer::GET_STATIC_DISPLAY_INFO, data, &reply); - const status_t result = reply.readInt32(); - if (result != NO_ERROR) return result; - return reply.read(*info); - } - status_t getDynamicDisplayInfo(const sp& display, ui::DynamicDisplayInfo* info) override { Parcel data, reply; @@ -1145,16 +1133,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case GET_STATIC_DISPLAY_INFO: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - ui::StaticDisplayInfo info; - const sp display = data.readStrongBinder(); - const status_t result = getStaticDisplayInfo(display, &info); - SAFE_PARCEL(reply->writeInt32, result); - if (result != NO_ERROR) return result; - SAFE_PARCEL(reply->write, info); - return NO_ERROR; - } case GET_DYNAMIC_DISPLAY_INFO: { CHECK_INTERFACE(ISurfaceComposer, data, reply); ui::DynamicDisplayInfo info; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index c916abee33..23a94fc21b 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2128,8 +2128,48 @@ status_t SurfaceComposerClient::getDisplayState(const sp& display, } status_t SurfaceComposerClient::getStaticDisplayInfo(const sp& display, - ui::StaticDisplayInfo* info) { - return ComposerService::getComposerService()->getStaticDisplayInfo(display, info); + ui::StaticDisplayInfo* outInfo) { + using Tag = android::gui::DeviceProductInfo::ManufactureOrModelDate::Tag; + gui::StaticDisplayInfo ginfo; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getStaticDisplayInfo(display, &ginfo); + if (status.isOk()) { + // convert gui::StaticDisplayInfo to ui::StaticDisplayInfo + outInfo->connectionType = static_cast(ginfo.connectionType); + outInfo->density = ginfo.density; + outInfo->secure = ginfo.secure; + outInfo->installOrientation = static_cast(ginfo.installOrientation); + + DeviceProductInfo info; + std::optional dpi = ginfo.deviceProductInfo; + gui::DeviceProductInfo::ManufactureOrModelDate& date = dpi->manufactureOrModelDate; + info.name = dpi->name; + if (dpi->manufacturerPnpId.size() > 0) { + // copid from PnpId = std::array in ui/DeviceProductInfo.h + constexpr int kMaxPnpIdSize = 4; + size_t count = std::max(kMaxPnpIdSize, dpi->manufacturerPnpId.size()); + std::copy_n(dpi->manufacturerPnpId.begin(), count, info.manufacturerPnpId.begin()); + } + info.productId = dpi->productId; + if (date.getTag() == Tag::modelYear) { + DeviceProductInfo::ModelYear modelYear; + modelYear.year = static_cast(date.get().year); + info.manufactureOrModelDate = modelYear; + } else if (date.getTag() == Tag::manufactureYear) { + DeviceProductInfo::ManufactureYear manufactureYear; + manufactureYear.year = date.get().modelYear.year; + info.manufactureOrModelDate = manufactureYear; + } else if (date.getTag() == Tag::manufactureWeekAndYear) { + DeviceProductInfo::ManufactureWeekAndYear weekAndYear; + weekAndYear.year = + date.get().manufactureYear.modelYear.year; + weekAndYear.week = date.get().week; + info.manufactureOrModelDate = weekAndYear; + } + + outInfo->deviceProductInfo = info; + } + return status.transactionError(); } status_t SurfaceComposerClient::getDynamicDisplayInfo(const sp& display, diff --git a/libs/gui/aidl/android/gui/DeviceProductInfo.aidl b/libs/gui/aidl/android/gui/DeviceProductInfo.aidl new file mode 100644 index 0000000000..98404cf0fd --- /dev/null +++ b/libs/gui/aidl/android/gui/DeviceProductInfo.aidl @@ -0,0 +1,58 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// Product-specific information about the display or the directly connected device on the +// display chain. For example, if the display is transitively connected, this field may contain +// product information about the intermediate device. + +/** @hide */ +parcelable DeviceProductInfo { + parcelable ModelYear { + int year; + } + + parcelable ManufactureYear { + ModelYear modelYear; + } + + parcelable ManufactureWeekAndYear { + ManufactureYear manufactureYear; + + // 1-base week number. Week numbering may not be consistent between manufacturers. + int week; + } + + union ManufactureOrModelDate { + ModelYear modelYear; + ManufactureYear manufactureYear; + ManufactureWeekAndYear manufactureWeekAndYear; + } + + // Display name. + @utf8InCpp String name; + + // NULL-terminated Manufacturer plug and play ID. + byte[] manufacturerPnpId; + + // Manufacturer product ID. + @utf8InCpp String productId; + + ManufactureOrModelDate manufactureOrModelDate; + + byte[] relativeAddress; +} diff --git a/libs/gui/aidl/android/gui/DisplayConnectionType.aidl b/libs/gui/aidl/android/gui/DisplayConnectionType.aidl new file mode 100644 index 0000000000..72c4ede7ac --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayConnectionType.aidl @@ -0,0 +1,24 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +@Backing(type="int") +enum DisplayConnectionType { + Internal = 0, + External = 1 +} diff --git a/libs/gui/aidl/android/gui/DisplayModelId.aidl b/libs/gui/aidl/android/gui/DisplayModelId.aidl new file mode 100644 index 0000000000..d75777b815 --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayModelId.aidl @@ -0,0 +1,26 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// Product-specific information about the display or the directly connected device on the +// display chain. For example, if the display is transitively connected, this field may contain +// product information about the intermediate device. + +/** @hide */ +parcelable DisplayModelId { + int id; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index a9977b0f45..f6cd5ec44f 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -20,13 +20,13 @@ import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; import android.gui.DisplayState; import android.gui.DisplayStatInfo; +import android.gui.StaticDisplayInfo; import android.gui.IHdrLayerInfoListener; import android.gui.LayerCaptureArgs; import android.gui.IScreenCaptureListener; /** @hide */ interface ISurfaceComposer { - /* create a virtual display * requires ACCESS_SURFACE_FLINGER permission. */ @@ -64,6 +64,11 @@ interface ISurfaceComposer { */ DisplayState getDisplayState(IBinder display); + /** + * Gets immutable information about given physical display. + */ + StaticDisplayInfo getStaticDisplayInfo(IBinder display); + /** * Clears the user-preferred display mode. The device should now boot in system preferred * display mode. diff --git a/libs/gui/aidl/android/gui/StaticDisplayInfo.aidl b/libs/gui/aidl/android/gui/StaticDisplayInfo.aidl new file mode 100644 index 0000000000..0ccda56ef5 --- /dev/null +++ b/libs/gui/aidl/android/gui/StaticDisplayInfo.aidl @@ -0,0 +1,30 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.DisplayConnectionType; +import android.gui.DeviceProductInfo; +import android.gui.Rotation; + +/** @hide */ +parcelable StaticDisplayInfo { + DisplayConnectionType connectionType = DisplayConnectionType.Internal; + float density; + boolean secure; + @nullable DeviceProductInfo deviceProductInfo; + Rotation installOrientation = Rotation.Rotation0; +} diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 511937b5f6..29e38b880b 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -85,7 +85,6 @@ namespace ui { struct DisplayMode; struct DisplayState; struct DynamicDisplayInfo; -struct StaticDisplayInfo; } // namespace ui @@ -161,11 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - /** - * Gets immutable information about given physical display. - */ - virtual status_t getStaticDisplayInfo(const sp& display, ui::StaticDisplayInfo*) = 0; - /** * Gets dynamic information about given physical display. */ @@ -443,7 +437,7 @@ public: // Java by ActivityManagerService. BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION, CREATE_CONNECTION, - GET_STATIC_DISPLAY_INFO, + GET_STATIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. CREATE_DISPLAY_EVENT_CONNECTION, CREATE_DISPLAY, // Deprecated. Autogenerated by .aidl now. DESTROY_DISPLAY, // Deprecated. Autogenerated by .aidl now. diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 9d03f58aa5..b17902d1f1 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -38,6 +38,7 @@ #include #include #include +#include #include #include diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index e0b86e02fb..e02299d123 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -733,9 +733,6 @@ public: return NO_ERROR; } - status_t getStaticDisplayInfo(const sp& /*display*/, ui::StaticDisplayInfo*) override { - return NO_ERROR; - } status_t getDynamicDisplayInfo(const sp& /*display*/, ui::DynamicDisplayInfo*) override { return NO_ERROR; @@ -929,6 +926,11 @@ public: return binder::Status::ok(); } + binder::Status getStaticDisplayInfo(const sp& /*display*/, + gui::StaticDisplayInfo* /*outInfo*/) override { + return binder::Status::ok(); + } + binder::Status clearBootDisplayMode(const sp& /*display*/) override { return binder::Status::ok(); } diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp index a9380c6e79..4af38c5218 100644 --- a/libs/ui/Android.bp +++ b/libs/ui/Android.bp @@ -145,7 +145,6 @@ cc_library_shared { "PixelFormat.cpp", "PublicFormat.cpp", "StaticAsserts.cpp", - "StaticDisplayInfo.cpp", ], include_dirs: [ diff --git a/libs/ui/DeviceProductInfo.cpp b/libs/ui/DeviceProductInfo.cpp index 4d6ce4306a..496e2a872e 100644 --- a/libs/ui/DeviceProductInfo.cpp +++ b/libs/ui/DeviceProductInfo.cpp @@ -17,7 +17,6 @@ #include #include -#include #include #define RETURN_IF_ERROR(op) \ @@ -27,35 +26,6 @@ namespace android { using base::StringAppendF; -size_t DeviceProductInfo::getFlattenedSize() const { - return FlattenableHelpers::getFlattenedSize(name) + - FlattenableHelpers::getFlattenedSize(manufacturerPnpId) + - FlattenableHelpers::getFlattenedSize(productId) + - FlattenableHelpers::getFlattenedSize(manufactureOrModelDate) + - FlattenableHelpers::getFlattenedSize(relativeAddress); -} - -status_t DeviceProductInfo::flatten(void* buffer, size_t size) const { - if (size < getFlattenedSize()) { - return NO_MEMORY; - } - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, name)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, manufacturerPnpId)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, productId)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, manufactureOrModelDate)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, relativeAddress)); - return OK; -} - -status_t DeviceProductInfo::unflatten(void const* buffer, size_t size) { - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &name)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &manufacturerPnpId)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &productId)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &manufactureOrModelDate)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &relativeAddress)); - return OK; -} - void DeviceProductInfo::dump(std::string& result) const { StringAppendF(&result, "{name=%s, ", name.c_str()); StringAppendF(&result, "manufacturerPnpId=%s, ", manufacturerPnpId.data()); diff --git a/libs/ui/StaticDisplayInfo.cpp b/libs/ui/StaticDisplayInfo.cpp deleted file mode 100644 index 03d15e4694..0000000000 --- a/libs/ui/StaticDisplayInfo.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include - -#include - -#define RETURN_IF_ERROR(op) \ - if (const status_t status = (op); status != OK) return status; - -namespace android::ui { - -size_t StaticDisplayInfo::getFlattenedSize() const { - return FlattenableHelpers::getFlattenedSize(connectionType) + - FlattenableHelpers::getFlattenedSize(density) + - FlattenableHelpers::getFlattenedSize(secure) + - FlattenableHelpers::getFlattenedSize(deviceProductInfo) + - FlattenableHelpers::getFlattenedSize(installOrientation); -} - -status_t StaticDisplayInfo::flatten(void* buffer, size_t size) const { - if (size < getFlattenedSize()) { - return NO_MEMORY; - } - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, connectionType)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, density)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, secure)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, deviceProductInfo)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, installOrientation)); - return OK; -} - -status_t StaticDisplayInfo::unflatten(void const* buffer, size_t size) { - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &connectionType)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &density)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &secure)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &deviceProductInfo)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &installOrientation)); - return OK; -} - -} // namespace android::ui diff --git a/libs/ui/include/ui/DeviceProductInfo.h b/libs/ui/include/ui/DeviceProductInfo.h index 807a5d96a3..879e46fbdc 100644 --- a/libs/ui/include/ui/DeviceProductInfo.h +++ b/libs/ui/include/ui/DeviceProductInfo.h @@ -24,8 +24,6 @@ #include #include -#include - namespace android { // NUL-terminated plug and play ID. @@ -34,7 +32,7 @@ using PnpId = std::array; // Product-specific information about the display or the directly connected device on the // display chain. For example, if the display is transitively connected, this field may contain // product information about the intermediate device. -struct DeviceProductInfo : LightFlattenable { +struct DeviceProductInfo { struct ModelYear { uint32_t year; }; @@ -64,11 +62,6 @@ struct DeviceProductInfo : LightFlattenable { // For example, for HDMI connected device this will be the physical address. std::vector relativeAddress; - bool isFixedSize() const { return false; } - size_t getFlattenedSize() const; - status_t flatten(void* buffer, size_t size) const; - status_t unflatten(void const* buffer, size_t size); - void dump(std::string& result) const; }; diff --git a/libs/ui/include/ui/StaticDisplayInfo.h b/libs/ui/include/ui/StaticDisplayInfo.h index cc7c869b3b..566e4172a1 100644 --- a/libs/ui/include/ui/StaticDisplayInfo.h +++ b/libs/ui/include/ui/StaticDisplayInfo.h @@ -20,24 +20,18 @@ #include #include -#include namespace android::ui { enum class DisplayConnectionType { Internal, External }; // Immutable information about physical display. -struct StaticDisplayInfo : LightFlattenable { +struct StaticDisplayInfo { DisplayConnectionType connectionType = DisplayConnectionType::Internal; float density = 0.f; bool secure = false; std::optional deviceProductInfo; Rotation installOrientation = ROTATION_0; - - bool isFixedSize() const { return false; } - size_t getFlattenedSize() const; - status_t flatten(void* buffer, size_t size) const; - status_t unflatten(void const* buffer, size_t size); }; } // namespace android::ui diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 26bd356529..decb732d8b 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -27,6 +27,7 @@ #include #include #include +#include #include #include #include @@ -5559,7 +5560,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_ACTIVE_DISPLAY_MODE: case GET_DISPLAY_COLOR_MODES: case GET_DISPLAY_NATIVE_PRIMARIES: - case GET_STATIC_DISPLAY_INFO: case GET_DYNAMIC_DISPLAY_INFO: case GET_DISPLAY_MODES: case GET_SUPPORTED_FRAME_TIMESTAMPS: @@ -5633,6 +5633,7 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case SET_POWER_MODE: case GET_DISPLAY_STATE: case GET_DISPLAY_STATS: + case GET_STATIC_DISPLAY_INFO: case CLEAR_BOOT_DISPLAY_MODE: case GET_BOOT_DISPLAY_MODE_SUPPORT: case SET_AUTO_LOW_LATENCY_MODE: @@ -7435,6 +7436,47 @@ binder::Status SurfaceComposerAIDL::getDisplayState(const sp& display, return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp& display, + gui::StaticDisplayInfo* outInfo) { + using Tag = gui::DeviceProductInfo::ManufactureOrModelDate::Tag; + ui::StaticDisplayInfo info; + status_t status = mFlinger->getStaticDisplayInfo(display, &info); + if (status == NO_ERROR) { + // convert ui::StaticDisplayInfo to gui::StaticDisplayInfo + outInfo->connectionType = static_cast(info.connectionType); + outInfo->density = info.density; + outInfo->secure = info.secure; + outInfo->installOrientation = static_cast(info.installOrientation); + + gui::DeviceProductInfo dinfo; + std::optional dpi = info.deviceProductInfo; + dinfo.name = std::move(dpi->name); + dinfo.manufacturerPnpId = + std::vector(dpi->manufacturerPnpId.begin(), dpi->manufacturerPnpId.end()); + dinfo.productId = dpi->productId; + if (const auto* model = + std::get_if(&dpi->manufactureOrModelDate)) { + gui::DeviceProductInfo::ModelYear modelYear; + modelYear.year = model->year; + dinfo.manufactureOrModelDate.set(modelYear); + } else if (const auto* manufacture = std::get_if( + &dpi->manufactureOrModelDate)) { + gui::DeviceProductInfo::ManufactureYear date; + date.modelYear.year = manufacture->year; + dinfo.manufactureOrModelDate.set(date); + } else if (const auto* manufacture = std::get_if( + &dpi->manufactureOrModelDate)) { + gui::DeviceProductInfo::ManufactureWeekAndYear date; + date.manufactureYear.modelYear.year = manufacture->year; + date.week = manufacture->week; + dinfo.manufactureOrModelDate.set(date); + } + + outInfo->deviceProductInfo = dinfo; + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { status_t status = checkAccessPermission(); if (status == OK) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 31d9d63344..bb0bc3f188 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -572,7 +572,7 @@ private: status_t getDisplayState(const sp& displayToken, ui::DisplayState*) EXCLUDES(mStateLock); status_t getStaticDisplayInfo(const sp& displayToken, ui::StaticDisplayInfo*) - EXCLUDES(mStateLock) override; + EXCLUDES(mStateLock); status_t getDynamicDisplayInfo(const sp& displayToken, ui::DynamicDisplayInfo*) EXCLUDES(mStateLock) override; status_t getDisplayNativePrimaries(const sp& displayToken, @@ -1465,6 +1465,8 @@ public: gui::DisplayStatInfo* outStatInfo) override; binder::Status getDisplayState(const sp& display, gui::DisplayState* outState) override; + binder::Status getStaticDisplayInfo(const sp& display, + gui::StaticDisplayInfo* outInfo) override; binder::Status clearBootDisplayMode(const sp& display) override; binder::Status getBootDisplayModeSupport(bool* outMode) override; binder::Status setAutoLowLatencyMode(const sp& display, bool on) override; -- cgit v1.2.3-59-g8ed1b From 38603fd683c5c0910db211d407172475cdf2f579 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Mon, 21 Feb 2022 14:32:54 -0800 Subject: Convert DynamicDisplayInfo to AIDL parcelable And migrate related ISurfaceComposer::getDynamicDisplayInfo() method to AIDL. (1) add android::gui::DynamicDisplayInfo etc. for serialization (2) remove serialization code from the orignal DynamicDisplayInfo and DisplayMode and HdrCapabilities classes (3) convert between ui::DynamicDisplayInfo and gui::DynamicDisplayInfo Bug: 220074970 Test: manual Change-Id: If3c81c5fd006c281f6d38766bf415a971b0a1925 --- libs/gui/ISurfaceComposer.cpp | 21 ------ libs/gui/Surface.cpp | 9 +-- libs/gui/SurfaceComposerClient.cpp | 49 ++++++++++++- libs/gui/aidl/android/gui/DisplayMode.aidl | 36 ++++++++++ libs/gui/aidl/android/gui/DisplayModelId.aidl | 26 ------- libs/gui/aidl/android/gui/DynamicDisplayInfo.aidl | 45 ++++++++++++ libs/gui/aidl/android/gui/HdrCapabilities.aidl | 27 +++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 6 ++ libs/gui/include/gui/ISurfaceComposer.h | 7 +- libs/gui/tests/Surface_test.cpp | 9 +-- libs/ui/Android.bp | 2 - libs/ui/DisplayMode.cpp | 69 ------------------ libs/ui/DynamicDisplayInfo.cpp | 43 ------------ libs/ui/HdrCapabilities.cpp | 86 ----------------------- libs/ui/include/ui/DisplayMode.h | 7 +- libs/ui/include/ui/DynamicDisplayInfo.h | 8 +-- libs/ui/include/ui/HdrCapabilities.h | 10 +-- services/surfaceflinger/SurfaceFlinger.cpp | 53 +++++++++++++- services/surfaceflinger/SurfaceFlinger.h | 4 +- 19 files changed, 230 insertions(+), 287 deletions(-) create mode 100644 libs/gui/aidl/android/gui/DisplayMode.aidl delete mode 100644 libs/gui/aidl/android/gui/DisplayModelId.aidl create mode 100644 libs/gui/aidl/android/gui/DynamicDisplayInfo.aidl create mode 100644 libs/gui/aidl/android/gui/HdrCapabilities.aidl delete mode 100644 libs/ui/DisplayMode.cpp delete mode 100644 libs/ui/HdrCapabilities.cpp (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index c5de09a4bf..a9473d4997 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -225,17 +225,6 @@ public: return result; } - status_t getDynamicDisplayInfo(const sp& display, - ui::DynamicDisplayInfo* info) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - remote()->transact(BnSurfaceComposer::GET_DYNAMIC_DISPLAY_INFO, data, &reply); - const status_t result = reply.readInt32(); - if (result != NO_ERROR) return result; - return reply.read(*info); - } - status_t getDisplayNativePrimaries(const sp& display, ui::DisplayPrimaries& primaries) override { Parcel data, reply; @@ -1133,16 +1122,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case GET_DYNAMIC_DISPLAY_INFO: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - ui::DynamicDisplayInfo info; - const sp display = data.readStrongBinder(); - const status_t result = getDynamicDisplayInfo(display, &info); - SAFE_PARCEL(reply->writeInt32, result); - if (result != NO_ERROR) return result; - SAFE_PARCEL(reply->write, info); - return NO_ERROR; - } case GET_DISPLAY_NATIVE_PRIMARIES: { CHECK_INTERFACE(ISurfaceComposer, data, reply); ui::DisplayPrimaries primaries; diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index 0f0a5c8504..bee820dfb1 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -366,12 +366,13 @@ status_t Surface::getHdrSupport(bool* supported) { return NAME_NOT_FOUND; } - ui::DynamicDisplayInfo info; - if (status_t err = composerService()->getDynamicDisplayInfo(display, &info); err != NO_ERROR) { - return err; + gui::DynamicDisplayInfo info; + if (binder::Status status = composerServiceAIDL()->getDynamicDisplayInfo(display, &info); + !status.isOk()) { + return status.transactionError(); } - *supported = !info.hdrCapabilities.getSupportedHdrTypes().empty(); + *supported = !info.hdrCapabilities.supportedHdrTypes.empty(); return NO_ERROR; } diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index b4979d9276..6702fef45e 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2187,8 +2187,53 @@ status_t SurfaceComposerClient::getStaticDisplayInfo(const sp& display, } status_t SurfaceComposerClient::getDynamicDisplayInfo(const sp& display, - ui::DynamicDisplayInfo* info) { - return ComposerService::getComposerService()->getDynamicDisplayInfo(display, info); + ui::DynamicDisplayInfo* outInfo) { + gui::DynamicDisplayInfo ginfo; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDynamicDisplayInfo(display, &ginfo); + if (status.isOk()) { + // convert gui::DynamicDisplayInfo to ui::DynamicDisplayInfo + outInfo->supportedDisplayModes.clear(); + outInfo->supportedDisplayModes.reserve(ginfo.supportedDisplayModes.size()); + for (const auto& mode : ginfo.supportedDisplayModes) { + ui::DisplayMode outMode; + outMode.id = mode.id; + outMode.resolution.width = mode.resolution.width; + outMode.resolution.height = mode.resolution.height; + outMode.xDpi = mode.xDpi; + outMode.yDpi = mode.yDpi; + outMode.refreshRate = mode.refreshRate; + outMode.appVsyncOffset = mode.appVsyncOffset; + outMode.sfVsyncOffset = mode.sfVsyncOffset; + outMode.presentationDeadline = mode.presentationDeadline; + outMode.group = mode.group; + outInfo->supportedDisplayModes.push_back(outMode); + } + + outInfo->activeDisplayModeId = ginfo.activeDisplayModeId; + + outInfo->supportedColorModes.clear(); + outInfo->supportedColorModes.reserve(ginfo.supportedColorModes.size()); + for (const auto& cmode : ginfo.supportedColorModes) { + outInfo->supportedColorModes.push_back(static_cast(cmode)); + } + + outInfo->activeColorMode = static_cast(ginfo.activeColorMode); + + std::vector types; + types.reserve(ginfo.hdrCapabilities.supportedHdrTypes.size()); + for (const auto& hdr : ginfo.hdrCapabilities.supportedHdrTypes) { + types.push_back(static_cast(hdr)); + } + outInfo->hdrCapabilities = HdrCapabilities(types, ginfo.hdrCapabilities.maxLuminance, + ginfo.hdrCapabilities.maxAverageLuminance, + ginfo.hdrCapabilities.minLuminance); + + outInfo->autoLowLatencyModeSupported = ginfo.autoLowLatencyModeSupported; + outInfo->gameContentTypeSupported = ginfo.gameContentTypeSupported; + outInfo->preferredBootDisplayMode = ginfo.preferredBootDisplayMode; + } + return status.transactionError(); } status_t SurfaceComposerClient::getActiveDisplayMode(const sp& display, diff --git a/libs/gui/aidl/android/gui/DisplayMode.aidl b/libs/gui/aidl/android/gui/DisplayMode.aidl new file mode 100644 index 0000000000..3cd77f82d7 --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayMode.aidl @@ -0,0 +1,36 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.Size; + +// Mode supported by physical display. +// Make sure to sync with libui DisplayMode.h + +/** @hide */ +parcelable DisplayMode { + int id; + Size resolution; + float xDpi = 0.0f; + float yDpi = 0.0f; + + float refreshRate = 0.0f; + long appVsyncOffset = 0; + long sfVsyncOffset = 0; + long presentationDeadline = 0; + int group = -1; +} diff --git a/libs/gui/aidl/android/gui/DisplayModelId.aidl b/libs/gui/aidl/android/gui/DisplayModelId.aidl deleted file mode 100644 index d75777b815..0000000000 --- a/libs/gui/aidl/android/gui/DisplayModelId.aidl +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.gui; - -// Product-specific information about the display or the directly connected device on the -// display chain. For example, if the display is transitively connected, this field may contain -// product information about the intermediate device. - -/** @hide */ -parcelable DisplayModelId { - int id; -} diff --git a/libs/gui/aidl/android/gui/DynamicDisplayInfo.aidl b/libs/gui/aidl/android/gui/DynamicDisplayInfo.aidl new file mode 100644 index 0000000000..57e6081e27 --- /dev/null +++ b/libs/gui/aidl/android/gui/DynamicDisplayInfo.aidl @@ -0,0 +1,45 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.DisplayMode; +import android.gui.HdrCapabilities; + +// Information about a physical display which may change on hotplug reconnect. +// Make sure to sync with libui DynamicDisplayInfo.h + +/** @hide */ +parcelable DynamicDisplayInfo { + List supportedDisplayModes; + + int activeDisplayModeId; + + int[] supportedColorModes; + int activeColorMode; + HdrCapabilities hdrCapabilities; + + // True if the display reports support for HDMI 2.1 Auto Low Latency Mode. + // For more information, see the HDMI 2.1 specification. + boolean autoLowLatencyModeSupported; + + // True if the display reports support for Game Content Type. + // For more information, see the HDMI 1.4 specification. + boolean gameContentTypeSupported; + + // The boot display mode preferred by the implementation. + int preferredBootDisplayMode; +} diff --git a/libs/gui/aidl/android/gui/HdrCapabilities.aidl b/libs/gui/aidl/android/gui/HdrCapabilities.aidl new file mode 100644 index 0000000000..9d06da9f27 --- /dev/null +++ b/libs/gui/aidl/android/gui/HdrCapabilities.aidl @@ -0,0 +1,27 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// Make sure to sync with libui HdrCapabilities.h + +/** @hide */ +parcelable HdrCapabilities { + int[] supportedHdrTypes; + float maxLuminance; + float maxAverageLuminance; + float minLuminance; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index f6cd5ec44f..175007d380 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -21,6 +21,7 @@ import android.gui.DisplayBrightness; import android.gui.DisplayState; import android.gui.DisplayStatInfo; import android.gui.StaticDisplayInfo; +import android.gui.DynamicDisplayInfo; import android.gui.IHdrLayerInfoListener; import android.gui.LayerCaptureArgs; import android.gui.IScreenCaptureListener; @@ -69,6 +70,11 @@ interface ISurfaceComposer { */ StaticDisplayInfo getStaticDisplayInfo(IBinder display); + /** + * Gets dynamic information about given physical display. + */ + DynamicDisplayInfo getDynamicDisplayInfo(IBinder display); + /** * Clears the user-preferred display mode. The device should now boot in system preferred * display mode. diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 29e38b880b..ed8254ae8b 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -160,11 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - /** - * Gets dynamic information about given physical display. - */ - virtual status_t getDynamicDisplayInfo(const sp& display, ui::DynamicDisplayInfo*) = 0; - virtual status_t getDisplayNativePrimaries(const sp& display, ui::DisplayPrimaries& primaries) = 0; virtual status_t setActiveColorMode(const sp& display, @@ -490,7 +485,7 @@ public: ADD_TRANSACTION_TRACE_LISTENER, GET_GPU_CONTEXT_PRIORITY, GET_MAX_ACQUIRED_BUFFER_COUNT, - GET_DYNAMIC_DISPLAY_INFO, + GET_DYNAMIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. ADD_FPS_LISTENER, REMOVE_FPS_LISTENER, OVERRIDE_HDR_TYPES, diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index e02299d123..bf1b43d2c0 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -733,10 +733,6 @@ public: return NO_ERROR; } - status_t getDynamicDisplayInfo(const sp& /*display*/, - ui::DynamicDisplayInfo*) override { - return NO_ERROR; - } status_t getDisplayNativePrimaries(const sp& /*display*/, ui::DisplayPrimaries& /*primaries*/) override { return NO_ERROR; @@ -931,6 +927,11 @@ public: return binder::Status::ok(); } + binder::Status getDynamicDisplayInfo(const sp& /*display*/, + gui::DynamicDisplayInfo* /*outInfo*/) override { + return binder::Status::ok(); + } + binder::Status clearBootDisplayMode(const sp& /*display*/) override { return binder::Status::ok(); } diff --git a/libs/ui/Android.bp b/libs/ui/Android.bp index 4af38c5218..0a85fe02e2 100644 --- a/libs/ui/Android.bp +++ b/libs/ui/Android.bp @@ -129,7 +129,6 @@ cc_library_shared { "DebugUtils.cpp", "DeviceProductInfo.cpp", "DisplayIdentification.cpp", - "DisplayMode.cpp", "DynamicDisplayInfo.cpp", "Fence.cpp", "FenceTime.cpp", @@ -141,7 +140,6 @@ cc_library_shared { "GraphicBuffer.cpp", "GraphicBufferAllocator.cpp", "GraphicBufferMapper.cpp", - "HdrCapabilities.cpp", "PixelFormat.cpp", "PublicFormat.cpp", "StaticAsserts.cpp", diff --git a/libs/ui/DisplayMode.cpp b/libs/ui/DisplayMode.cpp deleted file mode 100644 index cf05dbfb05..0000000000 --- a/libs/ui/DisplayMode.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -#include - -#include - -#define RETURN_IF_ERROR(op) \ - if (const status_t status = (op); status != OK) return status; - -namespace android::ui { - -size_t DisplayMode::getFlattenedSize() const { - return FlattenableHelpers::getFlattenedSize(id) + - FlattenableHelpers::getFlattenedSize(resolution) + - FlattenableHelpers::getFlattenedSize(xDpi) + - FlattenableHelpers::getFlattenedSize(yDpi) + - FlattenableHelpers::getFlattenedSize(refreshRate) + - FlattenableHelpers::getFlattenedSize(appVsyncOffset) + - FlattenableHelpers::getFlattenedSize(sfVsyncOffset) + - FlattenableHelpers::getFlattenedSize(presentationDeadline) + - FlattenableHelpers::getFlattenedSize(group); -} - -status_t DisplayMode::flatten(void* buffer, size_t size) const { - if (size < getFlattenedSize()) { - return NO_MEMORY; - } - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, id)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, resolution)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, xDpi)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, yDpi)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, refreshRate)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, appVsyncOffset)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, sfVsyncOffset)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, presentationDeadline)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, group)); - return OK; -} - -status_t DisplayMode::unflatten(const void* buffer, size_t size) { - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &id)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &resolution)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &xDpi)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &yDpi)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &refreshRate)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &appVsyncOffset)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &sfVsyncOffset)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &presentationDeadline)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &group)); - return OK; -} - -} // namespace android::ui diff --git a/libs/ui/DynamicDisplayInfo.cpp b/libs/ui/DynamicDisplayInfo.cpp index 78ba9965b6..f5feea925d 100644 --- a/libs/ui/DynamicDisplayInfo.cpp +++ b/libs/ui/DynamicDisplayInfo.cpp @@ -18,11 +18,6 @@ #include -#include - -#define RETURN_IF_ERROR(op) \ - if (const status_t status = (op); status != OK) return status; - namespace android::ui { std::optional DynamicDisplayInfo::getActiveDisplayMode() const { @@ -34,42 +29,4 @@ std::optional DynamicDisplayInfo::getActiveDisplayMode() const return {}; } -size_t DynamicDisplayInfo::getFlattenedSize() const { - return FlattenableHelpers::getFlattenedSize(supportedDisplayModes) + - FlattenableHelpers::getFlattenedSize(activeDisplayModeId) + - FlattenableHelpers::getFlattenedSize(supportedColorModes) + - FlattenableHelpers::getFlattenedSize(activeColorMode) + - FlattenableHelpers::getFlattenedSize(hdrCapabilities) + - FlattenableHelpers::getFlattenedSize(autoLowLatencyModeSupported) + - FlattenableHelpers::getFlattenedSize(gameContentTypeSupported) + - FlattenableHelpers::getFlattenedSize(preferredBootDisplayMode); -} - -status_t DynamicDisplayInfo::flatten(void* buffer, size_t size) const { - if (size < getFlattenedSize()) { - return NO_MEMORY; - } - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, supportedDisplayModes)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, activeDisplayModeId)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, supportedColorModes)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, activeColorMode)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, hdrCapabilities)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, autoLowLatencyModeSupported)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, gameContentTypeSupported)); - RETURN_IF_ERROR(FlattenableHelpers::flatten(&buffer, &size, preferredBootDisplayMode)); - return OK; -} - -status_t DynamicDisplayInfo::unflatten(const void* buffer, size_t size) { - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &supportedDisplayModes)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &activeDisplayModeId)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &supportedColorModes)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &activeColorMode)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &hdrCapabilities)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &autoLowLatencyModeSupported)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &gameContentTypeSupported)); - RETURN_IF_ERROR(FlattenableHelpers::unflatten(&buffer, &size, &preferredBootDisplayMode)); - return OK; -} - } // namespace android::ui diff --git a/libs/ui/HdrCapabilities.cpp b/libs/ui/HdrCapabilities.cpp deleted file mode 100644 index aec2fac780..0000000000 --- a/libs/ui/HdrCapabilities.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include - -namespace android { - -#if defined(__clang__) -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wundefined-reinterpret-cast" -#endif - -size_t HdrCapabilities::getFlattenedSize() const { - return sizeof(mMaxLuminance) + - sizeof(mMaxAverageLuminance) + - sizeof(mMinLuminance) + - sizeof(int32_t) + - mSupportedHdrTypes.size() * sizeof(ui::Hdr); -} - -status_t HdrCapabilities::flatten(void* buffer, size_t size) const { - - if (size < getFlattenedSize()) { - return NO_MEMORY; - } - - int32_t* const buf = static_cast(buffer); - reinterpret_cast(buf[0]) = mMaxLuminance; - reinterpret_cast(buf[1]) = mMaxAverageLuminance; - reinterpret_cast(buf[2]) = mMinLuminance; - buf[3] = static_cast(mSupportedHdrTypes.size()); - for (size_t i = 0, c = mSupportedHdrTypes.size(); i < c; ++i) { - buf[4 + i] = static_cast(mSupportedHdrTypes[i]); - } - return NO_ERROR; -} - -status_t HdrCapabilities::unflatten(void const* buffer, size_t size) { - - size_t minSize = sizeof(mMaxLuminance) + - sizeof(mMaxAverageLuminance) + - sizeof(mMinLuminance) + - sizeof(int32_t); - - if (size < minSize) { - return NO_MEMORY; - } - - int32_t const * const buf = static_cast(buffer); - const size_t itemCount = size_t(buf[3]); - - // check the buffer is large enough - if (size < minSize + itemCount * sizeof(int32_t)) { - return BAD_VALUE; - } - - mMaxLuminance = reinterpret_cast(buf[0]); - mMaxAverageLuminance = reinterpret_cast(buf[1]); - mMinLuminance = reinterpret_cast(buf[2]); - if (itemCount) { - mSupportedHdrTypes.resize(itemCount); - for (size_t i = 0; i < itemCount; ++i) { - mSupportedHdrTypes[i] = static_cast(buf[4 + i]); - } - } - return NO_ERROR; -} - -#if defined(__clang__) -#pragma clang diagnostic pop -#endif - -} // namespace android diff --git a/libs/ui/include/ui/DisplayMode.h b/libs/ui/include/ui/DisplayMode.h index 56f68e7bb2..a2791a6d44 100644 --- a/libs/ui/include/ui/DisplayMode.h +++ b/libs/ui/include/ui/DisplayMode.h @@ -29,7 +29,7 @@ namespace android::ui { using DisplayModeId = int32_t; // Mode supported by physical display. -struct DisplayMode : LightFlattenable { +struct DisplayMode { DisplayModeId id; ui::Size resolution; float xDpi = 0; @@ -40,11 +40,6 @@ struct DisplayMode : LightFlattenable { nsecs_t sfVsyncOffset = 0; nsecs_t presentationDeadline = 0; int32_t group = -1; - - bool isFixedSize() const { return false; } - size_t getFlattenedSize() const; - status_t flatten(void* buffer, size_t size) const; - status_t unflatten(const void* buffer, size_t size); }; } // namespace android::ui diff --git a/libs/ui/include/ui/DynamicDisplayInfo.h b/libs/ui/include/ui/DynamicDisplayInfo.h index ce75a65214..8c9fe4c311 100644 --- a/libs/ui/include/ui/DynamicDisplayInfo.h +++ b/libs/ui/include/ui/DynamicDisplayInfo.h @@ -24,12 +24,11 @@ #include #include -#include namespace android::ui { // Information about a physical display which may change on hotplug reconnect. -struct DynamicDisplayInfo : LightFlattenable { +struct DynamicDisplayInfo { std::vector supportedDisplayModes; // This struct is going to be serialized over binder, so @@ -53,11 +52,6 @@ struct DynamicDisplayInfo : LightFlattenable { ui::DisplayModeId preferredBootDisplayMode; std::optional getActiveDisplayMode() const; - - bool isFixedSize() const { return false; } - size_t getFlattenedSize() const; - status_t flatten(void* buffer, size_t size) const; - status_t unflatten(const void* buffer, size_t size); }; } // namespace android::ui diff --git a/libs/ui/include/ui/HdrCapabilities.h b/libs/ui/include/ui/HdrCapabilities.h index 813addeca6..ae54223585 100644 --- a/libs/ui/include/ui/HdrCapabilities.h +++ b/libs/ui/include/ui/HdrCapabilities.h @@ -22,12 +22,10 @@ #include #include -#include namespace android { -class HdrCapabilities : public LightFlattenable -{ +class HdrCapabilities { public: HdrCapabilities(const std::vector& types, float maxLuminance, float maxAverageLuminance, float minLuminance) @@ -49,12 +47,6 @@ public: float getDesiredMaxAverageLuminance() const { return mMaxAverageLuminance; } float getDesiredMinLuminance() const { return mMinLuminance; } - // Flattenable protocol - bool isFixedSize() const { return false; } - size_t getFlattenedSize() const; - status_t flatten(void* buffer, size_t size) const; - status_t unflatten(void const* buffer, size_t size); - private: std::vector mSupportedHdrTypes; float mMaxLuminance; diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 6b312db784..1080bb675d 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5517,7 +5517,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_ACTIVE_DISPLAY_MODE: case GET_DISPLAY_COLOR_MODES: case GET_DISPLAY_NATIVE_PRIMARIES: - case GET_DYNAMIC_DISPLAY_INFO: case GET_DISPLAY_MODES: case GET_SUPPORTED_FRAME_TIMESTAMPS: // Calling setTransactionState is safe, because you need to have been @@ -5591,6 +5590,7 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_DISPLAY_STATE: case GET_DISPLAY_STATS: case GET_STATIC_DISPLAY_INFO: + case GET_DYNAMIC_DISPLAY_INFO: case CLEAR_BOOT_DISPLAY_MODE: case GET_BOOT_DISPLAY_MODE_SUPPORT: case SET_AUTO_LOW_LATENCY_MODE: @@ -7436,6 +7436,57 @@ binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp& disp return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp& display, + gui::DynamicDisplayInfo* outInfo) { + ui::DynamicDisplayInfo info; + status_t status = mFlinger->getDynamicDisplayInfo(display, &info); + if (status == NO_ERROR) { + // convert ui::DynamicDisplayInfo to gui::DynamicDisplayInfo + outInfo->supportedDisplayModes.clear(); + outInfo->supportedDisplayModes.reserve(info.supportedDisplayModes.size()); + for (const auto& mode : info.supportedDisplayModes) { + gui::DisplayMode outMode; + outMode.id = mode.id; + outMode.resolution.width = mode.resolution.width; + outMode.resolution.height = mode.resolution.height; + outMode.xDpi = mode.xDpi; + outMode.yDpi = mode.yDpi; + outMode.refreshRate = mode.refreshRate; + outMode.appVsyncOffset = mode.appVsyncOffset; + outMode.sfVsyncOffset = mode.sfVsyncOffset; + outMode.presentationDeadline = mode.presentationDeadline; + outMode.group = mode.group; + outInfo->supportedDisplayModes.push_back(outMode); + } + + outInfo->activeDisplayModeId = info.activeDisplayModeId; + + outInfo->supportedColorModes.clear(); + outInfo->supportedColorModes.reserve(info.supportedColorModes.size()); + for (const auto& cmode : info.supportedColorModes) { + outInfo->supportedColorModes.push_back(static_cast(cmode)); + } + + outInfo->activeColorMode = static_cast(info.activeColorMode); + + gui::HdrCapabilities& hdrCapabilities = outInfo->hdrCapabilities; + hdrCapabilities.supportedHdrTypes.clear(); + hdrCapabilities.supportedHdrTypes.reserve( + info.hdrCapabilities.getSupportedHdrTypes().size()); + for (const auto& hdr : info.hdrCapabilities.getSupportedHdrTypes()) { + hdrCapabilities.supportedHdrTypes.push_back(static_cast(hdr)); + } + hdrCapabilities.maxLuminance = info.hdrCapabilities.getDesiredMaxLuminance(); + hdrCapabilities.maxAverageLuminance = info.hdrCapabilities.getDesiredMaxAverageLuminance(); + hdrCapabilities.minLuminance = info.hdrCapabilities.getDesiredMinLuminance(); + + outInfo->autoLowLatencyModeSupported = info.autoLowLatencyModeSupported; + outInfo->gameContentTypeSupported = info.gameContentTypeSupported; + outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode; + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { status_t status = checkAccessPermission(); if (status == OK) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 9e5d84c915..43174b61a0 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -570,7 +570,7 @@ private: status_t getStaticDisplayInfo(const sp& displayToken, ui::StaticDisplayInfo*) EXCLUDES(mStateLock); status_t getDynamicDisplayInfo(const sp& displayToken, ui::DynamicDisplayInfo*) - EXCLUDES(mStateLock) override; + EXCLUDES(mStateLock); status_t getDisplayNativePrimaries(const sp& displayToken, ui::DisplayPrimaries&) override; status_t setActiveColorMode(const sp& displayToken, ui::ColorMode colorMode) override; @@ -1463,6 +1463,8 @@ public: gui::DisplayState* outState) override; binder::Status getStaticDisplayInfo(const sp& display, gui::StaticDisplayInfo* outInfo) override; + binder::Status getDynamicDisplayInfo(const sp& display, + gui::DynamicDisplayInfo* outInfo) override; binder::Status clearBootDisplayMode(const sp& display) override; binder::Status getBootDisplayModeSupport(bool* outMode) override; binder::Status setAutoLowLatencyMode(const sp& display, bool on) override; -- cgit v1.2.3-59-g8ed1b From ca3d9a423ae718c62fcda4fb249e0760a6fb3727 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 22 Feb 2022 11:07:34 -0800 Subject: Convert DisplayPrimaries to AIDL parcelable And migrate related ISurfaceComposer::getDisplayNativePrimaries() method to AIDL. (1) add android::gui::DisplayNativePrimaries parcelable for serialization (2) convert between ui::DisplayPrimaries and gui::DisplayPrimaries (3) migrate setActiveColorMode (4) migrate setBootDisplayMode Bug: 220894272 Test: atest libgui_test Change-Id: I1371f6ef2c1f52f56db53d437cf919ee7f269b48 --- libs/gui/ISurfaceComposer.cpp | 131 --------------------- libs/gui/SurfaceComposerClient.cpp | 31 ++++- libs/gui/aidl/android/gui/DisplayPrimaries.aidl | 33 ++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 10 ++ libs/gui/include/gui/ISurfaceComposer.h | 22 +--- libs/gui/tests/Surface_test.cpp | 24 ++-- services/surfaceflinger/SurfaceFlinger.cpp | 48 +++++++- services/surfaceflinger/SurfaceFlinger.h | 11 +- .../surfaceflinger/tests/BootDisplayMode_test.cpp | 8 +- 9 files changed, 147 insertions(+), 171 deletions(-) create mode 100644 libs/gui/aidl/android/gui/DisplayPrimaries.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a9473d4997..768ce2cd07 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -225,82 +225,6 @@ public: return result; } - status_t getDisplayNativePrimaries(const sp& display, - ui::DisplayPrimaries& primaries) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("getDisplayNativePrimaries failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("getDisplayNativePrimaries failed to writeStrongBinder: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::GET_DISPLAY_NATIVE_PRIMARIES, data, &reply); - if (result != NO_ERROR) { - ALOGE("getDisplayNativePrimaries failed to transact: %d", result); - return result; - } - result = reply.readInt32(); - if (result == NO_ERROR) { - memcpy(&primaries, reply.readInplace(sizeof(ui::DisplayPrimaries)), - sizeof(ui::DisplayPrimaries)); - } - return result; - } - - status_t setActiveColorMode(const sp& display, ColorMode colorMode) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("setActiveColorMode failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("setActiveColorMode failed to writeStrongBinder: %d", result); - return result; - } - result = data.writeInt32(static_cast(colorMode)); - if (result != NO_ERROR) { - ALOGE("setActiveColorMode failed to writeInt32: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::SET_ACTIVE_COLOR_MODE, data, &reply); - if (result != NO_ERROR) { - ALOGE("setActiveColorMode failed to transact: %d", result); - return result; - } - return static_cast(reply.readInt32()); - } - - status_t setBootDisplayMode(const sp& display, - ui::DisplayModeId displayModeId) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(display); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to writeStrongBinder: %d", result); - return result; - } - result = data.writeInt32(displayModeId); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to writeIint32: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::SET_BOOT_DISPLAY_MODE, data, &reply); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to transact: %d", result); - } - return result; - } - status_t clearAnimationFrameStats() override { Parcel data, reply; status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); @@ -1122,61 +1046,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case GET_DISPLAY_NATIVE_PRIMARIES: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - ui::DisplayPrimaries primaries; - sp display = nullptr; - - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("getDisplayNativePrimaries failed to readStrongBinder: %d", result); - return result; - } - - result = getDisplayNativePrimaries(display, primaries); - reply->writeInt32(result); - if (result == NO_ERROR) { - memcpy(reply->writeInplace(sizeof(ui::DisplayPrimaries)), &primaries, - sizeof(ui::DisplayPrimaries)); - } - - return NO_ERROR; - } - case SET_ACTIVE_COLOR_MODE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("getActiveColorMode failed to readStrongBinder: %d", result); - return result; - } - int32_t colorModeInt = 0; - result = data.readInt32(&colorModeInt); - if (result != NO_ERROR) { - ALOGE("setActiveColorMode failed to readInt32: %d", result); - return result; - } - result = setActiveColorMode(display, - static_cast(colorModeInt)); - result = reply->writeInt32(result); - return result; - } - case SET_BOOT_DISPLAY_MODE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to readStrongBinder: %d", result); - return result; - } - ui::DisplayModeId displayModeId; - result = data.readInt32(&displayModeId); - if (result != NO_ERROR) { - ALOGE("setBootDisplayMode failed to readInt32: %d", result); - return result; - } - return setBootDisplayMode(display, displayModeId); - } case CLEAR_ANIMATION_FRAME_STATS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); status_t result = clearAnimationFrameStats(); diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 6702fef45e..82f63d3ae8 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2278,12 +2278,35 @@ status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp& di status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp& display, ui::DisplayPrimaries& outPrimaries) { - return ComposerService::getComposerService()->getDisplayNativePrimaries(display, outPrimaries); + gui::DisplayPrimaries primaries; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDisplayNativePrimaries(display, + &primaries); + if (status.isOk()) { + outPrimaries.red.X = primaries.red.X; + outPrimaries.red.Y = primaries.red.Y; + outPrimaries.red.Z = primaries.red.Z; + + outPrimaries.green.X = primaries.green.X; + outPrimaries.green.Y = primaries.green.Y; + outPrimaries.green.Z = primaries.green.Z; + + outPrimaries.blue.X = primaries.blue.X; + outPrimaries.blue.Y = primaries.blue.Y; + outPrimaries.blue.Z = primaries.blue.Z; + + outPrimaries.white.X = primaries.white.X; + outPrimaries.white.Y = primaries.white.Y; + outPrimaries.white.Z = primaries.white.Z; + } + return status.transactionError(); } status_t SurfaceComposerClient::setActiveColorMode(const sp& display, ColorMode colorMode) { - return ComposerService::getComposerService()->setActiveColorMode(display, colorMode); + binder::Status status = ComposerServiceAIDL::getComposerService() + ->setActiveColorMode(display, static_cast(colorMode)); + return status.transactionError(); } status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) { @@ -2294,7 +2317,9 @@ status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) { status_t SurfaceComposerClient::setBootDisplayMode(const sp& display, ui::DisplayModeId displayModeId) { - return ComposerService::getComposerService()->setBootDisplayMode(display, displayModeId); + binder::Status status = ComposerServiceAIDL::getComposerService() + ->setBootDisplayMode(display, static_cast(displayModeId)); + return status.transactionError(); } status_t SurfaceComposerClient::clearBootDisplayMode(const sp& display) { diff --git a/libs/gui/aidl/android/gui/DisplayPrimaries.aidl b/libs/gui/aidl/android/gui/DisplayPrimaries.aidl new file mode 100644 index 0000000000..dbf668c629 --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayPrimaries.aidl @@ -0,0 +1,33 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// copied from libui ConfigStoreTypes.h + +/** @hide */ +parcelable DisplayPrimaries { + parcelable CieXyz { + float X; + float Y; + float Z; + } + + CieXyz red; + CieXyz green; + CieXyz blue; + CieXyz white; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 175007d380..6b901f14aa 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -18,6 +18,7 @@ package android.gui; import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; +import android.gui.DisplayPrimaries; import android.gui.DisplayState; import android.gui.DisplayStatInfo; import android.gui.StaticDisplayInfo; @@ -75,6 +76,15 @@ interface ISurfaceComposer { */ DynamicDisplayInfo getDynamicDisplayInfo(IBinder display); + DisplayPrimaries getDisplayNativePrimaries(IBinder display); + + void setActiveColorMode(IBinder display, int colorMode); + + /** + * Sets the user-preferred display mode that a device should boot in. + */ + void setBootDisplayMode(IBinder display, int displayModeId); + /** * Clears the user-preferred display mode. The device should now boot in system preferred * display mode. diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index ed8254ae8b..f17070d3ff 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -160,16 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - virtual status_t getDisplayNativePrimaries(const sp& display, - ui::DisplayPrimaries& primaries) = 0; - virtual status_t setActiveColorMode(const sp& display, - ui::ColorMode colorMode) = 0; - - /** - * Sets the user-preferred display mode that a device should boot in. - */ - virtual status_t setBootDisplayMode(const sp& display, ui::DisplayModeId) = 0; - /* Clears the frame statistics for animations. * * Requires the ACCESS_SURFACE_FLINGER permission. @@ -452,7 +442,7 @@ public: GET_HDR_CAPABILITIES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_DISPLAY_COLOR_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_ACTIVE_COLOR_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - SET_ACTIVE_COLOR_MODE, + SET_ACTIVE_COLOR_MODE, // Deprecated. Autogenerated by .aidl now. ENABLE_VSYNC_INJECTIONS, INJECT_VSYNC, GET_LAYER_DEBUG_INFO, @@ -462,9 +452,9 @@ public: SET_DISPLAY_CONTENT_SAMPLING_ENABLED, GET_DISPLAYED_CONTENT_SAMPLE, GET_PROTECTED_CONTENT_SUPPORT, - IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. - GET_DISPLAY_NATIVE_PRIMARIES, - GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. + IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAY_NATIVE_PRIMARIES, // Deprecated. Autogenerated by .aidl now. + GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. ADD_REGION_SAMPLING_LISTENER, REMOVE_REGION_SAMPLING_LISTENER, SET_DESIRED_DISPLAY_MODE_SPECS, @@ -499,8 +489,8 @@ public: GET_PRIMARY_PHYSICAL_DISPLAY_ID, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_DECORATION_SUPPORT, GET_BOOT_DISPLAY_MODE_SUPPORT, // Deprecated. Autogenerated by .aidl now. - SET_BOOT_DISPLAY_MODE, - CLEAR_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. + SET_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. + CLEAR_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. SET_OVERRIDE_FRAME_RATE, // Always append new enum to the end. }; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index bf1b43d2c0..a2ab8c1eea 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -733,16 +733,6 @@ public: return NO_ERROR; } - status_t getDisplayNativePrimaries(const sp& /*display*/, - ui::DisplayPrimaries& /*primaries*/) override { - return NO_ERROR; - } - status_t setActiveColorMode(const sp& /*display*/, - ColorMode /*colorMode*/) override { return NO_ERROR; } - status_t setBootDisplayMode(const sp& /*display*/, ui::DisplayModeId /*id*/) override { - return NO_ERROR; - } - status_t clearAnimationFrameStats() override { return NO_ERROR; } status_t getAnimationFrameStats(FrameStats* /*outStats*/) const override { return NO_ERROR; @@ -932,6 +922,20 @@ public: return binder::Status::ok(); } + binder::Status getDisplayNativePrimaries(const sp& /*display*/, + gui::DisplayPrimaries* /*outPrimaries*/) override { + return binder::Status::ok(); + } + + binder::Status setActiveColorMode(const sp& /*display*/, int /*colorMode*/) override { + return binder::Status::ok(); + } + + binder::Status setBootDisplayMode(const sp& /*display*/, + int /*displayModeId*/) override { + return binder::Status::ok(); + } + binder::Status clearBootDisplayMode(const sp& /*display*/) override { return binder::Status::ok(); } diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 3d723d4b7a..884b4bc20a 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5472,8 +5472,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_HDR_CAPABILITIES: case SET_DESIRED_DISPLAY_MODE_SPECS: case GET_DESIRED_DISPLAY_MODE_SPECS: - case SET_ACTIVE_COLOR_MODE: - case SET_BOOT_DISPLAY_MODE: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: case GET_GAME_CONTENT_TYPE_SUPPORT: case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: @@ -5513,7 +5511,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_ACTIVE_COLOR_MODE: case GET_ACTIVE_DISPLAY_MODE: case GET_DISPLAY_COLOR_MODES: - case GET_DISPLAY_NATIVE_PRIMARIES: case GET_DISPLAY_MODES: case GET_SUPPORTED_FRAME_TIMESTAMPS: // Calling setTransactionState is safe, because you need to have been @@ -5588,6 +5585,9 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_DISPLAY_STATS: case GET_STATIC_DISPLAY_INFO: case GET_DYNAMIC_DISPLAY_INFO: + case GET_DISPLAY_NATIVE_PRIMARIES: + case SET_ACTIVE_COLOR_MODE: + case SET_BOOT_DISPLAY_MODE: case CLEAR_BOOT_DISPLAY_MODE: case GET_BOOT_DISPLAY_MODE_SUPPORT: case SET_AUTO_LOW_LATENCY_MODE: @@ -7484,6 +7484,48 @@ binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp& dis return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp& display, + gui::DisplayPrimaries* outPrimaries) { + ui::DisplayPrimaries primaries; + status_t status = mFlinger->getDisplayNativePrimaries(display, primaries); + if (status == NO_ERROR) { + outPrimaries->red.X = primaries.red.X; + outPrimaries->red.Y = primaries.red.Y; + outPrimaries->red.Z = primaries.red.Z; + + outPrimaries->green.X = primaries.green.X; + outPrimaries->green.Y = primaries.green.Y; + outPrimaries->green.Z = primaries.green.Z; + + outPrimaries->blue.X = primaries.blue.X; + outPrimaries->blue.Y = primaries.blue.Y; + outPrimaries->blue.Z = primaries.blue.Z; + + outPrimaries->white.X = primaries.white.X; + outPrimaries->white.Y = primaries.white.Y; + outPrimaries->white.Z = primaries.white.Z; + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp& display, int colorMode) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->setActiveColorMode(display, static_cast(colorMode)); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp& display, + int displayModeId) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->setBootDisplayMode(display, + static_cast(displayModeId)); + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { status_t status = checkAccessPermission(); if (status == OK) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 43174b61a0..5b21412576 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -571,11 +571,10 @@ private: EXCLUDES(mStateLock); status_t getDynamicDisplayInfo(const sp& displayToken, ui::DynamicDisplayInfo*) EXCLUDES(mStateLock); - status_t getDisplayNativePrimaries(const sp& displayToken, - ui::DisplayPrimaries&) override; - status_t setActiveColorMode(const sp& displayToken, ui::ColorMode colorMode) override; + status_t getDisplayNativePrimaries(const sp& displayToken, ui::DisplayPrimaries&); + status_t setActiveColorMode(const sp& displayToken, ui::ColorMode colorMode); status_t getBootDisplayModeSupport(bool* outSupport) const; - status_t setBootDisplayMode(const sp& displayToken, ui::DisplayModeId id) override; + status_t setBootDisplayMode(const sp& displayToken, ui::DisplayModeId id); status_t clearBootDisplayMode(const sp& displayToken); void setAutoLowLatencyMode(const sp& displayToken, bool on); void setGameContentType(const sp& displayToken, bool on); @@ -1465,6 +1464,10 @@ public: gui::StaticDisplayInfo* outInfo) override; binder::Status getDynamicDisplayInfo(const sp& display, gui::DynamicDisplayInfo* outInfo) override; + binder::Status getDisplayNativePrimaries(const sp& display, + gui::DisplayPrimaries* outPrimaries) override; + binder::Status setActiveColorMode(const sp& display, int colorMode) override; + binder::Status setBootDisplayMode(const sp& display, int displayModeId) override; binder::Status clearBootDisplayMode(const sp& display) override; binder::Status getBootDisplayModeSupport(bool* outMode) override; binder::Status setAutoLowLatencyMode(const sp& display, bool on) override; diff --git a/services/surfaceflinger/tests/BootDisplayMode_test.cpp b/services/surfaceflinger/tests/BootDisplayMode_test.cpp index d70908e390..4cd6ef8f1d 100644 --- a/services/surfaceflinger/tests/BootDisplayMode_test.cpp +++ b/services/surfaceflinger/tests/BootDisplayMode_test.cpp @@ -26,14 +26,14 @@ namespace android { TEST(BootDisplayModeTest, setBootDisplayMode) { - sp sf(ComposerService::getComposerService()); - sp sf_aidl(ComposerServiceAIDL::getComposerService()); + sp sf(ComposerServiceAIDL::getComposerService()); auto displayToken = SurfaceComposerClient::getInternalDisplayToken(); bool bootModeSupport = false; - binder::Status status = sf_aidl->getBootDisplayModeSupport(&bootModeSupport); + binder::Status status = sf->getBootDisplayModeSupport(&bootModeSupport); ASSERT_NO_FATAL_FAILURE(status.transactionError()); if (bootModeSupport) { - ASSERT_EQ(NO_ERROR, sf->setBootDisplayMode(displayToken, 0)); + status = sf->setBootDisplayMode(displayToken, 0); + ASSERT_EQ(NO_ERROR, status.transactionError()); } } -- cgit v1.2.3-59-g8ed1b From 4ed1c91900c539dd91797e89f51e5018fd2ba228 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 22 Feb 2022 14:30:01 -0800 Subject: Convert FrameStats to AIDL parcelable And migrate related ISurfaceComposer methods to AIDL. (1) add android::gui::FrameStats parcelable for serialization (2) convert between FrameStats and gui::FrameStats (3) migrate clearAnimationFrameStats (4) migrate getAnimationFrameStats Bug: 220910000 Test: atest libgui_test Change-Id: I7c0aadbd791834e6bd22ccfc75dad39642d08160 --- libs/gui/ISurfaceComposer.cpp | 37 ------------------- libs/gui/SurfaceComposerClient.cpp | 23 ++++++++++-- libs/gui/aidl/android/gui/FrameStats.aidl | 47 +++++++++++++++++++++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 13 +++++++ libs/gui/include/gui/ISurfaceComposer.h | 22 +++--------- libs/gui/tests/Surface_test.cpp | 10 +++--- services/surfaceflinger/SurfaceFlinger.cpp | 38 ++++++++++++++++++-- services/surfaceflinger/SurfaceFlinger.h | 6 ++-- 8 files changed, 132 insertions(+), 64 deletions(-) create mode 100644 libs/gui/aidl/android/gui/FrameStats.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 768ce2cd07..a20d428345 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -225,29 +225,6 @@ public: return result; } - status_t clearAnimationFrameStats() override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("clearAnimationFrameStats failed to writeInterfaceToken: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::CLEAR_ANIMATION_FRAME_STATS, data, &reply); - if (result != NO_ERROR) { - ALOGE("clearAnimationFrameStats failed to transact: %d", result); - return result; - } - return reply.readInt32(); - } - - status_t getAnimationFrameStats(FrameStats* outStats) const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - remote()->transact(BnSurfaceComposer::GET_ANIMATION_FRAME_STATS, data, &reply); - reply.read(*outStats); - return reply.readInt32(); - } - virtual status_t overrideHdrTypes(const sp& display, const std::vector& hdrTypes) { Parcel data, reply; @@ -1046,20 +1023,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case CLEAR_ANIMATION_FRAME_STATS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - status_t result = clearAnimationFrameStats(); - reply->writeInt32(result); - return NO_ERROR; - } - case GET_ANIMATION_FRAME_STATS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - FrameStats stats; - status_t result = getAnimationFrameStats(&stats); - reply->write(stats); - reply->writeInt32(result); - return NO_ERROR; - } case ENABLE_VSYNC_INJECTIONS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); bool enable = false; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 82f63d3ae8..be5f338c39 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2360,11 +2360,30 @@ bool SurfaceComposerClient::getProtectedContentSupport() { } status_t SurfaceComposerClient::clearAnimationFrameStats() { - return ComposerService::getComposerService()->clearAnimationFrameStats(); + binder::Status status = ComposerServiceAIDL::getComposerService()->clearAnimationFrameStats(); + return status.transactionError(); } status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) { - return ComposerService::getComposerService()->getAnimationFrameStats(outStats); + gui::FrameStats stats; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getAnimationFrameStats(&stats); + if (status.isOk()) { + outStats->refreshPeriodNano = stats.refreshPeriodNano; + outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size()); + for (const auto& t : stats.desiredPresentTimesNano) { + outStats->desiredPresentTimesNano.add(t); + } + outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size()); + for (const auto& t : stats.actualPresentTimesNano) { + outStats->actualPresentTimesNano.add(t); + } + outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size()); + for (const auto& t : stats.frameReadyTimesNano) { + outStats->frameReadyTimesNano.add(t); + } + } + return status.transactionError(); } status_t SurfaceComposerClient::overrideHdrTypes(const sp& display, diff --git a/libs/gui/aidl/android/gui/FrameStats.aidl b/libs/gui/aidl/android/gui/FrameStats.aidl new file mode 100644 index 0000000000..a145e74b11 --- /dev/null +++ b/libs/gui/aidl/android/gui/FrameStats.aidl @@ -0,0 +1,47 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// Make sure to sync with libui FrameStats.h + +/** @hide */ +parcelable FrameStats { + /* + * Approximate refresh time, in nanoseconds. + */ + long refreshPeriodNano; + + /* + * The times in nanoseconds for when the frame contents were posted by the producer (e.g. + * the application). They are either explicitly set or defaulted to the time when + * Surface::queueBuffer() was called. + */ + long[] desiredPresentTimesNano; + + /* + * The times in milliseconds for when the frame contents were presented on the screen. + */ + long[] actualPresentTimesNano; + + /* + * The times in nanoseconds for when the frame contents were ready to be presented. Note that + * a frame can be posted and still it contents being rendered asynchronously in GL. In such a + * case these are the times when the frame contents were completely rendered (i.e. their fences + * signaled). + */ + long[] frameReadyTimesNano; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 6b901f14aa..59e8dd61fb 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -21,6 +21,7 @@ import android.gui.DisplayBrightness; import android.gui.DisplayPrimaries; import android.gui.DisplayState; import android.gui.DisplayStatInfo; +import android.gui.FrameStats; import android.gui.StaticDisplayInfo; import android.gui.DynamicDisplayInfo; import android.gui.IHdrLayerInfoListener; @@ -138,6 +139,18 @@ interface ISurfaceComposer { */ void captureLayers(in LayerCaptureArgs args, IScreenCaptureListener listener); + /* Clears the frame statistics for animations. + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + void clearAnimationFrameStats(); + + /* Gets the frame statistics for animations. + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + FrameStats getAnimationFrameStats(); + /* * Queries whether the given display is a wide color display. * Requires the ACCESS_SURFACE_FLINGER permission. diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index f17070d3ff..35f6e4d328 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -160,18 +160,6 @@ public: virtual status_t getSupportedFrameTimestamps( std::vector* outSupported) const = 0; - /* Clears the frame statistics for animations. - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t clearAnimationFrameStats() = 0; - - /* Gets the frame statistics for animations. - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getAnimationFrameStats(FrameStats* outStats) const = 0; - /* Overrides the supported HDR modes for the given display device. * * Requires the ACCESS_SURFACE_FLINGER permission. @@ -433,11 +421,11 @@ public: GET_DISPLAY_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_ACTIVE_DISPLAY_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_DISPLAY_STATE, - CAPTURE_DISPLAY, // Deprecated. Autogenerated by .aidl now. - CAPTURE_LAYERS, // Deprecated. Autogenerated by .aidl now. - CLEAR_ANIMATION_FRAME_STATS, - GET_ANIMATION_FRAME_STATS, - SET_POWER_MODE, // Deprecated. Autogenerated by .aidl now. + CAPTURE_DISPLAY, // Deprecated. Autogenerated by .aidl now. + CAPTURE_LAYERS, // Deprecated. Autogenerated by .aidl now. + CLEAR_ANIMATION_FRAME_STATS, // Deprecated. Autogenerated by .aidl now. + GET_ANIMATION_FRAME_STATS, // Deprecated. Autogenerated by .aidl now. + SET_POWER_MODE, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_STATS, GET_HDR_CAPABILITIES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_DISPLAY_COLOR_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index a2ab8c1eea..6a10305651 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -733,10 +733,6 @@ public: return NO_ERROR; } - status_t clearAnimationFrameStats() override { return NO_ERROR; } - status_t getAnimationFrameStats(FrameStats* /*outStats*/) const override { - return NO_ERROR; - } status_t overrideHdrTypes(const sp& /*display*/, const std::vector& /*hdrTypes*/) override { return NO_ERROR; @@ -966,6 +962,12 @@ public: return binder::Status::ok(); } + binder::Status clearAnimationFrameStats() override { return binder::Status::ok(); } + + binder::Status getAnimationFrameStats(gui::FrameStats* /*outStats*/) override { + return binder::Status::ok(); + } + binder::Status isWideColorDisplay(const sp& /*token*/, bool* /*outIsWideColorDisplay*/) override { return binder::Status::ok(); diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 884b4bc20a..58d8acca56 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5466,8 +5466,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // These methods should at minimum make sure that the client requested // access to SF. case BOOT_FINISHED: - case CLEAR_ANIMATION_FRAME_STATS: - case GET_ANIMATION_FRAME_STATS: case OVERRIDE_HDR_TYPES: case GET_HDR_CAPABILITIES: case SET_DESIRED_DISPLAY_MODE_SPECS: @@ -5595,6 +5593,8 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case CAPTURE_LAYERS: case CAPTURE_DISPLAY: case CAPTURE_DISPLAY_BY_ID: + case CLEAR_ANIMATION_FRAME_STATS: + case GET_ANIMATION_FRAME_STATS: case IS_WIDE_COLOR_DISPLAY: case GET_DISPLAY_BRIGHTNESS_SUPPORT: case SET_DISPLAY_BRIGHTNESS: @@ -7586,6 +7586,40 @@ binder::Status SurfaceComposerAIDL::captureLayers( return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->clearAnimationFrameStats(); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + + FrameStats stats; + status = mFlinger->getAnimationFrameStats(&stats); + if (status == NO_ERROR) { + outStats->refreshPeriodNano = stats.refreshPeriodNano; + outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size()); + for (const auto& t : stats.desiredPresentTimesNano) { + outStats->desiredPresentTimesNano.push_back(t); + } + outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size()); + for (const auto& t : stats.actualPresentTimesNano) { + outStats->actualPresentTimesNano.push_back(t); + } + outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size()); + for (const auto& t : stats.frameReadyTimesNano) { + outStats->frameReadyTimesNano.push_back(t); + } + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) { status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay); diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 5b21412576..57b48c55f3 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -579,8 +579,8 @@ private: void setAutoLowLatencyMode(const sp& displayToken, bool on); void setGameContentType(const sp& displayToken, bool on); void setPowerMode(const sp& displayToken, int mode); - status_t clearAnimationFrameStats() override; - status_t getAnimationFrameStats(FrameStats* outStats) const override; + status_t clearAnimationFrameStats(); + status_t getAnimationFrameStats(FrameStats* outStats) const; status_t overrideHdrTypes(const sp& displayToken, const std::vector& hdrTypes) override; status_t onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) override; @@ -1477,6 +1477,8 @@ public: binder::Status captureDisplayById(int64_t, const sp&) override; binder::Status captureLayers(const LayerCaptureArgs&, const sp&) override; + binder::Status clearAnimationFrameStats() override; + binder::Status getAnimationFrameStats(gui::FrameStats* outStats) override; binder::Status isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) override; binder::Status getDisplayBrightnessSupport(const sp& displayToken, -- cgit v1.2.3-59-g8ed1b From 0a81aa312d9efa3369b31b1212b97f29f01fba74 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 22 Feb 2022 16:02:36 -0800 Subject: Migrate getSupportedFrameTimestamps() to AIDL Note that FrameEvent is converted to AIDL enum and some external projects are updated to reflect the changes, refer to the topic for other CLs. Bug: 220935835 Test: atest libgui_test Change-Id: I576360ad0684b1b010b773a2287050c9ba2f62f --- libs/bufferqueueconverter/Android.bp | 1 + libs/gui/Android.bp | 7 +++ libs/gui/ISurfaceComposer.cpp | 62 ------------------------- libs/gui/Surface.cpp | 6 +-- libs/gui/aidl/android/gui/FrameEvent.aidl | 35 ++++++++++++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 5 ++ libs/gui/include/gui/FrameTimestamps.h | 19 ++------ libs/gui/include/gui/ISurfaceComposer.h | 12 ++--- libs/gui/tests/Surface_test.cpp | 50 +++++++++++--------- libs/nativedisplay/Android.bp | 3 +- services/surfaceflinger/SurfaceFlinger.cpp | 14 +++++- services/surfaceflinger/SurfaceFlinger.h | 3 +- 12 files changed, 101 insertions(+), 116 deletions(-) create mode 100644 libs/gui/aidl/android/gui/FrameEvent.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/bufferqueueconverter/Android.bp b/libs/bufferqueueconverter/Android.bp index c5d3a3207c..5f145a149d 100644 --- a/libs/bufferqueueconverter/Android.bp +++ b/libs/bufferqueueconverter/Android.bp @@ -22,6 +22,7 @@ cc_library_shared { double_loadable: true, srcs: [ + ":libgui_frame_event_aidl", "BufferQueueConverter.cpp", ], diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index d634c58c53..6b64ac8597 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -120,6 +120,12 @@ filegroup { path: "aidl/", } +filegroup { + name: "libgui_frame_event_aidl", + srcs: ["aidl/android/gui/FrameEvent.aidl"], + path: "aidl/", +} + cc_library_static { name: "libgui_aidl_static", vendor_available: true, @@ -405,6 +411,7 @@ cc_library_static { ], srcs: [ + ":libgui_frame_event_aidl", "mock/GraphicBufferConsumer.cpp", "mock/GraphicBufferProducer.cpp", ], diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a20d428345..a1375684f9 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -159,49 +159,6 @@ public: return result != 0; } - status_t getSupportedFrameTimestamps(std::vector* outSupported) const override { - if (!outSupported) { - return UNEXPECTED_NULL; - } - outSupported->clear(); - - Parcel data, reply; - - status_t err = data.writeInterfaceToken( - ISurfaceComposer::getInterfaceDescriptor()); - if (err != NO_ERROR) { - return err; - } - - err = remote()->transact( - BnSurfaceComposer::GET_SUPPORTED_FRAME_TIMESTAMPS, - data, &reply); - if (err != NO_ERROR) { - return err; - } - - int32_t result = 0; - err = reply.readInt32(&result); - if (err != NO_ERROR) { - return err; - } - if (result != NO_ERROR) { - return result; - } - - std::vector supported; - err = reply.readInt32Vector(&supported); - if (err != NO_ERROR) { - return err; - } - - outSupported->reserve(supported.size()); - for (int32_t s : supported) { - outSupported->push_back(static_cast(s)); - } - return NO_ERROR; - } - sp createDisplayEventConnection( VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) override { Parcel data, reply; @@ -993,25 +950,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeInt32(result); return NO_ERROR; } - case GET_SUPPORTED_FRAME_TIMESTAMPS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - std::vector supportedTimestamps; - status_t result = getSupportedFrameTimestamps(&supportedTimestamps); - status_t err = reply->writeInt32(result); - if (err != NO_ERROR) { - return err; - } - if (result != NO_ERROR) { - return result; - } - - std::vector supported; - supported.reserve(supportedTimestamps.size()); - for (FrameEvent s : supportedTimestamps) { - supported.push_back(static_cast(s)); - } - return reply->writeInt32Vector(supported); - } case CREATE_DISPLAY_EVENT_CONNECTION: { CHECK_INTERFACE(ISurfaceComposer, data, reply); auto vsyncSource = static_cast(data.readInt32()); diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index bee820dfb1..128552dda3 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -1244,10 +1244,10 @@ void Surface::querySupportedTimestampsLocked() const { mQueriedSupportedTimestamps = true; std::vector supportedFrameTimestamps; - status_t err = composerService()->getSupportedFrameTimestamps( - &supportedFrameTimestamps); + binder::Status status = + composerServiceAIDL()->getSupportedFrameTimestamps(&supportedFrameTimestamps); - if (err != NO_ERROR) { + if (!status.isOk()) { return; } diff --git a/libs/gui/aidl/android/gui/FrameEvent.aidl b/libs/gui/aidl/android/gui/FrameEvent.aidl new file mode 100644 index 0000000000..aaabdb5b54 --- /dev/null +++ b/libs/gui/aidl/android/gui/FrameEvent.aidl @@ -0,0 +1,35 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// Identifiers for all the events that may be recorded or reported. + +/** @hide */ +@Backing(type="int") +enum FrameEvent { + POSTED = 0, + REQUESTED_PRESENT = 1, + LATCH = 2, + ACQUIRE = 3, + FIRST_REFRESH_START = 4, + LAST_REFRESH_START = 5, + GPU_COMPOSITION_DONE = 6, + DISPLAY_PRESENT = 7, + DEQUEUE_READY = 8, + RELEASE = 9, + EVENT_COUNT = 10 // Not an actual event. +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 59e8dd61fb..42e2d9bcf6 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -21,6 +21,7 @@ import android.gui.DisplayBrightness; import android.gui.DisplayPrimaries; import android.gui.DisplayState; import android.gui.DisplayStatInfo; +import android.gui.FrameEvent; import android.gui.FrameStats; import android.gui.StaticDisplayInfo; import android.gui.DynamicDisplayInfo; @@ -51,6 +52,10 @@ interface ISurfaceComposer { */ @nullable IBinder getPhysicalDisplayToken(long displayId); + /* Returns the frame timestamps supported by SurfaceFlinger. + */ + FrameEvent[] getSupportedFrameTimestamps(); + /* set display power mode. depending on the mode, it can either trigger * screen on, off or low power mode and wait for it to complete. * requires ACCESS_SURFACE_FLINGER permission. diff --git a/libs/gui/include/gui/FrameTimestamps.h b/libs/gui/include/gui/FrameTimestamps.h index dd3de58844..f73bc3b329 100644 --- a/libs/gui/include/gui/FrameTimestamps.h +++ b/libs/gui/include/gui/FrameTimestamps.h @@ -17,6 +17,8 @@ #ifndef ANDROID_GUI_FRAMETIMESTAMPS_H #define ANDROID_GUI_FRAMETIMESTAMPS_H +#include + #include #include #include @@ -31,22 +33,7 @@ namespace android { struct FrameEvents; class FrameEventHistoryDelta; - -// Identifiers for all the events that may be recorded or reported. -enum class FrameEvent { - POSTED, - REQUESTED_PRESENT, - LATCH, - ACQUIRE, - FIRST_REFRESH_START, - LAST_REFRESH_START, - GPU_COMPOSITION_DONE, - DISPLAY_PRESENT, - DEQUEUE_READY, - RELEASE, - EVENT_COUNT, // Not an actual event. -}; - +using gui::FrameEvent; // A collection of timestamps corresponding to a single frame. struct FrameEvents { diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 35f6e4d328..138d2edebd 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -66,7 +66,6 @@ class HdrCapabilities; class IGraphicBufferProducer; class ISurfaceComposerClient; class Rect; -enum class FrameEvent; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; @@ -155,11 +154,6 @@ public: virtual bool authenticateSurfaceTexture( const sp& surface) const = 0; - /* Returns the frame timestamps supported by SurfaceFlinger. - */ - virtual status_t getSupportedFrameTimestamps( - std::vector* outSupported) const = 0; - /* Overrides the supported HDR modes for the given display device. * * Requires the ACCESS_SURFACE_FLINGER permission. @@ -417,9 +411,9 @@ public: GET_PHYSICAL_DISPLAY_TOKEN, // Deprecated. Autogenerated by .aidl now. SET_TRANSACTION_STATE, AUTHENTICATE_SURFACE, - GET_SUPPORTED_FRAME_TIMESTAMPS, - GET_DISPLAY_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - GET_ACTIVE_DISPLAY_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + GET_SUPPORTED_FRAME_TIMESTAMPS, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAY_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + GET_ACTIVE_DISPLAY_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_DISPLAY_STATE, CAPTURE_DISPLAY, // Deprecated. Autogenerated by .aidl now. CAPTURE_LAYERS, // Deprecated. Autogenerated by .aidl now. diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 6a10305651..a644e042c9 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -714,25 +714,6 @@ public: return false; } - status_t getSupportedFrameTimestamps(std::vector* outSupported) - const override { - *outSupported = { - FrameEvent::REQUESTED_PRESENT, - FrameEvent::ACQUIRE, - FrameEvent::LATCH, - FrameEvent::FIRST_REFRESH_START, - FrameEvent::LAST_REFRESH_START, - FrameEvent::GPU_COMPOSITION_DONE, - FrameEvent::DEQUEUE_READY, - FrameEvent::RELEASE - }; - if (mSupportsPresent) { - outSupported->push_back( - FrameEvent::DISPLAY_PRESENT); - } - return NO_ERROR; - } - status_t overrideHdrTypes(const sp& /*display*/, const std::vector& /*hdrTypes*/) override { return NO_ERROR; @@ -898,6 +879,21 @@ public: return binder::Status::ok(); } + binder::Status getSupportedFrameTimestamps(std::vector* outSupported) override { + *outSupported = {FrameEvent::REQUESTED_PRESENT, + FrameEvent::ACQUIRE, + FrameEvent::LATCH, + FrameEvent::FIRST_REFRESH_START, + FrameEvent::LAST_REFRESH_START, + FrameEvent::GPU_COMPOSITION_DONE, + FrameEvent::DEQUEUE_READY, + FrameEvent::RELEASE}; + if (mSupportsPresent) { + outSupported->push_back(FrameEvent::DISPLAY_PRESENT); + } + return binder::Status::ok(); + } + binder::Status getDisplayStats(const sp& /*display*/, gui::DisplayStatInfo* /*outStatInfo*/) override { return binder::Status::ok(); @@ -1042,10 +1038,10 @@ protected: class TestSurface : public Surface { public: - TestSurface(const sp& bufferProducer, - FenceToFenceTimeMap* fenceMap) - : Surface(bufferProducer), - mFakeSurfaceComposer(new FakeSurfaceComposer) { + TestSurface(const sp& bufferProducer, FenceToFenceTimeMap* fenceMap) + : Surface(bufferProducer), + mFakeSurfaceComposer(new FakeSurfaceComposer), + mFakeSurfaceComposerAIDL(new FakeSurfaceComposerAIDL) { mFakeFrameEventHistory = new FakeProducerFrameEventHistory(fenceMap); mFrameEventHistory.reset(mFakeFrameEventHistory); } @@ -1056,6 +1052,10 @@ public: return mFakeSurfaceComposer; } + sp composerServiceAIDL() const override { + return mFakeSurfaceComposerAIDL; + } + nsecs_t now() const override { return mNow; } @@ -1066,6 +1066,7 @@ public: public: sp mFakeSurfaceComposer; + sp mFakeSurfaceComposerAIDL; nsecs_t mNow = 0; // mFrameEventHistory owns the instance of FakeProducerFrameEventHistory, @@ -1432,6 +1433,7 @@ TEST_F(GetFrameTimestampsTest, EnabledSimple) { TEST_F(GetFrameTimestampsTest, QueryPresentSupported) { bool displayPresentSupported = true; mSurface->mFakeSurfaceComposer->setSupportsPresent(displayPresentSupported); + mSurface->mFakeSurfaceComposerAIDL->setSupportsPresent(displayPresentSupported); // Verify supported bits are forwarded. int supportsPresent = -1; @@ -1443,6 +1445,7 @@ TEST_F(GetFrameTimestampsTest, QueryPresentSupported) { TEST_F(GetFrameTimestampsTest, QueryPresentNotSupported) { bool displayPresentSupported = false; mSurface->mFakeSurfaceComposer->setSupportsPresent(displayPresentSupported); + mSurface->mFakeSurfaceComposerAIDL->setSupportsPresent(displayPresentSupported); // Verify supported bits are forwarded. int supportsPresent = -1; @@ -2020,6 +2023,7 @@ TEST_F(GetFrameTimestampsTest, NoReleaseNoSync) { TEST_F(GetFrameTimestampsTest, PresentUnsupportedNoSync) { enableFrameTimestamps(); mSurface->mFakeSurfaceComposer->setSupportsPresent(false); + mSurface->mFakeSurfaceComposerAIDL->setSupportsPresent(false); // Dequeue and queue frame 1. const uint64_t fId1 = getNextFrameId(); diff --git a/libs/nativedisplay/Android.bp b/libs/nativedisplay/Android.bp index ed728dcb45..e3fad3db2a 100644 --- a/libs/nativedisplay/Android.bp +++ b/libs/nativedisplay/Android.bp @@ -33,7 +33,7 @@ license { cc_library_headers { name: "libnativedisplay_headers", - export_include_dirs: ["include",], + export_include_dirs: ["include"], } cc_library_shared { @@ -55,6 +55,7 @@ cc_library_shared { version_script: "libnativedisplay.map.txt", srcs: [ + ":libgui_frame_event_aidl", "AChoreographer.cpp", "ADisplay.cpp", "surfacetexture/surface_texture.cpp", diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 58d8acca56..b6d00b2da9 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5510,7 +5510,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_ACTIVE_DISPLAY_MODE: case GET_DISPLAY_COLOR_MODES: case GET_DISPLAY_MODES: - case GET_SUPPORTED_FRAME_TIMESTAMPS: // Calling setTransactionState is safe, because you need to have been // granted a reference to Client* and Handle* to do anything with it. case SET_TRANSACTION_STATE: @@ -5579,6 +5578,7 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_PHYSICAL_DISPLAY_IDS: case GET_PHYSICAL_DISPLAY_TOKEN: case SET_POWER_MODE: + case GET_SUPPORTED_FRAME_TIMESTAMPS: case GET_DISPLAY_STATE: case GET_DISPLAY_STATS: case GET_STATIC_DISPLAY_INFO: @@ -7368,6 +7368,18 @@ binder::Status SurfaceComposerAIDL::setPowerMode(const sp& display, int return binder::Status::ok(); } +binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps( + std::vector* outSupported) { + status_t status; + if (!outSupported) { + status = UNEXPECTED_NULL; + } else { + outSupported->clear(); + status = mFlinger->getSupportedFrameTimestamps(outSupported); + } + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::getDisplayStats(const sp& display, gui::DisplayStatInfo* outStatInfo) { DisplayStatInfo statInfo; diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 57b48c55f3..1ca36bdf72 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -555,7 +555,7 @@ private: void bootFinished() override; bool authenticateSurfaceTexture( const sp& bufferProducer) const override; - status_t getSupportedFrameTimestamps(std::vector* outSupported) const override; + virtual status_t getSupportedFrameTimestamps(std::vector* outSupported) const; sp createDisplayEventConnection( ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp, ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) override; @@ -1456,6 +1456,7 @@ public: binder::Status getPrimaryPhysicalDisplayId(int64_t* outDisplayId) override; binder::Status getPhysicalDisplayToken(int64_t displayId, sp* outDisplay) override; binder::Status setPowerMode(const sp& display, int mode) override; + binder::Status getSupportedFrameTimestamps(std::vector* outSupported) override; binder::Status getDisplayStats(const sp& display, gui::DisplayStatInfo* outStatInfo) override; binder::Status getDisplayState(const sp& display, -- cgit v1.2.3-59-g8ed1b From 05539a1ac638f03e070e571937928d2b050ffb1f Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Wed, 23 Feb 2022 10:29:40 -0800 Subject: Migrate 10 methods of ISurfaceComposer to AIDL Ten methods are migrated. LayerDebugInfo uses a c++ wrapper aidl for now due to large amount of existing code, but its namespace is changed to android::gui from android::. Parcelable CompositionPreference and ContentSamplingAttributes are added to pass the out values. Bug: 211009610 Test: atest libgui_test libsurfaceflinger_unittest Change-Id: I876a3394c9883ba3c6539154b95c7ace46f7a260 --- libs/gui/ISurfaceComposer.cpp | 359 --------------------- libs/gui/LayerDebugInfo.cpp | 4 +- libs/gui/SurfaceComposerClient.cpp | 68 +++- .../aidl/android/gui/CompositionPreference.aidl | 25 ++ .../android/gui/ContentSamplingAttributes.aidl | 24 ++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 104 ++++-- libs/gui/aidl/android/gui/LayerDebugInfo.aidl | 19 ++ libs/gui/aidl/android/gui/PullAtomData.aidl | 23 ++ libs/gui/include/gui/ISurfaceComposer.h | 94 ++---- libs/gui/include/gui/LayerDebugInfo.h | 4 +- libs/gui/tests/Surface_test.cpp | 75 +++-- services/surfaceflinger/Layer.cpp | 4 +- services/surfaceflinger/Layer.h | 7 +- services/surfaceflinger/SurfaceFlinger.cpp | 167 ++++++++-- services/surfaceflinger/SurfaceFlinger.h | 38 ++- services/surfaceflinger/tests/Credentials_test.cpp | 16 +- .../surfaceflinger/tests/LayerTransactionTest.h | 6 +- .../tests/fakehwc/SFFakeHwc_test.cpp | 10 +- 18 files changed, 483 insertions(+), 564 deletions(-) create mode 100644 libs/gui/aidl/android/gui/CompositionPreference.aidl create mode 100644 libs/gui/aidl/android/gui/ContentSamplingAttributes.aidl create mode 100644 libs/gui/aidl/android/gui/LayerDebugInfo.aidl create mode 100644 libs/gui/aidl/android/gui/PullAtomData.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a1375684f9..a10a2f06ba 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -182,206 +181,6 @@ public: return result; } - virtual status_t overrideHdrTypes(const sp& display, - const std::vector& hdrTypes) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, display); - - std::vector hdrTypesVector; - for (ui::Hdr i : hdrTypes) { - hdrTypesVector.push_back(static_cast(i)); - } - SAFE_PARCEL(data.writeInt32Vector, hdrTypesVector); - - status_t result = remote()->transact(BnSurfaceComposer::OVERRIDE_HDR_TYPES, data, &reply); - if (result != NO_ERROR) { - ALOGE("overrideHdrTypes failed to transact: %d", result); - return result; - } - return result; - } - - status_t onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeInt32, atomId); - - status_t err = remote()->transact(BnSurfaceComposer::ON_PULL_ATOM, data, &reply); - if (err != NO_ERROR) { - ALOGE("onPullAtom failed to transact: %d", err); - return err; - } - - int32_t size = 0; - SAFE_PARCEL(reply.readInt32, &size); - const void* dataPtr = reply.readInplace(size); - if (dataPtr == nullptr) { - return UNEXPECTED_NULL; - } - pulledData->assign((const char*)dataPtr, size); - SAFE_PARCEL(reply.readBool, success); - return NO_ERROR; - } - - status_t enableVSyncInjections(bool enable) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("enableVSyncInjections failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeBool(enable); - if (result != NO_ERROR) { - ALOGE("enableVSyncInjections failed to writeBool: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::ENABLE_VSYNC_INJECTIONS, data, &reply, - IBinder::FLAG_ONEWAY); - if (result != NO_ERROR) { - ALOGE("enableVSyncInjections failed to transact: %d", result); - return result; - } - return result; - } - - status_t injectVSync(nsecs_t when) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("injectVSync failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeInt64(when); - if (result != NO_ERROR) { - ALOGE("injectVSync failed to writeInt64: %d", result); - return result; - } - result = remote()->transact(BnSurfaceComposer::INJECT_VSYNC, data, &reply, - IBinder::FLAG_ONEWAY); - if (result != NO_ERROR) { - ALOGE("injectVSync failed to transact: %d", result); - return result; - } - return result; - } - - status_t getLayerDebugInfo(std::vector* outLayers) override { - if (!outLayers) { - return UNEXPECTED_NULL; - } - - Parcel data, reply; - - status_t err = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (err != NO_ERROR) { - return err; - } - - err = remote()->transact(BnSurfaceComposer::GET_LAYER_DEBUG_INFO, data, &reply); - if (err != NO_ERROR) { - return err; - } - - int32_t result = 0; - err = reply.readInt32(&result); - if (err != NO_ERROR) { - return err; - } - if (result != NO_ERROR) { - return result; - } - - outLayers->clear(); - return reply.readParcelableVector(outLayers); - } - - status_t getCompositionPreference(ui::Dataspace* defaultDataspace, - ui::PixelFormat* defaultPixelFormat, - ui::Dataspace* wideColorGamutDataspace, - ui::PixelFormat* wideColorGamutPixelFormat) const override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - return error; - } - error = remote()->transact(BnSurfaceComposer::GET_COMPOSITION_PREFERENCE, data, &reply); - if (error != NO_ERROR) { - return error; - } - error = static_cast(reply.readInt32()); - if (error == NO_ERROR) { - *defaultDataspace = static_cast(reply.readInt32()); - *defaultPixelFormat = static_cast(reply.readInt32()); - *wideColorGamutDataspace = static_cast(reply.readInt32()); - *wideColorGamutPixelFormat = static_cast(reply.readInt32()); - } - return error; - } - - status_t getColorManagement(bool* outGetColorManagement) const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - remote()->transact(BnSurfaceComposer::GET_COLOR_MANAGEMENT, data, &reply); - bool result; - status_t err = reply.readBool(&result); - if (err == NO_ERROR) { - *outGetColorManagement = result; - } - return err; - } - - status_t getDisplayedContentSamplingAttributes(const sp& display, - ui::PixelFormat* outFormat, - ui::Dataspace* outDataspace, - uint8_t* outComponentMask) const override { - if (!outFormat || !outDataspace || !outComponentMask) return BAD_VALUE; - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - - status_t error = - remote()->transact(BnSurfaceComposer::GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, - data, &reply); - if (error != NO_ERROR) { - return error; - } - - uint32_t value = 0; - error = reply.readUint32(&value); - if (error != NO_ERROR) { - return error; - } - *outFormat = static_cast(value); - - error = reply.readUint32(&value); - if (error != NO_ERROR) { - return error; - } - *outDataspace = static_cast(value); - - error = reply.readUint32(&value); - if (error != NO_ERROR) { - return error; - } - *outComponentMask = static_cast(value); - return error; - } - - status_t setDisplayContentSamplingEnabled(const sp& display, bool enable, - uint8_t componentMask, uint64_t maxFrames) override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - data.writeBool(enable); - data.writeByte(static_cast(componentMask)); - data.writeUint64(maxFrames); - status_t result = - remote()->transact(BnSurfaceComposer::SET_DISPLAY_CONTENT_SAMPLING_ENABLED, data, - &reply); - return result; - } - status_t getDisplayedContentSample(const sp& display, uint64_t maxFrames, uint64_t timestamp, DisplayedFrameStats* outStats) const override { @@ -421,18 +220,6 @@ public: return result; } - status_t getProtectedContentSupport(bool* outSupported) const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - status_t error = - remote()->transact(BnSurfaceComposer::GET_PROTECTED_CONTENT_SUPPORT, data, &reply); - if (error != NO_ERROR) { - return error; - } - error = reply.readBool(outSupported); - return error; - } - status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, const sp& listener) override { Parcel data, reply; @@ -961,116 +748,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case ENABLE_VSYNC_INJECTIONS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - bool enable = false; - status_t result = data.readBool(&enable); - if (result != NO_ERROR) { - ALOGE("enableVSyncInjections failed to readBool: %d", result); - return result; - } - return enableVSyncInjections(enable); - } - case INJECT_VSYNC: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int64_t when = 0; - status_t result = data.readInt64(&when); - if (result != NO_ERROR) { - ALOGE("enableVSyncInjections failed to readInt64: %d", result); - return result; - } - return injectVSync(when); - } - case GET_LAYER_DEBUG_INFO: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - std::vector outLayers; - status_t result = getLayerDebugInfo(&outLayers); - reply->writeInt32(result); - if (result == NO_ERROR) - { - result = reply->writeParcelableVector(outLayers); - } - return result; - } - case GET_COMPOSITION_PREFERENCE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - ui::Dataspace defaultDataspace; - ui::PixelFormat defaultPixelFormat; - ui::Dataspace wideColorGamutDataspace; - ui::PixelFormat wideColorGamutPixelFormat; - status_t error = - getCompositionPreference(&defaultDataspace, &defaultPixelFormat, - &wideColorGamutDataspace, &wideColorGamutPixelFormat); - reply->writeInt32(error); - if (error == NO_ERROR) { - reply->writeInt32(static_cast(defaultDataspace)); - reply->writeInt32(static_cast(defaultPixelFormat)); - reply->writeInt32(static_cast(wideColorGamutDataspace)); - reply->writeInt32(static_cast(wideColorGamutPixelFormat)); - } - return error; - } - case GET_COLOR_MANAGEMENT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - bool result; - status_t error = getColorManagement(&result); - if (error == NO_ERROR) { - reply->writeBool(result); - } - return error; - } - case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - - sp display = data.readStrongBinder(); - ui::PixelFormat format; - ui::Dataspace dataspace; - uint8_t component = 0; - auto result = - getDisplayedContentSamplingAttributes(display, &format, &dataspace, &component); - if (result == NO_ERROR) { - reply->writeUint32(static_cast(format)); - reply->writeUint32(static_cast(dataspace)); - reply->writeUint32(static_cast(component)); - } - return result; - } - case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - - sp display = nullptr; - bool enable = false; - int8_t componentMask = 0; - uint64_t maxFrames = 0; - status_t result = data.readStrongBinder(&display); - if (result != NO_ERROR) { - ALOGE("setDisplayContentSamplingEnabled failure in reading Display token: %d", - result); - return result; - } - - result = data.readBool(&enable); - if (result != NO_ERROR) { - ALOGE("setDisplayContentSamplingEnabled failure in reading enable: %d", result); - return result; - } - - result = data.readByte(static_cast(&componentMask)); - if (result != NO_ERROR) { - ALOGE("setDisplayContentSamplingEnabled failure in reading component mask: %d", - result); - return result; - } - - result = data.readUint64(&maxFrames); - if (result != NO_ERROR) { - ALOGE("setDisplayContentSamplingEnabled failure in reading max frames: %d", result); - return result; - } - - return setDisplayContentSamplingEnabled(display, enable, - static_cast(componentMask), maxFrames); - } case GET_DISPLAYED_CONTENT_SAMPLE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); @@ -1101,15 +778,6 @@ status_t BnSurfaceComposer::onTransact( } return result; } - case GET_PROTECTED_CONTENT_SUPPORT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - bool result; - status_t error = getProtectedContentSupport(&result); - if (error == NO_ERROR) { - reply->writeBool(result); - } - return error; - } case ADD_REGION_SAMPLING_LISTENER: { CHECK_INTERFACE(ISurfaceComposer, data, reply); Rect samplingArea; @@ -1413,33 +1081,6 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(reply->writeInt32, buffers); return NO_ERROR; } - case OVERRIDE_HDR_TYPES: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp display = nullptr; - SAFE_PARCEL(data.readStrongBinder, &display); - - std::vector hdrTypes; - SAFE_PARCEL(data.readInt32Vector, &hdrTypes); - - std::vector hdrTypesVector; - for (int i : hdrTypes) { - hdrTypesVector.push_back(static_cast(i)); - } - return overrideHdrTypes(display, hdrTypesVector); - } - case ON_PULL_ATOM: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int32_t atomId = 0; - SAFE_PARCEL(data.readInt32, &atomId); - - std::string pulledData; - bool success; - status_t err = onPullAtom(atomId, &pulledData, &success); - SAFE_PARCEL(reply->writeByteArray, pulledData.size(), - reinterpret_cast(pulledData.data())); - SAFE_PARCEL(reply->writeBool, success); - return err; - } case ADD_WINDOW_INFOS_LISTENER: { CHECK_INTERFACE(ISurfaceComposer, data, reply); sp listener; diff --git a/libs/gui/LayerDebugInfo.cpp b/libs/gui/LayerDebugInfo.cpp index ea5fb293a6..15b2221464 100644 --- a/libs/gui/LayerDebugInfo.cpp +++ b/libs/gui/LayerDebugInfo.cpp @@ -27,7 +27,7 @@ using android::base::StringAppendF; #define RETURN_ON_ERROR(X) do {status_t res = (X); if (res != NO_ERROR) return res;} while(false) -namespace android { +namespace android::gui { status_t LayerDebugInfo::writeToParcel(Parcel* parcel) const { RETURN_ON_ERROR(parcel->writeCString(mName.c_str())); @@ -149,4 +149,4 @@ std::string to_string(const LayerDebugInfo& info) { return result; } -} // android +} // namespace android::gui diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index be5f338c39..ca48ce63d0 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -2118,13 +2118,15 @@ status_t SurfaceComposerClient::getLayerFrameStats(const sp& token, // ---------------------------------------------------------------------------- status_t SurfaceComposerClient::enableVSyncInjections(bool enable) { - sp sf(ComposerService::getComposerService()); - return sf->enableVSyncInjections(enable); + sp sf(ComposerServiceAIDL::getComposerService()); + binder::Status status = sf->enableVSyncInjections(enable); + return status.transactionError(); } status_t SurfaceComposerClient::injectVSync(nsecs_t when) { - sp sf(ComposerService::getComposerService()); - return sf->injectVSync(when); + sp sf(ComposerServiceAIDL::getComposerService()); + binder::Status status = sf->injectVSync(when); + return status.transactionError(); } status_t SurfaceComposerClient::getDisplayState(const sp& display, @@ -2348,14 +2350,21 @@ void SurfaceComposerClient::setDisplayPowerMode(const sp& token, status_t SurfaceComposerClient::getCompositionPreference( ui::Dataspace* defaultDataspace, ui::PixelFormat* defaultPixelFormat, ui::Dataspace* wideColorGamutDataspace, ui::PixelFormat* wideColorGamutPixelFormat) { - return ComposerService::getComposerService() - ->getCompositionPreference(defaultDataspace, defaultPixelFormat, - wideColorGamutDataspace, wideColorGamutPixelFormat); + gui::CompositionPreference pref; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getCompositionPreference(&pref); + if (status.isOk()) { + *defaultDataspace = static_cast(pref.defaultDataspace); + *defaultPixelFormat = static_cast(pref.defaultPixelFormat); + *wideColorGamutDataspace = static_cast(pref.wideColorGamutDataspace); + *wideColorGamutPixelFormat = static_cast(pref.wideColorGamutPixelFormat); + } + return status.transactionError(); } bool SurfaceComposerClient::getProtectedContentSupport() { bool supported = false; - ComposerService::getComposerService()->getProtectedContentSupport(&supported); + ComposerServiceAIDL::getComposerService()->getProtectedContentSupport(&supported); return supported; } @@ -2388,29 +2397,56 @@ status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) { status_t SurfaceComposerClient::overrideHdrTypes(const sp& display, const std::vector& hdrTypes) { - return ComposerService::getComposerService()->overrideHdrTypes(display, hdrTypes); + std::vector hdrTypesVector; + hdrTypesVector.reserve(hdrTypes.size()); + for (auto t : hdrTypes) { + hdrTypesVector.push_back(static_cast(t)); + } + + binder::Status status = + ComposerServiceAIDL::getComposerService()->overrideHdrTypes(display, hdrTypesVector); + return status.transactionError(); } status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* outData, bool* success) { - return ComposerService::getComposerService()->onPullAtom(atomId, outData, success); + gui::PullAtomData pad; + binder::Status status = ComposerServiceAIDL::getComposerService()->onPullAtom(atomId, &pad); + if (status.isOk()) { + outData->assign((const char*)pad.data.data(), pad.data.size()); + *success = pad.success; + } + return status.transactionError(); } status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp& display, ui::PixelFormat* outFormat, ui::Dataspace* outDataspace, uint8_t* outComponentMask) { - return ComposerService::getComposerService() - ->getDisplayedContentSamplingAttributes(display, outFormat, outDataspace, - outComponentMask); + if (!outFormat || !outDataspace || !outComponentMask) { + return BAD_VALUE; + } + + gui::ContentSamplingAttributes attrs; + binder::Status status = ComposerServiceAIDL::getComposerService() + ->getDisplayedContentSamplingAttributes(display, &attrs); + if (status.isOk()) { + *outFormat = static_cast(attrs.format); + *outDataspace = static_cast(attrs.dataspace); + *outComponentMask = static_cast(attrs.componentMask); + } + return status.transactionError(); } status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const sp& display, bool enable, uint8_t componentMask, uint64_t maxFrames) { - return ComposerService::getComposerService()->setDisplayContentSamplingEnabled(display, enable, - componentMask, - maxFrames); + binder::Status status = + ComposerServiceAIDL::getComposerService() + ->setDisplayContentSamplingEnabled(display, enable, + static_cast(componentMask), + static_cast(maxFrames)); + return status.transactionError(); } status_t SurfaceComposerClient::getDisplayedContentSample(const sp& display, diff --git a/libs/gui/aidl/android/gui/CompositionPreference.aidl b/libs/gui/aidl/android/gui/CompositionPreference.aidl new file mode 100644 index 0000000000..b615824a7d --- /dev/null +++ b/libs/gui/aidl/android/gui/CompositionPreference.aidl @@ -0,0 +1,25 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable CompositionPreference { + int /*ui::Dataspace*/ defaultDataspace; + int /*ui::PixelFormat*/ defaultPixelFormat; + int /*ui::Dataspace*/ wideColorGamutDataspace; + int /*ui::PixelFormat*/ wideColorGamutPixelFormat; +} diff --git a/libs/gui/aidl/android/gui/ContentSamplingAttributes.aidl b/libs/gui/aidl/android/gui/ContentSamplingAttributes.aidl new file mode 100644 index 0000000000..5d913b1da6 --- /dev/null +++ b/libs/gui/aidl/android/gui/ContentSamplingAttributes.aidl @@ -0,0 +1,24 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable ContentSamplingAttributes { + int /*ui::PixelFormat*/ format; + int /*ui::Dataspace*/ dataspace; + byte componentMask; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 42e2d9bcf6..dc77416010 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -16,6 +16,8 @@ package android.gui; +import android.gui.CompositionPreference; +import android.gui.ContentSamplingAttributes; import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; import android.gui.DisplayPrimaries; @@ -23,6 +25,8 @@ import android.gui.DisplayState; import android.gui.DisplayStatInfo; import android.gui.FrameEvent; import android.gui.FrameStats; +import android.gui.LayerDebugInfo; +import android.gui.PullAtomData; import android.gui.StaticDisplayInfo; import android.gui.DynamicDisplayInfo; import android.gui.IHdrLayerInfoListener; @@ -31,43 +35,50 @@ import android.gui.IScreenCaptureListener; /** @hide */ interface ISurfaceComposer { - /* create a virtual display + /** + * Create a virtual display * requires ACCESS_SURFACE_FLINGER permission. */ @nullable IBinder createDisplay(@utf8InCpp String displayName, boolean secure); - /* destroy a virtual display + /** + * Destroy a virtual display * requires ACCESS_SURFACE_FLINGER permission. */ void destroyDisplay(IBinder display); - /* get stable IDs for connected physical displays. + /** + * Get stable IDs for connected physical displays. */ long[] getPhysicalDisplayIds(); long getPrimaryPhysicalDisplayId(); - /* get token for a physical display given its stable ID obtained via getPhysicalDisplayIds or a - * DisplayEventReceiver hotplug event. + /** + * Get token for a physical display given its stable ID obtained via getPhysicalDisplayIds or + * a DisplayEventReceiver hotplug event. */ @nullable IBinder getPhysicalDisplayToken(long displayId); - /* Returns the frame timestamps supported by SurfaceFlinger. + /** + * Returns the frame timestamps supported by SurfaceFlinger. */ FrameEvent[] getSupportedFrameTimestamps(); - /* set display power mode. depending on the mode, it can either trigger + /** + * Set display power mode. depending on the mode, it can either trigger * screen on, off or low power mode and wait for it to complete. * requires ACCESS_SURFACE_FLINGER permission. */ void setPowerMode(IBinder display, int mode); - /* returns display statistics for a given display + /** + * Returns display statistics for a given display * intended to be used by the media framework to properly schedule * video frames */ DisplayStatInfo getDisplayStats(IBinder display); - /** + /** * Get transactional state of given display. */ DisplayState getDisplayState(IBinder display); @@ -136,7 +147,9 @@ interface ISurfaceComposer { * match the size of the output buffer. */ void captureDisplay(in DisplayCaptureArgs args, IScreenCaptureListener listener); + void captureDisplayById(long displayId, IScreenCaptureListener listener); + /** * Capture a subtree of the layer hierarchy, potentially ignoring the root node. * This requires READ_FRAME_BUFFER permission. This function will fail if there @@ -144,25 +157,80 @@ interface ISurfaceComposer { */ void captureLayers(in LayerCaptureArgs args, IScreenCaptureListener listener); - /* Clears the frame statistics for animations. + /** + * Clears the frame statistics for animations. * * Requires the ACCESS_SURFACE_FLINGER permission. */ void clearAnimationFrameStats(); - /* Gets the frame statistics for animations. + /** + * Gets the frame statistics for animations. * * Requires the ACCESS_SURFACE_FLINGER permission. */ FrameStats getAnimationFrameStats(); - /* + /** + * Overrides the supported HDR modes for the given display device. + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + void overrideHdrTypes(IBinder display, in int[] hdrTypes); + + /** + * Pulls surfaceflinger atoms global stats and layer stats to pipe to statsd. + * + * Requires the calling uid be from system server. + */ + PullAtomData onPullAtom(int atomId); + + oneway void enableVSyncInjections(boolean enable); + + oneway void injectVSync(long when); + + /** + * Gets the list of active layers in Z order for debugging purposes + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + List getLayerDebugInfo(); + + boolean getColorManagement(); + + /** + * Gets the composition preference of the default data space and default pixel format, + * as well as the wide color gamut data space and wide color gamut pixel format. + * If the wide color gamut data space is V0_SRGB, then it implies that the platform + * has no wide color gamut support. + * + */ + CompositionPreference getCompositionPreference(); + + /** + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + ContentSamplingAttributes getDisplayedContentSamplingAttributes(IBinder display); + + /** + * Turns on the color sampling engine on the display. + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + void setDisplayContentSamplingEnabled(IBinder display, boolean enable, byte componentMask, long maxFrames); + + /** + * Gets whether SurfaceFlinger can support protected content in GPU composition. + */ + boolean getProtectedContentSupport(); + + /** * Queries whether the given display is a wide color display. * Requires the ACCESS_SURFACE_FLINGER permission. */ boolean isWideColorDisplay(IBinder token); - /* + /** * Gets whether brightness operations are supported on a display. * * displayToken @@ -176,7 +244,7 @@ interface ISurfaceComposer { */ boolean getDisplayBrightnessSupport(IBinder displayToken); - /* + /** * Sets the brightness of a display. * * displayToken @@ -191,7 +259,7 @@ interface ISurfaceComposer { */ void setDisplayBrightness(IBinder displayToken, in DisplayBrightness brightness); - /* + /** * Adds a listener that receives HDR layer information. This is used in combination * with setDisplayBrightness to adjust the display brightness depending on factors such * as whether or not HDR is in use. @@ -200,7 +268,7 @@ interface ISurfaceComposer { */ void addHdrLayerInfoListener(IBinder displayToken, IHdrLayerInfoListener listener); - /* + /** * Removes a listener that was added with addHdrLayerInfoListener. * * Returns NO_ERROR upon success, NAME_NOT_FOUND if the display is invalid, and BAD_VALUE if @@ -209,7 +277,7 @@ interface ISurfaceComposer { */ void removeHdrLayerInfoListener(IBinder displayToken, IHdrLayerInfoListener listener); - /* + /** * Sends a power boost to the composer. This function is asynchronous. * * boostId @@ -217,5 +285,5 @@ interface ISurfaceComposer { * * Returns NO_ERROR upon success. */ - void notifyPowerBoost(int boostId); + oneway void notifyPowerBoost(int boostId); } diff --git a/libs/gui/aidl/android/gui/LayerDebugInfo.aidl b/libs/gui/aidl/android/gui/LayerDebugInfo.aidl new file mode 100644 index 0000000000..faca980f3c --- /dev/null +++ b/libs/gui/aidl/android/gui/LayerDebugInfo.aidl @@ -0,0 +1,19 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +parcelable LayerDebugInfo cpp_header "gui/LayerDebugInfo.h"; diff --git a/libs/gui/aidl/android/gui/PullAtomData.aidl b/libs/gui/aidl/android/gui/PullAtomData.aidl new file mode 100644 index 0000000000..14d33c6d0b --- /dev/null +++ b/libs/gui/aidl/android/gui/PullAtomData.aidl @@ -0,0 +1,23 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable PullAtomData { + @utf8InCpp String data; + boolean success; +} diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 138d2edebd..927912463b 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -61,7 +61,6 @@ struct ComposerState; struct DisplayStatInfo; struct DisplayState; struct InputWindowCommands; -class LayerDebugInfo; class HdrCapabilities; class IGraphicBufferProducer; class ISurfaceComposerClient; @@ -76,6 +75,7 @@ namespace gui { struct DisplayCaptureArgs; struct LayerCaptureArgs; +class LayerDebugInfo; } // namespace gui @@ -154,58 +154,6 @@ public: virtual bool authenticateSurfaceTexture( const sp& surface) const = 0; - /* Overrides the supported HDR modes for the given display device. - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t overrideHdrTypes(const sp& display, - const std::vector& hdrTypes) = 0; - - /* Pulls surfaceflinger atoms global stats and layer stats to pipe to statsd. - * - * Requires the calling uid be from system server. - */ - virtual status_t onPullAtom(const int32_t atomId, std::string* outData, bool* success) = 0; - - virtual status_t enableVSyncInjections(bool enable) = 0; - - virtual status_t injectVSync(nsecs_t when) = 0; - - /* Gets the list of active layers in Z order for debugging purposes - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getLayerDebugInfo(std::vector* outLayers) = 0; - - virtual status_t getColorManagement(bool* outGetColorManagement) const = 0; - - /* Gets the composition preference of the default data space and default pixel format, - * as well as the wide color gamut data space and wide color gamut pixel format. - * If the wide color gamut data space is V0_SRGB, then it implies that the platform - * has no wide color gamut support. - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getCompositionPreference(ui::Dataspace* defaultDataspace, - ui::PixelFormat* defaultPixelFormat, - ui::Dataspace* wideColorGamutDataspace, - ui::PixelFormat* wideColorGamutPixelFormat) const = 0; - /* - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getDisplayedContentSamplingAttributes(const sp& display, - ui::PixelFormat* outFormat, - ui::Dataspace* outDataspace, - uint8_t* outComponentMask) const = 0; - - /* Turns on the color sampling engine on the display. - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t setDisplayContentSamplingEnabled(const sp& display, bool enable, - uint8_t componentMask, - uint64_t maxFrames) = 0; - /* Returns statistics on the color profile of the last frame displayed for a given display * * Requires the ACCESS_SURFACE_FLINGER permission. @@ -214,12 +162,6 @@ public: uint64_t timestamp, DisplayedFrameStats* outStats) const = 0; - /* - * Gets whether SurfaceFlinger can support protected content in GPU composition. - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getProtectedContentSupport(bool* outSupported) const = 0; - /* Registers a listener to stream median luma updates from SurfaceFlinger. * * The sampling area is bounded by both samplingArea and the given stopLayerHandle @@ -421,22 +363,22 @@ public: GET_ANIMATION_FRAME_STATS, // Deprecated. Autogenerated by .aidl now. SET_POWER_MODE, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_STATS, - GET_HDR_CAPABILITIES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - GET_DISPLAY_COLOR_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - GET_ACTIVE_COLOR_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - SET_ACTIVE_COLOR_MODE, // Deprecated. Autogenerated by .aidl now. - ENABLE_VSYNC_INJECTIONS, - INJECT_VSYNC, - GET_LAYER_DEBUG_INFO, - GET_COMPOSITION_PREFERENCE, - GET_COLOR_MANAGEMENT, - GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, - SET_DISPLAY_CONTENT_SAMPLING_ENABLED, + GET_HDR_CAPABILITIES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + GET_DISPLAY_COLOR_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + GET_ACTIVE_COLOR_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. + SET_ACTIVE_COLOR_MODE, // Deprecated. Autogenerated by .aidl now. + ENABLE_VSYNC_INJECTIONS, // Deprecated. Autogenerated by .aidl now. + INJECT_VSYNC, // Deprecated. Autogenerated by .aidl now. + GET_LAYER_DEBUG_INFO, // Deprecated. Autogenerated by .aidl now. + GET_COMPOSITION_PREFERENCE, // Deprecated. Autogenerated by .aidl now. + GET_COLOR_MANAGEMENT, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, // Deprecated. Autogenerated by .aidl now. + SET_DISPLAY_CONTENT_SAMPLING_ENABLED, // Deprecated. Autogenerated by .aidl now. GET_DISPLAYED_CONTENT_SAMPLE, - GET_PROTECTED_CONTENT_SUPPORT, - IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. - GET_DISPLAY_NATIVE_PRIMARIES, // Deprecated. Autogenerated by .aidl now. - GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. + GET_PROTECTED_CONTENT_SUPPORT, // Deprecated. Autogenerated by .aidl now. + IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAY_NATIVE_PRIMARIES, // Deprecated. Autogenerated by .aidl now. + GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. ADD_REGION_SAMPLING_LISTENER, REMOVE_REGION_SAMPLING_LISTENER, SET_DESIRED_DISPLAY_MODE_SPECS, @@ -460,10 +402,10 @@ public: GET_DYNAMIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. ADD_FPS_LISTENER, REMOVE_FPS_LISTENER, - OVERRIDE_HDR_TYPES, + OVERRIDE_HDR_TYPES, // Deprecated. Autogenerated by .aidl now. ADD_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. REMOVE_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. - ON_PULL_ATOM, + ON_PULL_ATOM, // Deprecated. Autogenerated by .aidl now. ADD_TUNNEL_MODE_ENABLED_LISTENER, REMOVE_TUNNEL_MODE_ENABLED_LISTENER, ADD_WINDOW_INFOS_LISTENER, diff --git a/libs/gui/include/gui/LayerDebugInfo.h b/libs/gui/include/gui/LayerDebugInfo.h index af834d78df..1c1bbef123 100644 --- a/libs/gui/include/gui/LayerDebugInfo.h +++ b/libs/gui/include/gui/LayerDebugInfo.h @@ -25,7 +25,7 @@ #include #include -namespace android { +namespace android::gui { /* Class for transporting debug info from SurfaceFlinger to authorized * recipients. The class is intended to be a data container. There are @@ -71,4 +71,4 @@ public: std::string to_string(const LayerDebugInfo& info); -} // namespace android +} // namespace android::gui diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index a644e042c9..58964d6878 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -714,47 +714,12 @@ public: return false; } - status_t overrideHdrTypes(const sp& /*display*/, - const std::vector& /*hdrTypes*/) override { - return NO_ERROR; - } - status_t onPullAtom(const int32_t /*atomId*/, std::string* /*outData*/, - bool* /*success*/) override { - return NO_ERROR; - } - status_t enableVSyncInjections(bool /*enable*/) override { - return NO_ERROR; - } - status_t injectVSync(nsecs_t /*when*/) override { return NO_ERROR; } - status_t getLayerDebugInfo(std::vector* /*layers*/) override { - return NO_ERROR; - } - status_t getCompositionPreference( - ui::Dataspace* /*outDefaultDataspace*/, ui::PixelFormat* /*outDefaultPixelFormat*/, - ui::Dataspace* /*outWideColorGamutDataspace*/, - ui::PixelFormat* /*outWideColorGamutPixelFormat*/) const override { - return NO_ERROR; - } - status_t getDisplayedContentSamplingAttributes(const sp& /*display*/, - ui::PixelFormat* /*outFormat*/, - ui::Dataspace* /*outDataspace*/, - uint8_t* /*outComponentMask*/) const override { - return NO_ERROR; - } - status_t setDisplayContentSamplingEnabled(const sp& /*display*/, bool /*enable*/, - uint8_t /*componentMask*/, - uint64_t /*maxFrames*/) override { - return NO_ERROR; - } status_t getDisplayedContentSample(const sp& /*display*/, uint64_t /*maxFrames*/, uint64_t /*timestamp*/, DisplayedFrameStats* /*outStats*/) const override { return NO_ERROR; } - status_t getColorManagement(bool* /*outGetColorManagement*/) const override { return NO_ERROR; } - status_t getProtectedContentSupport(bool* /*outSupported*/) const override { return NO_ERROR; } - status_t addRegionSamplingListener(const Rect& /*samplingArea*/, const sp& /*stopLayerHandle*/, const sp& /*listener*/) override { @@ -964,6 +929,46 @@ public: return binder::Status::ok(); } + binder::Status overrideHdrTypes(const sp& /*display*/, + const std::vector& /*hdrTypes*/) override { + return binder::Status::ok(); + } + + binder::Status onPullAtom(int32_t /*atomId*/, gui::PullAtomData* /*outPullData*/) override { + return binder::Status::ok(); + } + + binder::Status enableVSyncInjections(bool /*enable*/) override { return binder::Status::ok(); } + + binder::Status injectVSync(int64_t /*when*/) override { return binder::Status::ok(); } + + binder::Status getLayerDebugInfo(std::vector* /*outLayers*/) override { + return binder::Status::ok(); + } + + binder::Status getColorManagement(bool* /*outGetColorManagement*/) override { + return binder::Status::ok(); + } + + binder::Status getCompositionPreference(gui::CompositionPreference* /*outPref*/) override { + return binder::Status::ok(); + } + + binder::Status getDisplayedContentSamplingAttributes( + const sp& /*display*/, gui::ContentSamplingAttributes* /*outAttrs*/) override { + return binder::Status::ok(); + } + + binder::Status setDisplayContentSamplingEnabled(const sp& /*display*/, bool /*enable*/, + int8_t /*componentMask*/, + int64_t /*maxFrames*/) override { + return binder::Status::ok(); + } + + binder::Status getProtectedContentSupport(bool* /*outSupporte*/) override { + return binder::Status::ok(); + } + binder::Status isWideColorDisplay(const sp& /*token*/, bool* /*outIsWideColorDisplay*/) override { return binder::Status::ok(); diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index 3d00b90816..1b56cb224f 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -1386,10 +1386,10 @@ void Layer::updateTransformHint(ui::Transform::RotationFlags transformHint) { // ---------------------------------------------------------------------------- // TODO(marissaw): add new layer state info to layer debugging -LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const { +gui::LayerDebugInfo Layer::getLayerDebugInfo(const DisplayDevice* display) const { using namespace std::string_literals; - LayerDebugInfo info; + gui::LayerDebugInfo info; const State& ds = getDrawingState(); info.mName = getName(); sp parent = mDrawingParent.promote(); diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h index 565a6ff726..455920be62 100644 --- a/services/surfaceflinger/Layer.h +++ b/services/surfaceflinger/Layer.h @@ -69,13 +69,16 @@ class Colorizer; class DisplayDevice; class GraphicBuffer; class SurfaceFlinger; -class LayerDebugInfo; namespace compositionengine { class OutputLayer; struct LayerFECompositionState; } +namespace gui { +class LayerDebugInfo; +} + namespace impl { class SurfaceInterceptor; } @@ -741,7 +744,7 @@ public: inline const State& getDrawingState() const { return mDrawingState; } inline State& getDrawingState() { return mDrawingState; } - LayerDebugInfo getLayerDebugInfo(const DisplayDevice*) const; + gui::LayerDebugInfo getLayerDebugInfo(const DisplayDevice*) const; void miniDump(std::string& result, const DisplayDevice&) const; void dumpFrameStats(std::string& result) const; diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index b6d00b2da9..c9afc921af 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -1561,7 +1561,7 @@ status_t SurfaceFlinger::injectVSync(nsecs_t when) { : BAD_VALUE; } -status_t SurfaceFlinger::getLayerDebugInfo(std::vector* outLayers) { +status_t SurfaceFlinger::getLayerDebugInfo(std::vector* outLayers) { outLayers->clear(); auto future = mScheduler->schedule([=] { const auto display = FTL_FAKE_GUARD(mStateLock, getDefaultDisplayDeviceLocked()); @@ -5459,21 +5459,14 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { #pragma clang diagnostic push #pragma clang diagnostic error "-Wswitch-enum" switch (static_cast(code)) { - case ENABLE_VSYNC_INJECTIONS: - case INJECT_VSYNC: - if (!hasMockHwc()) return PERMISSION_DENIED; - [[fallthrough]]; // These methods should at minimum make sure that the client requested // access to SF. case BOOT_FINISHED: - case OVERRIDE_HDR_TYPES: case GET_HDR_CAPABILITIES: case SET_DESIRED_DISPLAY_MODE_SPECS: case GET_DESIRED_DISPLAY_MODE_SPECS: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: case GET_GAME_CONTENT_TYPE_SUPPORT: - case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: - case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: case GET_DISPLAYED_CONTENT_SAMPLE: case ADD_TUNNEL_MODE_ENABLED_LISTENER: case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: @@ -5490,16 +5483,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { } return OK; } - case GET_LAYER_DEBUG_INFO: { - IPCThreadState* ipc = IPCThreadState::self(); - const int pid = ipc->getCallingPid(); - const int uid = ipc->getCallingUid(); - if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) { - ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid); - return PERMISSION_DENIED; - } - return OK; - } // Used by apps to hook Choreographer to SurfaceFlinger. case CREATE_DISPLAY_EVENT_CONNECTION: // The following calls are currently used by clients that do not @@ -5514,9 +5497,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // granted a reference to Client* and Handle* to do anything with it. case SET_TRANSACTION_STATE: case CREATE_CONNECTION: - case GET_COLOR_MANAGEMENT: - case GET_COMPOSITION_PREFERENCE: - case GET_PROTECTED_CONTENT_SUPPORT: // setFrameRate() is deliberately available for apps to call without any // special permissions. case SET_FRAME_RATE: @@ -5557,13 +5537,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { } return PERMISSION_DENIED; } - case ON_PULL_ATOM: { - const int uid = IPCThreadState::self()->getCallingUid(); - if (uid == AID_SYSTEM) { - return OK; - } - return PERMISSION_DENIED; - } case ADD_WINDOW_INFOS_LISTENER: case REMOVE_WINDOW_INFOS_LISTENER: { const int uid = IPCThreadState::self()->getCallingUid(); @@ -5595,6 +5568,16 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case CAPTURE_DISPLAY_BY_ID: case CLEAR_ANIMATION_FRAME_STATS: case GET_ANIMATION_FRAME_STATS: + case OVERRIDE_HDR_TYPES: + case ON_PULL_ATOM: + case ENABLE_VSYNC_INJECTIONS: + case INJECT_VSYNC: + case GET_LAYER_DEBUG_INFO: + case GET_COLOR_MANAGEMENT: + case GET_COMPOSITION_PREFERENCE: + case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: + case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: + case GET_PROTECTED_CONTENT_SUPPORT: case IS_WIDE_COLOR_DISPLAY: case GET_DISPLAY_BRIGHTNESS_SUPPORT: case SET_DISPLAY_BRIGHTNESS: @@ -7632,6 +7615,134 @@ binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outS return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp& display, + const std::vector& hdrTypes) { + // overrideHdrTypes is used by CTS tests, which acquire the necessary + // permission dynamically. Don't use the permission cache for this check. + status_t status = checkAccessPermission(false); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + + std::vector hdrTypesVector; + for (int32_t i : hdrTypes) { + hdrTypesVector.push_back(static_cast(i)); + } + status = mFlinger->overrideHdrTypes(display, hdrTypesVector); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) { + status_t status; + const int uid = IPCThreadState::self()->getCallingUid(); + if (uid != AID_SYSTEM) { + status = PERMISSION_DENIED; + } else { + status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) { + if (!mFlinger->hasMockHwc()) { + return binder::Status::fromStatusT(PERMISSION_DENIED); + } + + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->enableVSyncInjections(enable); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) { + if (!mFlinger->hasMockHwc()) { + return binder::Status::fromStatusT(PERMISSION_DENIED); + } + + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->injectVSync(when); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector* outLayers) { + if (!outLayers) { + return binder::Status::fromStatusT(UNEXPECTED_NULL); + } + + IPCThreadState* ipc = IPCThreadState::self(); + const int pid = ipc->getCallingPid(); + const int uid = ipc->getCallingUid(); + if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) { + ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid); + return binder::Status::fromStatusT(PERMISSION_DENIED); + } + status_t status = mFlinger->getLayerDebugInfo(outLayers); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) { + status_t status = mFlinger->getColorManagement(outGetColorManagement); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) { + ui::Dataspace dataspace; + ui::PixelFormat pixelFormat; + ui::Dataspace wideColorGamutDataspace; + ui::PixelFormat wideColorGamutPixelFormat; + status_t status = + mFlinger->getCompositionPreference(&dataspace, &pixelFormat, &wideColorGamutDataspace, + &wideColorGamutPixelFormat); + if (status == NO_ERROR) { + outPref->defaultDataspace = static_cast(dataspace); + outPref->defaultPixelFormat = static_cast(pixelFormat); + outPref->wideColorGamutDataspace = static_cast(wideColorGamutDataspace); + outPref->wideColorGamutPixelFormat = static_cast(wideColorGamutPixelFormat); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes( + const sp& display, gui::ContentSamplingAttributes* outAttrs) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + + ui::PixelFormat format; + ui::Dataspace dataspace; + uint8_t componentMask; + status = mFlinger->getDisplayedContentSamplingAttributes(display, &format, &dataspace, + &componentMask); + if (status == NO_ERROR) { + outAttrs->format = static_cast(format); + outAttrs->dataspace = static_cast(dataspace); + outAttrs->componentMask = static_cast(componentMask); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp& display, + bool enable, + int8_t componentMask, + int64_t maxFrames) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->setDisplayContentSamplingEnabled(display, enable, + static_cast(componentMask), + static_cast(maxFrames)); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) { + status_t status = mFlinger->getProtectedContentSupport(outSupported); + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) { status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay); diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 1ca36bdf72..b32462dadc 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -582,25 +583,24 @@ private: status_t clearAnimationFrameStats(); status_t getAnimationFrameStats(FrameStats* outStats) const; status_t overrideHdrTypes(const sp& displayToken, - const std::vector& hdrTypes) override; - status_t onPullAtom(const int32_t atomId, std::string* pulledData, bool* success) override; - status_t enableVSyncInjections(bool enable) override; - status_t injectVSync(nsecs_t when) override; - status_t getLayerDebugInfo(std::vector* outLayers) override; - status_t getColorManagement(bool* outGetColorManagement) const override; + const std::vector& hdrTypes); + status_t onPullAtom(const int32_t atomId, std::string* pulledData, bool* success); + status_t enableVSyncInjections(bool enable); + status_t injectVSync(nsecs_t when); + status_t getLayerDebugInfo(std::vector* outLayers); + status_t getColorManagement(bool* outGetColorManagement) const; status_t getCompositionPreference(ui::Dataspace* outDataspace, ui::PixelFormat* outPixelFormat, ui::Dataspace* outWideColorGamutDataspace, - ui::PixelFormat* outWideColorGamutPixelFormat) const override; + ui::PixelFormat* outWideColorGamutPixelFormat) const; status_t getDisplayedContentSamplingAttributes(const sp& displayToken, ui::PixelFormat* outFormat, ui::Dataspace* outDataspace, - uint8_t* outComponentMask) const override; + uint8_t* outComponentMask) const; status_t setDisplayContentSamplingEnabled(const sp& displayToken, bool enable, - uint8_t componentMask, uint64_t maxFrames) override; + uint8_t componentMask, uint64_t maxFrames); status_t getDisplayedContentSample(const sp& displayToken, uint64_t maxFrames, - uint64_t timestamp, - DisplayedFrameStats* outStats) const override; - status_t getProtectedContentSupport(bool* outSupported) const override; + uint64_t timestamp, DisplayedFrameStats* outStats) const; + status_t getProtectedContentSupport(bool* outSupported) const; status_t isWideColorDisplay(const sp& displayToken, bool* outIsWideColorDisplay) const; status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, const sp& listener) override; @@ -1480,6 +1480,20 @@ public: const sp&) override; binder::Status clearAnimationFrameStats() override; binder::Status getAnimationFrameStats(gui::FrameStats* outStats) override; + binder::Status overrideHdrTypes(const sp& display, + const std::vector& hdrTypes) override; + binder::Status onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) override; + binder::Status enableVSyncInjections(bool enable) override; + binder::Status injectVSync(int64_t when) override; + binder::Status getLayerDebugInfo(std::vector* outLayers) override; + binder::Status getColorManagement(bool* outGetColorManagement) override; + binder::Status getCompositionPreference(gui::CompositionPreference* outPref) override; + binder::Status getDisplayedContentSamplingAttributes( + const sp& display, gui::ContentSamplingAttributes* outAttrs) override; + binder::Status setDisplayContentSamplingEnabled(const sp& display, bool enable, + int8_t componentMask, + int64_t maxFrames) override; + binder::Status getProtectedContentSupport(bool* outSupporte) override; binder::Status isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) override; binder::Status getDisplayBrightnessSupport(const sp& displayToken, diff --git a/services/surfaceflinger/tests/Credentials_test.cpp b/services/surfaceflinger/tests/Credentials_test.cpp index d33bc1080c..6549a224e6 100644 --- a/services/surfaceflinger/tests/Credentials_test.cpp +++ b/services/surfaceflinger/tests/Credentials_test.cpp @@ -18,13 +18,13 @@ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wconversion" +#include #include -#include #include #include #include #include -#include +#include #include #include #include @@ -34,6 +34,7 @@ namespace android { using Transaction = SurfaceComposerClient::Transaction; +using gui::LayerDebugInfo; using ui::ColorMode; namespace { @@ -307,23 +308,26 @@ TEST_F(CredentialsTest, CaptureLayersTest) { */ TEST_F(CredentialsTest, GetLayerDebugInfo) { setupBackgroundSurface(); - sp sf(ComposerService::getComposerService()); + sp sf(ComposerServiceAIDL::getComposerService()); // Historically, only root and shell can access the getLayerDebugInfo which // is called when we call dumpsys. I don't see a reason why we should change this. std::vector outLayers; // Check with root. seteuid(AID_ROOT); - ASSERT_EQ(NO_ERROR, sf->getLayerDebugInfo(&outLayers)); + binder::Status status = sf->getLayerDebugInfo(&outLayers); + ASSERT_EQ(NO_ERROR, status.transactionError()); // Check as a shell. seteuid(AID_SHELL); - ASSERT_EQ(NO_ERROR, sf->getLayerDebugInfo(&outLayers)); + status = sf->getLayerDebugInfo(&outLayers); + ASSERT_EQ(NO_ERROR, status.transactionError()); // Check as anyone else. seteuid(AID_ROOT); seteuid(AID_BIN); - ASSERT_EQ(PERMISSION_DENIED, sf->getLayerDebugInfo(&outLayers)); + status = sf->getLayerDebugInfo(&outLayers); + ASSERT_EQ(PERMISSION_DENIED, status.transactionError()); } TEST_F(CredentialsTest, IsWideColorDisplayBasicCorrectness) { diff --git a/services/surfaceflinger/tests/LayerTransactionTest.h b/services/surfaceflinger/tests/LayerTransactionTest.h index 6bd7920a62..43386b2ae7 100644 --- a/services/surfaceflinger/tests/LayerTransactionTest.h +++ b/services/surfaceflinger/tests/LayerTransactionTest.h @@ -26,6 +26,7 @@ #include #include #include +#include #include #include "BufferGenerator.h" @@ -44,8 +45,9 @@ protected: ASSERT_NO_FATAL_FAILURE(SetUpDisplay()); - sp sf(ComposerService::getComposerService()); - ASSERT_NO_FATAL_FAILURE(sf->getColorManagement(&mColorManagementUsed)); + sp sf(ComposerServiceAIDL::getComposerService()); + binder::Status status = sf->getColorManagement(&mColorManagementUsed); + ASSERT_NO_FATAL_FAILURE(status.transactionError()); mCaptureArgs.displayToken = mDisplay; } diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp index b3b4ec15cd..12e5d46a79 100644 --- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp +++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include #include @@ -992,7 +993,7 @@ using DisplayTest_2_1 = DisplayTest; // Tests that VSYNC injection can be safely toggled while invalidating. TEST_F(DisplayTest_2_1, VsyncInjection) { - const auto flinger = ComposerService::getComposerService(); + const auto flinger = ComposerServiceAIDL::getComposerService(); bool enable = true; for (int i = 0; i < 100; i++) { @@ -1238,9 +1239,10 @@ protected: sFakeComposer->clearFrames(); ASSERT_EQ(0, sFakeComposer->getFrameCount()); - sp sf(ComposerService::getComposerService()); - std::vector layers; - status_t result = sf->getLayerDebugInfo(&layers); + sp sf(ComposerServiceAIDL::getComposerService()); + std::vector layers; + binder::Status status = sf->getLayerDebugInfo(&layers); + status_t result = status.transactionError(); if (result != NO_ERROR) { ALOGE("Failed to get layers %s %d", strerror(-result), result); } else { -- cgit v1.2.3-59-g8ed1b From 02186fbaa27f4a7e78a0207da49ef38baacd1571 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Wed, 23 Feb 2022 14:21:54 -0800 Subject: Migrate 13 methods of ISurfaceComposer to AIDL More misc methods are migrated to AIDL. ARect parcelable is added to serialize Rect data structure, defined in libui Rect.h. Bug: 211009610 Test: atest libgui_test libsurfaceflinger_unittest SurfaceFlinger_test Change-Id: I549e06c6f550760974d965d08783338635a5a5fe --- libs/gui/Android.bp | 16 +- libs/gui/BLASTBufferQueue.cpp | 3 +- libs/gui/ISurfaceComposer.cpp | 519 --------------------- libs/gui/SurfaceComposerClient.cpp | 83 +++- libs/gui/TransactionTracing.cpp | 8 +- libs/gui/WindowInfosListenerReporter.cpp | 17 +- libs/gui/aidl/android/gui/ARect.aidl | 35 ++ libs/gui/aidl/android/gui/DisplayModeSpecs.aidl | 27 ++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 122 ++++- libs/gui/aidl/android/gui/Rect.aidl | 35 -- libs/gui/include/gui/ISurfaceComposer.h | 164 +------ libs/gui/include/gui/LayerDebugInfo.h | 2 +- libs/gui/include/gui/SurfaceComposerClient.h | 2 +- libs/gui/include/gui/WindowInfosListenerReporter.h | 13 +- libs/gui/include/private/gui/ComposerServiceAIDL.h | 1 + libs/gui/tests/RegionSampling_test.cpp | 97 +++- libs/gui/tests/SamplingDemo.cpp | 20 +- libs/gui/tests/Surface_test.cpp | 128 ++--- services/surfaceflinger/SurfaceFlinger.cpp | 221 +++++++-- services/surfaceflinger/SurfaceFlinger.h | 57 ++- .../fuzzer/surfaceflinger_fuzzers_utils.h | 2 +- .../tests/unittests/TestableSurfaceFlinger.h | 2 +- 22 files changed, 686 insertions(+), 888 deletions(-) create mode 100644 libs/gui/aidl/android/gui/ARect.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayModeSpecs.aidl delete mode 100644 libs/gui/aidl/android/gui/Rect.aidl (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index 6b64ac8597..dd7e082487 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -142,16 +142,24 @@ cc_library_static { "include", ], + include_dirs: [ + "frameworks/native/include", + ], + export_shared_lib_headers: [ "libbinder", ], static_libs: [ "libui-types", + "libgui_window_info_static", ], aidl: { export_aidl_headers: true, + include_dirs: [ + "frameworks/native/libs/gui", + ], }, } @@ -288,10 +296,16 @@ cc_library_static { defaults: ["libgui_bufferqueue-defaults"], srcs: [ + ":libgui_frame_event_aidl", ":inputconstants_aidl", ":libgui_bufferqueue_sources", - ":libgui_aidl", ], + + aidl: { + include_dirs: [ + "frameworks/native/libs/gui", + ], + }, } filegroup { diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp index c2793ac5de..bba7387c3a 100644 --- a/libs/gui/BLASTBufferQueue.cpp +++ b/libs/gui/BLASTBufferQueue.cpp @@ -33,6 +33,7 @@ #include #include +#include #include @@ -160,7 +161,7 @@ BLASTBufferQueue::BLASTBufferQueue(const std::string& name, bool updateDestinati mBufferItemConsumer->setFrameAvailableListener(this); mBufferItemConsumer->setBufferFreedListener(this); - ComposerService::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers); + ComposerServiceAIDL::getComposerService()->getMaxAcquiredBufferCount(&mMaxAcquiredBuffers); mBufferItemConsumer->setMaxAcquiredBufferCount(mMaxAcquiredBuffers); mCurrentMaxAcquiredBufferCount = mMaxAcquiredBuffers; mNumAcquired = 0; diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a10a2f06ba..c3b33cb595 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -220,238 +220,6 @@ public: return result; } - status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, - const sp& listener) override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to write interface token"); - return error; - } - error = data.write(samplingArea); - if (error != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to write sampling area"); - return error; - } - error = data.writeStrongBinder(stopLayerHandle); - if (error != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to write stop layer handle"); - return error; - } - error = data.writeStrongBinder(IInterface::asBinder(listener)); - if (error != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to write listener"); - return error; - } - error = remote()->transact(BnSurfaceComposer::ADD_REGION_SAMPLING_LISTENER, data, &reply); - if (error != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to transact"); - } - return error; - } - - status_t removeRegionSamplingListener(const sp& listener) override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("removeRegionSamplingListener: Failed to write interface token"); - return error; - } - error = data.writeStrongBinder(IInterface::asBinder(listener)); - if (error != NO_ERROR) { - ALOGE("removeRegionSamplingListener: Failed to write listener"); - return error; - } - error = remote()->transact(BnSurfaceComposer::REMOVE_REGION_SAMPLING_LISTENER, data, - &reply); - if (error != NO_ERROR) { - ALOGE("removeRegionSamplingListener: Failed to transact"); - } - return error; - } - - virtual status_t addFpsListener(int32_t taskId, const sp& listener) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeInt32, taskId); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - const status_t error = - remote()->transact(BnSurfaceComposer::ADD_FPS_LISTENER, data, &reply); - if (error != OK) { - ALOGE("addFpsListener: Failed to transact"); - } - return error; - } - - virtual status_t removeFpsListener(const sp& listener) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - - const status_t error = - remote()->transact(BnSurfaceComposer::REMOVE_FPS_LISTENER, data, &reply); - if (error != OK) { - ALOGE("removeFpsListener: Failed to transact"); - } - return error; - } - - virtual status_t addTunnelModeEnabledListener( - const sp& listener) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - - const status_t error = - remote()->transact(BnSurfaceComposer::ADD_TUNNEL_MODE_ENABLED_LISTENER, data, - &reply); - if (error != NO_ERROR) { - ALOGE("addTunnelModeEnabledListener: Failed to transact"); - } - return error; - } - - virtual status_t removeTunnelModeEnabledListener( - const sp& listener) { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - - const status_t error = - remote()->transact(BnSurfaceComposer::REMOVE_TUNNEL_MODE_ENABLED_LISTENER, data, - &reply); - if (error != NO_ERROR) { - ALOGE("removeTunnelModeEnabledListener: Failed to transact"); - } - return error; - } - - status_t setDesiredDisplayModeSpecs(const sp& displayToken, - ui::DisplayModeId defaultMode, bool allowGroupSwitching, - float primaryRefreshRateMin, float primaryRefreshRateMax, - float appRequestRefreshRateMin, - float appRequestRefreshRateMax) override { - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(displayToken); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to write display token: %d", result); - return result; - } - result = data.writeInt32(defaultMode); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write defaultMode: %d", result); - return result; - } - result = data.writeBool(allowGroupSwitching); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write allowGroupSwitching: %d", result); - return result; - } - result = data.writeFloat(primaryRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write primaryRefreshRateMin: %d", result); - return result; - } - result = data.writeFloat(primaryRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write primaryRefreshRateMax: %d", result); - return result; - } - result = data.writeFloat(appRequestRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write appRequestRefreshRateMin: %d", - result); - return result; - } - result = data.writeFloat(appRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to write appRequestRefreshRateMax: %d", - result); - return result; - } - - result = - remote()->transact(BnSurfaceComposer::SET_DESIRED_DISPLAY_MODE_SPECS, data, &reply); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs failed to transact: %d", result); - return result; - } - return reply.readInt32(); - } - - status_t getDesiredDisplayModeSpecs(const sp& displayToken, - ui::DisplayModeId* outDefaultMode, - bool* outAllowGroupSwitching, - float* outPrimaryRefreshRateMin, - float* outPrimaryRefreshRateMax, - float* outAppRequestRefreshRateMin, - float* outAppRequestRefreshRateMax) override { - if (!outDefaultMode || !outAllowGroupSwitching || !outPrimaryRefreshRateMin || - !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || - !outAppRequestRefreshRateMax) { - return BAD_VALUE; - } - Parcel data, reply; - status_t result = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to writeInterfaceToken: %d", result); - return result; - } - result = data.writeStrongBinder(displayToken); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to writeStrongBinder: %d", result); - return result; - } - result = - remote()->transact(BnSurfaceComposer::GET_DESIRED_DISPLAY_MODE_SPECS, data, &reply); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to transact: %d", result); - return result; - } - - result = reply.readInt32(outDefaultMode); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read defaultMode: %d", result); - return result; - } - if (*outDefaultMode < 0) { - ALOGE("%s: defaultMode must be non-negative but it was %d", __func__, *outDefaultMode); - return BAD_VALUE; - } - - result = reply.readBool(outAllowGroupSwitching); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read allowGroupSwitching: %d", result); - return result; - } - result = reply.readFloat(outPrimaryRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read primaryRefreshRateMin: %d", result); - return result; - } - result = reply.readFloat(outPrimaryRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read primaryRefreshRateMax: %d", result); - return result; - } - result = reply.readFloat(outAppRequestRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read appRequestRefreshRateMin: %d", result); - return result; - } - result = reply.readFloat(outAppRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs failed to read appRequestRefreshRateMax: %d", result); - return result; - } - return reply.readInt32(); - } - status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, float lightPosY, float lightPosZ, float lightRadius) override { Parcel data, reply; @@ -573,59 +341,6 @@ public: return reply.readInt32(); } - status_t addTransactionTraceListener( - const sp& listener) override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(listener)); - - return remote()->transact(BnSurfaceComposer::ADD_TRANSACTION_TRACE_LISTENER, data, &reply); - } - - /** - * Get priority of the RenderEngine in surface flinger. - */ - int getGPUContextPriority() override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - status_t err = - remote()->transact(BnSurfaceComposer::GET_GPU_CONTEXT_PRIORITY, data, &reply); - if (err != NO_ERROR) { - ALOGE("getGPUContextPriority failed to read data: %s (%d)", strerror(-err), err); - return 0; - } - return reply.readInt32(); - } - - status_t getMaxAcquiredBufferCount(int* buffers) const override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - status_t err = - remote()->transact(BnSurfaceComposer::GET_MAX_ACQUIRED_BUFFER_COUNT, data, &reply); - if (err != NO_ERROR) { - ALOGE("getMaxAcquiredBufferCount failed to read data: %s (%d)", strerror(-err), err); - return err; - } - - return reply.readInt32(buffers); - } - - status_t addWindowInfosListener( - const sp& windowInfosListener) const override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(windowInfosListener)); - return remote()->transact(BnSurfaceComposer::ADD_WINDOW_INFOS_LISTENER, data, &reply); - } - - status_t removeWindowInfosListener( - const sp& windowInfosListener) const override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(windowInfosListener)); - return remote()->transact(BnSurfaceComposer::REMOVE_WINDOW_INFOS_LISTENER, data, &reply); - } - status_t setOverrideFrameRate(uid_t uid, float frameRate) override { Parcel data, reply; SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); @@ -778,203 +493,6 @@ status_t BnSurfaceComposer::onTransact( } return result; } - case ADD_REGION_SAMPLING_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - Rect samplingArea; - status_t result = data.read(samplingArea); - if (result != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to read sampling area"); - return result; - } - sp stopLayerHandle; - result = data.readNullableStrongBinder(&stopLayerHandle); - if (result != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to read stop layer handle"); - return result; - } - sp listener; - result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("addRegionSamplingListener: Failed to read listener"); - return result; - } - return addRegionSamplingListener(samplingArea, stopLayerHandle, listener); - } - case REMOVE_REGION_SAMPLING_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - status_t result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("removeRegionSamplingListener: Failed to read listener"); - return result; - } - return removeRegionSamplingListener(listener); - } - case ADD_FPS_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int32_t taskId; - status_t result = data.readInt32(&taskId); - if (result != NO_ERROR) { - ALOGE("addFpsListener: Failed to read layer handle"); - return result; - } - sp listener; - result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("addFpsListener: Failed to read listener"); - return result; - } - return addFpsListener(taskId, listener); - } - case REMOVE_FPS_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - status_t result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("removeFpsListener: Failed to read listener"); - return result; - } - return removeFpsListener(listener); - } - case ADD_TUNNEL_MODE_ENABLED_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - status_t result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("addTunnelModeEnabledListener: Failed to read listener"); - return result; - } - return addTunnelModeEnabledListener(listener); - } - case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - status_t result = data.readNullableStrongBinder(&listener); - if (result != NO_ERROR) { - ALOGE("removeTunnelModeEnabledListener: Failed to read listener"); - return result; - } - return removeTunnelModeEnabledListener(listener); - } - case SET_DESIRED_DISPLAY_MODE_SPECS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken = data.readStrongBinder(); - ui::DisplayModeId defaultMode; - status_t result = data.readInt32(&defaultMode); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read defaultMode: %d", result); - return result; - } - if (defaultMode < 0) { - ALOGE("%s: defaultMode must be non-negative but it was %d", __func__, defaultMode); - return BAD_VALUE; - } - bool allowGroupSwitching; - result = data.readBool(&allowGroupSwitching); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read allowGroupSwitching: %d", result); - return result; - } - float primaryRefreshRateMin; - result = data.readFloat(&primaryRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read primaryRefreshRateMin: %d", - result); - return result; - } - float primaryRefreshRateMax; - result = data.readFloat(&primaryRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read primaryRefreshRateMax: %d", - result); - return result; - } - float appRequestRefreshRateMin; - result = data.readFloat(&appRequestRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read appRequestRefreshRateMin: %d", - result); - return result; - } - float appRequestRefreshRateMax; - result = data.readFloat(&appRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to read appRequestRefreshRateMax: %d", - result); - return result; - } - result = setDesiredDisplayModeSpecs(displayToken, defaultMode, allowGroupSwitching, - primaryRefreshRateMin, primaryRefreshRateMax, - appRequestRefreshRateMin, appRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("setDesiredDisplayModeSpecs: failed to call setDesiredDisplayModeSpecs: " - "%d", - result); - return result; - } - reply->writeInt32(result); - return result; - } - case GET_DESIRED_DISPLAY_MODE_SPECS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken = data.readStrongBinder(); - ui::DisplayModeId defaultMode; - bool allowGroupSwitching; - float primaryRefreshRateMin; - float primaryRefreshRateMax; - float appRequestRefreshRateMin; - float appRequestRefreshRateMax; - - status_t result = - getDesiredDisplayModeSpecs(displayToken, &defaultMode, &allowGroupSwitching, - &primaryRefreshRateMin, &primaryRefreshRateMax, - &appRequestRefreshRateMin, - &appRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to get getDesiredDisplayModeSpecs: " - "%d", - result); - return result; - } - - result = reply->writeInt32(defaultMode); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write defaultMode: %d", result); - return result; - } - result = reply->writeBool(allowGroupSwitching); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write allowGroupSwitching: %d", - result); - return result; - } - result = reply->writeFloat(primaryRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write primaryRefreshRateMin: %d", - result); - return result; - } - result = reply->writeFloat(primaryRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write primaryRefreshRateMax: %d", - result); - return result; - } - result = reply->writeFloat(appRequestRefreshRateMin); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write appRequestRefreshRateMin: %d", - result); - return result; - } - result = reply->writeFloat(appRequestRefreshRateMax); - if (result != NO_ERROR) { - ALOGE("getDesiredDisplayModeSpecs: failed to write appRequestRefreshRateMax: %d", - result); - return result; - } - reply->writeInt32(result); - return result; - } case SET_GLOBAL_SHADOW_SETTINGS: { CHECK_INTERFACE(ISurfaceComposer, data, reply); @@ -1058,43 +576,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeInt32(result); return NO_ERROR; } - case ADD_TRANSACTION_TRACE_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - SAFE_PARCEL(data.readStrongBinder, &listener); - - return addTransactionTraceListener(listener); - } - case GET_GPU_CONTEXT_PRIORITY: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int priority = getGPUContextPriority(); - SAFE_PARCEL(reply->writeInt32, priority); - return NO_ERROR; - } - case GET_MAX_ACQUIRED_BUFFER_COUNT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - int buffers = 0; - int err = getMaxAcquiredBufferCount(&buffers); - if (err != NO_ERROR) { - return err; - } - SAFE_PARCEL(reply->writeInt32, buffers); - return NO_ERROR; - } - case ADD_WINDOW_INFOS_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - SAFE_PARCEL(data.readStrongBinder, &listener); - - return addWindowInfosListener(listener); - } - case REMOVE_WINDOW_INFOS_LISTENER: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp listener; - SAFE_PARCEL(data.readStrongBinder, &listener); - - return removeWindowInfosListener(listener); - } case SET_OVERRIDE_FRAME_RATE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 4facef403d..e54ff49391 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -111,7 +111,6 @@ bool ComposerService::connectLocked() { if (instance.mComposerService == nullptr) { if (ComposerService::getInstance().connectLocked()) { ALOGD("ComposerService reconnected"); - WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService); } } return instance.mComposerService; @@ -159,6 +158,7 @@ bool ComposerServiceAIDL::connectLocked() { if (instance.mComposerService == nullptr) { if (ComposerServiceAIDL::getInstance().connectLocked()) { ALOGD("ComposerServiceAIDL reconnected"); + WindowInfosListenerReporter::getInstance()->reconnect(instance.mComposerService); } } return instance.mComposerService; @@ -2261,10 +2261,13 @@ status_t SurfaceComposerClient::setDesiredDisplayModeSpecs( const sp& displayToken, ui::DisplayModeId defaultMode, bool allowGroupSwitching, float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin, float appRequestRefreshRateMax) { - return ComposerService::getComposerService() - ->setDesiredDisplayModeSpecs(displayToken, defaultMode, allowGroupSwitching, - primaryRefreshRateMin, primaryRefreshRateMax, - appRequestRefreshRateMin, appRequestRefreshRateMax); + binder::Status status = + ComposerServiceAIDL::getComposerService() + ->setDesiredDisplayModeSpecs(displayToken, defaultMode, allowGroupSwitching, + primaryRefreshRateMin, primaryRefreshRateMax, + appRequestRefreshRateMin, + appRequestRefreshRateMax); + return status.transactionError(); } status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp& displayToken, @@ -2274,10 +2277,23 @@ status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp& di float* outPrimaryRefreshRateMax, float* outAppRequestRefreshRateMin, float* outAppRequestRefreshRateMax) { - return ComposerService::getComposerService() - ->getDesiredDisplayModeSpecs(displayToken, outDefaultMode, outAllowGroupSwitching, - outPrimaryRefreshRateMin, outPrimaryRefreshRateMax, - outAppRequestRefreshRateMin, outAppRequestRefreshRateMax); + if (!outDefaultMode || !outAllowGroupSwitching || !outPrimaryRefreshRateMin || + !outPrimaryRefreshRateMax || !outAppRequestRefreshRateMin || !outAppRequestRefreshRateMax) { + return BAD_VALUE; + } + gui::DisplayModeSpecs specs; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDesiredDisplayModeSpecs(displayToken, + &specs); + if (status.isOk()) { + *outDefaultMode = specs.defaultMode; + *outAllowGroupSwitching = specs.allowGroupSwitching; + *outPrimaryRefreshRateMin = specs.primaryRefreshRateMin; + *outPrimaryRefreshRateMax = specs.primaryRefreshRateMax; + *outAppRequestRefreshRateMin = specs.appRequestRefreshRateMin; + *outAppRequestRefreshRateMax = specs.appRequestRefreshRateMax; + } + return status.transactionError(); } status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp& display, @@ -2469,33 +2485,49 @@ status_t SurfaceComposerClient::isWideColorDisplay(const sp& display, status_t SurfaceComposerClient::addRegionSamplingListener( const Rect& samplingArea, const sp& stopLayerHandle, const sp& listener) { - return ComposerService::getComposerService()->addRegionSamplingListener(samplingArea, - stopLayerHandle, - listener); + gui::ARect rect; + rect.left = samplingArea.left; + rect.top = samplingArea.top; + rect.right = samplingArea.right; + rect.bottom = samplingArea.bottom; + binder::Status status = + ComposerServiceAIDL::getComposerService()->addRegionSamplingListener(rect, + stopLayerHandle, + listener); + return status.transactionError(); } status_t SurfaceComposerClient::removeRegionSamplingListener( const sp& listener) { - return ComposerService::getComposerService()->removeRegionSamplingListener(listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->removeRegionSamplingListener(listener); + return status.transactionError(); } status_t SurfaceComposerClient::addFpsListener(int32_t taskId, const sp& listener) { - return ComposerService::getComposerService()->addFpsListener(taskId, listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->addFpsListener(taskId, listener); + return status.transactionError(); } status_t SurfaceComposerClient::removeFpsListener(const sp& listener) { - return ComposerService::getComposerService()->removeFpsListener(listener); + binder::Status status = ComposerServiceAIDL::getComposerService()->removeFpsListener(listener); + return status.transactionError(); } status_t SurfaceComposerClient::addTunnelModeEnabledListener( const sp& listener) { - return ComposerService::getComposerService()->addTunnelModeEnabledListener(listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->addTunnelModeEnabledListener(listener); + return status.transactionError(); } status_t SurfaceComposerClient::removeTunnelModeEnabledListener( const sp& listener) { - return ComposerService::getComposerService()->removeTunnelModeEnabledListener(listener); + binder::Status status = + ComposerServiceAIDL::getComposerService()->removeTunnelModeEnabledListener(listener); + return status.transactionError(); } bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp& displayToken) { @@ -2550,22 +2582,31 @@ std::optional SurfaceComposerClient::getDisplayDecorat return support; } -int SurfaceComposerClient::getGPUContextPriority() { - return ComposerService::getComposerService()->getGPUContextPriority(); +int SurfaceComposerClient::getGpuContextPriority() { + int priority; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getGpuContextPriority(&priority); + if (!status.isOk()) { + status_t err = status.transactionError(); + ALOGE("getGpuContextPriority failed to read data: %s (%d)", strerror(-err), err); + return 0; + } + return priority; } status_t SurfaceComposerClient::addWindowInfosListener( const sp& windowInfosListener, std::pair, std::vector>* outInitialInfo) { return WindowInfosListenerReporter::getInstance() - ->addWindowInfosListener(windowInfosListener, ComposerService::getComposerService(), + ->addWindowInfosListener(windowInfosListener, ComposerServiceAIDL::getComposerService(), outInitialInfo); } status_t SurfaceComposerClient::removeWindowInfosListener( const sp& windowInfosListener) { return WindowInfosListenerReporter::getInstance() - ->removeWindowInfosListener(windowInfosListener, ComposerService::getComposerService()); + ->removeWindowInfosListener(windowInfosListener, + ComposerServiceAIDL::getComposerService()); } // ---------------------------------------------------------------------------- diff --git a/libs/gui/TransactionTracing.cpp b/libs/gui/TransactionTracing.cpp index eedc3df009..59450fb411 100644 --- a/libs/gui/TransactionTracing.cpp +++ b/libs/gui/TransactionTracing.cpp @@ -15,9 +15,9 @@ */ #include "gui/TransactionTracing.h" -#include "gui/ISurfaceComposer.h" +#include "android/gui/ISurfaceComposer.h" -#include +#include namespace android { @@ -32,7 +32,7 @@ sp TransactionTraceListener::getInstance() { if (sInstance == nullptr) { sInstance = new TransactionTraceListener; - sp sf(ComposerService::getComposerService()); + sp sf(ComposerServiceAIDL::getComposerService()); sf->addTransactionTraceListener(sInstance); } @@ -50,4 +50,4 @@ bool TransactionTraceListener::isTracingEnabled() { return mTracingEnabled; } -} // namespace android \ No newline at end of file +} // namespace android diff --git a/libs/gui/WindowInfosListenerReporter.cpp b/libs/gui/WindowInfosListenerReporter.cpp index cfc7dbc463..0ed83f272c 100644 --- a/libs/gui/WindowInfosListenerReporter.cpp +++ b/libs/gui/WindowInfosListenerReporter.cpp @@ -14,7 +14,7 @@ * limitations under the License. */ -#include +#include #include namespace android { @@ -31,13 +31,14 @@ sp WindowInfosListenerReporter::getInstance() { status_t WindowInfosListenerReporter::addWindowInfosListener( const sp& windowInfosListener, - const sp& surfaceComposer, + const sp& surfaceComposer, std::pair, std::vector>* outInitialInfo) { status_t status = OK; { std::scoped_lock lock(mListenersMutex); if (mWindowInfosListeners.empty()) { - status = surfaceComposer->addWindowInfosListener(this); + binder::Status s = surfaceComposer->addWindowInfosListener(this); + status = s.transactionError(); } if (status == OK) { @@ -55,12 +56,13 @@ status_t WindowInfosListenerReporter::addWindowInfosListener( status_t WindowInfosListenerReporter::removeWindowInfosListener( const sp& windowInfosListener, - const sp& surfaceComposer) { + const sp& surfaceComposer) { status_t status = OK; { std::scoped_lock lock(mListenersMutex); if (mWindowInfosListeners.size() == 1) { - status = surfaceComposer->removeWindowInfosListener(this); + binder::Status s = surfaceComposer->removeWindowInfosListener(this); + status = s.transactionError(); // Clear the last stored state since we're disabling updates and don't want to hold // stale values mLastWindowInfos.clear(); @@ -78,7 +80,8 @@ status_t WindowInfosListenerReporter::removeWindowInfosListener( binder::Status WindowInfosListenerReporter::onWindowInfosChanged( const std::vector& windowInfos, const std::vector& displayInfos, const sp& windowInfosReportedListener) { - std::unordered_set, SpHash> windowInfosListeners; + std::unordered_set, gui::SpHash> + windowInfosListeners; { std::scoped_lock lock(mListenersMutex); @@ -101,7 +104,7 @@ binder::Status WindowInfosListenerReporter::onWindowInfosChanged( return binder::Status::ok(); } -void WindowInfosListenerReporter::reconnect(const sp& composerService) { +void WindowInfosListenerReporter::reconnect(const sp& composerService) { std::scoped_lock lock(mListenersMutex); if (!mWindowInfosListeners.empty()) { composerService->addWindowInfosListener(this); diff --git a/libs/gui/aidl/android/gui/ARect.aidl b/libs/gui/aidl/android/gui/ARect.aidl new file mode 100644 index 0000000000..5785907a9c --- /dev/null +++ b/libs/gui/aidl/android/gui/ARect.aidl @@ -0,0 +1,35 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// copied from libs/arect/include/android/rect.h +// TODO(b/221473398): +// use hardware/interfaces/graphics/common/aidl/android/hardware/graphics/common/Rect.aidl +/** @hide */ +parcelable ARect { + /// Minimum X coordinate of the rectangle. + int left; + + /// Minimum Y coordinate of the rectangle. + int top; + + /// Maximum X coordinate of the rectangle. + int right; + + /// Maximum Y coordinate of the rectangle. + int bottom; +} diff --git a/libs/gui/aidl/android/gui/DisplayModeSpecs.aidl b/libs/gui/aidl/android/gui/DisplayModeSpecs.aidl new file mode 100644 index 0000000000..fb4fcdf8e8 --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayModeSpecs.aidl @@ -0,0 +1,27 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable DisplayModeSpecs { + int defaultMode; + boolean allowGroupSwitching; + float primaryRefreshRateMin; + float primaryRefreshRateMax; + float appRequestRefreshRateMin; + float appRequestRefreshRateMax; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index dc77416010..1fed69f88f 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -20,18 +20,25 @@ import android.gui.CompositionPreference; import android.gui.ContentSamplingAttributes; import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; +import android.gui.DisplayModeSpecs; import android.gui.DisplayPrimaries; import android.gui.DisplayState; import android.gui.DisplayStatInfo; +import android.gui.DynamicDisplayInfo; import android.gui.FrameEvent; import android.gui.FrameStats; +import android.gui.IFpsListener; +import android.gui.IHdrLayerInfoListener; +import android.gui.IRegionSamplingListener; +import android.gui.IScreenCaptureListener; +import android.gui.ITransactionTraceListener; +import android.gui.ITunnelModeEnabledListener; +import android.gui.IWindowInfosListener; +import android.gui.LayerCaptureArgs; import android.gui.LayerDebugInfo; import android.gui.PullAtomData; +import android.gui.ARect; import android.gui.StaticDisplayInfo; -import android.gui.DynamicDisplayInfo; -import android.gui.IHdrLayerInfoListener; -import android.gui.LayerCaptureArgs; -import android.gui.IScreenCaptureListener; /** @hide */ interface ISurfaceComposer { @@ -230,6 +237,82 @@ interface ISurfaceComposer { */ boolean isWideColorDisplay(IBinder token); + /** + * Registers a listener to stream median luma updates from SurfaceFlinger. + * + * The sampling area is bounded by both samplingArea and the given stopLayerHandle + * (i.e., only layers behind the stop layer will be captured and sampled). + * + * Multiple listeners may be provided so long as they have independent listeners. + * If multiple listeners are provided, the effective sampling region for each listener will + * be bounded by whichever stop layer has a lower Z value. + * + * Requires the same permissions as captureLayers and captureScreen. + */ + void addRegionSamplingListener(in ARect samplingArea, @nullable IBinder stopLayerHandle, IRegionSamplingListener listener); + + /** + * Removes a listener that was streaming median luma updates from SurfaceFlinger. + */ + void removeRegionSamplingListener(IRegionSamplingListener listener); + + /** + * Registers a listener that streams fps updates from SurfaceFlinger. + * + * The listener will stream fps updates for the layer tree rooted at the layer denoted by the + * task ID, i.e., the layer must have the task ID as part of its layer metadata with key + * METADATA_TASK_ID. If there is no such layer, then no fps is expected to be reported. + * + * Multiple listeners may be supported. + * + * Requires the READ_FRAME_BUFFER permission. + */ + void addFpsListener(int taskId, IFpsListener listener); + + /** + * Removes a listener that was streaming fps updates from SurfaceFlinger. + */ + void removeFpsListener(IFpsListener listener); + + /** + * Registers a listener to receive tunnel mode enabled updates from SurfaceFlinger. + * + * Requires ACCESS_SURFACE_FLINGER permission. + */ + void addTunnelModeEnabledListener(ITunnelModeEnabledListener listener); + + /** + * Removes a listener that was receiving tunnel mode enabled updates from SurfaceFlinger. + * + * Requires ACCESS_SURFACE_FLINGER permission. + */ + void removeTunnelModeEnabledListener(ITunnelModeEnabledListener listener); + + /** + * Sets the refresh rate boundaries for the display. + * + * The primary refresh rate range represents display manager's general guidance on the display + * modes we'll consider when switching refresh rates. Unless we get an explicit signal from an + * app, we should stay within this range. + * + * The app request refresh rate range allows us to consider more display modes when switching + * refresh rates. Although we should generally stay within the primary range, specific + * considerations, such as layer frame rate settings specified via the setFrameRate() api, may + * cause us to go outside the primary range. We never go outside the app request range. The app + * request range will be greater than or equal to the primary refresh rate range, never smaller. + * + * defaultMode is used to narrow the list of display modes SurfaceFlinger will consider + * switching between. Only modes with a mode group and resolution matching defaultMode + * will be considered for switching. The defaultMode corresponds to an ID of mode in the list + * of supported modes returned from getDynamicDisplayInfo(). + */ + void setDesiredDisplayModeSpecs( + IBinder displayToken, int defaultMode, + boolean allowGroupSwitching, float primaryRefreshRateMin, float primaryRefreshRateMax, + float appRequestRefreshRateMin, float appRequestRefreshRateMax); + + DisplayModeSpecs getDesiredDisplayModeSpecs(IBinder displayToken); + /** * Gets whether brightness operations are supported on a display. * @@ -286,4 +369,35 @@ interface ISurfaceComposer { * Returns NO_ERROR upon success. */ oneway void notifyPowerBoost(int boostId); + + /** + * Adds a TransactionTraceListener to listen for transaction tracing state updates. + */ + void addTransactionTraceListener(ITransactionTraceListener listener); + + /** + * Gets priority of the RenderEngine in SurfaceFlinger. + */ + int getGpuContextPriority(); + + /** + * Gets the number of buffers SurfaceFlinger would need acquire. This number + * would be propagated to the client via MIN_UNDEQUEUED_BUFFERS so that the + * client could allocate enough buffers to match SF expectations of the + * pipeline depth. SurfaceFlinger will make sure that it will give the app at + * least the time configured as the 'appDuration' before trying to latch + * the buffer. + * + * The total buffers needed for a given configuration is basically the + * numbers of vsyncs a single buffer is used across the stack. For the default + * configuration a buffer is held ~1 vsync by the app, ~1 vsync by SurfaceFlinger + * and 1 vsync by the display. The extra buffers are calculated as the + * number of additional buffers on top of the 2 buffers already present + * in MIN_UNDEQUEUED_BUFFERS. + */ + int getMaxAcquiredBufferCount(); + + void addWindowInfosListener(IWindowInfosListener windowInfosListener); + + void removeWindowInfosListener(IWindowInfosListener windowInfosListener); } diff --git a/libs/gui/aidl/android/gui/Rect.aidl b/libs/gui/aidl/android/gui/Rect.aidl deleted file mode 100644 index 1b13761392..0000000000 --- a/libs/gui/aidl/android/gui/Rect.aidl +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.gui; - -// copied from libs/arect/include/android/rect.h -// TODO(b/221473398): -// use hardware/interfaces/graphics/common/aidl/android/hardware/graphics/common/Rect.aidl -/** @hide */ -parcelable Rect { - /// Minimum X coordinate of the rectangle. - int left; - - /// Minimum Y coordinate of the rectangle. - int top; - - /// Maximum X coordinate of the rectangle. - int right; - - /// Maximum Y coordinate of the rectangle. - int bottom; -} diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 7f59a5affb..858bd1d55e 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -162,87 +162,6 @@ public: uint64_t timestamp, DisplayedFrameStats* outStats) const = 0; - /* Registers a listener to stream median luma updates from SurfaceFlinger. - * - * The sampling area is bounded by both samplingArea and the given stopLayerHandle - * (i.e., only layers behind the stop layer will be captured and sampled). - * - * Multiple listeners may be provided so long as they have independent listeners. - * If multiple listeners are provided, the effective sampling region for each listener will - * be bounded by whichever stop layer has a lower Z value. - * - * Requires the same permissions as captureLayers and captureScreen. - */ - virtual status_t addRegionSamplingListener(const Rect& samplingArea, - const sp& stopLayerHandle, - const sp& listener) = 0; - - /* - * Removes a listener that was streaming median luma updates from SurfaceFlinger. - */ - virtual status_t removeRegionSamplingListener(const sp& listener) = 0; - - /* Registers a listener that streams fps updates from SurfaceFlinger. - * - * The listener will stream fps updates for the layer tree rooted at the layer denoted by the - * task ID, i.e., the layer must have the task ID as part of its layer metadata with key - * METADATA_TASK_ID. If there is no such layer, then no fps is expected to be reported. - * - * Multiple listeners may be supported. - * - * Requires the READ_FRAME_BUFFER permission. - */ - virtual status_t addFpsListener(int32_t taskId, const sp& listener) = 0; - /* - * Removes a listener that was streaming fps updates from SurfaceFlinger. - */ - virtual status_t removeFpsListener(const sp& listener) = 0; - - /* Registers a listener to receive tunnel mode enabled updates from SurfaceFlinger. - * - * Requires ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t addTunnelModeEnabledListener( - const sp& listener) = 0; - - /* - * Removes a listener that was receiving tunnel mode enabled updates from SurfaceFlinger. - * - * Requires ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t removeTunnelModeEnabledListener( - const sp& listener) = 0; - - /* Sets the refresh rate boundaries for the display. - * - * The primary refresh rate range represents display manager's general guidance on the display - * modes we'll consider when switching refresh rates. Unless we get an explicit signal from an - * app, we should stay within this range. - * - * The app request refresh rate range allows us to consider more display modes when switching - * refresh rates. Although we should generally stay within the primary range, specific - * considerations, such as layer frame rate settings specified via the setFrameRate() api, may - * cause us to go outside the primary range. We never go outside the app request range. The app - * request range will be greater than or equal to the primary refresh rate range, never smaller. - * - * defaultMode is used to narrow the list of display modes SurfaceFlinger will consider - * switching between. Only modes with a mode group and resolution matching defaultMode - * will be considered for switching. The defaultMode corresponds to an ID of mode in the list - * of supported modes returned from getDynamicDisplayInfo(). - */ - virtual status_t setDesiredDisplayModeSpecs( - const sp& displayToken, ui::DisplayModeId defaultMode, - bool allowGroupSwitching, float primaryRefreshRateMin, float primaryRefreshRateMax, - float appRequestRefreshRateMin, float appRequestRefreshRateMax) = 0; - - virtual status_t getDesiredDisplayModeSpecs(const sp& displayToken, - ui::DisplayModeId* outDefaultMode, - bool* outAllowGroupSwitching, - float* outPrimaryRefreshRateMin, - float* outPrimaryRefreshRateMax, - float* outAppRequestRefreshRateMin, - float* outAppRequestRefreshRateMax) = 0; - /* * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows * material design guidelines. @@ -302,39 +221,6 @@ public: */ virtual status_t setFrameTimelineInfo(const sp& surface, const FrameTimelineInfo& frameTimelineInfo) = 0; - - /* - * Adds a TransactionTraceListener to listen for transaction tracing state updates. - */ - virtual status_t addTransactionTraceListener( - const sp& listener) = 0; - - /** - * Gets priority of the RenderEngine in SurfaceFlinger. - */ - virtual int getGPUContextPriority() = 0; - - /** - * Gets the number of buffers SurfaceFlinger would need acquire. This number - * would be propagated to the client via MIN_UNDEQUEUED_BUFFERS so that the - * client could allocate enough buffers to match SF expectations of the - * pipeline depth. SurfaceFlinger will make sure that it will give the app at - * least the time configured as the 'appDuration' before trying to latch - * the buffer. - * - * The total buffers needed for a given configuration is basically the - * numbers of vsyncs a single buffer is used across the stack. For the default - * configuration a buffer is held ~1 vsync by the app, ~1 vsync by SurfaceFlinger - * and 1 vsync by the display. The extra buffers are calculated as the - * number of additional buffers on top of the 2 buffers already present - * in MIN_UNDEQUEUED_BUFFERS. - */ - virtual status_t getMaxAcquiredBufferCount(int* buffers) const = 0; - - virtual status_t addWindowInfosListener( - const sp& windowInfosListener) const = 0; - virtual status_t removeWindowInfosListener( - const sp& windowInfosListener) const = 0; }; // ---------------------------------------------------------------------------- @@ -375,18 +261,18 @@ public: GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES, // Deprecated. Autogenerated by .aidl now. SET_DISPLAY_CONTENT_SAMPLING_ENABLED, // Deprecated. Autogenerated by .aidl now. GET_DISPLAYED_CONTENT_SAMPLE, - GET_PROTECTED_CONTENT_SUPPORT, // Deprecated. Autogenerated by .aidl now. - IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. - GET_DISPLAY_NATIVE_PRIMARIES, // Deprecated. Autogenerated by .aidl now. - GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. - ADD_REGION_SAMPLING_LISTENER, - REMOVE_REGION_SAMPLING_LISTENER, - SET_DESIRED_DISPLAY_MODE_SPECS, - GET_DESIRED_DISPLAY_MODE_SPECS, - GET_DISPLAY_BRIGHTNESS_SUPPORT, // Deprecated. Autogenerated by .aidl now. - SET_DISPLAY_BRIGHTNESS, // Deprecated. Autogenerated by .aidl now. - CAPTURE_DISPLAY_BY_ID, // Deprecated. Autogenerated by .aidl now. - NOTIFY_POWER_BOOST, // Deprecated. Autogenerated by .aidl now. + GET_PROTECTED_CONTENT_SUPPORT, // Deprecated. Autogenerated by .aidl now. + IS_WIDE_COLOR_DISPLAY, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAY_NATIVE_PRIMARIES, // Deprecated. Autogenerated by .aidl now. + GET_PHYSICAL_DISPLAY_IDS, // Deprecated. Autogenerated by .aidl now. + ADD_REGION_SAMPLING_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_REGION_SAMPLING_LISTENER, // Deprecated. Autogenerated by .aidl now. + SET_DESIRED_DISPLAY_MODE_SPECS, // Deprecated. Autogenerated by .aidl now. + GET_DESIRED_DISPLAY_MODE_SPECS, // Deprecated. Autogenerated by .aidl now. + GET_DISPLAY_BRIGHTNESS_SUPPORT, // Deprecated. Autogenerated by .aidl now. + SET_DISPLAY_BRIGHTNESS, // Deprecated. Autogenerated by .aidl now. + CAPTURE_DISPLAY_BY_ID, // Deprecated. Autogenerated by .aidl now. + NOTIFY_POWER_BOOST, // Deprecated. Autogenerated by .aidl now. SET_GLOBAL_SHADOW_SETTINGS, GET_AUTO_LOW_LATENCY_MODE_SUPPORT, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. SET_AUTO_LOW_LATENCY_MODE, // Deprecated. Autogenerated by .aidl now. @@ -396,21 +282,21 @@ public: // Deprecated. Use DisplayManager.setShouldAlwaysRespectAppRequestedMode(true); ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN, SET_FRAME_TIMELINE_INFO, - ADD_TRANSACTION_TRACE_LISTENER, + ADD_TRANSACTION_TRACE_LISTENER, // Deprecated. Autogenerated by .aidl now. GET_GPU_CONTEXT_PRIORITY, GET_MAX_ACQUIRED_BUFFER_COUNT, - GET_DYNAMIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. - ADD_FPS_LISTENER, - REMOVE_FPS_LISTENER, - OVERRIDE_HDR_TYPES, // Deprecated. Autogenerated by .aidl now. - ADD_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. - REMOVE_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. - ON_PULL_ATOM, // Deprecated. Autogenerated by .aidl now. - ADD_TUNNEL_MODE_ENABLED_LISTENER, - REMOVE_TUNNEL_MODE_ENABLED_LISTENER, - ADD_WINDOW_INFOS_LISTENER, - REMOVE_WINDOW_INFOS_LISTENER, - GET_PRIMARY_PHYSICAL_DISPLAY_ID, // Deprecated. Autogenerated by .aidl now. + GET_DYNAMIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. + ADD_FPS_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_FPS_LISTENER, // Deprecated. Autogenerated by .aidl now. + OVERRIDE_HDR_TYPES, // Deprecated. Autogenerated by .aidl now. + ADD_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_HDR_LAYER_INFO_LISTENER, // Deprecated. Autogenerated by .aidl now. + ON_PULL_ATOM, // Deprecated. Autogenerated by .aidl now. + ADD_TUNNEL_MODE_ENABLED_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_TUNNEL_MODE_ENABLED_LISTENER, // Deprecated. Autogenerated by .aidl now. + ADD_WINDOW_INFOS_LISTENER, // Deprecated. Autogenerated by .aidl now. + REMOVE_WINDOW_INFOS_LISTENER, // Deprecated. Autogenerated by .aidl now. + GET_PRIMARY_PHYSICAL_DISPLAY_ID, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_DECORATION_SUPPORT, GET_BOOT_DISPLAY_MODE_SUPPORT, // Deprecated. Autogenerated by .aidl now. SET_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. diff --git a/libs/gui/include/gui/LayerDebugInfo.h b/libs/gui/include/gui/LayerDebugInfo.h index 1c1bbef123..dbb80e583c 100644 --- a/libs/gui/include/gui/LayerDebugInfo.h +++ b/libs/gui/include/gui/LayerDebugInfo.h @@ -52,7 +52,7 @@ public: uint32_t mZ = 0 ; int32_t mWidth = -1; int32_t mHeight = -1; - Rect mCrop = Rect::INVALID_RECT; + android::Rect mCrop = android::Rect::INVALID_RECT; half4 mColor = half4(1.0_hf, 1.0_hf, 1.0_hf, 0.0_hf); uint32_t mFlags = 0; PixelFormat mPixelFormat = PIXEL_FORMAT_NONE; diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index a30a3fa731..48b870dd3b 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -216,7 +216,7 @@ public: /** * Gets the context priority of surface flinger's render engine. */ - static int getGPUContextPriority(); + static int getGpuContextPriority(); /** * Uncaches a buffer in ISurfaceComposer. It must be uncached via a transaction so that it is diff --git a/libs/gui/include/gui/WindowInfosListenerReporter.h b/libs/gui/include/gui/WindowInfosListenerReporter.h index 3b4aed442e..2754442a95 100644 --- a/libs/gui/include/gui/WindowInfosListenerReporter.h +++ b/libs/gui/include/gui/WindowInfosListenerReporter.h @@ -17,15 +17,14 @@ #pragma once #include +#include #include #include -#include #include #include #include namespace android { -class ISurfaceComposer; class WindowInfosListenerReporter : public gui::BnWindowInfosListener { public: @@ -33,17 +32,17 @@ public: binder::Status onWindowInfosChanged(const std::vector&, const std::vector&, const sp&) override; - status_t addWindowInfosListener( - const sp& windowInfosListener, const sp&, + const sp& windowInfosListener, + const sp&, std::pair, std::vector>* outInitialInfo); status_t removeWindowInfosListener(const sp& windowInfosListener, - const sp& surfaceComposer); - void reconnect(const sp&); + const sp& surfaceComposer); + void reconnect(const sp&); private: std::mutex mListenersMutex; - std::unordered_set, SpHash> + std::unordered_set, gui::SpHash> mWindowInfosListeners GUARDED_BY(mListenersMutex); std::vector mLastWindowInfos GUARDED_BY(mListenersMutex); diff --git a/libs/gui/include/private/gui/ComposerServiceAIDL.h b/libs/gui/include/private/gui/ComposerServiceAIDL.h index 9a96976c0f..296358329b 100644 --- a/libs/gui/include/private/gui/ComposerServiceAIDL.h +++ b/libs/gui/include/private/gui/ComposerServiceAIDL.h @@ -20,6 +20,7 @@ #include #include +#include #include #include diff --git a/libs/gui/tests/RegionSampling_test.cpp b/libs/gui/tests/RegionSampling_test.cpp index c9106bed4c..e6a9d6caaf 100644 --- a/libs/gui/tests/RegionSampling_test.cpp +++ b/libs/gui/tests/RegionSampling_test.cpp @@ -23,7 +23,7 @@ #include #include #include -#include +#include #include using namespace std::chrono_literals; @@ -242,24 +242,33 @@ protected: }; TEST_F(RegionSamplingTest, invalidLayerHandle_doesNotCrash) { - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); - const Rect sampleArea{100, 100, 200, 200}; + gui::ARect sampleArea; + sampleArea.left = 100; + sampleArea.top = 100; + sampleArea.right = 200; + sampleArea.bottom = 200; // Passing in composer service as the layer handle should not crash, we'll // treat it as a layer that no longer exists and silently allow sampling to // occur. - status_t status = composer->addRegionSamplingListener(sampleArea, - IInterface::asBinder(composer), listener); - ASSERT_EQ(NO_ERROR, status); + binder::Status status = + composer->addRegionSamplingListener(sampleArea, IInterface::asBinder(composer), + listener); + ASSERT_EQ(NO_ERROR, status.transactionError()); composer->removeRegionSamplingListener(listener); } TEST_F(RegionSamplingTest, DISABLED_CollectsLuma) { fill_render(rgba_green); - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); - const Rect sampleArea{100, 100, 200, 200}; + gui::ARect sampleArea; + sampleArea.left = 100; + sampleArea.top = 100; + sampleArea.right = 200; + sampleArea.bottom = 200; composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), listener); EXPECT_TRUE(listener->wait_event(300ms)) << "timed out waiting for luma event to be received"; @@ -271,9 +280,13 @@ TEST_F(RegionSamplingTest, DISABLED_CollectsLuma) { TEST_F(RegionSamplingTest, DISABLED_CollectsChangingLuma) { fill_render(rgba_green); - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); - const Rect sampleArea{100, 100, 200, 200}; + gui::ARect sampleArea; + sampleArea.left = 100; + sampleArea.top = 100; + sampleArea.right = 200; + sampleArea.bottom = 200; composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), listener); EXPECT_TRUE(listener->wait_event(300ms)) << "timed out waiting for luma event to be received"; @@ -291,13 +304,21 @@ TEST_F(RegionSamplingTest, DISABLED_CollectsChangingLuma) { TEST_F(RegionSamplingTest, DISABLED_CollectsLumaFromTwoRegions) { fill_render(rgba_green); - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp greenListener = new Listener(); - const Rect greenSampleArea{100, 100, 200, 200}; + gui::ARect greenSampleArea; + greenSampleArea.left = 100; + greenSampleArea.top = 100; + greenSampleArea.right = 200; + greenSampleArea.bottom = 200; composer->addRegionSamplingListener(greenSampleArea, mTopLayer->getHandle(), greenListener); sp grayListener = new Listener(); - const Rect graySampleArea{500, 100, 600, 200}; + gui::ARect graySampleArea; + graySampleArea.left = 500; + graySampleArea.top = 100; + graySampleArea.right = 600; + graySampleArea.bottom = 200; composer->addRegionSamplingListener(graySampleArea, mTopLayer->getHandle(), grayListener); EXPECT_TRUE(grayListener->wait_event(300ms)) @@ -312,29 +333,46 @@ TEST_F(RegionSamplingTest, DISABLED_CollectsLumaFromTwoRegions) { } TEST_F(RegionSamplingTest, DISABLED_TestIfInvalidInputParameters) { - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); - const Rect sampleArea{100, 100, 200, 200}; + + gui::ARect invalidRect; + invalidRect.left = Rect::INVALID_RECT.left; + invalidRect.top = Rect::INVALID_RECT.top; + invalidRect.right = Rect::INVALID_RECT.right; + invalidRect.bottom = Rect::INVALID_RECT.bottom; + + gui::ARect sampleArea; + sampleArea.left = 100; + sampleArea.top = 100; + sampleArea.right = 200; + sampleArea.bottom = 200; // Invalid input sampleArea EXPECT_EQ(BAD_VALUE, - composer->addRegionSamplingListener(Rect::INVALID_RECT, mTopLayer->getHandle(), - listener)); + composer->addRegionSamplingListener(invalidRect, mTopLayer->getHandle(), listener) + .transactionError()); listener->reset(); // Invalid input binder - EXPECT_EQ(NO_ERROR, composer->addRegionSamplingListener(sampleArea, NULL, listener)); + EXPECT_EQ(NO_ERROR, + composer->addRegionSamplingListener(sampleArea, NULL, listener).transactionError()); // Invalid input listener EXPECT_EQ(BAD_VALUE, - composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), NULL)); - EXPECT_EQ(BAD_VALUE, composer->removeRegionSamplingListener(NULL)); + composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), NULL) + .transactionError()); + EXPECT_EQ(BAD_VALUE, composer->removeRegionSamplingListener(NULL).transactionError()); // remove the listener composer->removeRegionSamplingListener(listener); } TEST_F(RegionSamplingTest, DISABLED_TestCallbackAfterRemoveListener) { fill_render(rgba_green); - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); - const Rect sampleArea{100, 100, 200, 200}; + gui::ARect sampleArea; + sampleArea.left = 100; + sampleArea.top = 100; + sampleArea.right = 200; + sampleArea.bottom = 200; composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), listener); fill_render(rgba_green); @@ -349,13 +387,18 @@ TEST_F(RegionSamplingTest, DISABLED_TestCallbackAfterRemoveListener) { } TEST_F(RegionSamplingTest, DISABLED_CollectsLumaFromMovingLayer) { - sp composer = ComposerService::getComposerService(); + sp composer = ComposerServiceAIDL::getComposerService(); sp listener = new Listener(); Rect sampleArea{100, 100, 200, 200}; + gui::ARect sampleAreaA; + sampleAreaA.left = sampleArea.left; + sampleAreaA.top = sampleArea.top; + sampleAreaA.right = sampleArea.right; + sampleAreaA.bottom = sampleArea.bottom; // Test: listener in (100, 100). See layer before move, no layer after move. fill_render(rgba_blue); - composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), listener); + composer->addRegionSamplingListener(sampleAreaA, mTopLayer->getHandle(), listener); EXPECT_TRUE(listener->wait_event(300ms)) << "timed out waiting for luma event to be received"; EXPECT_NEAR(listener->luma(), luma_blue, error_margin); listener->reset(); @@ -367,7 +410,11 @@ TEST_F(RegionSamplingTest, DISABLED_CollectsLumaFromMovingLayer) { // Test: listener offset to (600, 600). No layer before move, see layer after move. fill_render(rgba_green); sampleArea.offsetTo(600, 600); - composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), listener); + sampleAreaA.left = sampleArea.left; + sampleAreaA.top = sampleArea.top; + sampleAreaA.right = sampleArea.right; + sampleAreaA.bottom = sampleArea.bottom; + composer->addRegionSamplingListener(sampleAreaA, mTopLayer->getHandle(), listener); EXPECT_TRUE(listener->wait_event(300ms)) << "timed out waiting for luma event to be received"; EXPECT_NEAR(listener->luma(), luma_gray, error_margin); listener->reset(); diff --git a/libs/gui/tests/SamplingDemo.cpp b/libs/gui/tests/SamplingDemo.cpp index a083a228a6..f98437b4f8 100644 --- a/libs/gui/tests/SamplingDemo.cpp +++ b/libs/gui/tests/SamplingDemo.cpp @@ -26,7 +26,7 @@ #include #include #include -#include +#include #include using namespace std::chrono_literals; @@ -121,10 +121,22 @@ int main(int, const char**) { const Rect backButtonArea{200, 1606, 248, 1654}; sp backButton = new android::Button("BackButton", backButtonArea); - sp composer = ComposerService::getComposerService(); - composer->addRegionSamplingListener(homeButtonArea, homeButton->getStopLayerHandle(), + gui::ARect homeButtonAreaA; + homeButtonAreaA.left = 490; + homeButtonAreaA.top = 1606; + homeButtonAreaA.right = 590; + homeButtonAreaA.bottom = 1654; + + gui::ARect backButtonAreaA; + backButtonAreaA.left = 200; + backButtonAreaA.top = 1606; + backButtonAreaA.right = 248; + backButtonAreaA.bottom = 1654; + + sp composer = ComposerServiceAIDL::getComposerService(); + composer->addRegionSamplingListener(homeButtonAreaA, homeButton->getStopLayerHandle(), homeButton); - composer->addRegionSamplingListener(backButtonArea, backButton->getStopLayerHandle(), + composer->addRegionSamplingListener(backButtonAreaA, backButton->getStopLayerHandle(), backButton); ProcessState::self()->startThreadPool(); diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 58964d6878..1758aba6d4 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -720,48 +720,6 @@ public: return NO_ERROR; } - status_t addRegionSamplingListener(const Rect& /*samplingArea*/, - const sp& /*stopLayerHandle*/, - const sp& /*listener*/) override { - return NO_ERROR; - } - status_t removeRegionSamplingListener( - const sp& /*listener*/) override { - return NO_ERROR; - } - status_t addFpsListener(int32_t /*taskId*/, const sp& /*listener*/) { - return NO_ERROR; - } - status_t removeFpsListener(const sp& /*listener*/) { return NO_ERROR; } - - status_t addTunnelModeEnabledListener(const sp& /*listener*/) { - return NO_ERROR; - } - - status_t removeTunnelModeEnabledListener( - const sp& /*listener*/) { - return NO_ERROR; - } - - status_t setDesiredDisplayModeSpecs(const sp& /*displayToken*/, - ui::DisplayModeId /*defaultMode*/, - bool /*allowGroupSwitching*/, - float /*primaryRefreshRateMin*/, - float /*primaryRefreshRateMax*/, - float /*appRequestRefreshRateMin*/, - float /*appRequestRefreshRateMax*/) { - return NO_ERROR; - } - status_t getDesiredDisplayModeSpecs(const sp& /*displayToken*/, - ui::DisplayModeId* /*outDefaultMode*/, - bool* /*outAllowGroupSwitching*/, - float* /*outPrimaryRefreshRateMin*/, - float* /*outPrimaryRefreshRateMax*/, - float* /*outAppRequestRefreshRateMin*/, - float* /*outAppRequestRefreshRateMax*/) override { - return NO_ERROR; - }; - status_t setGlobalShadowSettings(const half4& /*ambientColor*/, const half4& /*spotColor*/, float /*lightPosY*/, float /*lightPosZ*/, float /*lightRadius*/) override { @@ -784,25 +742,6 @@ public: return NO_ERROR; } - status_t addTransactionTraceListener( - const sp& /*listener*/) override { - return NO_ERROR; - } - - int getGPUContextPriority() override { return 0; }; - - status_t getMaxAcquiredBufferCount(int* /*buffers*/) const override { return NO_ERROR; } - - status_t addWindowInfosListener( - const sp& /*windowInfosListener*/) const override { - return NO_ERROR; - } - - status_t removeWindowInfosListener( - const sp& /*windowInfosListener*/) const override { - return NO_ERROR; - } - status_t setOverrideFrameRate(uid_t /*uid*/, float /*frameRate*/) override { return NO_ERROR; } protected: @@ -974,6 +913,50 @@ public: return binder::Status::ok(); } + binder::Status addRegionSamplingListener( + const gui::ARect& /*samplingArea*/, const sp& /*stopLayerHandle*/, + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status removeRegionSamplingListener( + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status addFpsListener(int32_t /*taskId*/, + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status removeFpsListener(const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status addTunnelModeEnabledListener( + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status removeTunnelModeEnabledListener( + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status setDesiredDisplayModeSpecs(const sp& /*displayToken*/, + int32_t /*defaultMode*/, bool /*allowGroupSwitching*/, + float /*primaryRefreshRateMin*/, + float /*primaryRefreshRateMax*/, + float /*appRequestRefreshRateMin*/, + float /*appRequestRefreshRateMax*/) override { + return binder::Status::ok(); + } + + binder::Status getDesiredDisplayModeSpecs(const sp& /*displayToken*/, + gui::DisplayModeSpecs* /*outSpecs*/) override { + return binder::Status::ok(); + } + binder::Status getDisplayBrightnessSupport(const sp& /*displayToken*/, bool* /*outSupport*/) override { return binder::Status::ok(); @@ -998,6 +981,29 @@ public: binder::Status notifyPowerBoost(int /*boostId*/) override { return binder::Status::ok(); } + binder::Status addTransactionTraceListener( + const sp& /*listener*/) override { + return binder::Status::ok(); + } + + binder::Status getGpuContextPriority(int32_t* /*outPriority*/) override { + return binder::Status::ok(); + } + + binder::Status getMaxAcquiredBufferCount(int32_t* /*buffers*/) override { + return binder::Status::ok(); + } + + binder::Status addWindowInfosListener( + const sp& /*windowInfosListener*/) override { + return binder::Status::ok(); + } + + binder::Status removeWindowInfosListener( + const sp& /*windowInfosListener*/) override { + return binder::Status::ok(); + } + protected: IBinder* onAsBinder() override { return nullptr; } diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 333e5b0a82..2cd1393085 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -5467,13 +5467,9 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // access to SF. case BOOT_FINISHED: case GET_HDR_CAPABILITIES: - case SET_DESIRED_DISPLAY_MODE_SPECS: - case GET_DESIRED_DISPLAY_MODE_SPECS: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: case GET_GAME_CONTENT_TYPE_SUPPORT: case GET_DISPLAYED_CONTENT_SAMPLE: - case ADD_TUNNEL_MODE_ENABLED_LISTENER: - case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: case SET_GLOBAL_SHADOW_SETTINGS: case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: { // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary @@ -5505,35 +5501,10 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // special permissions. case SET_FRAME_RATE: case GET_DISPLAY_DECORATION_SUPPORT: - case SET_FRAME_TIMELINE_INFO: - case GET_GPU_CONTEXT_PRIORITY: - case GET_MAX_ACQUIRED_BUFFER_COUNT: { + case SET_FRAME_TIMELINE_INFO: { // This is not sensitive information, so should not require permission control. return OK; } - case ADD_FPS_LISTENER: - case REMOVE_FPS_LISTENER: - case ADD_REGION_SAMPLING_LISTENER: - case REMOVE_REGION_SAMPLING_LISTENER: { - // codes that require permission check - IPCThreadState* ipc = IPCThreadState::self(); - const int pid = ipc->getCallingPid(); - const int uid = ipc->getCallingUid(); - if ((uid != AID_GRAPHICS) && - !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { - ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid); - return PERMISSION_DENIED; - } - return OK; - } - case ADD_TRANSACTION_TRACE_LISTENER: { - IPCThreadState* ipc = IPCThreadState::self(); - const int uid = ipc->getCallingUid(); - if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) { - return OK; - } - return PERMISSION_DENIED; - } case SET_OVERRIDE_FRAME_RATE: { const int uid = IPCThreadState::self()->getCallingUid(); if (uid == AID_ROOT || uid == AID_SYSTEM) { @@ -5541,14 +5512,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { } return PERMISSION_DENIED; } - case ADD_WINDOW_INFOS_LISTENER: - case REMOVE_WINDOW_INFOS_LISTENER: { - const int uid = IPCThreadState::self()->getCallingUid(); - if (uid == AID_SYSTEM || uid == AID_GRAPHICS) { - return OK; - } - return PERMISSION_DENIED; - } case CREATE_DISPLAY: case DESTROY_DISPLAY: case GET_PRIMARY_PHYSICAL_DISPLAY_ID: @@ -5583,11 +5546,24 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: case GET_PROTECTED_CONTENT_SUPPORT: case IS_WIDE_COLOR_DISPLAY: + case ADD_REGION_SAMPLING_LISTENER: + case REMOVE_REGION_SAMPLING_LISTENER: + case ADD_FPS_LISTENER: + case REMOVE_FPS_LISTENER: + case ADD_TUNNEL_MODE_ENABLED_LISTENER: + case REMOVE_TUNNEL_MODE_ENABLED_LISTENER: + case ADD_WINDOW_INFOS_LISTENER: + case REMOVE_WINDOW_INFOS_LISTENER: + case SET_DESIRED_DISPLAY_MODE_SPECS: + case GET_DESIRED_DISPLAY_MODE_SPECS: case GET_DISPLAY_BRIGHTNESS_SUPPORT: case SET_DISPLAY_BRIGHTNESS: case ADD_HDR_LAYER_INFO_LISTENER: case REMOVE_HDR_LAYER_INFO_LISTENER: case NOTIFY_POWER_BOOST: + case ADD_TRANSACTION_TRACE_LISTENER: + case GET_GPU_CONTEXT_PRIORITY: + case GET_MAX_ACQUIRED_BUFFER_COUNT: LOG_FATAL("Deprecated opcode: %d, migrated to AIDL", code); return PERMISSION_DENIED; } @@ -7103,7 +7079,7 @@ status_t SurfaceFlinger::addTransactionTraceListener( return NO_ERROR; } -int SurfaceFlinger::getGPUContextPriority() { +int SurfaceFlinger::getGpuContextPriority() { return getRenderEngine().getContextPriority(); } @@ -7753,6 +7729,115 @@ binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp& token, return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::addRegionSamplingListener( + const gui::ARect& samplingArea, const sp& stopLayerHandle, + const sp& listener) { + status_t status = checkReadFrameBufferPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + android::Rect rect; + rect.left = samplingArea.left; + rect.top = samplingArea.top; + rect.right = samplingArea.right; + rect.bottom = samplingArea.bottom; + status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::removeRegionSamplingListener( + const sp& listener) { + status_t status = checkReadFrameBufferPermission(); + if (status == OK) { + status = mFlinger->removeRegionSamplingListener(listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId, + const sp& listener) { + status_t status = checkReadFrameBufferPermission(); + if (status == OK) { + status = mFlinger->addFpsListener(taskId, listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::removeFpsListener(const sp& listener) { + status_t status = checkReadFrameBufferPermission(); + if (status == OK) { + status = mFlinger->removeFpsListener(listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener( + const sp& listener) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->addTunnelModeEnabledListener(listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener( + const sp& listener) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->removeTunnelModeEnabledListener(listener); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs( + const sp& displayToken, int32_t defaultMode, bool allowGroupSwitching, + float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin, + float appRequestRefreshRateMax) { + status_t status = checkAccessPermission(); + if (status == OK) { + status = mFlinger->setDesiredDisplayModeSpecs(displayToken, + static_cast(defaultMode), + allowGroupSwitching, primaryRefreshRateMin, + primaryRefreshRateMax, + appRequestRefreshRateMin, + appRequestRefreshRateMax); + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp& displayToken, + gui::DisplayModeSpecs* outSpecs) { + if (!outSpecs) { + return binder::Status::fromStatusT(BAD_VALUE); + } + + status_t status = checkAccessPermission(); + if (status != OK) { + return binder::Status::fromStatusT(status); + } + + ui::DisplayModeId displayModeId; + bool allowGroupSwitching; + float primaryRefreshRateMin; + float primaryRefreshRateMax; + float appRequestRefreshRateMin; + float appRequestRefreshRateMax; + status = mFlinger->getDesiredDisplayModeSpecs(displayToken, &displayModeId, + &allowGroupSwitching, &primaryRefreshRateMin, + &primaryRefreshRateMax, &appRequestRefreshRateMin, + &appRequestRefreshRateMax); + if (status == NO_ERROR) { + outSpecs->defaultMode = displayModeId; + outSpecs->allowGroupSwitching = allowGroupSwitching; + outSpecs->primaryRefreshRateMin = primaryRefreshRateMin; + outSpecs->primaryRefreshRateMax = primaryRefreshRateMax; + outSpecs->appRequestRefreshRateMin = appRequestRefreshRateMin; + outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax; + } + + return binder::Status::fromStatusT(status); +} + binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp& displayToken, bool* outSupport) { status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport); @@ -7794,6 +7879,53 @@ binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) { return binder::Status::fromStatusT(status); } +binder::Status SurfaceComposerAIDL::addTransactionTraceListener( + const sp& listener) { + status_t status; + IPCThreadState* ipc = IPCThreadState::self(); + const int uid = ipc->getCallingUid(); + if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) { + status = mFlinger->addTransactionTraceListener(listener); + } else { + status = PERMISSION_DENIED; + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) { + *outPriority = mFlinger->getGpuContextPriority(); + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) { + status_t status = mFlinger->getMaxAcquiredBufferCount(buffers); + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::addWindowInfosListener( + const sp& windowInfosListener) { + status_t status; + const int uid = IPCThreadState::self()->getCallingUid(); + if (uid == AID_SYSTEM || uid == AID_GRAPHICS) { + status = mFlinger->addWindowInfosListener(windowInfosListener); + } else { + status = PERMISSION_DENIED; + } + return binder::Status::fromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::removeWindowInfosListener( + const sp& windowInfosListener) { + status_t status; + const int uid = IPCThreadState::self()->getCallingUid(); + if (uid == AID_SYSTEM || uid == AID_GRAPHICS) { + status = mFlinger->removeWindowInfosListener(windowInfosListener); + } else { + status = PERMISSION_DENIED; + } + return binder::Status::fromStatusT(status); +} + status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) { if (!mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) { IPCThreadState* ipc = IPCThreadState::self(); @@ -7816,6 +7948,17 @@ status_t SurfaceComposerAIDL::checkControlDisplayBrightnessPermission() { return OK; } +status_t SurfaceComposerAIDL::checkReadFrameBufferPermission() { + IPCThreadState* ipc = IPCThreadState::self(); + const int pid = ipc->getCallingPid(); + const int uid = ipc->getCallingUid(); + if ((uid != AID_GRAPHICS) && !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { + ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid); + return PERMISSION_DENIED; + } + return OK; +} + } // namespace android #if defined(__gl_h_) diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 8bd5345403..5e4041de41 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -608,26 +608,24 @@ private: status_t getProtectedContentSupport(bool* outSupported) const; status_t isWideColorDisplay(const sp& displayToken, bool* outIsWideColorDisplay) const; status_t addRegionSamplingListener(const Rect& samplingArea, const sp& stopLayerHandle, - const sp& listener) override; - status_t removeRegionSamplingListener(const sp& listener) override; - status_t addFpsListener(int32_t taskId, const sp& listener) override; - status_t removeFpsListener(const sp& listener) override; - status_t addTunnelModeEnabledListener( - const sp& listener) override; - status_t removeTunnelModeEnabledListener( - const sp& listener) override; + const sp& listener); + status_t removeRegionSamplingListener(const sp& listener); + status_t addFpsListener(int32_t taskId, const sp& listener); + status_t removeFpsListener(const sp& listener); + status_t addTunnelModeEnabledListener(const sp& listener); + status_t removeTunnelModeEnabledListener(const sp& listener); status_t setDesiredDisplayModeSpecs(const sp& displayToken, ui::DisplayModeId displayModeId, bool allowGroupSwitching, float primaryRefreshRateMin, float primaryRefreshRateMax, float appRequestRefreshRateMin, - float appRequestRefreshRateMax) override; + float appRequestRefreshRateMax); status_t getDesiredDisplayModeSpecs(const sp& displayToken, ui::DisplayModeId* outDefaultMode, bool* outAllowGroupSwitching, float* outPrimaryRefreshRateMin, float* outPrimaryRefreshRateMax, float* outAppRequestRefreshRateMin, - float* outAppRequestRefreshRateMax) override; + float* outAppRequestRefreshRateMax); status_t getDisplayBrightnessSupport(const sp& displayToken, bool* outSupport) const; status_t setDisplayBrightness(const sp& displayToken, const gui::DisplayBrightness& brightness); @@ -650,17 +648,15 @@ private: status_t setOverrideFrameRate(uid_t uid, float frameRate) override; - status_t addTransactionTraceListener( - const sp& listener) override; + status_t addTransactionTraceListener(const sp& listener); - int getGPUContextPriority() override; + int getGpuContextPriority(); - status_t getMaxAcquiredBufferCount(int* buffers) const override; + status_t getMaxAcquiredBufferCount(int* buffers) const; - status_t addWindowInfosListener( - const sp& windowInfosListener) const override; + status_t addWindowInfosListener(const sp& windowInfosListener) const; status_t removeWindowInfosListener( - const sp& windowInfosListener) const override; + const sp& windowInfosListener) const; // Implements IBinder::DeathRecipient. void binderDied(const wp& who) override; @@ -1501,6 +1497,24 @@ public: binder::Status getProtectedContentSupport(bool* outSupporte) override; binder::Status isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) override; + binder::Status addRegionSamplingListener( + const gui::ARect& samplingArea, const sp& stopLayerHandle, + const sp& listener) override; + binder::Status removeRegionSamplingListener( + const sp& listener) override; + binder::Status addFpsListener(int32_t taskId, const sp& listener) override; + binder::Status removeFpsListener(const sp& listener) override; + binder::Status addTunnelModeEnabledListener( + const sp& listener) override; + binder::Status removeTunnelModeEnabledListener( + const sp& listener) override; + binder::Status setDesiredDisplayModeSpecs(const sp& displayToken, int32_t defaultMode, + bool allowGroupSwitching, float primaryRefreshRateMin, + float primaryRefreshRateMax, + float appRequestRefreshRateMin, + float appRequestRefreshRateMax) override; + binder::Status getDesiredDisplayModeSpecs(const sp& displayToken, + gui::DisplayModeSpecs* outSpecs) override; binder::Status getDisplayBrightnessSupport(const sp& displayToken, bool* outSupport) override; binder::Status setDisplayBrightness(const sp& displayToken, @@ -1511,11 +1525,20 @@ public: const sp& displayToken, const sp& listener) override; binder::Status notifyPowerBoost(int boostId) override; + binder::Status addTransactionTraceListener( + const sp& listener) override; + binder::Status getGpuContextPriority(int32_t* outPriority) override; + binder::Status getMaxAcquiredBufferCount(int32_t* buffers) override; + binder::Status addWindowInfosListener( + const sp& windowInfosListener) override; + binder::Status removeWindowInfosListener( + const sp& windowInfosListener) override; private: static const constexpr bool kUsePermissionCache = true; status_t checkAccessPermission(bool usePermissionCache = kUsePermissionCache); status_t checkControlDisplayBrightnessPermission(); + status_t checkReadFrameBufferPermission(); private: sp mFlinger; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index a80aca2f73..e90753ab3f 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -782,7 +782,7 @@ public: return mFlinger->onTransact(code, data, reply, flags); } - auto getGPUContextPriority() { return mFlinger->getGPUContextPriority(); } + auto getGpuContextPriority() { return mFlinger->getGpuContextPriority(); } auto calculateMaxAcquiredBufferCount(Fps refreshRate, std::chrono::nanoseconds presentLatency) const { diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index bf2465ff2d..490d00a7a0 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -436,7 +436,7 @@ public: return mFlinger->onTransact(code, data, reply, flags); } - auto getGPUContextPriority() { return mFlinger->getGPUContextPriority(); } + auto getGpuContextPriority() { return mFlinger->getGpuContextPriority(); } auto calculateMaxAcquiredBufferCount(Fps refreshRate, std::chrono::nanoseconds presentLatency) const { -- cgit v1.2.3-59-g8ed1b From 3bdef86d85259d70529ef56b481279ec834df22c Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Thu, 3 Mar 2022 11:57:19 -0800 Subject: Migrate and clean up methods of ISurfaceComposer Convert FrameTimelineInfo to aidl parcelable. Add Color, DisplayDecorationSupport and DisplayedFrameStats parcelables. Remove the following methods: authenticateSurfaceTexture, setFrameRate and setFrameTimelineInfo, which alway retrun errors for BLAST. Ramp up error handling. Bug: 222537482 Bug: 222763616 Test: atest libgui_test libsurfaceflinger_unittest SurfaceFlinger_test Change-Id: I3b46bae068ac3d482881dac96972a40e46581d34 --- libs/gui/Android.bp | 1 - libs/gui/FrameTimelineInfo.cpp | 68 ---- libs/gui/ISurfaceComposer.cpp | 345 +-------------------- libs/gui/Surface.cpp | 42 ++- libs/gui/SurfaceComposerClient.cpp | 173 ++++++++--- libs/gui/WindowInfosListenerReporter.cpp | 6 +- libs/gui/aidl/android/gui/Color.aidl | 25 ++ .../aidl/android/gui/DisplayDecorationSupport.aidl | 25 ++ libs/gui/aidl/android/gui/DisplayedFrameStats.aidl | 40 +++ libs/gui/aidl/android/gui/FrameTimelineInfo.aidl | 36 +++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 54 +++- libs/gui/include/gui/AidlStatusUtil.h | 114 +++++++ libs/gui/include/gui/FrameTimelineInfo.h | 49 --- libs/gui/include/gui/ISurfaceComposer.h | 84 +---- libs/gui/include/gui/Surface.h | 4 +- libs/gui/include/gui/SurfaceComposerClient.h | 2 + libs/gui/include/gui/VsyncEventData.h | 2 +- libs/gui/tests/BLASTBufferQueue_test.cpp | 6 +- libs/gui/tests/RegionSampling_test.cpp | 19 +- libs/gui/tests/Surface_test.cpp | 62 ++-- services/surfaceflinger/SurfaceFlinger.cpp | 295 +++++++++--------- services/surfaceflinger/SurfaceFlinger.h | 25 +- .../fuzzer/surfaceflinger_fuzzers_utils.h | 1 - .../fuzzer/surfaceflinger_layer_fuzzer.cpp | 6 +- .../surfaceflinger/tests/BootDisplayMode_test.cpp | 11 +- services/surfaceflinger/tests/Credentials_test.cpp | 8 +- .../surfaceflinger/tests/LayerCallback_test.cpp | 5 +- .../surfaceflinger/tests/LayerTransactionTest.h | 3 +- .../tests/fakehwc/SFFakeHwc_test.cpp | 3 +- .../tests/unittests/FrameTimelineTest.cpp | 313 ++++++++++++------- .../unittests/TransactionSurfaceFrameTest.cpp | 97 +++--- .../surfaceflinger/tests/utils/ScreenshotUtils.h | 14 +- 32 files changed, 973 insertions(+), 965 deletions(-) delete mode 100644 libs/gui/FrameTimelineInfo.cpp create mode 100644 libs/gui/aidl/android/gui/Color.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayDecorationSupport.aidl create mode 100644 libs/gui/aidl/android/gui/DisplayedFrameStats.aidl create mode 100644 libs/gui/aidl/android/gui/FrameTimelineInfo.aidl create mode 100644 libs/gui/include/gui/AidlStatusUtil.h delete mode 100644 libs/gui/include/gui/FrameTimelineInfo.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index dd7e082487..a3f5a06d3b 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -198,7 +198,6 @@ cc_library_shared { "DebugEGLImageTracker.cpp", "DisplayEventDispatcher.cpp", "DisplayEventReceiver.cpp", - "FrameTimelineInfo.cpp", "GLConsumer.cpp", "IConsumerListener.cpp", "IGraphicBufferConsumer.cpp", diff --git a/libs/gui/FrameTimelineInfo.cpp b/libs/gui/FrameTimelineInfo.cpp deleted file mode 100644 index 3800b88ab0..0000000000 --- a/libs/gui/FrameTimelineInfo.cpp +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright (C) 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#define LOG_TAG "FrameTimelineInfo" - -#include - -#include -#include -#include -#include -#include - -#include - -using android::os::IInputConstants; - -namespace android { - -status_t FrameTimelineInfo::write(Parcel& output) const { - SAFE_PARCEL(output.writeInt64, vsyncId); - SAFE_PARCEL(output.writeInt32, inputEventId); - SAFE_PARCEL(output.writeInt64, startTimeNanos); - return NO_ERROR; -} - -status_t FrameTimelineInfo::read(const Parcel& input) { - SAFE_PARCEL(input.readInt64, &vsyncId); - SAFE_PARCEL(input.readInt32, &inputEventId); - SAFE_PARCEL(input.readInt64, &startTimeNanos); - return NO_ERROR; -} - -void FrameTimelineInfo::merge(const FrameTimelineInfo& other) { - // When merging vsync Ids we take the oldest valid one - if (vsyncId != INVALID_VSYNC_ID && other.vsyncId != INVALID_VSYNC_ID) { - if (other.vsyncId > vsyncId) { - vsyncId = other.vsyncId; - inputEventId = other.inputEventId; - startTimeNanos = other.startTimeNanos; - } - } else if (vsyncId == INVALID_VSYNC_ID) { - vsyncId = other.vsyncId; - inputEventId = other.inputEventId; - startTimeNanos = other.startTimeNanos; - } -} - -void FrameTimelineInfo::clear() { - vsyncId = INVALID_VSYNC_ID; - inputEventId = IInputConstants::INVALID_INPUT_EVENT_ID; - startTimeNanos = 0; -} - -}; // namespace android diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index c3b33cb595..80e512379f 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -80,7 +80,7 @@ public: Parcel data, reply; data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(frameTimelineInfo.write, data); + frameTimelineInfo.writeToParcel(&data); SAFE_PARCEL(data.writeUint32, static_cast(state.size())); for (const auto& s : state) { @@ -124,40 +124,6 @@ public: remote()->transact(BnSurfaceComposer::BOOT_FINISHED, data, &reply); } - bool authenticateSurfaceTexture( - const sp& bufferProducer) const override { - Parcel data, reply; - int err = NO_ERROR; - err = data.writeInterfaceToken( - ISurfaceComposer::getInterfaceDescriptor()); - if (err != NO_ERROR) { - ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error writing " - "interface descriptor: %s (%d)", strerror(-err), -err); - return false; - } - err = data.writeStrongBinder(IInterface::asBinder(bufferProducer)); - if (err != NO_ERROR) { - ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error writing " - "strong binder to parcel: %s (%d)", strerror(-err), -err); - return false; - } - err = remote()->transact(BnSurfaceComposer::AUTHENTICATE_SURFACE, data, - &reply); - if (err != NO_ERROR) { - ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error " - "performing transaction: %s (%d)", strerror(-err), -err); - return false; - } - int32_t result = 0; - err = reply.readInt32(&result); - if (err != NO_ERROR) { - ALOGE("ISurfaceComposer::authenticateSurfaceTexture: error " - "retrieving result: %s (%d)", strerror(-err), -err); - return false; - } - return result != 0; - } - sp createDisplayEventConnection( VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) override { Parcel data, reply; @@ -180,181 +146,6 @@ public: result = interface_cast(reply.readStrongBinder()); return result; } - - status_t getDisplayedContentSample(const sp& display, uint64_t maxFrames, - uint64_t timestamp, - DisplayedFrameStats* outStats) const override { - if (!outStats) return BAD_VALUE; - - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - data.writeStrongBinder(display); - data.writeUint64(maxFrames); - data.writeUint64(timestamp); - - status_t result = - remote()->transact(BnSurfaceComposer::GET_DISPLAYED_CONTENT_SAMPLE, data, &reply); - - if (result != NO_ERROR) { - return result; - } - - result = reply.readUint64(&outStats->numFrames); - if (result != NO_ERROR) { - return result; - } - - result = reply.readUint64Vector(&outStats->component_0_sample); - if (result != NO_ERROR) { - return result; - } - result = reply.readUint64Vector(&outStats->component_1_sample); - if (result != NO_ERROR) { - return result; - } - result = reply.readUint64Vector(&outStats->component_2_sample); - if (result != NO_ERROR) { - return result; - } - result = reply.readUint64Vector(&outStats->component_3_sample); - return result; - } - - status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, - float lightPosY, float lightPosZ, float lightRadius) override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("setGlobalShadowSettings: failed to write interface token: %d", error); - return error; - } - - std::vector shadowConfig = {ambientColor.r, ambientColor.g, ambientColor.b, - ambientColor.a, spotColor.r, spotColor.g, - spotColor.b, spotColor.a, lightPosY, - lightPosZ, lightRadius}; - - error = data.writeFloatVector(shadowConfig); - if (error != NO_ERROR) { - ALOGE("setGlobalShadowSettings: failed to write shadowConfig: %d", error); - return error; - } - - error = remote()->transact(BnSurfaceComposer::SET_GLOBAL_SHADOW_SETTINGS, data, &reply, - IBinder::FLAG_ONEWAY); - if (error != NO_ERROR) { - ALOGE("setGlobalShadowSettings: failed to transact: %d", error); - return error; - } - return NO_ERROR; - } - - status_t getDisplayDecorationSupport( - const sp& displayToken, - std::optional* outSupport) const override { - Parcel data, reply; - status_t error = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to write interface token: %d", error); - return error; - } - error = data.writeStrongBinder(displayToken); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to write display token: %d", error); - return error; - } - error = remote()->transact(BnSurfaceComposer::GET_DISPLAY_DECORATION_SUPPORT, data, &reply); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to transact: %d", error); - return error; - } - bool support; - error = reply.readBool(&support); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to read support: %d", error); - return error; - } - - if (support) { - int32_t format, alphaInterpretation; - error = reply.readInt32(&format); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to read format: %d", error); - return error; - } - error = reply.readInt32(&alphaInterpretation); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport: failed to read alphaInterpretation: %d", error); - return error; - } - outSupport->emplace(); - outSupport->value().format = static_cast(format); - outSupport->value().alphaInterpretation = - static_cast(alphaInterpretation); - } else { - outSupport->reset(); - } - return NO_ERROR; - } - - status_t setFrameRate(const sp& surface, float frameRate, - int8_t compatibility, int8_t changeFrameRateStrategy) override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeStrongBinder, IInterface::asBinder(surface)); - SAFE_PARCEL(data.writeFloat, frameRate); - SAFE_PARCEL(data.writeByte, compatibility); - SAFE_PARCEL(data.writeByte, changeFrameRateStrategy); - - status_t err = remote()->transact(BnSurfaceComposer::SET_FRAME_RATE, data, &reply); - if (err != NO_ERROR) { - ALOGE("setFrameRate: failed to transact: %s (%d)", strerror(-err), err); - return err; - } - - return reply.readInt32(); - } - - status_t setFrameTimelineInfo(const sp& surface, - const FrameTimelineInfo& frameTimelineInfo) override { - Parcel data, reply; - status_t err = data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - if (err != NO_ERROR) { - ALOGE("%s: failed writing interface token: %s (%d)", __func__, strerror(-err), -err); - return err; - } - - err = data.writeStrongBinder(IInterface::asBinder(surface)); - if (err != NO_ERROR) { - ALOGE("%s: failed writing strong binder: %s (%d)", __func__, strerror(-err), -err); - return err; - } - - SAFE_PARCEL(frameTimelineInfo.write, data); - - err = remote()->transact(BnSurfaceComposer::SET_FRAME_TIMELINE_INFO, data, &reply); - if (err != NO_ERROR) { - ALOGE("%s: failed to transact: %s (%d)", __func__, strerror(-err), err); - return err; - } - - return reply.readInt32(); - } - - status_t setOverrideFrameRate(uid_t uid, float frameRate) override { - Parcel data, reply; - SAFE_PARCEL(data.writeInterfaceToken, ISurfaceComposer::getInterfaceDescriptor()); - SAFE_PARCEL(data.writeUint32, uid); - SAFE_PARCEL(data.writeFloat, frameRate); - - status_t err = remote()->transact(BnSurfaceComposer::SET_OVERRIDE_FRAME_RATE, data, &reply); - if (err != NO_ERROR) { - ALOGE("setOverrideFrameRate: failed to transact %s (%d)", strerror(-err), err); - return err; - } - - return NO_ERROR; - } }; // Out-of-line virtual method definition to trigger vtable emission in this @@ -379,7 +170,7 @@ status_t BnSurfaceComposer::onTransact( CHECK_INTERFACE(ISurfaceComposer, data, reply); FrameTimelineInfo frameTimelineInfo; - SAFE_PARCEL(frameTimelineInfo.read, data); + frameTimelineInfo.readFromParcel(&data); uint32_t count = 0; SAFE_PARCEL_READ_SIZE(data.readUint32, &count, data.dataSize()); @@ -444,14 +235,6 @@ status_t BnSurfaceComposer::onTransact( bootFinished(); return NO_ERROR; } - case AUTHENTICATE_SURFACE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp bufferProducer = - interface_cast(data.readStrongBinder()); - int32_t result = authenticateSurfaceTexture(bufferProducer) ? 1 : 0; - reply->writeInt32(result); - return NO_ERROR; - } case CREATE_DISPLAY_EVENT_CONNECTION: { CHECK_INTERFACE(ISurfaceComposer, data, reply); auto vsyncSource = static_cast(data.readInt32()); @@ -463,130 +246,6 @@ status_t BnSurfaceComposer::onTransact( reply->writeStrongBinder(IInterface::asBinder(connection)); return NO_ERROR; } - case GET_DISPLAYED_CONTENT_SAMPLE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - - sp display = data.readStrongBinder(); - uint64_t maxFrames = 0; - uint64_t timestamp = 0; - - status_t result = data.readUint64(&maxFrames); - if (result != NO_ERROR) { - ALOGE("getDisplayedContentSample failure in reading max frames: %d", result); - return result; - } - - result = data.readUint64(×tamp); - if (result != NO_ERROR) { - ALOGE("getDisplayedContentSample failure in reading timestamp: %d", result); - return result; - } - - DisplayedFrameStats stats; - result = getDisplayedContentSample(display, maxFrames, timestamp, &stats); - if (result == NO_ERROR) { - reply->writeUint64(stats.numFrames); - reply->writeUint64Vector(stats.component_0_sample); - reply->writeUint64Vector(stats.component_1_sample); - reply->writeUint64Vector(stats.component_2_sample); - reply->writeUint64Vector(stats.component_3_sample); - } - return result; - } - case SET_GLOBAL_SHADOW_SETTINGS: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - - std::vector shadowConfig; - status_t error = data.readFloatVector(&shadowConfig); - if (error != NO_ERROR || shadowConfig.size() != 11) { - ALOGE("setGlobalShadowSettings: failed to read shadowConfig: %d", error); - return error; - } - - half4 ambientColor = {shadowConfig[0], shadowConfig[1], shadowConfig[2], - shadowConfig[3]}; - half4 spotColor = {shadowConfig[4], shadowConfig[5], shadowConfig[6], shadowConfig[7]}; - float lightPosY = shadowConfig[8]; - float lightPosZ = shadowConfig[9]; - float lightRadius = shadowConfig[10]; - return setGlobalShadowSettings(ambientColor, spotColor, lightPosY, lightPosZ, - lightRadius); - } - case GET_DISPLAY_DECORATION_SUPPORT: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp displayToken; - SAFE_PARCEL(data.readNullableStrongBinder, &displayToken); - std::optional support; - auto error = getDisplayDecorationSupport(displayToken, &support); - if (error != NO_ERROR) { - ALOGE("getDisplayDecorationSupport failed with error %d", error); - return error; - } - reply->writeBool(support.has_value()); - if (support) { - reply->writeInt32(static_cast(support.value().format)); - reply->writeInt32(static_cast(support.value().alphaInterpretation)); - } - return error; - } - case SET_FRAME_RATE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp binder; - SAFE_PARCEL(data.readStrongBinder, &binder); - - sp surface = interface_cast(binder); - if (!surface) { - ALOGE("setFrameRate: failed to cast to IGraphicBufferProducer"); - return BAD_VALUE; - } - float frameRate; - SAFE_PARCEL(data.readFloat, &frameRate); - - int8_t compatibility; - SAFE_PARCEL(data.readByte, &compatibility); - - int8_t changeFrameRateStrategy; - SAFE_PARCEL(data.readByte, &changeFrameRateStrategy); - - status_t result = - setFrameRate(surface, frameRate, compatibility, changeFrameRateStrategy); - reply->writeInt32(result); - return NO_ERROR; - } - case SET_FRAME_TIMELINE_INFO: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp binder; - status_t err = data.readStrongBinder(&binder); - if (err != NO_ERROR) { - ALOGE("setFrameTimelineInfo: failed to read strong binder: %s (%d)", strerror(-err), - -err); - return err; - } - sp surface = interface_cast(binder); - if (!surface) { - ALOGE("setFrameTimelineInfo: failed to cast to IGraphicBufferProducer: %s (%d)", - strerror(-err), -err); - return err; - } - - FrameTimelineInfo frameTimelineInfo; - SAFE_PARCEL(frameTimelineInfo.read, data); - - status_t result = setFrameTimelineInfo(surface, frameTimelineInfo); - reply->writeInt32(result); - return NO_ERROR; - } - case SET_OVERRIDE_FRAME_RATE: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - - uid_t uid; - SAFE_PARCEL(data.readUint32, &uid); - - float frameRate; - SAFE_PARCEL(data.readFloat, &frameRate); - - return setOverrideFrameRate(uid, frameRate); - } default: { return BBinder::onTransact(code, data, reply, flags); } diff --git a/libs/gui/Surface.cpp b/libs/gui/Surface.cpp index a40837ce2a..7a2615f439 100644 --- a/libs/gui/Surface.cpp +++ b/libs/gui/Surface.cpp @@ -39,6 +39,7 @@ #include #include +#include #include #include @@ -49,6 +50,7 @@ namespace android { +using gui::aidl_utils::statusTFromBinderStatus; using ui::Dataspace; namespace { @@ -182,7 +184,7 @@ status_t Surface::getDisplayRefreshCycleDuration(nsecs_t* outRefreshDuration) { gui::DisplayStatInfo stats; binder::Status status = composerServiceAIDL()->getDisplayStats(nullptr, &stats); if (!status.isOk()) { - return status.transactionError(); + return statusTFromBinderStatus(status); } *outRefreshDuration = stats.vsyncPeriod; @@ -355,7 +357,7 @@ status_t Surface::getWideColorSupport(bool* supported) { *supported = false; binder::Status status = composerServiceAIDL()->isWideColorDisplay(display, supported); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t Surface::getHdrSupport(bool* supported) { @@ -369,7 +371,7 @@ status_t Surface::getHdrSupport(bool* supported) { gui::DynamicDisplayInfo info; if (binder::Status status = composerServiceAIDL()->getDynamicDisplayInfo(display, &info); !status.isOk()) { - return status.transactionError(); + return statusTFromBinderStatus(status); } *supported = !info.hdrCapabilities.supportedHdrTypes.empty(); @@ -1288,15 +1290,12 @@ int Surface::query(int what, int* value) const { if (err == NO_ERROR) { return NO_ERROR; } - sp surfaceComposer = composerService(); + sp surfaceComposer = composerServiceAIDL(); if (surfaceComposer == nullptr) { return -EPERM; // likely permissions error } - if (surfaceComposer->authenticateSurfaceTexture(mGraphicBufferProducer)) { - *value = 1; - } else { - *value = 0; - } + // ISurfaceComposer no longer supports authenticateSurfaceTexture + *value = 0; return NO_ERROR; } case NATIVE_WINDOW_CONCRETE_TYPE: @@ -1868,7 +1867,11 @@ int Surface::dispatchSetFrameTimelineInfo(va_list args) { auto startTimeNanos = static_cast(va_arg(args, int64_t)); ALOGV("Surface::%s", __func__); - return setFrameTimelineInfo({frameTimelineVsyncId, inputEventId, startTimeNanos}); + FrameTimelineInfo ftlInfo; + ftlInfo.vsyncId = frameTimelineVsyncId; + ftlInfo.inputEventId = inputEventId; + ftlInfo.startTimeNanos = startTimeNanos; + return setFrameTimelineInfo(ftlInfo); } bool Surface::transformToDisplayInverse() const { @@ -2624,22 +2627,17 @@ void Surface::ProducerListenerProxy::onBuffersDiscarded(const std::vectoronBuffersDiscarded(discardedBufs); } -status_t Surface::setFrameRate(float frameRate, int8_t compatibility, - int8_t changeFrameRateStrategy) { +status_t Surface::setFrameRate(float /*frameRate*/, int8_t /*compatibility*/, + int8_t /*changeFrameRateStrategy*/) { ATRACE_CALL(); ALOGV("Surface::setFrameRate"); - - if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy, - "Surface::setFrameRate")) { - return BAD_VALUE; - } - - return composerService()->setFrameRate(mGraphicBufferProducer, frameRate, compatibility, - changeFrameRateStrategy); + // ISurfaceComposer no longer supports setFrameRate + return BAD_VALUE; } -status_t Surface::setFrameTimelineInfo(const FrameTimelineInfo& frameTimelineInfo) { - return composerService()->setFrameTimelineInfo(mGraphicBufferProducer, frameTimelineInfo); +status_t Surface::setFrameTimelineInfo(const FrameTimelineInfo& /*frameTimelineInfo*/) { + // ISurfaceComposer no longer supports setFrameTimelineInfo + return BAD_VALUE; } sp Surface::getSurfaceControlHandle() const { diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index e54ff49391..065deb6143 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -21,6 +21,7 @@ #include #include +#include #include #include #include @@ -33,6 +34,7 @@ #include +#include #include #include #include @@ -61,6 +63,7 @@ using gui::IRegionSamplingListener; using gui::WindowInfo; using gui::WindowInfoHandle; using gui::WindowInfosListener; +using gui::aidl_utils::statusTFromBinderStatus; using ui::ColorMode; // --------------------------------------------------------------------------- @@ -645,7 +648,7 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel const int64_t desiredPresentTime = parcel->readInt64(); const bool isAutoTimestamp = parcel->readBool(); FrameTimelineInfo frameTimelineInfo; - SAFE_PARCEL(frameTimelineInfo.read, *parcel); + frameTimelineInfo.readFromParcel(parcel); sp applyToken; parcel->readNullableStrongBinder(&applyToken); @@ -752,7 +755,7 @@ status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const parcel->writeBool(mContainsBuffer); parcel->writeInt64(mDesiredPresentTime); parcel->writeBool(mIsAutoTimestamp); - SAFE_PARCEL(mFrameTimelineInfo.write, *parcel); + mFrameTimelineInfo.writeToParcel(parcel); parcel->writeStrongBinder(mApplyToken); parcel->writeUint32(static_cast(mDisplayStates.size())); for (auto const& displayState : mDisplayStates) { @@ -853,7 +856,7 @@ SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Tr mEarlyWakeupEnd = mEarlyWakeupEnd || other.mEarlyWakeupEnd; mApplyToken = other.mApplyToken; - mFrameTimelineInfo.merge(other.mFrameTimelineInfo); + mergeFrameTimelineInfo(mFrameTimelineInfo, other.mFrameTimelineInfo); other.clear(); return *this; @@ -872,7 +875,7 @@ void SurfaceComposerClient::Transaction::clear() { mEarlyWakeupEnd = false; mDesiredPresentTime = 0; mIsAutoTimestamp = true; - mFrameTimelineInfo.clear(); + clearFrameTimelineInfo(mFrameTimelineInfo); mApplyToken = nullptr; } @@ -1060,7 +1063,7 @@ status_t SurfaceComposerClient::getPrimaryPhysicalDisplayId(PhysicalDisplayId* i if (status.isOk()) { *id = *DisplayId::fromValue(static_cast(displayId)); } - return status.transactionError(); + return statusTFromBinderStatus(status); } std::optional SurfaceComposerClient::getInternalDisplayId() { @@ -1809,7 +1812,7 @@ SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFixed SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::setFrameTimelineInfo( const FrameTimelineInfo& frameTimelineInfo) { - mFrameTimelineInfo.merge(frameTimelineInfo); + mergeFrameTimelineInfo(mFrameTimelineInfo, frameTimelineInfo); return *this; } @@ -1968,6 +1971,31 @@ void SurfaceComposerClient::Transaction::setDisplaySize(const sp& token s.what |= DisplayState::eDisplaySizeChanged; } +// copied from FrameTimelineInfo::merge() +void SurfaceComposerClient::Transaction::mergeFrameTimelineInfo(FrameTimelineInfo& t, + const FrameTimelineInfo& other) { + // When merging vsync Ids we take the oldest valid one + if (t.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID && + other.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) { + if (other.vsyncId > t.vsyncId) { + t.vsyncId = other.vsyncId; + t.inputEventId = other.inputEventId; + t.startTimeNanos = other.startTimeNanos; + } + } else if (t.vsyncId == FrameTimelineInfo::INVALID_VSYNC_ID) { + t.vsyncId = other.vsyncId; + t.inputEventId = other.inputEventId; + t.startTimeNanos = other.startTimeNanos; + } +} + +// copied from FrameTimelineInfo::clear() +void SurfaceComposerClient::Transaction::clearFrameTimelineInfo(FrameTimelineInfo& t) { + t.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID; + t.inputEventId = os::IInputConstants::INVALID_INPUT_EVENT_ID; + t.startTimeNanos = 0; +} + // --------------------------------------------------------------------------- SurfaceComposerClient::SurfaceComposerClient() : mStatus(NO_INIT) {} @@ -2122,13 +2150,13 @@ status_t SurfaceComposerClient::getLayerFrameStats(const sp& token, status_t SurfaceComposerClient::enableVSyncInjections(bool enable) { sp sf(ComposerServiceAIDL::getComposerService()); binder::Status status = sf->enableVSyncInjections(enable); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::injectVSync(nsecs_t when) { sp sf(ComposerServiceAIDL::getComposerService()); binder::Status status = sf->injectVSync(when); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDisplayState(const sp& display, @@ -2142,7 +2170,7 @@ status_t SurfaceComposerClient::getDisplayState(const sp& display, state->layerStackSpaceRect = ui::Size(ds.layerStackSpaceRect.width, ds.layerStackSpaceRect.height); } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getStaticDisplayInfo(const sp& display, @@ -2187,7 +2215,7 @@ status_t SurfaceComposerClient::getStaticDisplayInfo(const sp& display, outInfo->deviceProductInfo = info; } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDynamicDisplayInfo(const sp& display, @@ -2237,7 +2265,7 @@ status_t SurfaceComposerClient::getDynamicDisplayInfo(const sp& display outInfo->gameContentTypeSupported = ginfo.gameContentTypeSupported; outInfo->preferredBootDisplayMode = ginfo.preferredBootDisplayMode; } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getActiveDisplayMode(const sp& display, @@ -2267,7 +2295,7 @@ status_t SurfaceComposerClient::setDesiredDisplayModeSpecs( primaryRefreshRateMin, primaryRefreshRateMax, appRequestRefreshRateMin, appRequestRefreshRateMax); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp& displayToken, @@ -2293,7 +2321,7 @@ status_t SurfaceComposerClient::getDesiredDisplayModeSpecs(const sp& di *outAppRequestRefreshRateMin = specs.appRequestRefreshRateMin; *outAppRequestRefreshRateMax = specs.appRequestRefreshRateMax; } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp& display, @@ -2319,37 +2347,39 @@ status_t SurfaceComposerClient::getDisplayNativePrimaries(const sp& dis outPrimaries.white.Y = primaries.white.Y; outPrimaries.white.Z = primaries.white.Z; } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::setActiveColorMode(const sp& display, ColorMode colorMode) { binder::Status status = ComposerServiceAIDL::getComposerService() ->setActiveColorMode(display, static_cast(colorMode)); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getBootDisplayModeSupport(bool* support) { binder::Status status = ComposerServiceAIDL::getComposerService()->getBootDisplayModeSupport(support); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::setBootDisplayMode(const sp& display, ui::DisplayModeId displayModeId) { binder::Status status = ComposerServiceAIDL::getComposerService() ->setBootDisplayMode(display, static_cast(displayModeId)); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::clearBootDisplayMode(const sp& display) { binder::Status status = ComposerServiceAIDL::getComposerService()->clearBootDisplayMode(display); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::setOverrideFrameRate(uid_t uid, float frameRate) { - return ComposerService::getComposerService()->setOverrideFrameRate(uid, frameRate); + binder::Status status = + ComposerServiceAIDL::getComposerService()->setOverrideFrameRate(uid, frameRate); + return statusTFromBinderStatus(status); } void SurfaceComposerClient::setAutoLowLatencyMode(const sp& display, bool on) { @@ -2377,7 +2407,7 @@ status_t SurfaceComposerClient::getCompositionPreference( *wideColorGamutDataspace = static_cast(pref.wideColorGamutDataspace); *wideColorGamutPixelFormat = static_cast(pref.wideColorGamutPixelFormat); } - return status.transactionError(); + return statusTFromBinderStatus(status); } bool SurfaceComposerClient::getProtectedContentSupport() { @@ -2388,7 +2418,7 @@ bool SurfaceComposerClient::getProtectedContentSupport() { status_t SurfaceComposerClient::clearAnimationFrameStats() { binder::Status status = ComposerServiceAIDL::getComposerService()->clearAnimationFrameStats(); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) { @@ -2410,7 +2440,7 @@ status_t SurfaceComposerClient::getAnimationFrameStats(FrameStats* outStats) { outStats->frameReadyTimesNano.add(t); } } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::overrideHdrTypes(const sp& display, @@ -2423,7 +2453,7 @@ status_t SurfaceComposerClient::overrideHdrTypes(const sp& display, binder::Status status = ComposerServiceAIDL::getComposerService()->overrideHdrTypes(display, hdrTypesVector); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* outData, @@ -2434,7 +2464,7 @@ status_t SurfaceComposerClient::onPullAtom(const int32_t atomId, std::string* ou outData->assign((const char*)pad.data.data(), pad.data.size()); *success = pad.success; } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp& display, @@ -2453,7 +2483,7 @@ status_t SurfaceComposerClient::getDisplayedContentSamplingAttributes(const sp(attrs.dataspace); *outComponentMask = static_cast(attrs.componentMask); } - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const sp& display, @@ -2464,14 +2494,41 @@ status_t SurfaceComposerClient::setDisplayContentSamplingEnabled(const spsetDisplayContentSamplingEnabled(display, enable, static_cast(componentMask), static_cast(maxFrames)); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getDisplayedContentSample(const sp& display, uint64_t maxFrames, uint64_t timestamp, DisplayedFrameStats* outStats) { - return ComposerService::getComposerService()->getDisplayedContentSample(display, maxFrames, - timestamp, outStats); + if (!outStats) { + return BAD_VALUE; + } + + gui::DisplayedFrameStats stats; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDisplayedContentSample(display, maxFrames, + timestamp, &stats); + if (status.isOk()) { + // convert gui::DisplayedFrameStats to ui::DisplayedFrameStats + outStats->numFrames = static_cast(stats.numFrames); + outStats->component_0_sample.reserve(stats.component_0_sample.size()); + for (const auto& s : stats.component_0_sample) { + outStats->component_0_sample.push_back(static_cast(s)); + } + outStats->component_1_sample.reserve(stats.component_1_sample.size()); + for (const auto& s : stats.component_1_sample) { + outStats->component_1_sample.push_back(static_cast(s)); + } + outStats->component_2_sample.reserve(stats.component_2_sample.size()); + for (const auto& s : stats.component_2_sample) { + outStats->component_2_sample.push_back(static_cast(s)); + } + outStats->component_3_sample.reserve(stats.component_3_sample.size()); + for (const auto& s : stats.component_3_sample) { + outStats->component_3_sample.push_back(static_cast(s)); + } + } + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::isWideColorDisplay(const sp& display, @@ -2479,7 +2536,7 @@ status_t SurfaceComposerClient::isWideColorDisplay(const sp& display, binder::Status status = ComposerServiceAIDL::getComposerService()->isWideColorDisplay(display, outIsWideColorDisplay); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::addRegionSamplingListener( @@ -2494,40 +2551,40 @@ status_t SurfaceComposerClient::addRegionSamplingListener( ComposerServiceAIDL::getComposerService()->addRegionSamplingListener(rect, stopLayerHandle, listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::removeRegionSamplingListener( const sp& listener) { binder::Status status = ComposerServiceAIDL::getComposerService()->removeRegionSamplingListener(listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::addFpsListener(int32_t taskId, const sp& listener) { binder::Status status = ComposerServiceAIDL::getComposerService()->addFpsListener(taskId, listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::removeFpsListener(const sp& listener) { binder::Status status = ComposerServiceAIDL::getComposerService()->removeFpsListener(listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::addTunnelModeEnabledListener( const sp& listener) { binder::Status status = ComposerServiceAIDL::getComposerService()->addTunnelModeEnabledListener(listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::removeTunnelModeEnabledListener( const sp& listener) { binder::Status status = ComposerServiceAIDL::getComposerService()->removeTunnelModeEnabledListener(listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } bool SurfaceComposerClient::getDisplayBrightnessSupport(const sp& displayToken) { @@ -2543,7 +2600,7 @@ status_t SurfaceComposerClient::setDisplayBrightness(const sp& displayT binder::Status status = ComposerServiceAIDL::getComposerService()->setDisplayBrightness(displayToken, brightness); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::addHdrLayerInfoListener( @@ -2551,7 +2608,7 @@ status_t SurfaceComposerClient::addHdrLayerInfoListener( binder::Status status = ComposerServiceAIDL::getComposerService()->addHdrLayerInfoListener(displayToken, listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::removeHdrLayerInfoListener( @@ -2559,26 +2616,48 @@ status_t SurfaceComposerClient::removeHdrLayerInfoListener( binder::Status status = ComposerServiceAIDL::getComposerService()->removeHdrLayerInfoListener(displayToken, listener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::notifyPowerBoost(int32_t boostId) { binder::Status status = ComposerServiceAIDL::getComposerService()->notifyPowerBoost(boostId); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, float lightPosY, float lightPosZ, float lightRadius) { - return ComposerService::getComposerService()->setGlobalShadowSettings(ambientColor, spotColor, - lightPosY, lightPosZ, - lightRadius); + gui::Color ambientColorG, spotColorG; + ambientColorG.r = ambientColor.r; + ambientColorG.g = ambientColor.g; + ambientColorG.b = ambientColor.b; + ambientColorG.a = ambientColor.a; + spotColorG.r = spotColor.r; + spotColorG.g = spotColor.g; + spotColorG.b = spotColor.b; + spotColorG.a = spotColor.a; + binder::Status status = + ComposerServiceAIDL::getComposerService()->setGlobalShadowSettings(ambientColorG, + spotColorG, + lightPosY, lightPosZ, + lightRadius); + return statusTFromBinderStatus(status); } std::optional SurfaceComposerClient::getDisplayDecorationSupport( const sp& displayToken) { + std::optional gsupport; + binder::Status status = + ComposerServiceAIDL::getComposerService()->getDisplayDecorationSupport(displayToken, + &gsupport); std::optional support; - ComposerService::getComposerService()->getDisplayDecorationSupport(displayToken, &support); + if (status.isOk() && gsupport.has_value()) { + support->format = static_cast( + gsupport->format); + support->alphaInterpretation = + static_cast( + gsupport->alphaInterpretation); + } return support; } @@ -2587,7 +2666,7 @@ int SurfaceComposerClient::getGpuContextPriority() { binder::Status status = ComposerServiceAIDL::getComposerService()->getGpuContextPriority(&priority); if (!status.isOk()) { - status_t err = status.transactionError(); + status_t err = statusTFromBinderStatus(status); ALOGE("getGpuContextPriority failed to read data: %s (%d)", strerror(-err), err); return 0; } @@ -2617,7 +2696,7 @@ status_t ScreenshotClient::captureDisplay(const DisplayCaptureArgs& captureArgs, if (s == nullptr) return NO_INIT; binder::Status status = s->captureDisplay(captureArgs, captureListener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t ScreenshotClient::captureDisplay(DisplayId displayId, @@ -2626,7 +2705,7 @@ status_t ScreenshotClient::captureDisplay(DisplayId displayId, if (s == nullptr) return NO_INIT; binder::Status status = s->captureDisplayById(displayId.value, captureListener); - return status.transactionError(); + return statusTFromBinderStatus(status); } status_t ScreenshotClient::captureLayers(const LayerCaptureArgs& captureArgs, @@ -2635,7 +2714,7 @@ status_t ScreenshotClient::captureLayers(const LayerCaptureArgs& captureArgs, if (s == nullptr) return NO_INIT; binder::Status status = s->captureLayers(captureArgs, captureListener); - return status.transactionError(); + return statusTFromBinderStatus(status); } // --------------------------------------------------------------------------------- diff --git a/libs/gui/WindowInfosListenerReporter.cpp b/libs/gui/WindowInfosListenerReporter.cpp index 0ed83f272c..01e865da6a 100644 --- a/libs/gui/WindowInfosListenerReporter.cpp +++ b/libs/gui/WindowInfosListenerReporter.cpp @@ -15,6 +15,7 @@ */ #include +#include #include namespace android { @@ -23,6 +24,7 @@ using gui::DisplayInfo; using gui::IWindowInfosReportedListener; using gui::WindowInfo; using gui::WindowInfosListener; +using gui::aidl_utils::statusTFromBinderStatus; sp WindowInfosListenerReporter::getInstance() { static sp sInstance = new WindowInfosListenerReporter; @@ -38,7 +40,7 @@ status_t WindowInfosListenerReporter::addWindowInfosListener( std::scoped_lock lock(mListenersMutex); if (mWindowInfosListeners.empty()) { binder::Status s = surfaceComposer->addWindowInfosListener(this); - status = s.transactionError(); + status = statusTFromBinderStatus(s); } if (status == OK) { @@ -62,7 +64,7 @@ status_t WindowInfosListenerReporter::removeWindowInfosListener( std::scoped_lock lock(mListenersMutex); if (mWindowInfosListeners.size() == 1) { binder::Status s = surfaceComposer->removeWindowInfosListener(this); - status = s.transactionError(); + status = statusTFromBinderStatus(s); // Clear the last stored state since we're disabling updates and don't want to hold // stale values mLastWindowInfos.clear(); diff --git a/libs/gui/aidl/android/gui/Color.aidl b/libs/gui/aidl/android/gui/Color.aidl new file mode 100644 index 0000000000..12af066562 --- /dev/null +++ b/libs/gui/aidl/android/gui/Color.aidl @@ -0,0 +1,25 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable Color { + float r; + float g; + float b; + float a; +} diff --git a/libs/gui/aidl/android/gui/DisplayDecorationSupport.aidl b/libs/gui/aidl/android/gui/DisplayDecorationSupport.aidl new file mode 100644 index 0000000000..023049657b --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayDecorationSupport.aidl @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2022, The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +// TODO(b/222607970): +// remove this aidl and use android.hardware.graphics.common.DisplayDecorationSupport +/** @hide */ +parcelable DisplayDecorationSupport { + int format; + int alphaInterpretation; +} diff --git a/libs/gui/aidl/android/gui/DisplayedFrameStats.aidl b/libs/gui/aidl/android/gui/DisplayedFrameStats.aidl new file mode 100644 index 0000000000..f4b6dadc49 --- /dev/null +++ b/libs/gui/aidl/android/gui/DisplayedFrameStats.aidl @@ -0,0 +1,40 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable DisplayedFrameStats { + /* The number of frames represented by this sample. */ + long numFrames = 0; + + /* A histogram counting how many times a pixel of a given value was displayed onscreen for + * FORMAT_COMPONENT_0. The buckets of the histogram are evenly weighted, the number of buckets + * is device specific. eg, for RGBA_8888, if sampleComponent0 is {10, 6, 4, 1} this means that + * 10 red pixels were displayed onscreen in range 0x00->0x3F, 6 red pixels + * were displayed onscreen in range 0x40->0x7F, etc. + */ + long[] component_0_sample; + + /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_1. */ + long[] component_1_sample; + + /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_2. */ + long[] component_2_sample; + + /* The same sample definition as sampleComponent0, but for FORMAT_COMPONENT_3. */ + long[] component_3_sample; +} diff --git a/libs/gui/aidl/android/gui/FrameTimelineInfo.aidl b/libs/gui/aidl/android/gui/FrameTimelineInfo.aidl new file mode 100644 index 0000000000..6ffe466f20 --- /dev/null +++ b/libs/gui/aidl/android/gui/FrameTimelineInfo.aidl @@ -0,0 +1,36 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable FrameTimelineInfo { + // Needs to be in sync with android.graphics.FrameInfo.INVALID_VSYNC_ID in java + const long INVALID_VSYNC_ID = -1; + + // The vsync id that was used to start the transaction + long vsyncId = INVALID_VSYNC_ID; + + // The id of the input event that caused this buffer + // Default is android::os::IInputConstants::INVALID_INPUT_EVENT_ID = 0 + // We copy the value of the input event ID instead of including the header, because libgui + // header libraries containing FrameTimelineInfo must be available to vendors, but libinput is + // not directly vendor available. + int inputEventId = 0; + + // The current time in nanoseconds the application started to render the frame. + long startTimeNanos = 0; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 1fed69f88f..6ec6f760ae 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -16,10 +16,13 @@ package android.gui; +import android.gui.Color; import android.gui.CompositionPreference; import android.gui.ContentSamplingAttributes; -import android.gui.DisplayCaptureArgs; import android.gui.DisplayBrightness; +import android.gui.DisplayCaptureArgs; +import android.gui.DisplayDecorationSupport; +import android.gui.DisplayedFrameStats; import android.gui.DisplayModeSpecs; import android.gui.DisplayPrimaries; import android.gui.DisplayState; @@ -226,6 +229,13 @@ interface ISurfaceComposer { */ void setDisplayContentSamplingEnabled(IBinder display, boolean enable, byte componentMask, long maxFrames); + /** + * Returns statistics on the color profile of the last frame displayed for a given display + * + * Requires the ACCESS_SURFACE_FLINGER permission. + */ + DisplayedFrameStats getDisplayedContentSample(IBinder display, long maxFrames, long timestamp); + /** * Gets whether SurfaceFlinger can support protected content in GPU composition. */ @@ -370,6 +380,48 @@ interface ISurfaceComposer { */ oneway void notifyPowerBoost(int boostId); + /* + * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows + * material design guidelines. + * + * ambientColor + * Color to the ambient shadow. The alpha is premultiplied. + * + * spotColor + * Color to the spot shadow. The alpha is premultiplied. The position of the spot shadow + * depends on the light position. + * + * lightPosY/lightPosZ + * Position of the light used to cast the spot shadow. The X value is always the display + * width / 2. + * + * lightRadius + * Radius of the light casting the shadow. + */ + oneway void setGlobalShadowSettings(in Color ambientColor, in Color spotColor, float lightPosY, float lightPosZ, float lightRadius); + + /** + * Gets whether a display supports DISPLAY_DECORATION layers. + * + * displayToken + * The token of the display. + * outSupport + * An output parameter for whether/how the display supports + * DISPLAY_DECORATION layers. + * + * Returns NO_ERROR upon success. Otherwise, + * NAME_NOT_FOUND if the display is invalid, or + * BAD_VALUE if the output parameter is invalid. + */ + @nullable DisplayDecorationSupport getDisplayDecorationSupport(IBinder displayToken); + + /** + * Set the override frame rate for a specified uid by GameManagerService. + * Passing the frame rate and uid to SurfaceFlinger to update the override mapping + * in the scheduler. + */ + void setOverrideFrameRate(int uid, float frameRate); + /** * Adds a TransactionTraceListener to listen for transaction tracing state updates. */ diff --git a/libs/gui/include/gui/AidlStatusUtil.h b/libs/gui/include/gui/AidlStatusUtil.h new file mode 100644 index 0000000000..55be27bf35 --- /dev/null +++ b/libs/gui/include/gui/AidlStatusUtil.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include + +// Extracted from frameworks/av/media/libaudioclient/include/media/AidlConversionUtil.h +namespace android::gui::aidl_utils { + +/** + * Return the equivalent Android status_t from a binder exception code. + * + * Generally one should use statusTFromBinderStatus() instead. + * + * Exception codes can be generated from a remote Java service exception, translate + * them for use on the Native side. + * + * Note: for EX_TRANSACTION_FAILED and EX_SERVICE_SPECIFIC a more detailed error code + * can be found from transactionError() or serviceSpecificErrorCode(). + */ +static inline status_t statusTFromExceptionCode(int32_t exceptionCode) { + using namespace ::android::binder; + switch (exceptionCode) { + case Status::EX_NONE: + return OK; + case Status::EX_SECURITY: // Java SecurityException, rethrows locally in Java + return PERMISSION_DENIED; + case Status::EX_BAD_PARCELABLE: // Java BadParcelableException, rethrows in Java + case Status::EX_ILLEGAL_ARGUMENT: // Java IllegalArgumentException, rethrows in Java + case Status::EX_NULL_POINTER: // Java NullPointerException, rethrows in Java + return BAD_VALUE; + case Status::EX_ILLEGAL_STATE: // Java IllegalStateException, rethrows in Java + case Status::EX_UNSUPPORTED_OPERATION: // Java UnsupportedOperationException, rethrows + return INVALID_OPERATION; + case Status::EX_HAS_REPLY_HEADER: // Native strictmode violation + case Status::EX_PARCELABLE: // Java bootclass loader (not standard exception), rethrows + case Status::EX_NETWORK_MAIN_THREAD: // Java NetworkOnMainThreadException, rethrows + case Status::EX_TRANSACTION_FAILED: // Native - see error code + case Status::EX_SERVICE_SPECIFIC: // Java ServiceSpecificException, + // rethrows in Java with integer error code + return UNKNOWN_ERROR; + } + return UNKNOWN_ERROR; +} + +/** + * Return the equivalent Android status_t from a binder status. + * + * Used to handle errors from a AIDL method declaration + * + * [oneway] void method(type0 param0, ...) + * + * or the following (where return_type is not a status_t) + * + * return_type method(type0 param0, ...) + */ +static inline status_t statusTFromBinderStatus(const ::android::binder::Status &status) { + return status.isOk() ? OK // check OK, + : status.serviceSpecificErrorCode() // service-side error, not standard Java exception + // (fromServiceSpecificError) + ?: status.transactionError() // a native binder transaction error (fromStatusT) + ?: statusTFromExceptionCode(status.exceptionCode()); // a service-side error with a + // standard Java exception (fromExceptionCode) +} + +/** + * Return a binder::Status from native service status. + * + * This is used for methods not returning an explicit status_t, + * where Java callers expect an exception, not an integer return value. + */ +static inline ::android::binder::Status binderStatusFromStatusT( + status_t status, const char *optionalMessage = nullptr) { + const char *const emptyIfNull = optionalMessage == nullptr ? "" : optionalMessage; + // From binder::Status instructions: + // Prefer a generic exception code when possible, then a service specific + // code, and finally a status_t for low level failures or legacy support. + // Exception codes and service specific errors map to nicer exceptions for + // Java clients. + + using namespace ::android::binder; + switch (status) { + case OK: + return Status::ok(); + case PERMISSION_DENIED: // throw SecurityException on Java side + return Status::fromExceptionCode(Status::EX_SECURITY, emptyIfNull); + case BAD_VALUE: // throw IllegalArgumentException on Java side + return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, emptyIfNull); + case INVALID_OPERATION: // throw IllegalStateException on Java side + return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, emptyIfNull); + } + + // A service specific error will not show on status.transactionError() so + // be sure to use statusTFromBinderStatus() for reliable error handling. + + // throw a ServiceSpecificException. + return Status::fromServiceSpecificError(status, emptyIfNull); +} + +} // namespace android::gui::aidl_utils diff --git a/libs/gui/include/gui/FrameTimelineInfo.h b/libs/gui/include/gui/FrameTimelineInfo.h deleted file mode 100644 index 255ce568d2..0000000000 --- a/libs/gui/include/gui/FrameTimelineInfo.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2021 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include - -namespace android { - -struct FrameTimelineInfo { - // Needs to be in sync with android.graphics.FrameInfo.INVALID_VSYNC_ID in java - static constexpr int64_t INVALID_VSYNC_ID = -1; - - // The vsync id that was used to start the transaction - int64_t vsyncId = INVALID_VSYNC_ID; - - // The id of the input event that caused this buffer - // Default is android::os::IInputConstants::INVALID_INPUT_EVENT_ID = 0 - // We copy the value of the input event ID instead of including the header, because libgui - // header libraries containing FrameTimelineInfo must be available to vendors, but libinput is - // not directly vendor available. - int32_t inputEventId = 0; - - // The current time in nanoseconds the application started to render the frame. - int64_t startTimeNanos = 0; - - status_t write(Parcel& output) const; - status_t read(const Parcel& input); - - void merge(const FrameTimelineInfo& other); - void clear(); -}; - -} // namespace android diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 858bd1d55e..8f75d296c4 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -17,6 +17,7 @@ #pragma once #include +#include #include #include #include @@ -28,7 +29,6 @@ #include #include #include -#include #include #include #include @@ -66,6 +66,7 @@ class IGraphicBufferProducer; class ISurfaceComposerClient; class Rect; +using gui::FrameTimelineInfo; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; using gui::IScreenCaptureListener; @@ -148,79 +149,6 @@ public: * Requires ACCESS_SURFACE_FLINGER permission */ virtual void bootFinished() = 0; - - /* verify that an IGraphicBufferProducer was created by SurfaceFlinger. - */ - virtual bool authenticateSurfaceTexture( - const sp& surface) const = 0; - - /* Returns statistics on the color profile of the last frame displayed for a given display - * - * Requires the ACCESS_SURFACE_FLINGER permission. - */ - virtual status_t getDisplayedContentSample(const sp& display, uint64_t maxFrames, - uint64_t timestamp, - DisplayedFrameStats* outStats) const = 0; - - /* - * Sets the global configuration for all the shadows drawn by SurfaceFlinger. Shadow follows - * material design guidelines. - * - * ambientColor - * Color to the ambient shadow. The alpha is premultiplied. - * - * spotColor - * Color to the spot shadow. The alpha is premultiplied. The position of the spot shadow - * depends on the light position. - * - * lightPosY/lightPosZ - * Position of the light used to cast the spot shadow. The X value is always the display - * width / 2. - * - * lightRadius - * Radius of the light casting the shadow. - */ - virtual status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, - float lightPosY, float lightPosZ, - float lightRadius) = 0; - - /* - * Gets whether a display supports DISPLAY_DECORATION layers. - * - * displayToken - * The token of the display. - * outSupport - * An output parameter for whether/how the display supports - * DISPLAY_DECORATION layers. - * - * Returns NO_ERROR upon success. Otherwise, - * NAME_NOT_FOUND if the display is invalid, or - * BAD_VALUE if the output parameter is invalid. - */ - virtual status_t getDisplayDecorationSupport( - const sp& displayToken, - std::optional* - outSupport) const = 0; - - /* - * Sets the intended frame rate for a surface. See ANativeWindow_setFrameRate() for more info. - */ - virtual status_t setFrameRate(const sp& surface, float frameRate, - int8_t compatibility, int8_t changeFrameRateStrategy) = 0; - - /* - * Set the override frame rate for a specified uid by GameManagerService. - * Passing the frame rate and uid to SurfaceFlinger to update the override mapping - * in the scheduler. - */ - virtual status_t setOverrideFrameRate(uid_t uid, float frameRate) = 0; - - /* - * Sets the frame timeline vsync info received from choreographer that corresponds to next - * buffer submitted on that surface. - */ - virtual status_t setFrameTimelineInfo(const sp& surface, - const FrameTimelineInfo& frameTimelineInfo) = 0; }; // ---------------------------------------------------------------------------- @@ -238,7 +166,7 @@ public: DESTROY_DISPLAY, // Deprecated. Autogenerated by .aidl now. GET_PHYSICAL_DISPLAY_TOKEN, // Deprecated. Autogenerated by .aidl now. SET_TRANSACTION_STATE, - AUTHENTICATE_SURFACE, + AUTHENTICATE_SURFACE, // Deprecated. Autogenerated by .aidl now. GET_SUPPORTED_FRAME_TIMESTAMPS, // Deprecated. Autogenerated by .aidl now. GET_DISPLAY_MODES, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. GET_ACTIVE_DISPLAY_MODE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. @@ -278,10 +206,10 @@ public: SET_AUTO_LOW_LATENCY_MODE, // Deprecated. Autogenerated by .aidl now. GET_GAME_CONTENT_TYPE_SUPPORT, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. SET_GAME_CONTENT_TYPE, // Deprecated. Use GET_DYNAMIC_DISPLAY_INFO instead. - SET_FRAME_RATE, + SET_FRAME_RATE, // Deprecated. Autogenerated by .aidl now. // Deprecated. Use DisplayManager.setShouldAlwaysRespectAppRequestedMode(true); ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN, - SET_FRAME_TIMELINE_INFO, + SET_FRAME_TIMELINE_INFO, // Deprecated. Autogenerated by .aidl now. ADD_TRANSACTION_TRACE_LISTENER, // Deprecated. Autogenerated by .aidl now. GET_GPU_CONTEXT_PRIORITY, GET_MAX_ACQUIRED_BUFFER_COUNT, @@ -301,7 +229,7 @@ public: GET_BOOT_DISPLAY_MODE_SUPPORT, // Deprecated. Autogenerated by .aidl now. SET_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. CLEAR_BOOT_DISPLAY_MODE, // Deprecated. Autogenerated by .aidl now. - SET_OVERRIDE_FRAME_RATE, + SET_OVERRIDE_FRAME_RATE, // Deprecated. Autogenerated by .aidl now. // Always append new enum to the end. }; diff --git a/libs/gui/include/gui/Surface.h b/libs/gui/include/gui/Surface.h index ab9ebaa882..267c28fde2 100644 --- a/libs/gui/include/gui/Surface.h +++ b/libs/gui/include/gui/Surface.h @@ -17,8 +17,8 @@ #ifndef ANDROID_GUI_SURFACE_H #define ANDROID_GUI_SURFACE_H +#include #include -#include #include #include #include @@ -41,6 +41,8 @@ class ISurfaceComposer; class ISurfaceComposer; +using gui::FrameTimelineInfo; + /* This is the same as ProducerListener except that onBuffersDiscarded is * called with a vector of graphic buffers instead of buffer slots. */ diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 48b870dd3b..8569a27808 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -397,6 +397,8 @@ public: class Transaction : public Parcelable { private: void releaseBufferIfOverwriting(const layer_state_t& state); + static void mergeFrameTimelineInfo(FrameTimelineInfo& t, const FrameTimelineInfo& other); + static void clearFrameTimelineInfo(FrameTimelineInfo& t); protected: std::unordered_map, ComposerState, IBinderHash> mComposerStates; diff --git a/libs/gui/include/gui/VsyncEventData.h b/libs/gui/include/gui/VsyncEventData.h index 8e99539fe9..dfdae214d2 100644 --- a/libs/gui/include/gui/VsyncEventData.h +++ b/libs/gui/include/gui/VsyncEventData.h @@ -16,7 +16,7 @@ #pragma once -#include +#include #include diff --git a/libs/gui/tests/BLASTBufferQueue_test.cpp b/libs/gui/tests/BLASTBufferQueue_test.cpp index cb7e94c932..3a9b2b8dcd 100644 --- a/libs/gui/tests/BLASTBufferQueue_test.cpp +++ b/libs/gui/tests/BLASTBufferQueue_test.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -301,8 +302,9 @@ protected: const sp captureListener = new SyncScreenCaptureListener(); binder::Status status = sf->captureDisplay(captureArgs, captureListener); - if (status.transactionError() != NO_ERROR) { - return status.transactionError(); + status_t err = gui::aidl_utils::statusTFromBinderStatus(status); + if (err != NO_ERROR) { + return err; } captureResults = captureListener->waitForResults(); return captureResults.result; diff --git a/libs/gui/tests/RegionSampling_test.cpp b/libs/gui/tests/RegionSampling_test.cpp index e6a9d6caaf..b18b544257 100644 --- a/libs/gui/tests/RegionSampling_test.cpp +++ b/libs/gui/tests/RegionSampling_test.cpp @@ -19,6 +19,7 @@ #include #include +#include #include #include #include @@ -27,6 +28,7 @@ #include using namespace std::chrono_literals; +using android::gui::aidl_utils::statusTFromBinderStatus; namespace android::test { @@ -255,7 +257,7 @@ TEST_F(RegionSamplingTest, invalidLayerHandle_doesNotCrash) { binder::Status status = composer->addRegionSamplingListener(sampleArea, IInterface::asBinder(composer), listener); - ASSERT_EQ(NO_ERROR, status.transactionError()); + ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status)); composer->removeRegionSamplingListener(listener); } @@ -349,17 +351,20 @@ TEST_F(RegionSamplingTest, DISABLED_TestIfInvalidInputParameters) { sampleArea.bottom = 200; // Invalid input sampleArea EXPECT_EQ(BAD_VALUE, - composer->addRegionSamplingListener(invalidRect, mTopLayer->getHandle(), listener) - .transactionError()); + statusTFromBinderStatus(composer->addRegionSamplingListener(invalidRect, + mTopLayer->getHandle(), + listener))); listener->reset(); // Invalid input binder EXPECT_EQ(NO_ERROR, - composer->addRegionSamplingListener(sampleArea, NULL, listener).transactionError()); + statusTFromBinderStatus( + composer->addRegionSamplingListener(sampleArea, NULL, listener))); // Invalid input listener EXPECT_EQ(BAD_VALUE, - composer->addRegionSamplingListener(sampleArea, mTopLayer->getHandle(), NULL) - .transactionError()); - EXPECT_EQ(BAD_VALUE, composer->removeRegionSamplingListener(NULL).transactionError()); + statusTFromBinderStatus(composer->addRegionSamplingListener(sampleArea, + mTopLayer->getHandle(), + NULL))); + EXPECT_EQ(BAD_VALUE, statusTFromBinderStatus(composer->removeRegionSamplingListener(NULL))); // remove the listener composer->removeRegionSamplingListener(listener); } diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 1758aba6d4..a9d8436e41 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -212,8 +213,9 @@ protected: const sp captureListener = new SyncScreenCaptureListener(); binder::Status status = sf->captureDisplay(captureArgs, captureListener); - if (status.transactionError() != NO_ERROR) { - return status.transactionError(); + status_t err = gui::aidl_utils::statusTFromBinderStatus(status); + if (err != NO_ERROR) { + return err; } captureResults = captureListener->waitForResults(); return captureResults.result; @@ -709,40 +711,6 @@ public: } void bootFinished() override {} - bool authenticateSurfaceTexture( - const sp& /*surface*/) const override { - return false; - } - - status_t getDisplayedContentSample(const sp& /*display*/, uint64_t /*maxFrames*/, - uint64_t /*timestamp*/, - DisplayedFrameStats* /*outStats*/) const override { - return NO_ERROR; - } - - status_t setGlobalShadowSettings(const half4& /*ambientColor*/, const half4& /*spotColor*/, - float /*lightPosY*/, float /*lightPosZ*/, - float /*lightRadius*/) override { - return NO_ERROR; - } - - status_t getDisplayDecorationSupport( - const sp& /*displayToken*/, - std::optional* /*outSupport*/) const override { - return NO_ERROR; - } - - status_t setFrameRate(const sp& /*surface*/, float /*frameRate*/, - int8_t /*compatibility*/, int8_t /*changeFrameRateStrategy*/) override { - return NO_ERROR; - } - - status_t setFrameTimelineInfo(const sp& /*surface*/, - const FrameTimelineInfo& /*frameTimelineInfo*/) override { - return NO_ERROR; - } - - status_t setOverrideFrameRate(uid_t /*uid*/, float /*frameRate*/) override { return NO_ERROR; } protected: IBinder* onAsBinder() override { return nullptr; } @@ -908,6 +876,12 @@ public: return binder::Status::ok(); } + binder::Status getDisplayedContentSample(const sp& /*display*/, int64_t /*maxFrames*/, + int64_t /*timestamp*/, + gui::DisplayedFrameStats* /*outStats*/) override { + return binder::Status::ok(); + } + binder::Status isWideColorDisplay(const sp& /*token*/, bool* /*outIsWideColorDisplay*/) override { return binder::Status::ok(); @@ -981,6 +955,22 @@ public: binder::Status notifyPowerBoost(int /*boostId*/) override { return binder::Status::ok(); } + binder::Status setGlobalShadowSettings(const gui::Color& /*ambientColor*/, + const gui::Color& /*spotColor*/, float /*lightPosY*/, + float /*lightPosZ*/, float /*lightRadius*/) override { + return binder::Status::ok(); + } + + binder::Status getDisplayDecorationSupport( + const sp& /*displayToken*/, + std::optional* /*outSupport*/) override { + return binder::Status::ok(); + } + + binder::Status setOverrideFrameRate(int32_t /*uid*/, float /*frameRate*/) override { + return binder::Status::ok(); + } + binder::Status addTransactionTraceListener( const sp& /*listener*/) override { return binder::Status::ok(); diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index d8cfeeebd6..df84167dbb 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -56,6 +56,7 @@ #include #include #include +#include #include #include #include @@ -171,6 +172,7 @@ using gui::DisplayInfo; using gui::IDisplayEventConnection; using gui::IWindowInfosListener; using gui::WindowInfo; +using gui::aidl_utils::binderStatusFromStatusT; using ui::ColorMode; using ui::Dataspace; using ui::DisplayPrimaries; @@ -873,17 +875,6 @@ void SurfaceFlinger::startBootAnim() { // ---------------------------------------------------------------------------- -bool SurfaceFlinger::authenticateSurfaceTexture( - const sp& bufferProducer) const { - Mutex::Autolock _l(mStateLock); - return authenticateSurfaceTextureLocked(bufferProducer); -} - -bool SurfaceFlinger::authenticateSurfaceTextureLocked( - const sp& /* bufferProducer */) const { - return false; -} - status_t SurfaceFlinger::getSupportedFrameTimestamps( std::vector* outSupported) const { *outSupported = { @@ -5466,8 +5457,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_HDR_CAPABILITIES: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: case GET_GAME_CONTENT_TYPE_SUPPORT: - case GET_DISPLAYED_CONTENT_SAMPLE: - case SET_GLOBAL_SHADOW_SETTINGS: case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: { // OVERRIDE_HDR_TYPES is used by CTS tests, which acquire the necessary // permission dynamically. Don't use the permission cache for this check. @@ -5485,7 +5474,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // The following calls are currently used by clients that do not // request necessary permissions. However, they do not expose any secret // information, so it is OK to pass them. - case AUTHENTICATE_SURFACE: case GET_ACTIVE_COLOR_MODE: case GET_ACTIVE_DISPLAY_MODE: case GET_DISPLAY_COLOR_MODES: @@ -5493,27 +5481,16 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // Calling setTransactionState is safe, because you need to have been // granted a reference to Client* and Handle* to do anything with it. case SET_TRANSACTION_STATE: - case CREATE_CONNECTION: - // setFrameRate() is deliberately available for apps to call without any - // special permissions. - case SET_FRAME_RATE: - case GET_DISPLAY_DECORATION_SUPPORT: - case SET_FRAME_TIMELINE_INFO: { + case CREATE_CONNECTION: { // This is not sensitive information, so should not require permission control. return OK; } - case SET_OVERRIDE_FRAME_RATE: { - const int uid = IPCThreadState::self()->getCallingUid(); - if (uid == AID_ROOT || uid == AID_SYSTEM) { - return OK; - } - return PERMISSION_DENIED; - } case CREATE_DISPLAY: case DESTROY_DISPLAY: case GET_PRIMARY_PHYSICAL_DISPLAY_ID: case GET_PHYSICAL_DISPLAY_IDS: case GET_PHYSICAL_DISPLAY_TOKEN: + case AUTHENTICATE_SURFACE: case SET_POWER_MODE: case GET_SUPPORTED_FRAME_TIMESTAMPS: case GET_DISPLAY_STATE: @@ -5541,6 +5518,7 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_COMPOSITION_PREFERENCE: case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES: case SET_DISPLAY_CONTENT_SAMPLING_ENABLED: + case GET_DISPLAYED_CONTENT_SAMPLE: case GET_PROTECTED_CONTENT_SUPPORT: case IS_WIDE_COLOR_DISPLAY: case ADD_REGION_SAMPLING_LISTENER: @@ -5558,6 +5536,11 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case ADD_HDR_LAYER_INFO_LISTENER: case REMOVE_HDR_LAYER_INFO_LISTENER: case NOTIFY_POWER_BOOST: + case SET_GLOBAL_SHADOW_SETTINGS: + case GET_DISPLAY_DECORATION_SUPPORT: + case SET_FRAME_RATE: + case SET_OVERRIDE_FRAME_RATE: + case SET_FRAME_TIMELINE_INFO: case ADD_TRANSACTION_TRACE_LISTENER: case GET_GPU_CONTEXT_PRIORITY: case GET_MAX_ACQUIRED_BUFFER_COUNT: @@ -6995,39 +6978,6 @@ const std::unordered_map& SurfaceFlinger::getGenericLayer return genericLayerMetadataKeyMap; } -status_t SurfaceFlinger::setFrameRate(const sp& surface, float frameRate, - int8_t compatibility, int8_t changeFrameRateStrategy) { - if (!ValidateFrameRate(frameRate, compatibility, changeFrameRateStrategy, - "SurfaceFlinger::setFrameRate")) { - return BAD_VALUE; - } - - static_cast(mScheduler->schedule([=] { - Mutex::Autolock lock(mStateLock); - if (authenticateSurfaceTextureLocked(surface)) { - sp layer = (static_cast(surface.get()))->getLayer(); - if (layer == nullptr) { - ALOGE("Attempt to set frame rate on a layer that no longer exists"); - return BAD_VALUE; - } - const auto strategy = - Layer::FrameRate::convertChangeFrameRateStrategy(changeFrameRateStrategy); - if (layer->setFrameRate( - Layer::FrameRate(Fps::fromValue(frameRate), - Layer::FrameRate::convertCompatibility(compatibility), - strategy))) { - setTransactionFlags(eTraversalNeeded); - } - } else { - ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer"); - return BAD_VALUE; - } - return NO_ERROR; - })); - - return NO_ERROR; -} - status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) { PhysicalDisplayId displayId = [&]() { Mutex::Autolock lock(mStateLock); @@ -7039,24 +6989,6 @@ status_t SurfaceFlinger::setOverrideFrameRate(uid_t uid, float frameRate) { return NO_ERROR; } -status_t SurfaceFlinger::setFrameTimelineInfo(const sp& surface, - const FrameTimelineInfo& frameTimelineInfo) { - Mutex::Autolock lock(mStateLock); - if (!authenticateSurfaceTextureLocked(surface)) { - ALOGE("Attempt to set frame timeline info on an unrecognized IGraphicBufferProducer"); - return BAD_VALUE; - } - - sp layer = (static_cast(surface.get()))->getLayer(); - if (layer == nullptr) { - ALOGE("Attempt to set frame timeline info on a layer that no longer exists"); - return BAD_VALUE; - } - - layer->setFrameTimelineInfoForBuffer(frameTimelineInfo); - return NO_ERROR; -} - void SurfaceFlinger::enableRefreshRateOverlay(bool enable) { for (const auto& [ignored, display] : mDisplays) { if (display->isInternal()) { @@ -7262,7 +7194,7 @@ binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName sp* outDisplay) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } String8 displayName8 = String8::format("%s", displayName.c_str()); *outDisplay = mFlinger->createDisplay(displayName8, secure); @@ -7272,7 +7204,7 @@ binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName binder::Status SurfaceComposerAIDL::destroyDisplay(const sp& display) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } mFlinger->destroyDisplay(display); return binder::Status::ok(); @@ -7292,7 +7224,7 @@ binder::Status SurfaceComposerAIDL::getPhysicalDisplayIds(std::vector* binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisplayId) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } PhysicalDisplayId id; @@ -7300,7 +7232,7 @@ binder::Status SurfaceComposerAIDL::getPrimaryPhysicalDisplayId(int64_t* outDisp if (status == NO_ERROR) { *outDisplayId = id.value; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId, @@ -7313,7 +7245,7 @@ binder::Status SurfaceComposerAIDL::getPhysicalDisplayToken(int64_t displayId, binder::Status SurfaceComposerAIDL::setPowerMode(const sp& display, int mode) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } mFlinger->setPowerMode(display, mode); return binder::Status::ok(); @@ -7328,7 +7260,7 @@ binder::Status SurfaceComposerAIDL::getSupportedFrameTimestamps( outSupported->clear(); status = mFlinger->getSupportedFrameTimestamps(outSupported); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDisplayStats(const sp& display, @@ -7339,7 +7271,7 @@ binder::Status SurfaceComposerAIDL::getDisplayStats(const sp& display, outStatInfo->vsyncTime = static_cast(statInfo.vsyncTime); outStatInfo->vsyncPeriod = static_cast(statInfo.vsyncPeriod); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDisplayState(const sp& display, @@ -7352,7 +7284,7 @@ binder::Status SurfaceComposerAIDL::getDisplayState(const sp& display, outState->layerStackSpaceRect.width = state.layerStackSpaceRect.width; outState->layerStackSpaceRect.height = state.layerStackSpaceRect.height; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp& display, @@ -7393,7 +7325,7 @@ binder::Status SurfaceComposerAIDL::getStaticDisplayInfo(const sp& disp outInfo->deviceProductInfo = dinfo; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp& display, @@ -7444,7 +7376,7 @@ binder::Status SurfaceComposerAIDL::getDynamicDisplayInfo(const sp& dis outInfo->gameContentTypeSupported = info.gameContentTypeSupported; outInfo->preferredBootDisplayMode = info.preferredBootDisplayMode; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp& display, @@ -7468,7 +7400,7 @@ binder::Status SurfaceComposerAIDL::getDisplayNativePrimaries(const sp& outPrimaries->white.Y = primaries.white.Y; outPrimaries->white.Z = primaries.white.Z; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp& display, int colorMode) { @@ -7476,7 +7408,7 @@ binder::Status SurfaceComposerAIDL::setActiveColorMode(const sp& displa if (status == OK) { status = mFlinger->setActiveColorMode(display, static_cast(colorMode)); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp& display, @@ -7486,7 +7418,7 @@ binder::Status SurfaceComposerAIDL::setBootDisplayMode(const sp& displa status = mFlinger->setBootDisplayMode(display, static_cast(displayModeId)); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& display) { @@ -7494,7 +7426,7 @@ binder::Status SurfaceComposerAIDL::clearBootDisplayMode(const sp& disp if (status == OK) { status = mFlinger->clearBootDisplayMode(display); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) { @@ -7502,13 +7434,13 @@ binder::Status SurfaceComposerAIDL::getBootDisplayModeSupport(bool* outMode) { if (status == OK) { status = mFlinger->getBootDisplayModeSupport(outMode); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp& display, bool on) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } mFlinger->setAutoLowLatencyMode(display, on); return binder::Status::ok(); @@ -7517,7 +7449,7 @@ binder::Status SurfaceComposerAIDL::setAutoLowLatencyMode(const sp& dis binder::Status SurfaceComposerAIDL::setGameContentType(const sp& display, bool on) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } mFlinger->setGameContentType(display, on); return binder::Status::ok(); @@ -7526,7 +7458,7 @@ binder::Status SurfaceComposerAIDL::setGameContentType(const sp& displa binder::Status SurfaceComposerAIDL::captureDisplay( const DisplayCaptureArgs& args, const sp& captureListener) { status_t status = mFlinger->captureDisplay(args, captureListener); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::captureDisplayById( @@ -7540,13 +7472,13 @@ binder::Status SurfaceComposerAIDL::captureDisplayById( } else { status = PERMISSION_DENIED; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::captureLayers( const LayerCaptureArgs& args, const sp& captureListener) { status_t status = mFlinger->captureLayers(args, captureListener); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() { @@ -7554,13 +7486,13 @@ binder::Status SurfaceComposerAIDL::clearAnimationFrameStats() { if (status == OK) { status = mFlinger->clearAnimationFrameStats(); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outStats) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } FrameStats stats; @@ -7580,7 +7512,7 @@ binder::Status SurfaceComposerAIDL::getAnimationFrameStats(gui::FrameStats* outS outStats->frameReadyTimesNano.push_back(t); } } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp& display, @@ -7589,7 +7521,7 @@ binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp& display, // permission dynamically. Don't use the permission cache for this check. status_t status = checkAccessPermission(false); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } std::vector hdrTypesVector; @@ -7597,7 +7529,7 @@ binder::Status SurfaceComposerAIDL::overrideHdrTypes(const sp& display, hdrTypesVector.push_back(static_cast(i)); } status = mFlinger->overrideHdrTypes(display, hdrTypesVector); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData* outPullData) { @@ -7608,36 +7540,36 @@ binder::Status SurfaceComposerAIDL::onPullAtom(int32_t atomId, gui::PullAtomData } else { status = mFlinger->onPullAtom(atomId, &outPullData->data, &outPullData->success); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::enableVSyncInjections(bool enable) { if (!mFlinger->hasMockHwc()) { - return binder::Status::fromStatusT(PERMISSION_DENIED); + return binderStatusFromStatusT(PERMISSION_DENIED); } status_t status = checkAccessPermission(); if (status == OK) { status = mFlinger->enableVSyncInjections(enable); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::injectVSync(int64_t when) { if (!mFlinger->hasMockHwc()) { - return binder::Status::fromStatusT(PERMISSION_DENIED); + return binderStatusFromStatusT(PERMISSION_DENIED); } status_t status = checkAccessPermission(); if (status == OK) { status = mFlinger->injectVSync(when); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vector* outLayers) { if (!outLayers) { - return binder::Status::fromStatusT(UNEXPECTED_NULL); + return binderStatusFromStatusT(UNEXPECTED_NULL); } IPCThreadState* ipc = IPCThreadState::self(); @@ -7645,15 +7577,15 @@ binder::Status SurfaceComposerAIDL::getLayerDebugInfo(std::vectorgetCallingUid(); if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) { ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid); - return binder::Status::fromStatusT(PERMISSION_DENIED); + return binderStatusFromStatusT(PERMISSION_DENIED); } status_t status = mFlinger->getLayerDebugInfo(outLayers); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getColorManagement(bool* outGetColorManagement) { status_t status = mFlinger->getColorManagement(outGetColorManagement); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPreference* outPref) { @@ -7670,14 +7602,14 @@ binder::Status SurfaceComposerAIDL::getCompositionPreference(gui::CompositionPre outPref->wideColorGamutDataspace = static_cast(wideColorGamutDataspace); outPref->wideColorGamutPixelFormat = static_cast(wideColorGamutPixelFormat); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes( const sp& display, gui::ContentSamplingAttributes* outAttrs) { status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } ui::PixelFormat format; @@ -7690,7 +7622,7 @@ binder::Status SurfaceComposerAIDL::getDisplayedContentSamplingAttributes( outAttrs->dataspace = static_cast(dataspace); outAttrs->componentMask = static_cast(componentMask); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp& display, @@ -7703,18 +7635,56 @@ binder::Status SurfaceComposerAIDL::setDisplayContentSamplingEnabled(const sp(componentMask), static_cast(maxFrames)); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDisplayedContentSample(const sp& display, + int64_t maxFrames, int64_t timestamp, + gui::DisplayedFrameStats* outStats) { + if (!outStats) { + return binderStatusFromStatusT(BAD_VALUE); + } + + status_t status = checkAccessPermission(); + if (status != OK) { + return binderStatusFromStatusT(status); + } + + DisplayedFrameStats stats; + status = mFlinger->getDisplayedContentSample(display, static_cast(maxFrames), + static_cast(timestamp), &stats); + if (status == NO_ERROR) { + // convert from ui::DisplayedFrameStats to gui::DisplayedFrameStats + outStats->numFrames = static_cast(stats.numFrames); + outStats->component_0_sample.reserve(stats.component_0_sample.size()); + for (const auto& s : stats.component_0_sample) { + outStats->component_0_sample.push_back(static_cast(s)); + } + outStats->component_1_sample.reserve(stats.component_1_sample.size()); + for (const auto& s : stats.component_1_sample) { + outStats->component_1_sample.push_back(static_cast(s)); + } + outStats->component_2_sample.reserve(stats.component_2_sample.size()); + for (const auto& s : stats.component_2_sample) { + outStats->component_2_sample.push_back(static_cast(s)); + } + outStats->component_3_sample.reserve(stats.component_3_sample.size()); + for (const auto& s : stats.component_3_sample) { + outStats->component_3_sample.push_back(static_cast(s)); + } + } + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getProtectedContentSupport(bool* outSupported) { status_t status = mFlinger->getProtectedContentSupport(outSupported); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) { status_t status = mFlinger->isWideColorDisplay(token, outIsWideColorDisplay); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addRegionSamplingListener( @@ -7722,7 +7692,7 @@ binder::Status SurfaceComposerAIDL::addRegionSamplingListener( const sp& listener) { status_t status = checkReadFrameBufferPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } android::Rect rect; rect.left = samplingArea.left; @@ -7730,7 +7700,7 @@ binder::Status SurfaceComposerAIDL::addRegionSamplingListener( rect.right = samplingArea.right; rect.bottom = samplingArea.bottom; status = mFlinger->addRegionSamplingListener(rect, stopLayerHandle, listener); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::removeRegionSamplingListener( @@ -7739,7 +7709,7 @@ binder::Status SurfaceComposerAIDL::removeRegionSamplingListener( if (status == OK) { status = mFlinger->removeRegionSamplingListener(listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId, @@ -7748,7 +7718,7 @@ binder::Status SurfaceComposerAIDL::addFpsListener(int32_t taskId, if (status == OK) { status = mFlinger->addFpsListener(taskId, listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::removeFpsListener(const sp& listener) { @@ -7756,7 +7726,7 @@ binder::Status SurfaceComposerAIDL::removeFpsListener(const spremoveFpsListener(listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener( @@ -7765,7 +7735,7 @@ binder::Status SurfaceComposerAIDL::addTunnelModeEnabledListener( if (status == OK) { status = mFlinger->addTunnelModeEnabledListener(listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener( @@ -7774,7 +7744,7 @@ binder::Status SurfaceComposerAIDL::removeTunnelModeEnabledListener( if (status == OK) { status = mFlinger->removeTunnelModeEnabledListener(listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs( @@ -7790,18 +7760,18 @@ binder::Status SurfaceComposerAIDL::setDesiredDisplayModeSpecs( appRequestRefreshRateMin, appRequestRefreshRateMax); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp& displayToken, gui::DisplayModeSpecs* outSpecs) { if (!outSpecs) { - return binder::Status::fromStatusT(BAD_VALUE); + return binderStatusFromStatusT(BAD_VALUE); } status_t status = checkAccessPermission(); if (status != OK) { - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } ui::DisplayModeId displayModeId; @@ -7823,13 +7793,13 @@ binder::Status SurfaceComposerAIDL::getDesiredDisplayModeSpecs(const sp outSpecs->appRequestRefreshRateMax = appRequestRefreshRateMax; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getDisplayBrightnessSupport(const sp& displayToken, bool* outSupport) { status_t status = mFlinger->getDisplayBrightnessSupport(displayToken, outSupport); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp& displayToken, @@ -7838,7 +7808,7 @@ binder::Status SurfaceComposerAIDL::setDisplayBrightness(const sp& disp if (status == OK) { status = mFlinger->setDisplayBrightness(displayToken, brightness); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener( @@ -7847,7 +7817,7 @@ binder::Status SurfaceComposerAIDL::addHdrLayerInfoListener( if (status == OK) { status = mFlinger->addHdrLayerInfoListener(displayToken, listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener( @@ -7856,7 +7826,7 @@ binder::Status SurfaceComposerAIDL::removeHdrLayerInfoListener( if (status == OK) { status = mFlinger->removeHdrLayerInfoListener(displayToken, listener); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) { @@ -7864,7 +7834,56 @@ binder::Status SurfaceComposerAIDL::notifyPowerBoost(int boostId) { if (status == OK) { status = mFlinger->notifyPowerBoost(boostId); } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::setGlobalShadowSettings(const gui::Color& ambientColor, + const gui::Color& spotColor, + float lightPosY, float lightPosZ, + float lightRadius) { + status_t status = checkAccessPermission(); + if (status != OK) { + return binderStatusFromStatusT(status); + } + + half4 ambientColorHalf = {ambientColor.r, ambientColor.g, ambientColor.b, ambientColor.a}; + half4 spotColorHalf = {spotColor.r, spotColor.g, spotColor.b, spotColor.a}; + status = mFlinger->setGlobalShadowSettings(ambientColorHalf, spotColorHalf, lightPosY, + lightPosZ, lightRadius); + return binderStatusFromStatusT(status); +} + +binder::Status SurfaceComposerAIDL::getDisplayDecorationSupport( + const sp& displayToken, std::optional* outSupport) { + std::optional support; + status_t status = mFlinger->getDisplayDecorationSupport(displayToken, &support); + if (status != NO_ERROR) { + ALOGE("getDisplayDecorationSupport failed with error %d", status); + return binderStatusFromStatusT(status); + } + + if (!support || !support.has_value()) { + outSupport->reset(); + } else { + outSupport->emplace(); + outSupport->value().format = static_cast(support->format); + outSupport->value().alphaInterpretation = + static_cast(support->alphaInterpretation); + } + + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float frameRate) { + status_t status; + const int c_uid = IPCThreadState::self()->getCallingUid(); + if (c_uid == AID_ROOT || c_uid == AID_SYSTEM) { + status = mFlinger->setOverrideFrameRate(uid, frameRate); + } else { + ALOGE("setOverrideFrameRate() permission denied for uid: %d", c_uid); + status = PERMISSION_DENIED; + } + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addTransactionTraceListener( @@ -7877,7 +7896,7 @@ binder::Status SurfaceComposerAIDL::addTransactionTraceListener( } else { status = PERMISSION_DENIED; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) { @@ -7887,7 +7906,7 @@ binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) binder::Status SurfaceComposerAIDL::getMaxAcquiredBufferCount(int32_t* buffers) { status_t status = mFlinger->getMaxAcquiredBufferCount(buffers); - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::addWindowInfosListener( @@ -7899,7 +7918,7 @@ binder::Status SurfaceComposerAIDL::addWindowInfosListener( } else { status = PERMISSION_DENIED; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } binder::Status SurfaceComposerAIDL::removeWindowInfosListener( @@ -7911,7 +7930,7 @@ binder::Status SurfaceComposerAIDL::removeWindowInfosListener( } else { status = PERMISSION_DENIED; } - return binder::Status::fromStatusT(status); + return binderStatusFromStatusT(status); } status_t SurfaceComposerAIDL::checkAccessPermission(bool usePermissionCache) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index fc33ade0a2..0d6ac4eb35 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -311,9 +311,6 @@ public: renderengine::RenderEngine& getRenderEngine() const; - bool authenticateSurfaceTextureLocked( - const sp& bufferProducer) const; - void onLayerFirstRef(Layer*); void onLayerDestroyed(Layer*); void onLayerUpdate(); @@ -559,8 +556,6 @@ private: const std::vector& listenerCallbacks, uint64_t transactionId) override; void bootFinished() override; - bool authenticateSurfaceTexture( - const sp& bufferProducer) const override; virtual status_t getSupportedFrameTimestamps(std::vector* outSupported) const; sp createDisplayEventConnection( ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp, @@ -635,18 +630,18 @@ private: const sp& listener); status_t notifyPowerBoost(int32_t boostId); status_t setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor, - float lightPosY, float lightPosZ, float lightRadius) override; + float lightPosY, float lightPosZ, float lightRadius); status_t getDisplayDecorationSupport( const sp& displayToken, std::optional* - outSupport) const override; + outSupport) const; status_t setFrameRate(const sp& surface, float frameRate, - int8_t compatibility, int8_t changeFrameRateStrategy) override; + int8_t compatibility, int8_t changeFrameRateStrategy); status_t setFrameTimelineInfo(const sp& surface, - const FrameTimelineInfo& frameTimelineInfo) override; + const gui::FrameTimelineInfo& frameTimelineInfo); - status_t setOverrideFrameRate(uid_t uid, float frameRate) override; + status_t setOverrideFrameRate(uid_t uid, float frameRate); status_t addTransactionTraceListener(const sp& listener); @@ -1495,6 +1490,9 @@ public: binder::Status setDisplayContentSamplingEnabled(const sp& display, bool enable, int8_t componentMask, int64_t maxFrames) override; + binder::Status getDisplayedContentSample(const sp& display, int64_t maxFrames, + int64_t timestamp, + gui::DisplayedFrameStats* outStats) override; binder::Status getProtectedContentSupport(bool* outSupporte) override; binder::Status isWideColorDisplay(const sp& token, bool* outIsWideColorDisplay) override; @@ -1526,6 +1524,13 @@ public: const sp& displayToken, const sp& listener) override; binder::Status notifyPowerBoost(int boostId) override; + binder::Status setGlobalShadowSettings(const gui::Color& ambientColor, + const gui::Color& spotColor, float lightPosY, + float lightPosZ, float lightRadius) override; + binder::Status getDisplayDecorationSupport( + const sp& displayToken, + std::optional* outSupport) override; + binder::Status setOverrideFrameRate(int32_t uid, float frameRate) override; binder::Status addTransactionTraceListener( const sp& listener) override; binder::Status getGpuContextPriority(int32_t* outPriority) override; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index e90753ab3f..2a4d6ed86f 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -588,7 +588,6 @@ public: sp display = fuzzBoot(&mFdp); sp bufferProducer = sp::make(); - mFlinger->authenticateSurfaceTexture(bufferProducer.get()); mFlinger->createDisplayEventConnection(); diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp index 46d52dd221..685b44af6b 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_layer_fuzzer.cpp @@ -58,8 +58,10 @@ Rect LayerFuzzer::getFuzzedRect() { } FrameTimelineInfo LayerFuzzer::getFuzzedFrameTimelineInfo() { - return FrameTimelineInfo{.vsyncId = mFdp.ConsumeIntegral(), - .inputEventId = mFdp.ConsumeIntegral()}; + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = mFdp.ConsumeIntegral(); + ftInfo.inputEventId = mFdp.ConsumeIntegral(); + return ftInfo; } LayerCreationArgs LayerFuzzer::createLayerCreationArgs(TestableSurfaceFlinger* flinger, diff --git a/services/surfaceflinger/tests/BootDisplayMode_test.cpp b/services/surfaceflinger/tests/BootDisplayMode_test.cpp index 4cd6ef8f1d..432e227cae 100644 --- a/services/surfaceflinger/tests/BootDisplayMode_test.cpp +++ b/services/surfaceflinger/tests/BootDisplayMode_test.cpp @@ -18,6 +18,7 @@ #include +#include #include #include #include @@ -25,15 +26,17 @@ namespace android { +using gui::aidl_utils::statusTFromBinderStatus; + TEST(BootDisplayModeTest, setBootDisplayMode) { sp sf(ComposerServiceAIDL::getComposerService()); auto displayToken = SurfaceComposerClient::getInternalDisplayToken(); bool bootModeSupport = false; binder::Status status = sf->getBootDisplayModeSupport(&bootModeSupport); - ASSERT_NO_FATAL_FAILURE(status.transactionError()); + ASSERT_NO_FATAL_FAILURE(statusTFromBinderStatus(status)); if (bootModeSupport) { status = sf->setBootDisplayMode(displayToken, 0); - ASSERT_EQ(NO_ERROR, status.transactionError()); + ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status)); } } @@ -42,10 +45,10 @@ TEST(BootDisplayModeTest, clearBootDisplayMode) { auto displayToken = SurfaceComposerClient::getInternalDisplayToken(); bool bootModeSupport = false; binder::Status status = sf->getBootDisplayModeSupport(&bootModeSupport); - ASSERT_NO_FATAL_FAILURE(status.transactionError()); + ASSERT_NO_FATAL_FAILURE(statusTFromBinderStatus(status)); if (bootModeSupport) { status = sf->clearBootDisplayMode(displayToken); - ASSERT_EQ(NO_ERROR, status.transactionError()); + ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status)); } } diff --git a/services/surfaceflinger/tests/Credentials_test.cpp b/services/surfaceflinger/tests/Credentials_test.cpp index 6549a224e6..8a443b823d 100644 --- a/services/surfaceflinger/tests/Credentials_test.cpp +++ b/services/surfaceflinger/tests/Credentials_test.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,7 @@ namespace android { using Transaction = SurfaceComposerClient::Transaction; using gui::LayerDebugInfo; +using gui::aidl_utils::statusTFromBinderStatus; using ui::ColorMode; namespace { @@ -316,18 +318,18 @@ TEST_F(CredentialsTest, GetLayerDebugInfo) { // Check with root. seteuid(AID_ROOT); binder::Status status = sf->getLayerDebugInfo(&outLayers); - ASSERT_EQ(NO_ERROR, status.transactionError()); + ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status)); // Check as a shell. seteuid(AID_SHELL); status = sf->getLayerDebugInfo(&outLayers); - ASSERT_EQ(NO_ERROR, status.transactionError()); + ASSERT_EQ(NO_ERROR, statusTFromBinderStatus(status)); // Check as anyone else. seteuid(AID_ROOT); seteuid(AID_BIN); status = sf->getLayerDebugInfo(&outLayers); - ASSERT_EQ(PERMISSION_DENIED, status.transactionError()); + ASSERT_EQ(PERMISSION_DENIED, statusTFromBinderStatus(status)); } TEST_F(CredentialsTest, IsWideColorDisplayBasicCorrectness) { diff --git a/services/surfaceflinger/tests/LayerCallback_test.cpp b/services/surfaceflinger/tests/LayerCallback_test.cpp index 8a2305b365..9c0c788a6d 100644 --- a/services/surfaceflinger/tests/LayerCallback_test.cpp +++ b/services/surfaceflinger/tests/LayerCallback_test.cpp @@ -1040,7 +1040,10 @@ TEST_F(LayerCallbackTest, ExpectedPresentTime) { } const Vsync vsync = waitForNextVsync(); - transaction.setFrameTimelineInfo({vsync.vsyncId, 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = vsync.vsyncId; + ftInfo.inputEventId = 0; + transaction.setFrameTimelineInfo(ftInfo); transaction.apply(); ExpectedResult expected; diff --git a/services/surfaceflinger/tests/LayerTransactionTest.h b/services/surfaceflinger/tests/LayerTransactionTest.h index 43386b2ae7..b46db65f84 100644 --- a/services/surfaceflinger/tests/LayerTransactionTest.h +++ b/services/surfaceflinger/tests/LayerTransactionTest.h @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -47,7 +48,7 @@ protected: sp sf(ComposerServiceAIDL::getComposerService()); binder::Status status = sf->getColorManagement(&mColorManagementUsed); - ASSERT_NO_FATAL_FAILURE(status.transactionError()); + ASSERT_NO_FATAL_FAILURE(gui::aidl_utils::statusTFromBinderStatus(status)); mCaptureArgs.displayToken = mDisplay; } diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp index 12e5d46a79..67df8b8d61 100644 --- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp +++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp @@ -29,6 +29,7 @@ #include "MockComposerHal.h" #include +#include #include #include #include @@ -1242,7 +1243,7 @@ protected: sp sf(ComposerServiceAIDL::getComposerService()); std::vector layers; binder::Status status = sf->getLayerDebugInfo(&layers); - status_t result = status.transactionError(); + status_t result = gui::aidl_utils::statusTFromBinderStatus(status); if (result != NO_ERROR) { ALOGE("Failed to get layers %s %d", strerror(-result), result); } else { diff --git a/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp b/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp index f1efa9286d..bc379f2fb5 100644 --- a/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp +++ b/services/surfaceflinger/tests/unittests/FrameTimelineTest.cpp @@ -217,9 +217,12 @@ TEST_F(FrameTimelineTest, createSurfaceFrameForToken_noToken) { TEST_F(FrameTimelineTest, createSurfaceFrameForToken_expiredToken) { int64_t token1 = mTokenManager->generateTokenForPredictions({0, 0, 0}); flushTokens(); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({token1, sInputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); EXPECT_EQ(surfaceFrame->getPredictionState(), PredictionState::Expired); @@ -227,9 +230,12 @@ TEST_F(FrameTimelineTest, createSurfaceFrameForToken_expiredToken) { TEST_F(FrameTimelineTest, createSurfaceFrameForToken_validToken) { int64_t token1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({token1, sInputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); EXPECT_EQ(surfaceFrame->getPredictionState(), PredictionState::Valid); @@ -239,9 +245,12 @@ TEST_F(FrameTimelineTest, createSurfaceFrameForToken_validToken) { TEST_F(FrameTimelineTest, createSurfaceFrameForToken_validInputEventId) { int64_t token1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); constexpr int32_t inputEventId = 1; + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = inputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({token1, inputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); EXPECT_EQ(inputEventId, surfaceFrame->getInputEventId()); @@ -250,9 +259,12 @@ TEST_F(FrameTimelineTest, createSurfaceFrameForToken_validInputEventId) { TEST_F(FrameTimelineTest, presentFenceSignaled_droppedFramesNotUpdated) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t token1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({token1, sInputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); // Set up the display frame @@ -278,14 +290,17 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_presentedFramesUpdated) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({22, 26, 30}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdTwo, sLayerNameTwo, - sLayerNameTwo, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdTwo, + sLayerNameTwo, sLayerNameTwo, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 22, Fps::fromPeriodNsecs(11)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); mFrameTimeline->addSurfaceFrame(surfaceFrame1); @@ -324,9 +339,11 @@ TEST_F(FrameTimelineTest, displayFramesSlidingWindowMovesAfterLimit) { {10 + frameTimeFactor, 20 + frameTimeFactor, 30 + frameTimeFactor}); int64_t sfToken = mTokenManager->generateTokenForPredictions( {22 + frameTimeFactor, 26 + frameTimeFactor, 30 + frameTimeFactor}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, sInputEventId}, - sPidOne, sUidOne, sLayerIdOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken, 22 + frameTimeFactor, Fps::fromPeriodNsecs(11)); @@ -347,10 +364,13 @@ TEST_F(FrameTimelineTest, displayFramesSlidingWindowMovesAfterLimit) { {10 + frameTimeFactor, 20 + frameTimeFactor, 30 + frameTimeFactor}); int64_t sfToken = mTokenManager->generateTokenForPredictions( {22 + frameTimeFactor, 26 + frameTimeFactor, 30 + frameTimeFactor}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken, 22 + frameTimeFactor, Fps::fromPeriodNsecs(11)); surfaceFrame->setPresentState(SurfaceFrame::PresentState::Presented); mFrameTimeline->addSurfaceFrame(surfaceFrame); @@ -442,11 +462,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_invalidSignalTime) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); surfaceFrame1->setAcquireFenceTime(20); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -470,11 +493,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_doesNotReportForInvalidTokens) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = -1; int64_t sfToken1 = -1; + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); surfaceFrame1->setAcquireFenceTime(20); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -495,11 +521,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsLongSfCpu) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); surfaceFrame1->setAcquireFenceTime(20); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -521,11 +550,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsLongSfGpu) { auto gpuFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); surfaceFrame1->setAcquireFenceTime(20); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -546,11 +578,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsDisplayMiss) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); surfaceFrame1->setAcquireFenceTime(20); @@ -570,11 +605,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsAppMiss) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({82, 90, 90}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(45); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); @@ -596,11 +634,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsSfScheduling) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({40, 60, 92}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(50); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); @@ -622,11 +663,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsSfPredictionError) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({30, 40, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(40); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); @@ -648,11 +692,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsAppBufferStuffing) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({30, 40, 58}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({82, 90, 90}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(40); mFrameTimeline->setSfWakeUp(sfToken1, 82, refreshRate); @@ -676,11 +723,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_reportsAppMissWithRenderRate) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({82, 90, 90}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(45); mFrameTimeline->setSfWakeUp(sfToken1, 52, refreshRate); @@ -706,11 +756,14 @@ TEST_F(FrameTimelineTest, presentFenceSignaled_displayFramePredictionExpiredPres auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({10, 20, 60}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({82, 90, 90}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(45); // Trigger a prediction expiry flushTokens(); @@ -744,9 +797,12 @@ TEST_F(FrameTimelineTest, tracing_noPacketsSentWithoutTraceStart) { auto tracingSession = getTracingSessionForTest(); auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t token1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({token1, sInputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); // Set up the display frame @@ -771,9 +827,12 @@ TEST_F(FrameTimelineTest, tracing_sanityTest) { tracingSession->StartBlocking(); int64_t token1 = mTokenManager->generateTokenForPredictions({10, 20, 30}); int64_t token2 = mTokenManager->generateTokenForPredictions({40, 50, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = token1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({token1, sInputEventId}, sPidOne, sUidOne, - sLayerIdOne, sLayerNameOne, sLayerNameOne, + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, /*isBuffer*/ true, sGameMode); // Set up the display frame @@ -1133,14 +1192,18 @@ TEST_F(FrameTimelineTest, traceSurfaceFrame_emitsValidTracePacket) { int64_t surfaceFrameToken = mTokenManager->generateTokenForPredictions({10, 25, 40}); int64_t displayFrameToken1 = mTokenManager->generateTokenForPredictions({30, 35, 40}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = sInputEventId; + auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setActualQueueTime(10); surfaceFrame1->setDropTime(15); @@ -1293,10 +1356,13 @@ TEST_F(FrameTimelineTest, traceSurfaceFrame_predictionExpiredIsAppMissedDeadline // Flush the token so that it would expire flushTokens(); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = 0; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, /*inputEventId*/ 0}, - sPidOne, sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setActualQueueTime(appEndTime); surfaceFrame1->setAcquireFenceTime(appEndTime); @@ -1369,10 +1435,13 @@ TEST_F(FrameTimelineTest, traceSurfaceFrame_predictionExpiredDroppedFramesTraced // Flush the token so that it would expire flushTokens(); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = 0; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, /*inputEventId*/ 0}, - sPidOne, sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); constexpr nsecs_t sfStartTime = std::chrono::nanoseconds(22ms).count(); constexpr nsecs_t sfEndTime = std::chrono::nanoseconds(30ms).count(); @@ -1438,10 +1507,13 @@ TEST_F(FrameTimelineTest, jankClassification_presentOnTimeDoesNotClassify) { auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t surfaceFrameToken = mTokenManager->generateTokenForPredictions({10, 20, 30}); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({22, 30, 30}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); mFrameTimeline->setSfWakeUp(sfToken1, 22, Fps::fromPeriodNsecs(11)); surfaceFrame->setPresentState(SurfaceFrame::PresentState::Presented); mFrameTimeline->addSurfaceFrame(surfaceFrame); @@ -1654,10 +1726,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameOnTimeFinishEarlyPresen int64_t sfToken2 = mTokenManager->generateTokenForPredictions({52, 60, 70}); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({5, 16, 40}); int64_t surfaceFrameToken2 = mTokenManager->generateTokenForPredictions({25, 36, 70}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(16); mFrameTimeline->setSfWakeUp(sfToken1, 22, Fps::fromPeriodNsecs(11)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1674,10 +1749,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameOnTimeFinishEarlyPresen // Trigger a flush by finalizing the next DisplayFrame auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = surfaceFrameToken2; + ftInfo2.inputEventId = sInputEventId; auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken2, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo2, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame2->setAcquireFenceTime(36); mFrameTimeline->setSfWakeUp(sfToken2, 52, Fps::fromPeriodNsecs(11)); surfaceFrame2->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1734,10 +1812,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameOnTimeFinishLatePresent int64_t sfToken2 = mTokenManager->generateTokenForPredictions({52, 60, 70}); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({5, 16, 40}); int64_t surfaceFrameToken2 = mTokenManager->generateTokenForPredictions({25, 36, 70}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(16); mFrameTimeline->setSfWakeUp(sfToken1, 22, Fps::fromPeriodNsecs(11)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1754,10 +1835,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameOnTimeFinishLatePresent // Trigger a flush by finalizing the next DisplayFrame auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = surfaceFrameToken2; + ftInfo2.inputEventId = sInputEventId; auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken2, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo2, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame2->setAcquireFenceTime(36); mFrameTimeline->setSfWakeUp(sfToken2, 52, Fps::fromPeriodNsecs(11)); surfaceFrame2->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1813,10 +1897,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameLateFinishEarlyPresent) auto presentFence1 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); int64_t sfToken1 = mTokenManager->generateTokenForPredictions({42, 50, 50}); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({5, 26, 60}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(40); mFrameTimeline->setSfWakeUp(sfToken1, 42, Fps::fromPeriodNsecs(11)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1857,10 +1944,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameLateFinishLatePresent) int64_t sfToken2 = mTokenManager->generateTokenForPredictions({42, 50, 50}); int64_t surfaceFrameToken1 = mTokenManager->generateTokenForPredictions({5, 16, 30}); int64_t surfaceFrameToken2 = mTokenManager->generateTokenForPredictions({25, 36, 50}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(26); mFrameTimeline->setSfWakeUp(sfToken1, 32, Fps::fromPeriodNsecs(11)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1877,10 +1967,13 @@ TEST_F(FrameTimelineTest, jankClassification_surfaceFrameLateFinishLatePresent) // Trigger a flush by finalizing the next DisplayFrame auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = surfaceFrameToken2; + ftInfo2.inputEventId = sInputEventId; auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken2, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo2, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame2->setAcquireFenceTime(40); mFrameTimeline->setSfWakeUp(sfToken2, 43, Fps::fromPeriodNsecs(11)); surfaceFrame2->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1932,10 +2025,13 @@ TEST_F(FrameTimelineTest, jankClassification_multiJankBufferStuffingAndAppDeadli int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); int64_t sfToken2 = mTokenManager->generateTokenForPredictions({112, 120, 120}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(50); mFrameTimeline->setSfWakeUp(sfToken1, 52, Fps::fromPeriodNsecs(30)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -1952,10 +2048,13 @@ TEST_F(FrameTimelineTest, jankClassification_multiJankBufferStuffingAndAppDeadli // Trigger a flush by finalizing the next DisplayFrame auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = surfaceFrameToken2; + ftInfo2.inputEventId = sInputEventId; auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken2, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo2, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame2->setAcquireFenceTime(84); mFrameTimeline->setSfWakeUp(sfToken2, 112, Fps::fromPeriodNsecs(30)); surfaceFrame2->setPresentState(SurfaceFrame::PresentState::Presented, 54); @@ -2010,10 +2109,13 @@ TEST_F(FrameTimelineTest, jankClassification_appDeadlineAdjustedForBufferStuffin int64_t sfToken1 = mTokenManager->generateTokenForPredictions({52, 60, 60}); int64_t sfToken2 = mTokenManager->generateTokenForPredictions({82, 90, 90}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = surfaceFrameToken1; + ftInfo.inputEventId = sInputEventId; auto surfaceFrame1 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken1, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame1->setAcquireFenceTime(50); mFrameTimeline->setSfWakeUp(sfToken1, 52, Fps::fromPeriodNsecs(30)); surfaceFrame1->setPresentState(SurfaceFrame::PresentState::Presented); @@ -2030,10 +2132,13 @@ TEST_F(FrameTimelineTest, jankClassification_appDeadlineAdjustedForBufferStuffin // Trigger a flush by finalizing the next DisplayFrame auto presentFence2 = fenceFactory.createFenceTimeForTest(Fence::NO_FENCE); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = surfaceFrameToken2; + ftInfo2.inputEventId = sInputEventId; auto surfaceFrame2 = - mFrameTimeline->createSurfaceFrameForToken({surfaceFrameToken2, sInputEventId}, sPidOne, - sUidOne, sLayerIdOne, sLayerNameOne, - sLayerNameOne, /*isBuffer*/ true, sGameMode); + mFrameTimeline->createSurfaceFrameForToken(ftInfo2, sPidOne, sUidOne, sLayerIdOne, + sLayerNameOne, sLayerNameOne, + /*isBuffer*/ true, sGameMode); surfaceFrame2->setAcquireFenceTime(80); mFrameTimeline->setSfWakeUp(sfToken2, 82, Fps::fromPeriodNsecs(30)); // Setting previous latch time to 54, adjusted deadline will be 54 + vsyncTime(30) = 84 diff --git a/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp b/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp index 5bb4c92a8e..6d583036fa 100644 --- a/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionSurfaceFrameTest.cpp @@ -100,8 +100,10 @@ public: void PresentedSurfaceFrameForBufferlessTransaction() { sp layer = createBufferStateLayer(); - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 1, /*inputEventId*/ 0}, - 10); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo, 10); EXPECT_EQ(1u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_TRUE(layer->mDrawingState.bufferSurfaceFrameTX == nullptr); const auto surfaceFrame = layer->mDrawingState.bufferlessSurfaceFramesTX.at(/*token*/ 1); @@ -125,8 +127,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, ftInfo); acquireFence->signalForTest(12); commitTransaction(layer.get()); @@ -159,8 +163,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, ftInfo); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto droppedSurfaceFrame = layer->mDrawingState.bufferSurfaceFrameTX; @@ -177,8 +183,7 @@ public: 2ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, ftInfo); nsecs_t end = systemTime(); acquireFence2->signalForTest(12); @@ -204,9 +209,11 @@ public: void BufferlessSurfaceFramePromotedToBufferSurfaceFrame() { sp layer = createBufferStateLayer(); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 1, /*inputEventId*/ 0}, - 10); + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo, 10); EXPECT_EQ(1u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_EQ(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); @@ -223,8 +230,7 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, ftInfo); acquireFence->signalForTest(12); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); @@ -257,28 +263,33 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, ftInfo); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 1, /*inputEventId*/ 0}, - 10); + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo, 10); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); } void MultipleSurfaceFramesPresentedTogether() { sp layer = createBufferStateLayer(); - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 1, /*inputEventId*/ 0}, - 10); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo, 10); EXPECT_EQ(1u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_EQ(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto bufferlessSurfaceFrame1 = layer->mDrawingState.bufferlessSurfaceFramesTX.at(/*token*/ 1); - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 4, /*inputEventId*/ 0}, - 10); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = 4; + ftInfo2.inputEventId = 0; + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo2, 10); EXPECT_EQ(2u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_EQ(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto bufferlessSurfaceFrame2 = layer->mDrawingState.bufferlessSurfaceFramesTX[4]; @@ -295,8 +306,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 3, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo3; + ftInfo3.vsyncId = 3; + ftInfo3.inputEventId = 0; + layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, ftInfo3); EXPECT_EQ(2u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto bufferSurfaceFrameTX = layer->mDrawingState.bufferSurfaceFrameTX; @@ -339,8 +352,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, ftInfo); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto droppedSurfaceFrame = layer->mDrawingState.bufferSurfaceFrameTX; @@ -355,8 +370,7 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, ftInfo); acquireFence2->signalForTest(12); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); @@ -391,8 +405,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture1, bufferData, 10, 20, false, std::nullopt, ftInfo); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); const auto droppedSurfaceFrame1 = layer->mDrawingState.bufferSurfaceFrameTX; @@ -409,8 +425,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ FrameTimelineInfo::INVALID_VSYNC_ID, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfoInv; + ftInfoInv.vsyncId = FrameTimelineInfo::INVALID_VSYNC_ID; + ftInfoInv.inputEventId = 0; + layer->setBuffer(externalTexture2, bufferData, 10, 20, false, std::nullopt, ftInfoInv); auto dropEndTime1 = systemTime(); EXPECT_EQ(0u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); @@ -428,8 +446,10 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture3, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 2, /*inputEventId*/ 0}); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = 2; + ftInfo2.inputEventId = 0; + layer->setBuffer(externalTexture3, bufferData, 10, 20, false, std::nullopt, ftInfo2); auto dropEndTime2 = systemTime(); acquireFence3->signalForTest(12); @@ -476,11 +496,14 @@ public: 1ULL /* bufferId */, HAL_PIXEL_FORMAT_RGBA_8888, 0ULL /*usage*/); - layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, - {/*vsyncId*/ 1, /*inputEventId*/ 0}); - layer->setFrameTimelineVsyncForBufferlessTransaction({/*vsyncId*/ 2, - /*inputEventId*/ 0}, - 10); + FrameTimelineInfo ftInfo; + ftInfo.vsyncId = 1; + ftInfo.inputEventId = 0; + layer->setBuffer(externalTexture, bufferData, 10, 20, false, std::nullopt, ftInfo); + FrameTimelineInfo ftInfo2; + ftInfo2.vsyncId = 2; + ftInfo2.inputEventId = 0; + layer->setFrameTimelineVsyncForBufferlessTransaction(ftInfo2, 10); ASSERT_NE(nullptr, layer->mDrawingState.bufferSurfaceFrameTX); EXPECT_EQ(1u, layer->mDrawingState.bufferlessSurfaceFramesTX.size()); auto& bufferlessSurfaceFrame = diff --git a/services/surfaceflinger/tests/utils/ScreenshotUtils.h b/services/surfaceflinger/tests/utils/ScreenshotUtils.h index ee7e92cbf6..dfd3b91302 100644 --- a/services/surfaceflinger/tests/utils/ScreenshotUtils.h +++ b/services/surfaceflinger/tests/utils/ScreenshotUtils.h @@ -15,6 +15,7 @@ */ #pragma once +#include #include #include #include @@ -24,6 +25,8 @@ namespace android { +using gui::aidl_utils::statusTFromBinderStatus; + namespace { // A ScreenCapture is a screenshot from SurfaceFlinger that can be used to check @@ -38,9 +41,9 @@ public: captureArgs.dataspace = ui::Dataspace::V0_SRGB; const sp captureListener = new SyncScreenCaptureListener(); binder::Status status = sf->captureDisplay(captureArgs, captureListener); - - if (status.transactionError() != NO_ERROR) { - return status.transactionError(); + status_t err = statusTFromBinderStatus(status); + if (err != NO_ERROR) { + return err; } captureResults = captureListener->waitForResults(); return captureResults.result; @@ -71,8 +74,9 @@ public: captureArgs.dataspace = ui::Dataspace::V0_SRGB; const sp captureListener = new SyncScreenCaptureListener(); binder::Status status = sf->captureLayers(captureArgs, captureListener); - if (status.transactionError() != NO_ERROR) { - return status.transactionError(); + status_t err = statusTFromBinderStatus(status); + if (err != NO_ERROR) { + return err; } captureResults = captureListener->waitForResults(); return captureResults.result; -- cgit v1.2.3-59-g8ed1b From d3d8f8e3501a07d55090c287ac45943d687b7006 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 8 Mar 2022 14:48:46 -0800 Subject: Migrate ISurfaceComposerClient to AIDL Migrate and clean up ISurfaceComposerClient to aidl, removed the deprecated createWithParent method, removed non used parameters. Bug: 172002646 Test: atest libgui_test Change-Id: I8ceb7cd90104f2ad9ca72c8025f6298de1fb1ba0 --- libs/binder/include/binder/IInterface.h | 147 ++++++++++----------- libs/gui/Android.bp | 1 - libs/gui/BLASTBufferQueue.cpp | 2 +- libs/gui/ISurfaceComposer.cpp | 17 +-- libs/gui/ISurfaceComposerClient.cpp | 124 ----------------- libs/gui/LayerMetadata.cpp | 4 +- libs/gui/LayerState.cpp | 2 +- libs/gui/SurfaceComposerClient.cpp | 89 ++++++------- libs/gui/SurfaceControl.cpp | 15 +-- libs/gui/aidl/android/gui/CreateSurfaceResult.aidl | 24 ++++ libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 7 + .../aidl/android/gui/ISurfaceComposerClient.aidl | 62 +++++++++ libs/gui/aidl/android/gui/LayerMetadata.aidl | 19 +++ libs/gui/aidl/android/gui/MirrorSurfaceResult.aidl | 23 ++++ libs/gui/include/gui/ISurfaceComposer.h | 9 +- libs/gui/include/gui/ISurfaceComposerClient.h | 97 -------------- libs/gui/include/gui/LayerMetadata.h | 13 +- libs/gui/include/gui/LayerState.h | 4 +- libs/gui/include/gui/SurfaceComposerClient.h | 19 +-- libs/gui/include/gui/SurfaceControl.h | 9 +- libs/gui/tests/Surface_test.cpp | 6 +- services/surfaceflinger/BufferLayer.h | 2 +- services/surfaceflinger/Client.cpp | 96 +++++++++----- services/surfaceflinger/Client.h | 28 ++-- services/surfaceflinger/FpsReporter.cpp | 4 +- services/surfaceflinger/Layer.cpp | 14 +- services/surfaceflinger/Layer.h | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 31 +++-- services/surfaceflinger/SurfaceFlinger.h | 4 +- services/surfaceflinger/TimeStats/TimeStats.h | 2 + .../include/timestatsproto/TimeStatsHelper.h | 3 + .../Tracing/TransactionProtoParser.cpp | 4 +- .../fuzzer/surfaceflinger_fuzzers_utils.h | 2 +- .../include/layerproto/LayerProtoParser.h | 2 + .../surfaceflinger/tests/InvalidHandles_test.cpp | 4 +- .../tests/unittests/FpsReporterTest.cpp | 5 +- .../tests/unittests/GameModeTest.cpp | 4 +- .../tests/unittests/LayerMetadataTest.cpp | 4 +- .../tests/unittests/TransactionProtoParserTest.cpp | 3 +- 39 files changed, 413 insertions(+), 494 deletions(-) delete mode 100644 libs/gui/ISurfaceComposerClient.cpp create mode 100644 libs/gui/aidl/android/gui/CreateSurfaceResult.aidl create mode 100644 libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl create mode 100644 libs/gui/aidl/android/gui/LayerMetadata.aidl create mode 100644 libs/gui/aidl/android/gui/MirrorSurfaceResult.aidl delete mode 100644 libs/gui/include/gui/ISurfaceComposerClient.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/binder/include/binder/IInterface.h b/libs/binder/include/binder/IInterface.h index 706783093c..1576c9427d 100644 --- a/libs/binder/include/binder/IInterface.h +++ b/libs/binder/include/binder/IInterface.h @@ -219,80 +219,79 @@ inline IBinder* BpInterface::onAsBinder() namespace internal { constexpr const char* const kManualInterfaces[] = { - "android.app.IActivityManager", - "android.app.IUidObserver", - "android.drm.IDrm", - "android.dvr.IVsyncCallback", - "android.dvr.IVsyncService", - "android.gfx.tests.ICallback", - "android.gfx.tests.IIPCTest", - "android.gfx.tests.ISafeInterfaceTest", - "android.graphicsenv.IGpuService", - "android.gui.IConsumerListener", - "android.gui.IGraphicBufferConsumer", - "android.gui.ITransactionComposerListener", - "android.gui.SensorEventConnection", - "android.gui.SensorServer", - "android.hardware.ICamera", - "android.hardware.ICameraClient", - "android.hardware.ICameraRecordingProxy", - "android.hardware.ICameraRecordingProxyListener", - "android.hardware.ICrypto", - "android.hardware.IOMXObserver", - "android.hardware.IStreamListener", - "android.hardware.IStreamSource", - "android.media.IAudioService", - "android.media.IDataSource", - "android.media.IDrmClient", - "android.media.IMediaCodecList", - "android.media.IMediaDrmService", - "android.media.IMediaExtractor", - "android.media.IMediaExtractorService", - "android.media.IMediaHTTPConnection", - "android.media.IMediaHTTPService", - "android.media.IMediaLogService", - "android.media.IMediaMetadataRetriever", - "android.media.IMediaMetricsService", - "android.media.IMediaPlayer", - "android.media.IMediaPlayerClient", - "android.media.IMediaPlayerService", - "android.media.IMediaRecorder", - "android.media.IMediaRecorderClient", - "android.media.IMediaResourceMonitor", - "android.media.IMediaSource", - "android.media.IRemoteDisplay", - "android.media.IRemoteDisplayClient", - "android.media.IResourceManagerClient", - "android.media.IResourceManagerService", - "android.os.IComplexTypeInterface", - "android.os.IPermissionController", - "android.os.IPingResponder", - "android.os.IProcessInfoService", - "android.os.ISchedulingPolicyService", - "android.os.IStringConstants", - "android.os.storage.IObbActionListener", - "android.os.storage.IStorageEventListener", - "android.os.storage.IStorageManager", - "android.os.storage.IStorageShutdownObserver", - "android.service.vr.IPersistentVrStateCallbacks", - "android.service.vr.IVrManager", - "android.service.vr.IVrStateCallbacks", - "android.ui.ISurfaceComposer", - "android.ui.ISurfaceComposerClient", - "android.utils.IMemory", - "android.utils.IMemoryHeap", - "com.android.car.procfsinspector.IProcfsInspector", - "com.android.internal.app.IAppOpsCallback", - "com.android.internal.app.IAppOpsService", - "com.android.internal.app.IBatteryStats", - "com.android.internal.os.IResultReceiver", - "com.android.internal.os.IShellCallback", - "drm.IDrmManagerService", - "drm.IDrmServiceListener", - "IAAudioClient", - "IAAudioService", - "VtsFuzzer", - nullptr, + "android.app.IActivityManager", + "android.app.IUidObserver", + "android.drm.IDrm", + "android.dvr.IVsyncCallback", + "android.dvr.IVsyncService", + "android.gfx.tests.ICallback", + "android.gfx.tests.IIPCTest", + "android.gfx.tests.ISafeInterfaceTest", + "android.graphicsenv.IGpuService", + "android.gui.IConsumerListener", + "android.gui.IGraphicBufferConsumer", + "android.gui.ITransactionComposerListener", + "android.gui.SensorEventConnection", + "android.gui.SensorServer", + "android.hardware.ICamera", + "android.hardware.ICameraClient", + "android.hardware.ICameraRecordingProxy", + "android.hardware.ICameraRecordingProxyListener", + "android.hardware.ICrypto", + "android.hardware.IOMXObserver", + "android.hardware.IStreamListener", + "android.hardware.IStreamSource", + "android.media.IAudioService", + "android.media.IDataSource", + "android.media.IDrmClient", + "android.media.IMediaCodecList", + "android.media.IMediaDrmService", + "android.media.IMediaExtractor", + "android.media.IMediaExtractorService", + "android.media.IMediaHTTPConnection", + "android.media.IMediaHTTPService", + "android.media.IMediaLogService", + "android.media.IMediaMetadataRetriever", + "android.media.IMediaMetricsService", + "android.media.IMediaPlayer", + "android.media.IMediaPlayerClient", + "android.media.IMediaPlayerService", + "android.media.IMediaRecorder", + "android.media.IMediaRecorderClient", + "android.media.IMediaResourceMonitor", + "android.media.IMediaSource", + "android.media.IRemoteDisplay", + "android.media.IRemoteDisplayClient", + "android.media.IResourceManagerClient", + "android.media.IResourceManagerService", + "android.os.IComplexTypeInterface", + "android.os.IPermissionController", + "android.os.IPingResponder", + "android.os.IProcessInfoService", + "android.os.ISchedulingPolicyService", + "android.os.IStringConstants", + "android.os.storage.IObbActionListener", + "android.os.storage.IStorageEventListener", + "android.os.storage.IStorageManager", + "android.os.storage.IStorageShutdownObserver", + "android.service.vr.IPersistentVrStateCallbacks", + "android.service.vr.IVrManager", + "android.service.vr.IVrStateCallbacks", + "android.ui.ISurfaceComposer", + "android.utils.IMemory", + "android.utils.IMemoryHeap", + "com.android.car.procfsinspector.IProcfsInspector", + "com.android.internal.app.IAppOpsCallback", + "com.android.internal.app.IAppOpsService", + "com.android.internal.app.IBatteryStats", + "com.android.internal.os.IResultReceiver", + "com.android.internal.os.IShellCallback", + "drm.IDrmManagerService", + "drm.IDrmServiceListener", + "IAAudioClient", + "IAAudioService", + "VtsFuzzer", + nullptr, }; constexpr const char* const kDownstreamManualInterfaces[] = { diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index a3f5a06d3b..648bcc33cb 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -204,7 +204,6 @@ cc_library_shared { "IGraphicBufferProducer.cpp", "IProducerListener.cpp", "ISurfaceComposer.cpp", - "ISurfaceComposerClient.cpp", "ITransactionCompletedListener.cpp", "LayerDebugInfo.cpp", "LayerMetadata.cpp", diff --git a/libs/gui/BLASTBufferQueue.cpp b/libs/gui/BLASTBufferQueue.cpp index bba7387c3a..ccb901c6a7 100644 --- a/libs/gui/BLASTBufferQueue.cpp +++ b/libs/gui/BLASTBufferQueue.cpp @@ -551,7 +551,7 @@ void BLASTBufferQueue::acquireNextBufferLocked( if (dequeueTime != mDequeueTimestamps.end()) { Parcel p; p.writeInt64(dequeueTime->second); - t->setMetadata(mSurfaceControl, METADATA_DEQUEUE_TIME, p); + t->setMetadata(mSurfaceControl, gui::METADATA_DEQUEUE_TIME, p); mDequeueTimestamps.erase(dequeueTime); } } diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 80e512379f..54e50b50ac 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include #include #include @@ -61,14 +60,6 @@ public: virtual ~BpSurfaceComposer(); - virtual sp createConnection() - { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - remote()->transact(BnSurfaceComposer::CREATE_CONNECTION, data, &reply); - return interface_cast(reply.readStrongBinder()); - } - status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, const Vector& state, const Vector& displays, uint32_t flags, @@ -159,13 +150,7 @@ IMPLEMENT_META_INTERFACE(SurfaceComposer, "android.ui.ISurfaceComposer"); status_t BnSurfaceComposer::onTransact( uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) { - switch(code) { - case CREATE_CONNECTION: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - sp b = IInterface::asBinder(createConnection()); - reply->writeStrongBinder(b); - return NO_ERROR; - } + switch (code) { case SET_TRANSACTION_STATE: { CHECK_INTERFACE(ISurfaceComposer, data, reply); diff --git a/libs/gui/ISurfaceComposerClient.cpp b/libs/gui/ISurfaceComposerClient.cpp deleted file mode 100644 index 5e7a7ec67b..0000000000 --- a/libs/gui/ISurfaceComposerClient.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// tag as surfaceflinger -#define LOG_TAG "SurfaceFlinger" - -#include - -#include - -#include - -#include - -namespace android { - -namespace { // Anonymous - -enum class Tag : uint32_t { - CREATE_SURFACE = IBinder::FIRST_CALL_TRANSACTION, - CREATE_WITH_SURFACE_PARENT, - CLEAR_LAYER_FRAME_STATS, - GET_LAYER_FRAME_STATS, - MIRROR_SURFACE, - LAST = MIRROR_SURFACE, -}; - -} // Anonymous namespace - -class BpSurfaceComposerClient : public SafeBpInterface { -public: - explicit BpSurfaceComposerClient(const sp& impl) - : SafeBpInterface(impl, "BpSurfaceComposerClient") {} - - ~BpSurfaceComposerClient() override; - - status_t createSurface(const String8& name, uint32_t width, uint32_t height, PixelFormat format, - uint32_t flags, const sp& parent, LayerMetadata metadata, - sp* handle, sp* gbp, - int32_t* outLayerId, uint32_t* outTransformHint) override { - return callRemote(Tag::CREATE_SURFACE, - name, width, height, - format, flags, parent, - std::move(metadata), - handle, gbp, outLayerId, - outTransformHint); - } - - status_t createWithSurfaceParent(const String8& name, uint32_t width, uint32_t height, - PixelFormat format, uint32_t flags, - const sp& parent, - LayerMetadata metadata, sp* handle, - sp* gbp, int32_t* outLayerId, - uint32_t* outTransformHint) override { - return callRemote(Tag::CREATE_WITH_SURFACE_PARENT, - name, width, height, format, - flags, parent, - std::move(metadata), handle, gbp, - outLayerId, outTransformHint); - } - - status_t clearLayerFrameStats(const sp& handle) const override { - return callRemote(Tag::CLEAR_LAYER_FRAME_STATS, - handle); - } - - status_t getLayerFrameStats(const sp& handle, FrameStats* outStats) const override { - return callRemote(Tag::GET_LAYER_FRAME_STATS, handle, - outStats); - } - - status_t mirrorSurface(const sp& mirrorFromHandle, sp* outHandle, - int32_t* outLayerId) override { - return callRemote(Tag::MIRROR_SURFACE, - mirrorFromHandle, - outHandle, outLayerId); - } -}; - -// Out-of-line virtual method definition to trigger vtable emission in this -// translation unit (see clang warning -Wweak-vtables) -BpSurfaceComposerClient::~BpSurfaceComposerClient() {} - -IMPLEMENT_META_INTERFACE(SurfaceComposerClient, "android.ui.ISurfaceComposerClient"); - -// ---------------------------------------------------------------------- - -status_t BnSurfaceComposerClient::onTransact(uint32_t code, const Parcel& data, Parcel* reply, - uint32_t flags) { - if (code < IBinder::FIRST_CALL_TRANSACTION || code > static_cast(Tag::LAST)) { - return BBinder::onTransact(code, data, reply, flags); - } - auto tag = static_cast(code); - switch (tag) { - case Tag::CREATE_SURFACE: - return callLocal(data, reply, &ISurfaceComposerClient::createSurface); - case Tag::CREATE_WITH_SURFACE_PARENT: - return callLocal(data, reply, &ISurfaceComposerClient::createWithSurfaceParent); - case Tag::CLEAR_LAYER_FRAME_STATS: - return callLocal(data, reply, &ISurfaceComposerClient::clearLayerFrameStats); - case Tag::GET_LAYER_FRAME_STATS: - return callLocal(data, reply, &ISurfaceComposerClient::getLayerFrameStats); - case Tag::MIRROR_SURFACE: - return callLocal(data, reply, &ISurfaceComposerClient::mirrorSurface); - } -} - -} // namespace android diff --git a/libs/gui/LayerMetadata.cpp b/libs/gui/LayerMetadata.cpp index 189d51a4c1..4e12fd330c 100644 --- a/libs/gui/LayerMetadata.cpp +++ b/libs/gui/LayerMetadata.cpp @@ -23,7 +23,7 @@ using android::base::StringPrintf; -namespace android { +namespace android::gui { LayerMetadata::LayerMetadata() = default; @@ -144,4 +144,4 @@ std::string LayerMetadata::itemToString(uint32_t key, const char* separator) con } } -} // namespace android +} // namespace android::gui diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp index 502031c8d8..3ab9e974bc 100644 --- a/libs/gui/LayerState.cpp +++ b/libs/gui/LayerState.cpp @@ -19,10 +19,10 @@ #include #include +#include #include #include #include -#include #include #include #include diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 065deb6143..035aac9530 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -20,6 +20,7 @@ #include #include +#include #include #include #include @@ -39,7 +40,6 @@ #include #include #include -#include #include #include #include @@ -2004,11 +2004,11 @@ SurfaceComposerClient::SurfaceComposerClient(const sp& c : mStatus(NO_ERROR), mClient(client) {} void SurfaceComposerClient::onFirstRef() { - sp sf(ComposerService::getComposerService()); + sp sf(ComposerServiceAIDL::getComposerService()); if (sf != nullptr && mStatus == NO_INIT) { sp conn; - conn = sf->createConnection(); - if (conn != nullptr) { + binder::Status status = sf->createConnection(&conn); + if (status.isOk() && conn != nullptr) { mClient = conn; mStatus = NO_ERROR; } @@ -2046,7 +2046,7 @@ void SurfaceComposerClient::dispose() { } sp SurfaceComposerClient::createSurface(const String8& name, uint32_t w, uint32_t h, - PixelFormat format, uint32_t flags, + PixelFormat format, int32_t flags, const sp& parentHandle, LayerMetadata metadata, uint32_t* outTransformHint) { @@ -2056,38 +2056,9 @@ sp SurfaceComposerClient::createSurface(const String8& name, uin return s; } -sp SurfaceComposerClient::createWithSurfaceParent(const String8& name, uint32_t w, - uint32_t h, PixelFormat format, - uint32_t flags, Surface* parent, - LayerMetadata metadata, - uint32_t* outTransformHint) { - sp sur; - status_t err = mStatus; - - if (mStatus == NO_ERROR) { - sp handle; - sp parentGbp = parent->getIGraphicBufferProducer(); - sp gbp; - - uint32_t transformHint = 0; - int32_t id = -1; - err = mClient->createWithSurfaceParent(name, w, h, format, flags, parentGbp, - std::move(metadata), &handle, &gbp, &id, - &transformHint); - if (outTransformHint) { - *outTransformHint = transformHint; - } - ALOGE_IF(err, "SurfaceComposerClient::createWithSurfaceParent error %s", strerror(-err)); - if (err == NO_ERROR) { - return new SurfaceControl(this, handle, gbp, id, transformHint); - } - } - return nullptr; -} - status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32_t w, uint32_t h, PixelFormat format, - sp* outSurface, uint32_t flags, + sp* outSurface, int32_t flags, const sp& parentHandle, LayerMetadata metadata, uint32_t* outTransformHint) { @@ -2095,21 +2066,17 @@ status_t SurfaceComposerClient::createSurfaceChecked(const String8& name, uint32 status_t err = mStatus; if (mStatus == NO_ERROR) { - sp handle; - sp gbp; - - uint32_t transformHint = 0; - int32_t id = -1; - err = mClient->createSurface(name, w, h, format, flags, parentHandle, std::move(metadata), - &handle, &gbp, &id, &transformHint); - + gui::CreateSurfaceResult result; + binder::Status status = mClient->createSurface(std::string(name.string()), flags, + parentHandle, std::move(metadata), &result); + err = statusTFromBinderStatus(status); if (outTransformHint) { - *outTransformHint = transformHint; + *outTransformHint = result.transformHint; } ALOGE_IF(err, "SurfaceComposerClient::createSurface error %s", strerror(-err)); if (err == NO_ERROR) { - *outSurface = - new SurfaceControl(this, handle, gbp, id, w, h, format, transformHint, flags); + *outSurface = new SurfaceControl(this, result.handle, result.layerId, w, h, format, + result.transformHint, flags); } } return err; @@ -2120,12 +2087,12 @@ sp SurfaceComposerClient::mirrorSurface(SurfaceControl* mirrorFr return nullptr; } - sp handle; sp mirrorFromHandle = mirrorFromSurface->getHandle(); - int32_t layer_id = -1; - status_t err = mClient->mirrorSurface(mirrorFromHandle, &handle, &layer_id); + gui::MirrorSurfaceResult result; + const binder::Status status = mClient->mirrorSurface(mirrorFromHandle, &result); + const status_t err = statusTFromBinderStatus(status); if (err == NO_ERROR) { - return new SurfaceControl(this, handle, nullptr, layer_id, true /* owned */); + return new SurfaceControl(this, result.handle, result.layerId); } return nullptr; } @@ -2134,7 +2101,8 @@ status_t SurfaceComposerClient::clearLayerFrameStats(const sp& token) c if (mStatus != NO_ERROR) { return mStatus; } - return mClient->clearLayerFrameStats(token); + const binder::Status status = mClient->clearLayerFrameStats(token); + return statusTFromBinderStatus(status); } status_t SurfaceComposerClient::getLayerFrameStats(const sp& token, @@ -2142,7 +2110,24 @@ status_t SurfaceComposerClient::getLayerFrameStats(const sp& token, if (mStatus != NO_ERROR) { return mStatus; } - return mClient->getLayerFrameStats(token, outStats); + gui::FrameStats stats; + const binder::Status status = mClient->getLayerFrameStats(token, &stats); + if (status.isOk()) { + outStats->refreshPeriodNano = stats.refreshPeriodNano; + outStats->desiredPresentTimesNano.setCapacity(stats.desiredPresentTimesNano.size()); + for (const auto& t : stats.desiredPresentTimesNano) { + outStats->desiredPresentTimesNano.add(t); + } + outStats->actualPresentTimesNano.setCapacity(stats.actualPresentTimesNano.size()); + for (const auto& t : stats.actualPresentTimesNano) { + outStats->actualPresentTimesNano.add(t); + } + outStats->frameReadyTimesNano.setCapacity(stats.frameReadyTimesNano.size()); + for (const auto& t : stats.frameReadyTimesNano) { + outStats->frameReadyTimesNano.add(t); + } + } + return statusTFromBinderStatus(status); } // ---------------------------------------------------------------------------- diff --git a/libs/gui/SurfaceControl.cpp b/libs/gui/SurfaceControl.cpp index 654fb336fe..84257dee9b 100644 --- a/libs/gui/SurfaceControl.cpp +++ b/libs/gui/SurfaceControl.cpp @@ -49,12 +49,10 @@ namespace android { // ============================================================================ SurfaceControl::SurfaceControl(const sp& client, const sp& handle, - const sp& gbp, int32_t layerId, - uint32_t w, uint32_t h, PixelFormat format, uint32_t transform, - uint32_t flags) + int32_t layerId, uint32_t w, uint32_t h, PixelFormat format, + uint32_t transform, uint32_t flags) : mClient(client), mHandle(handle), - mGraphicBufferProducer(gbp), mLayerId(layerId), mTransformHint(transform), mWidth(w), @@ -65,7 +63,6 @@ SurfaceControl::SurfaceControl(const sp& client, const sp SurfaceControl::SurfaceControl(const sp& other) { mClient = other->mClient; mHandle = other->mHandle; - mGraphicBufferProducer = other->mGraphicBufferProducer; mTransformHint = other->mTransformHint; mLayerId = other->mLayerId; mWidth = other->mWidth; @@ -165,11 +162,11 @@ sp SurfaceControl::createSurface() void SurfaceControl::updateDefaultBufferSize(uint32_t width, uint32_t height) { Mutex::Autolock _l(mLock); - mWidth = width; mHeight = height; + mWidth = width; + mHeight = height; if (mBbq) { mBbq->update(mBbqChild, width, height, mFormat); } - } sp SurfaceControl::getLayerStateHandle() const @@ -245,9 +242,7 @@ status_t SurfaceControl::readFromParcel(const Parcel& parcel, *outSurfaceControl = new SurfaceControl(new SurfaceComposerClient( interface_cast(client)), - handle.get(), nullptr, layerId, - width, height, format, - transformHint); + handle.get(), layerId, width, height, format, transformHint); return NO_ERROR; } diff --git a/libs/gui/aidl/android/gui/CreateSurfaceResult.aidl b/libs/gui/aidl/android/gui/CreateSurfaceResult.aidl new file mode 100644 index 0000000000..39e49167aa --- /dev/null +++ b/libs/gui/aidl/android/gui/CreateSurfaceResult.aidl @@ -0,0 +1,24 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable CreateSurfaceResult { + IBinder handle; + int layerId; + int transformHint; +} diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 6ec6f760ae..26b4e819ee 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -34,6 +34,7 @@ import android.gui.IFpsListener; import android.gui.IHdrLayerInfoListener; import android.gui.IRegionSamplingListener; import android.gui.IScreenCaptureListener; +import android.gui.ISurfaceComposerClient; import android.gui.ITransactionTraceListener; import android.gui.ITunnelModeEnabledListener; import android.gui.IWindowInfosListener; @@ -45,6 +46,12 @@ import android.gui.StaticDisplayInfo; /** @hide */ interface ISurfaceComposer { + + /** + * Create a connection with SurfaceFlinger. + */ + @nullable ISurfaceComposerClient createConnection(); + /** * Create a virtual display * requires ACCESS_SURFACE_FLINGER permission. diff --git a/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl b/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl new file mode 100644 index 0000000000..71933aa6ff --- /dev/null +++ b/libs/gui/aidl/android/gui/ISurfaceComposerClient.aidl @@ -0,0 +1,62 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.CreateSurfaceResult; +import android.gui.FrameStats; +import android.gui.LayerMetadata; +import android.gui.MirrorSurfaceResult; + +/** @hide */ +interface ISurfaceComposerClient { + + // flags for createSurface() + // (keep in sync with SurfaceControl.java) + const int eHidden = 0x00000004; + const int eDestroyBackbuffer = 0x00000020; + const int eSkipScreenshot = 0x00000040; + const int eSecure = 0x00000080; + const int eNonPremultiplied = 0x00000100; + const int eOpaque = 0x00000400; + const int eProtectedByApp = 0x00000800; + const int eProtectedByDRM = 0x00001000; + const int eCursorWindow = 0x00002000; + const int eNoColorFill = 0x00004000; + + const int eFXSurfaceBufferQueue = 0x00000000; + const int eFXSurfaceEffect = 0x00020000; + const int eFXSurfaceBufferState = 0x00040000; + const int eFXSurfaceContainer = 0x00080000; + const int eFXSurfaceMask = 0x000F0000; + + /** + * Requires ACCESS_SURFACE_FLINGER permission + */ + CreateSurfaceResult createSurface(@utf8InCpp String name, int flags, @nullable IBinder parent, in LayerMetadata metadata); + + /** + * Requires ACCESS_SURFACE_FLINGER permission + */ + void clearLayerFrameStats(IBinder handle); + + /** + * Requires ACCESS_SURFACE_FLINGER permission + */ + FrameStats getLayerFrameStats(IBinder handle); + + MirrorSurfaceResult mirrorSurface(IBinder mirrorFromHandle); +} diff --git a/libs/gui/aidl/android/gui/LayerMetadata.aidl b/libs/gui/aidl/android/gui/LayerMetadata.aidl new file mode 100644 index 0000000000..1368ac512f --- /dev/null +++ b/libs/gui/aidl/android/gui/LayerMetadata.aidl @@ -0,0 +1,19 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +parcelable LayerMetadata cpp_header "gui/LayerMetadata.h"; diff --git a/libs/gui/aidl/android/gui/MirrorSurfaceResult.aidl b/libs/gui/aidl/android/gui/MirrorSurfaceResult.aidl new file mode 100644 index 0000000000..9fac3e8644 --- /dev/null +++ b/libs/gui/aidl/android/gui/MirrorSurfaceResult.aidl @@ -0,0 +1,23 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +/** @hide */ +parcelable MirrorSurfaceResult { + IBinder handle; + int layerId; +} diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 8f75d296c4..7139e1bb93 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -62,8 +62,6 @@ struct DisplayStatInfo; struct DisplayState; struct InputWindowCommands; class HdrCapabilities; -class IGraphicBufferProducer; -class ISurfaceComposerClient; class Rect; using gui::FrameTimelineInfo; @@ -127,11 +125,6 @@ public: using EventRegistrationFlags = ftl::Flags; - /* - * Create a connection with SurfaceFlinger. - */ - virtual sp createConnection() = 0; - /* return an IDisplayEventConnection */ virtual sp createDisplayEventConnection( VsyncSource vsyncSource = eVsyncSourceApp, @@ -159,7 +152,7 @@ public: // Note: BOOT_FINISHED must remain this value, it is called from // Java by ActivityManagerService. BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION, - CREATE_CONNECTION, + CREATE_CONNECTION, // Deprecated. Autogenerated by .aidl now. GET_STATIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. CREATE_DISPLAY_EVENT_CONNECTION, CREATE_DISPLAY, // Deprecated. Autogenerated by .aidl now. diff --git a/libs/gui/include/gui/ISurfaceComposerClient.h b/libs/gui/include/gui/ISurfaceComposerClient.h deleted file mode 100644 index 9e9e191480..0000000000 --- a/libs/gui/include/gui/ISurfaceComposerClient.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (C) 2007 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include -#include -#include - -#include - -namespace android { - -class FrameStats; -class IGraphicBufferProducer; - -class ISurfaceComposerClient : public IInterface { -public: - DECLARE_META_INTERFACE(SurfaceComposerClient) - - // flags for createSurface() - enum { // (keep in sync with SurfaceControl.java) - eHidden = 0x00000004, - eDestroyBackbuffer = 0x00000020, - eSkipScreenshot = 0x00000040, - eSecure = 0x00000080, - eNonPremultiplied = 0x00000100, - eOpaque = 0x00000400, - eProtectedByApp = 0x00000800, - eProtectedByDRM = 0x00001000, - eCursorWindow = 0x00002000, - eNoColorFill = 0x00004000, - - eFXSurfaceBufferQueue = 0x00000000, - eFXSurfaceEffect = 0x00020000, - eFXSurfaceBufferState = 0x00040000, - eFXSurfaceContainer = 0x00080000, - eFXSurfaceMask = 0x000F0000, - }; - - // TODO(b/172002646): Clean up the Surface Creation Arguments - /* - * Requires ACCESS_SURFACE_FLINGER permission - */ - virtual status_t createSurface(const String8& name, uint32_t w, uint32_t h, PixelFormat format, - uint32_t flags, const sp& parent, - LayerMetadata metadata, sp* handle, - sp* gbp, int32_t* outLayerId, - uint32_t* outTransformHint) = 0; - - /* - * Requires ACCESS_SURFACE_FLINGER permission - */ - virtual status_t createWithSurfaceParent(const String8& name, uint32_t w, uint32_t h, - PixelFormat format, uint32_t flags, - const sp& parent, - LayerMetadata metadata, sp* handle, - sp* gbp, int32_t* outLayerId, - uint32_t* outTransformHint) = 0; - - /* - * Requires ACCESS_SURFACE_FLINGER permission - */ - virtual status_t clearLayerFrameStats(const sp& handle) const = 0; - - /* - * Requires ACCESS_SURFACE_FLINGER permission - */ - virtual status_t getLayerFrameStats(const sp& handle, FrameStats* outStats) const = 0; - - virtual status_t mirrorSurface(const sp& mirrorFromHandle, sp* outHandle, - int32_t* outLayerId) = 0; -}; - -class BnSurfaceComposerClient : public SafeBnInterface { -public: - BnSurfaceComposerClient() - : SafeBnInterface("BnSurfaceComposerClient") {} - - status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override; -}; - -} // namespace android diff --git a/libs/gui/include/gui/LayerMetadata.h b/libs/gui/include/gui/LayerMetadata.h index 27f4d379e9..5af598956b 100644 --- a/libs/gui/include/gui/LayerMetadata.h +++ b/libs/gui/include/gui/LayerMetadata.h @@ -20,7 +20,7 @@ #include -namespace android { +namespace android::gui { enum { METADATA_OWNER_UID = 1, @@ -69,4 +69,13 @@ enum class GameMode : int32_t { ftl_last = Battery }; -} // namespace android +} // namespace android::gui + +using android::gui::METADATA_ACCESSIBILITY_ID; +using android::gui::METADATA_DEQUEUE_TIME; +using android::gui::METADATA_GAME_MODE; +using android::gui::METADATA_MOUSE_CURSOR; +using android::gui::METADATA_OWNER_PID; +using android::gui::METADATA_OWNER_UID; +using android::gui::METADATA_TASK_ID; +using android::gui::METADATA_WINDOW_TYPE; diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h index 0a9b75a7f1..4cd9a56fcd 100644 --- a/libs/gui/include/gui/LayerState.h +++ b/libs/gui/include/gui/LayerState.h @@ -51,7 +51,9 @@ namespace android { class Parcel; -class ISurfaceComposerClient; + +using gui::ISurfaceComposerClient; +using gui::LayerMetadata; struct client_cache_t { wp token = nullptr; diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 8569a27808..dc9624269b 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -40,6 +40,8 @@ #include #include +#include + #include #include #include @@ -53,14 +55,15 @@ namespace android { class HdrCapabilities; -class ISurfaceComposerClient; class IGraphicBufferProducer; class ITunnelModeEnabledListener; class Region; using gui::DisplayCaptureArgs; using gui::IRegionSamplingListener; +using gui::ISurfaceComposerClient; using gui::LayerCaptureArgs; +using gui::LayerMetadata; struct SurfaceControlStats { SurfaceControlStats(const sp& sc, nsecs_t latchTime, @@ -312,7 +315,7 @@ public: uint32_t w, // width in pixel uint32_t h, // height in pixel PixelFormat format, // pixel-format desired - uint32_t flags = 0, // usage flags + int32_t flags = 0, // usage flags const sp& parentHandle = nullptr, // parentHandle LayerMetadata metadata = LayerMetadata(), // metadata uint32_t* outTransformHint = nullptr); @@ -322,21 +325,11 @@ public: uint32_t h, // height in pixel PixelFormat format, // pixel-format desired sp* outSurface, - uint32_t flags = 0, // usage flags + int32_t flags = 0, // usage flags const sp& parentHandle = nullptr, // parentHandle LayerMetadata metadata = LayerMetadata(), // metadata uint32_t* outTransformHint = nullptr); - //! Create a surface - sp createWithSurfaceParent(const String8& name, // name of the surface - uint32_t w, // width in pixel - uint32_t h, // height in pixel - PixelFormat format, // pixel-format desired - uint32_t flags = 0, // usage flags - Surface* parent = nullptr, // parent - LayerMetadata metadata = LayerMetadata(), // metadata - uint32_t* outTransformHint = nullptr); - // Creates a mirrored hierarchy for the mirrorFromSurface. This returns a SurfaceControl // which is a parent of the root of the mirrored hierarchy. // diff --git a/libs/gui/include/gui/SurfaceControl.h b/libs/gui/include/gui/SurfaceControl.h index b72cf8390e..e4a1350643 100644 --- a/libs/gui/include/gui/SurfaceControl.h +++ b/libs/gui/include/gui/SurfaceControl.h @@ -24,11 +24,12 @@ #include #include +#include + #include #include #include -#include #include namespace android { @@ -93,8 +94,7 @@ public: explicit SurfaceControl(const sp& other); SurfaceControl(const sp& client, const sp& handle, - const sp& gbp, int32_t layerId, - uint32_t width = 0, uint32_t height = 0, PixelFormat format = 0, + int32_t layerId, uint32_t width = 0, uint32_t height = 0, PixelFormat format = 0, uint32_t transformHint = 0, uint32_t flags = 0); sp getParentingLayer(); @@ -115,8 +115,7 @@ private: status_t validate() const; sp mClient; - sp mHandle; - sp mGraphicBufferProducer; + sp mHandle; mutable Mutex mLock; mutable sp mSurfaceData; mutable sp mBbq; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index a9d8436e41..4ab380c8b8 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -692,7 +692,6 @@ public: mSupportsPresent = supportsPresent; } - sp createConnection() override { return nullptr; } sp createDisplayEventConnection( ISurfaceComposer::VsyncSource, ISurfaceComposer::EventRegistrationFlags) override { return nullptr; @@ -725,6 +724,11 @@ public: void setSupportsPresent(bool supportsPresent) { mSupportsPresent = supportsPresent; } + binder::Status createConnection(sp* outClient) override { + *outClient = nullptr; + return binder::Status::ok(); + } + binder::Status createDisplay(const std::string& /*displayName*/, bool /*secure*/, sp* /*outDisplay*/) override { return binder::Status::ok(); diff --git a/services/surfaceflinger/BufferLayer.h b/services/surfaceflinger/BufferLayer.h index 3e70493101..2f3db7428b 100644 --- a/services/surfaceflinger/BufferLayer.h +++ b/services/surfaceflinger/BufferLayer.h @@ -20,7 +20,7 @@ #include #include -#include +#include #include #include #include diff --git a/services/surfaceflinger/Client.cpp b/services/surfaceflinger/Client.cpp index 6d7b732b36..b27055d57a 100644 --- a/services/surfaceflinger/Client.cpp +++ b/services/surfaceflinger/Client.cpp @@ -21,12 +21,16 @@ #include +#include + #include "Client.h" #include "Layer.h" #include "SurfaceFlinger.h" namespace android { +using gui::aidl_utils::binderStatusFromStatusT; + // --------------------------------------------------------------------------- const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"); @@ -72,52 +76,74 @@ sp Client::getLayerUser(const sp& handle) const return lbc; } -status_t Client::createSurface(const String8& name, uint32_t /* w */, uint32_t /* h */, - PixelFormat /* format */, uint32_t flags, - const sp& parentHandle, LayerMetadata metadata, - sp* outHandle, sp* /* gbp */, - int32_t* outLayerId, uint32_t* outTransformHint) { +binder::Status Client::createSurface(const std::string& name, int32_t flags, + const sp& parent, const gui::LayerMetadata& metadata, + gui::CreateSurfaceResult* outResult) { // We rely on createLayer to check permissions. - LayerCreationArgs args(mFlinger.get(), this, name.c_str(), flags, std::move(metadata)); - return mFlinger->createLayer(args, outHandle, parentHandle, outLayerId, nullptr, - outTransformHint); -} - -status_t Client::createWithSurfaceParent(const String8& /* name */, uint32_t /* w */, - uint32_t /* h */, PixelFormat /* format */, - uint32_t /* flags */, - const sp& /* parent */, - LayerMetadata /* metadata */, sp* /* handle */, - sp* /* gbp */, - int32_t* /* outLayerId */, - uint32_t* /* outTransformHint */) { - // This api does not make sense with blast since SF no longer tracks IGBP. This api should be - // removed. - return BAD_VALUE; -} - -status_t Client::mirrorSurface(const sp& mirrorFromHandle, sp* outHandle, - int32_t* outLayerId) { - LayerCreationArgs args(mFlinger.get(), this, "MirrorRoot", 0 /* flags */, LayerMetadata()); - return mFlinger->mirrorLayer(args, mirrorFromHandle, outHandle, outLayerId); + sp handle; + int32_t layerId; + uint32_t transformHint; + LayerCreationArgs args(mFlinger.get(), this, name.c_str(), static_cast(flags), + std::move(metadata)); + const status_t status = + mFlinger->createLayer(args, &handle, parent, &layerId, nullptr, &transformHint); + if (status == NO_ERROR) { + outResult->handle = handle; + outResult->layerId = layerId; + outResult->transformHint = static_cast(transformHint); + } + return binderStatusFromStatusT(status); } -status_t Client::clearLayerFrameStats(const sp& handle) const { +binder::Status Client::clearLayerFrameStats(const sp& handle) { + status_t status; sp layer = getLayerUser(handle); if (layer == nullptr) { - return NAME_NOT_FOUND; + status = NAME_NOT_FOUND; + } else { + layer->clearFrameStats(); + status = NO_ERROR; } - layer->clearFrameStats(); - return NO_ERROR; + return binderStatusFromStatusT(status); } -status_t Client::getLayerFrameStats(const sp& handle, FrameStats* outStats) const { +binder::Status Client::getLayerFrameStats(const sp& handle, gui::FrameStats* outStats) { + status_t status; sp layer = getLayerUser(handle); if (layer == nullptr) { - return NAME_NOT_FOUND; + status = NAME_NOT_FOUND; + } else { + FrameStats stats; + layer->getFrameStats(&stats); + outStats->refreshPeriodNano = stats.refreshPeriodNano; + outStats->desiredPresentTimesNano.reserve(stats.desiredPresentTimesNano.size()); + for (const auto& t : stats.desiredPresentTimesNano) { + outStats->desiredPresentTimesNano.push_back(t); + } + outStats->actualPresentTimesNano.reserve(stats.actualPresentTimesNano.size()); + for (const auto& t : stats.actualPresentTimesNano) { + outStats->actualPresentTimesNano.push_back(t); + } + outStats->frameReadyTimesNano.reserve(stats.frameReadyTimesNano.size()); + for (const auto& t : stats.frameReadyTimesNano) { + outStats->frameReadyTimesNano.push_back(t); + } + status = NO_ERROR; } - layer->getFrameStats(outStats); - return NO_ERROR; + return binderStatusFromStatusT(status); +} + +binder::Status Client::mirrorSurface(const sp& mirrorFromHandle, + gui::MirrorSurfaceResult* outResult) { + sp handle; + int32_t layerId; + LayerCreationArgs args(mFlinger.get(), this, "MirrorRoot", 0 /* flags */, gui::LayerMetadata()); + status_t status = mFlinger->mirrorLayer(args, mirrorFromHandle, &handle, &layerId); + if (status == NO_ERROR) { + outResult->handle = handle; + outResult->layerId = layerId; + } + return binderStatusFromStatusT(status); } // --------------------------------------------------------------------------- diff --git a/services/surfaceflinger/Client.h b/services/surfaceflinger/Client.h index 15cd763822..4720d5c43d 100644 --- a/services/surfaceflinger/Client.h +++ b/services/surfaceflinger/Client.h @@ -24,15 +24,14 @@ #include #include -#include +#include namespace android { class Layer; class SurfaceFlinger; -class Client : public BnSurfaceComposerClient -{ +class Client : public gui::BnSurfaceComposerClient { public: explicit Client(const sp& flinger); ~Client() = default; @@ -47,25 +46,18 @@ public: private: // ISurfaceComposerClient interface - virtual status_t createSurface(const String8& name, uint32_t w, uint32_t h, PixelFormat format, - uint32_t flags, const sp& parent, - LayerMetadata metadata, sp* handle, - sp* gbp, int32_t* outLayerId, - uint32_t* outTransformHint = nullptr); - virtual status_t createWithSurfaceParent(const String8& name, uint32_t w, uint32_t h, - PixelFormat format, uint32_t flags, - const sp& parent, - LayerMetadata metadata, sp* handle, - sp* gbp, int32_t* outLayerId, - uint32_t* outTransformHint = nullptr); + binder::Status createSurface(const std::string& name, int32_t flags, const sp& parent, + const gui::LayerMetadata& metadata, + gui::CreateSurfaceResult* outResult) override; - status_t mirrorSurface(const sp& mirrorFromHandle, sp* handle, - int32_t* outLayerId); + binder::Status clearLayerFrameStats(const sp& handle) override; - virtual status_t clearLayerFrameStats(const sp& handle) const; + binder::Status getLayerFrameStats(const sp& handle, + gui::FrameStats* outStats) override; - virtual status_t getLayerFrameStats(const sp& handle, FrameStats* outStats) const; + binder::Status mirrorSurface(const sp& mirrorFromHandle, + gui::MirrorSurfaceResult* outResult) override; // constant sp mFlinger; diff --git a/services/surfaceflinger/FpsReporter.cpp b/services/surfaceflinger/FpsReporter.cpp index e12835f0f6..c89c9ffcd4 100644 --- a/services/surfaceflinger/FpsReporter.cpp +++ b/services/surfaceflinger/FpsReporter.cpp @@ -56,8 +56,8 @@ void FpsReporter::dispatchLayerFps() { mFlinger.mCurrentState.traverse([&](Layer* layer) { auto& currentState = layer->getDrawingState(); - if (currentState.metadata.has(METADATA_TASK_ID)) { - int32_t taskId = currentState.metadata.getInt32(METADATA_TASK_ID, 0); + if (currentState.metadata.has(gui::METADATA_TASK_ID)) { + int32_t taskId = currentState.metadata.getInt32(gui::METADATA_TASK_ID, 0); if (seenTasks.count(taskId) == 0) { // localListeners is expected to be tiny for (TrackedListener& listener : localListeners) { diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index b4f9c4e720..791ab06258 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -85,6 +85,8 @@ constexpr int kDumpTableRowLength = 159; using namespace ftl::flag_operators; using base::StringAppendF; +using gui::GameMode; +using gui::LayerMetadata; using gui::WindowInfo; using PresentState = frametimeline::SurfaceFrame::PresentState; @@ -96,7 +98,8 @@ Layer::Layer(const LayerCreationArgs& args) mFlinger(args.flinger), mName(base::StringPrintf("%s#%d", args.name.c_str(), sequence)), mClientRef(args.client), - mWindowType(static_cast(args.metadata.getInt32(METADATA_WINDOW_TYPE, 0))), + mWindowType(static_cast( + args.metadata.getInt32(gui::METADATA_WINDOW_TYPE, 0))), mLayerCreationFlags(args.flags) { uint32_t layerFlags = 0; if (args.flags & ISurfaceComposerClient::eHidden) layerFlags |= layer_state_t::eLayerHidden; @@ -161,8 +164,8 @@ Layer::Layer(const LayerCreationArgs& args) if (mCallingUid == AID_GRAPHICS || mCallingUid == AID_SYSTEM) { // If the system didn't send an ownerUid, use the callingUid for the ownerUid. - mOwnerUid = args.metadata.getInt32(METADATA_OWNER_UID, mCallingUid); - mOwnerPid = args.metadata.getInt32(METADATA_OWNER_PID, mCallingPid); + mOwnerUid = args.metadata.getInt32(gui::METADATA_OWNER_UID, mCallingUid); + mOwnerPid = args.metadata.getInt32(gui::METADATA_OWNER_PID, mCallingPid); } else { // A create layer request from a non system request cannot specify the owner uid mOwnerUid = mCallingUid; @@ -1576,8 +1579,9 @@ size_t Layer::getChildrenCount() const { void Layer::setGameModeForTree(GameMode gameMode) { const auto& currentState = getDrawingState(); - if (currentState.metadata.has(METADATA_GAME_MODE)) { - gameMode = static_cast(currentState.metadata.getInt32(METADATA_GAME_MODE, 0)); + if (currentState.metadata.has(gui::METADATA_GAME_MODE)) { + gameMode = + static_cast(currentState.metadata.getInt32(gui::METADATA_GAME_MODE, 0)); } setGameMode(gameMode); for (const sp& child : mCurrentChildren) { diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h index 455920be62..c89b254e99 100644 --- a/services/surfaceflinger/Layer.h +++ b/services/surfaceflinger/Layer.h @@ -17,8 +17,8 @@ #pragma once #include +#include #include -#include #include #include #include diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 3762033942..46b1a60a77 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -171,8 +171,10 @@ using CompositionStrategyPredictionState = android::compositionengine::impl:: using base::StringAppendF; using gui::DisplayInfo; +using gui::GameMode; using gui::IDisplayEventConnection; using gui::IWindowInfosListener; +using gui::LayerMetadata; using gui::WindowInfo; using gui::aidl_utils::binderStatusFromStatusT; using ui::ColorMode; @@ -477,11 +479,6 @@ void SurfaceFlinger::run() { mScheduler->run(); } -sp SurfaceFlinger::createConnection() { - const sp client = new Client(this); - return client->initCheck() == NO_ERROR ? client : nullptr; -} - sp SurfaceFlinger::createDisplay(const String8& displayName, bool secure) { // onTransact already checks for some permissions, but adding an additional check here. // This is to ensure that only system and graphics can request to create a secure @@ -4458,9 +4455,10 @@ uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTime } std::optional dequeueBufferTimestamp; if (what & layer_state_t::eMetadataChanged) { - dequeueBufferTimestamp = s.metadata.getInt64(METADATA_DEQUEUE_TIME); + dequeueBufferTimestamp = s.metadata.getInt64(gui::METADATA_DEQUEUE_TIME); - if (const int32_t gameMode = s.metadata.getInt32(METADATA_GAME_MODE, -1); gameMode != -1) { + if (const int32_t gameMode = s.metadata.getInt32(gui::METADATA_GAME_MODE, -1); + gameMode != -1) { // The transaction will be received on the Task layer and needs to be applied to all // child layers. Child layers that are added at a later point will obtain the game mode // info through addChild(). @@ -5503,11 +5501,11 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { case GET_DISPLAY_MODES: // Calling setTransactionState is safe, because you need to have been // granted a reference to Client* and Handle* to do anything with it. - case SET_TRANSACTION_STATE: - case CREATE_CONNECTION: { + case SET_TRANSACTION_STATE: { // This is not sensitive information, so should not require permission control. return OK; } + case CREATE_CONNECTION: case CREATE_DISPLAY: case DESTROY_DISPLAY: case GET_PRIMARY_PHYSICAL_DISPLAY_ID: @@ -6995,8 +6993,8 @@ const std::unordered_map& SurfaceFlinger::getGenericLayer // on the work to remove the table in that bug rather than adding more to // it. static const std::unordered_map genericLayerMetadataKeyMap{ - {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID}, - {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR}, + {"org.chromium.arc.V1_0.TaskId", gui::METADATA_TASK_ID}, + {"org.chromium.arc.V1_0.CursorInfo", gui::METADATA_MOUSE_CURSOR}, }; return genericLayerMetadataKeyMap; } @@ -7213,6 +7211,17 @@ bool SurfaceFlinger::commitCreatedLayers() { // gui::ISurfaceComposer +binder::Status SurfaceComposerAIDL::createConnection(sp* outClient) { + const sp client = new Client(mFlinger); + if (client->initCheck() == NO_ERROR) { + *outClient = client; + return binder::Status::ok(); + } else { + *outClient = nullptr; + return binderStatusFromStatusT(BAD_VALUE); + } +} + binder::Status SurfaceComposerAIDL::createDisplay(const std::string& displayName, bool secure, sp* outDisplay) { status_t status = checkAccessPermission(); diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index df00eeecdf..353df24f7f 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -25,12 +25,12 @@ #include #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -536,7 +536,6 @@ private: } // Implements ISurfaceComposer - sp createConnection() override; sp createDisplay(const String8& displayName, bool secure); void destroyDisplay(const sp& displayToken); std::vector getPhysicalDisplayIds() const EXCLUDES(mStateLock) { @@ -1446,6 +1445,7 @@ class SurfaceComposerAIDL : public gui::BnSurfaceComposer { public: SurfaceComposerAIDL(sp sf) : mFlinger(std::move(sf)) {} + binder::Status createConnection(sp* outClient) override; binder::Status createDisplay(const std::string& displayName, bool secure, sp* outDisplay) override; binder::Status destroyDisplay(const sp& display) override; diff --git a/services/surfaceflinger/TimeStats/TimeStats.h b/services/surfaceflinger/TimeStats/TimeStats.h index 7a159b8eb7..61d7c22a2a 100644 --- a/services/surfaceflinger/TimeStats/TimeStats.h +++ b/services/surfaceflinger/TimeStats/TimeStats.h @@ -34,6 +34,8 @@ #include +using android::gui::GameMode; +using android::gui::LayerMetadata; using namespace android::surfaceflinger; namespace android { diff --git a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h index 237ae8d761..60aa810e8b 100644 --- a/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h +++ b/services/surfaceflinger/TimeStats/timestatsproto/include/timestatsproto/TimeStatsHelper.h @@ -24,6 +24,9 @@ #include #include +using android::gui::GameMode; +using android::gui::LayerMetadata; + namespace android { namespace surfaceflinger { diff --git a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp index e8ecf2f33b..8ec6c99eb9 100644 --- a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp +++ b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp @@ -459,7 +459,7 @@ void TransactionProtoParser::fromProto(const proto::LayerState& proto, layer_sta layer.parentSurfaceControlForChild = new SurfaceControl(SurfaceComposerClient::getDefault(), mMapper->getLayerHandle(static_cast(layerId)), - nullptr, static_cast(layerId)); + static_cast(layerId)); } } if (proto.what() & layer_state_t::eRelativeLayerChanged) { @@ -470,7 +470,7 @@ void TransactionProtoParser::fromProto(const proto::LayerState& proto, layer_sta layer.relativeLayerSurfaceControl = new SurfaceControl(SurfaceComposerClient::getDefault(), mMapper->getLayerHandle(static_cast(layerId)), - nullptr, static_cast(layerId)); + static_cast(layerId)); } layer.z = proto.z(); } diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 2a4d6ed86f..c4cd089a5e 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -555,7 +555,7 @@ public: sp fuzzBoot(FuzzedDataProvider *fdp) { mFlinger->callingThreadHasUnscopedSurfaceFlingerAccess(fdp->ConsumeBool()); - mFlinger->createConnection(); + const sp client = new Client(mFlinger); DisplayIdGenerator kGenerator; HalVirtualDisplayId halVirtualDisplayId = kGenerator.generateId().value(); diff --git a/services/surfaceflinger/layerproto/include/layerproto/LayerProtoParser.h b/services/surfaceflinger/layerproto/include/layerproto/LayerProtoParser.h index 52503bad3a..cdc2706ee2 100644 --- a/services/surfaceflinger/layerproto/include/layerproto/LayerProtoParser.h +++ b/services/surfaceflinger/layerproto/include/layerproto/LayerProtoParser.h @@ -24,6 +24,8 @@ #include #include +using android::gui::LayerMetadata; + namespace android { namespace surfaceflinger { diff --git a/services/surfaceflinger/tests/InvalidHandles_test.cpp b/services/surfaceflinger/tests/InvalidHandles_test.cpp index d192a2d83d..023133f2c3 100644 --- a/services/surfaceflinger/tests/InvalidHandles_test.cpp +++ b/services/surfaceflinger/tests/InvalidHandles_test.cpp @@ -48,7 +48,7 @@ protected: } sp makeNotSurfaceControl() { - return new SurfaceControl(mScc, new NotALayer(), nullptr, true); + return new SurfaceControl(mScc, new NotALayer(), 1); } }; @@ -64,4 +64,4 @@ TEST_F(InvalidHandleTest, captureLayersInvalidHandle) { } // namespace android // TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic pop // ignored "-Wconversion" \ No newline at end of file +#pragma clang diagnostic pop // ignored "-Wconversion" diff --git a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp index bb1f4328b5..9cac7c1723 100644 --- a/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp +++ b/services/surfaceflinger/tests/unittests/FpsReporterTest.cpp @@ -51,6 +51,7 @@ using android::Hwc2::IComposer; using android::Hwc2::IComposerClient; using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector; +using gui::LayerMetadata; struct TestableFpsListener : public gui::BnFpsListener { TestableFpsListener() {} @@ -153,7 +154,7 @@ TEST_F(FpsReporterTest, callsListeners) { mParent = createBufferStateLayer(); constexpr int32_t kTaskId = 12; LayerMetadata targetMetadata; - targetMetadata.setInt32(METADATA_TASK_ID, kTaskId); + targetMetadata.setInt32(gui::METADATA_TASK_ID, kTaskId); mTarget = createBufferStateLayer(targetMetadata); mChild = createBufferStateLayer(); mGrandChild = createBufferStateLayer(); @@ -188,7 +189,7 @@ TEST_F(FpsReporterTest, callsListeners) { TEST_F(FpsReporterTest, rateLimits) { const constexpr int32_t kTaskId = 12; LayerMetadata targetMetadata; - targetMetadata.setInt32(METADATA_TASK_ID, kTaskId); + targetMetadata.setInt32(gui::METADATA_TASK_ID, kTaskId); mTarget = createBufferStateLayer(targetMetadata); mFlinger.mutableCurrentState().layersSortedByZ.add(mTarget); diff --git a/services/surfaceflinger/tests/unittests/GameModeTest.cpp b/services/surfaceflinger/tests/unittests/GameModeTest.cpp index 981ca1d227..b79909ad9d 100644 --- a/services/surfaceflinger/tests/unittests/GameModeTest.cpp +++ b/services/surfaceflinger/tests/unittests/GameModeTest.cpp @@ -34,6 +34,8 @@ using testing::_; using testing::Mock; using testing::Return; using FakeHwcDisplayInjector = TestableSurfaceFlinger::FakeHwcDisplayInjector; +using gui::GameMode; +using gui::LayerMetadata; class GameModeTest : public testing::Test { public: @@ -92,7 +94,7 @@ public: // Mocks the behavior of applying a transaction from WMShell void setGameModeMetadata(sp layer, GameMode gameMode) { - mLayerMetadata.setInt32(METADATA_GAME_MODE, static_cast(gameMode)); + mLayerMetadata.setInt32(gui::METADATA_GAME_MODE, static_cast(gameMode)); layer->setMetadata(mLayerMetadata); layer->setGameModeForTree(gameMode); } diff --git a/services/surfaceflinger/tests/unittests/LayerMetadataTest.cpp b/services/surfaceflinger/tests/unittests/LayerMetadataTest.cpp index 373fd74020..e6e02c1806 100644 --- a/services/surfaceflinger/tests/unittests/LayerMetadataTest.cpp +++ b/services/surfaceflinger/tests/unittests/LayerMetadataTest.cpp @@ -27,6 +27,8 @@ #include #include +using android::gui::LayerMetadata; + namespace android { namespace { @@ -113,4 +115,4 @@ TEST_F(LayerMetadataTest, merge) { } // namespace android // TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic pop // ignored "-Wextra" \ No newline at end of file +#pragma clang diagnostic pop // ignored "-Wextra" diff --git a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp index f5e3b77ca6..669fa3a7f0 100644 --- a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp @@ -49,8 +49,7 @@ TEST(TransactionProtoParserTest, parse) { ComposerState s; if (i == 1) { layer.parentSurfaceControlForChild = - new SurfaceControl(SurfaceComposerClient::getDefault(), layerHandle, nullptr, - 42); + new SurfaceControl(SurfaceComposerClient::getDefault(), layerHandle, 42); } s.state = layer; t1.states.add(s); -- cgit v1.2.3-59-g8ed1b From 1b0c49f83281b9433a6758ceb16ac4bc17a885f8 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 15 Mar 2022 19:18:21 -0700 Subject: Migrate bootFinished of ISurfaceComposer to AIDL And createDisplayEventConnection is migrated too. Bug: 221898546 Bug: 211009610 Test: atest libsurfaceflinger_unittest libgui_test SurfaceFlinger_test Change-Id: I2d0968262b86829b4cce13158446f1c85a4e55e4 --- libs/gui/DisplayEventDispatcher.cpp | 13 ++++--- libs/gui/DisplayEventReceiver.cpp | 20 ++++++---- libs/gui/ISurfaceComposer.cpp | 45 ---------------------- libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 25 ++++++++++++ libs/gui/include/gui/DisplayEventDispatcher.h | 8 ++-- libs/gui/include/gui/DisplayEventReceiver.h | 14 +++++-- libs/gui/include/gui/ISurfaceComposer.h | 37 +++--------------- libs/gui/tests/Surface_test.cpp | 15 +++++--- libs/nativedisplay/AChoreographer.cpp | 4 +- services/surfaceflinger/Scheduler/EventThread.cpp | 13 +++---- services/surfaceflinger/Scheduler/EventThread.h | 10 ++--- services/surfaceflinger/Scheduler/Scheduler.cpp | 4 +- services/surfaceflinger/Scheduler/Scheduler.h | 6 ++- services/surfaceflinger/SurfaceFlinger.cpp | 42 +++++++++++++++----- services/surfaceflinger/SurfaceFlinger.h | 15 ++++++-- .../tests/DisplayEventReceiver_test.cpp | 5 ++- .../tests/SetFrameRateOverride_test.cpp | 8 ++-- .../tests/fakehwc/SFFakeHwc_test.cpp | 5 ++- .../tests/unittests/EventThreadTest.cpp | 22 +++++------ .../tests/unittests/mock/MockEventThread.h | 3 +- 20 files changed, 159 insertions(+), 155 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/DisplayEventDispatcher.cpp b/libs/gui/DisplayEventDispatcher.cpp index dfdce20438..501e69ade5 100644 --- a/libs/gui/DisplayEventDispatcher.cpp +++ b/libs/gui/DisplayEventDispatcher.cpp @@ -35,11 +35,14 @@ static const size_t EVENT_BUFFER_SIZE = 100; static constexpr nsecs_t WAITING_FOR_VSYNC_TIMEOUT = ms2ns(300); -DisplayEventDispatcher::DisplayEventDispatcher( - const sp& looper, ISurfaceComposer::VsyncSource vsyncSource, - ISurfaceComposer::EventRegistrationFlags eventRegistration) - : mLooper(looper), mReceiver(vsyncSource, eventRegistration), mWaitingForVsync(false), - mLastVsyncCount(0), mLastScheduleVsyncTime(0) { +DisplayEventDispatcher::DisplayEventDispatcher(const sp& looper, + gui::ISurfaceComposer::VsyncSource vsyncSource, + EventRegistrationFlags eventRegistration) + : mLooper(looper), + mReceiver(vsyncSource, eventRegistration), + mWaitingForVsync(false), + mLastVsyncCount(0), + mLastScheduleVsyncTime(0) { ALOGV("dispatcher %p ~ Initializing display event dispatcher.", this); } diff --git a/libs/gui/DisplayEventReceiver.cpp b/libs/gui/DisplayEventReceiver.cpp index bfb77699c0..c52fb6b7c3 100644 --- a/libs/gui/DisplayEventReceiver.cpp +++ b/libs/gui/DisplayEventReceiver.cpp @@ -19,10 +19,9 @@ #include #include -#include #include -#include +#include #include @@ -32,15 +31,20 @@ namespace android { // --------------------------------------------------------------------------- -DisplayEventReceiver::DisplayEventReceiver( - ISurfaceComposer::VsyncSource vsyncSource, - ISurfaceComposer::EventRegistrationFlags eventRegistration) { - sp sf(ComposerService::getComposerService()); +DisplayEventReceiver::DisplayEventReceiver(gui::ISurfaceComposer::VsyncSource vsyncSource, + EventRegistrationFlags eventRegistration) { + sp sf(ComposerServiceAIDL::getComposerService()); if (sf != nullptr) { - mEventConnection = sf->createDisplayEventConnection(vsyncSource, eventRegistration); + mEventConnection = nullptr; + binder::Status status = + sf->createDisplayEventConnection(vsyncSource, + static_cast< + gui::ISurfaceComposer::EventRegistration>( + eventRegistration.get()), + &mEventConnection); if (mEventConnection != nullptr) { mDataChannel = std::make_unique(); - const auto status = mEventConnection->stealReceiveChannel(mDataChannel.get()); + status = mEventConnection->stealReceiveChannel(mDataChannel.get()); if (!status.isOk()) { ALOGE("stealReceiveChannel failed: %s", status.toString8().c_str()); mInitError = std::make_optional(status.transactionError()); diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 54e50b50ac..af64b3bd32 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -108,35 +108,6 @@ public: data, &reply); } } - - void bootFinished() override { - Parcel data, reply; - data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); - remote()->transact(BnSurfaceComposer::BOOT_FINISHED, data, &reply); - } - - sp createDisplayEventConnection( - VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) override { - Parcel data, reply; - sp result; - int err = data.writeInterfaceToken( - ISurfaceComposer::getInterfaceDescriptor()); - if (err != NO_ERROR) { - return result; - } - data.writeInt32(static_cast(vsyncSource)); - data.writeUint32(eventRegistration.get()); - err = remote()->transact( - BnSurfaceComposer::CREATE_DISPLAY_EVENT_CONNECTION, - data, &reply); - if (err != NO_ERROR) { - ALOGE("ISurfaceComposer::createDisplayEventConnection: error performing " - "transaction: %s (%d)", strerror(-err), -err); - return result; - } - result = interface_cast(reply.readStrongBinder()); - return result; - } }; // Out-of-line virtual method definition to trigger vtable emission in this @@ -215,22 +186,6 @@ status_t BnSurfaceComposer::onTransact( uncachedBuffer, hasListenerCallbacks, listenerCallbacks, transactionId); } - case BOOT_FINISHED: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - bootFinished(); - return NO_ERROR; - } - case CREATE_DISPLAY_EVENT_CONNECTION: { - CHECK_INTERFACE(ISurfaceComposer, data, reply); - auto vsyncSource = static_cast(data.readInt32()); - EventRegistrationFlags eventRegistration = - static_cast(data.readUint32()); - - sp connection( - createDisplayEventConnection(vsyncSource, eventRegistration)); - reply->writeStrongBinder(IInterface::asBinder(connection)); - return NO_ERROR; - } default: { return BBinder::onTransact(code, data, reply, flags); } diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 26b4e819ee..39833fe06b 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -30,6 +30,7 @@ import android.gui.DisplayStatInfo; import android.gui.DynamicDisplayInfo; import android.gui.FrameEvent; import android.gui.FrameStats; +import android.gui.IDisplayEventConnection; import android.gui.IFpsListener; import android.gui.IHdrLayerInfoListener; import android.gui.IRegionSamplingListener; @@ -47,6 +48,30 @@ import android.gui.StaticDisplayInfo; /** @hide */ interface ISurfaceComposer { + enum VsyncSource { + eVsyncSourceApp = 0, + eVsyncSourceSurfaceFlinger = 1 + } + + enum EventRegistration { + modeChanged = 1 << 0, + frameRateOverride = 1 << 1, + } + + /** + * Signal that we're done booting. + * Requires ACCESS_SURFACE_FLINGER permission + */ + // Note this must be the 1st method, so IBinder::FIRST_CALL_TRANSACTION + // is assigned, as it is called from Java by ActivityManagerService. + void bootFinished(); + + /** + * Create a display event connection + */ + @nullable IDisplayEventConnection createDisplayEventConnection(VsyncSource vsyncSource, + EventRegistration eventRegistration); + /** * Create a connection with SurfaceFlinger. */ diff --git a/libs/gui/include/gui/DisplayEventDispatcher.h b/libs/gui/include/gui/DisplayEventDispatcher.h index a3425395bf..bf3a07b6b5 100644 --- a/libs/gui/include/gui/DisplayEventDispatcher.h +++ b/libs/gui/include/gui/DisplayEventDispatcher.h @@ -23,10 +23,10 @@ using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride; class DisplayEventDispatcher : public LooperCallback { public: - explicit DisplayEventDispatcher( - const sp& looper, - ISurfaceComposer::VsyncSource vsyncSource = ISurfaceComposer::eVsyncSourceApp, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); + explicit DisplayEventDispatcher(const sp& looper, + gui::ISurfaceComposer::VsyncSource vsyncSource = + gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp, + EventRegistrationFlags eventRegistration = {}); status_t initialize(); void dispose(); diff --git a/libs/gui/include/gui/DisplayEventReceiver.h b/libs/gui/include/gui/DisplayEventReceiver.h index cf7a4e5522..0f4907fcb9 100644 --- a/libs/gui/include/gui/DisplayEventReceiver.h +++ b/libs/gui/include/gui/DisplayEventReceiver.h @@ -20,20 +20,26 @@ #include #include +#include + #include #include #include +#include #include -#include #include +#include + // ---------------------------------------------------------------------------- namespace android { // ---------------------------------------------------------------------------- +using EventRegistrationFlags = ftl::Flags; + using gui::IDisplayEventConnection; using gui::ParcelableVsyncEventData; using gui::VsyncEventData; @@ -111,9 +117,9 @@ public: * To receive ModeChanged and/or FrameRateOverrides events specify this in * the constructor. Other events start being delivered immediately. */ - explicit DisplayEventReceiver( - ISurfaceComposer::VsyncSource vsyncSource = ISurfaceComposer::eVsyncSourceApp, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); + explicit DisplayEventReceiver(gui::ISurfaceComposer::VsyncSource vsyncSource = + gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp, + EventRegistrationFlags eventRegistration = {}); /* * ~DisplayEventReceiver severs the connection with SurfaceFlinger, new events diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 7139e1bb93..1e85131386 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -28,7 +28,6 @@ #include #include #include -#include #include #include #include @@ -94,8 +93,6 @@ class ISurfaceComposer: public IInterface { public: DECLARE_META_INTERFACE(SurfaceComposer) - static constexpr size_t MAX_LAYERS = 4096; - // flags for setTransactionState() enum { eSynchronous = 0x01, @@ -113,23 +110,6 @@ public: eOneWay = 0x20 }; - enum VsyncSource { - eVsyncSourceApp = 0, - eVsyncSourceSurfaceFlinger = 1 - }; - - enum class EventRegistration { - modeChanged = 1 << 0, - frameRateOverride = 1 << 1, - }; - - using EventRegistrationFlags = ftl::Flags; - - /* return an IDisplayEventConnection */ - virtual sp createDisplayEventConnection( - VsyncSource vsyncSource = eVsyncSourceApp, - EventRegistrationFlags eventRegistration = {}) = 0; - /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */ virtual status_t setTransactionState( const FrameTimelineInfo& frameTimelineInfo, const Vector& state, @@ -137,11 +117,6 @@ public: const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) = 0; - - /* signal that we're done booting. - * Requires ACCESS_SURFACE_FLINGER permission - */ - virtual void bootFinished() = 0; }; // ---------------------------------------------------------------------------- @@ -152,12 +127,12 @@ public: // Note: BOOT_FINISHED must remain this value, it is called from // Java by ActivityManagerService. BOOT_FINISHED = IBinder::FIRST_CALL_TRANSACTION, - CREATE_CONNECTION, // Deprecated. Autogenerated by .aidl now. - GET_STATIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. - CREATE_DISPLAY_EVENT_CONNECTION, - CREATE_DISPLAY, // Deprecated. Autogenerated by .aidl now. - DESTROY_DISPLAY, // Deprecated. Autogenerated by .aidl now. - GET_PHYSICAL_DISPLAY_TOKEN, // Deprecated. Autogenerated by .aidl now. + CREATE_CONNECTION, // Deprecated. Autogenerated by .aidl now. + GET_STATIC_DISPLAY_INFO, // Deprecated. Autogenerated by .aidl now. + CREATE_DISPLAY_EVENT_CONNECTION, // Deprecated. Autogenerated by .aidl now. + CREATE_DISPLAY, // Deprecated. Autogenerated by .aidl now. + DESTROY_DISPLAY, // Deprecated. Autogenerated by .aidl now. + GET_PHYSICAL_DISPLAY_TOKEN, // Deprecated. Autogenerated by .aidl now. SET_TRANSACTION_STATE, AUTHENTICATE_SURFACE, // Deprecated. Autogenerated by .aidl now. GET_SUPPORTED_FRAME_TIMESTAMPS, // Deprecated. Autogenerated by .aidl now. diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 4ab380c8b8..7eff3b318f 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -692,10 +692,6 @@ public: mSupportsPresent = supportsPresent; } - sp createDisplayEventConnection( - ISurfaceComposer::VsyncSource, ISurfaceComposer::EventRegistrationFlags) override { - return nullptr; - } status_t setTransactionState(const FrameTimelineInfo& /*frameTimelineInfo*/, const Vector& /*state*/, const Vector& /*displays*/, uint32_t /*flags*/, @@ -709,8 +705,6 @@ public: return NO_ERROR; } - void bootFinished() override {} - protected: IBinder* onAsBinder() override { return nullptr; } @@ -724,6 +718,15 @@ public: void setSupportsPresent(bool supportsPresent) { mSupportsPresent = supportsPresent; } + binder::Status bootFinished() override { return binder::Status::ok(); } + + binder::Status createDisplayEventConnection( + VsyncSource /*vsyncSource*/, EventRegistration /*eventRegistration*/, + sp* outConnection) override { + *outConnection = nullptr; + return binder::Status::ok(); + } + binder::Status createConnection(sp* outClient) override { *outClient = nullptr; return binder::Status::ok(); diff --git a/libs/nativedisplay/AChoreographer.cpp b/libs/nativedisplay/AChoreographer.cpp index 8240b08085..539cbaa341 100644 --- a/libs/nativedisplay/AChoreographer.cpp +++ b/libs/nativedisplay/AChoreographer.cpp @@ -18,8 +18,8 @@ //#define LOG_NDEBUG 0 #include +#include #include -#include #include #include #include @@ -198,7 +198,7 @@ Choreographer* Choreographer::getForThread() { } Choreographer::Choreographer(const sp& looper) - : DisplayEventDispatcher(looper, ISurfaceComposer::VsyncSource::eVsyncSourceApp), + : DisplayEventDispatcher(looper, gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp), mLooper(looper), mThreadId(std::this_thread::get_id()) { std::lock_guard _l(gChoreographers.lock); diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp index cbea77e8fb..5d9920866f 100644 --- a/services/surfaceflinger/Scheduler/EventThread.cpp +++ b/services/surfaceflinger/Scheduler/EventThread.cpp @@ -157,9 +157,9 @@ DisplayEventReceiver::Event makeFrameRateOverrideFlushEvent(PhysicalDisplayId di } // namespace -EventThreadConnection::EventThreadConnection( - EventThread* eventThread, uid_t callingUid, ResyncCallback resyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration) +EventThreadConnection::EventThreadConnection(EventThread* eventThread, uid_t callingUid, + ResyncCallback resyncCallback, + EventRegistrationFlags eventRegistration) : resyncCallback(std::move(resyncCallback)), mOwnerUid(callingUid), mEventRegistration(eventRegistration), @@ -283,8 +283,7 @@ void EventThread::setDuration(std::chrono::nanoseconds workDuration, } sp EventThread::createEventConnection( - ResyncCallback resyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration) const { + ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const { return new EventThreadConnection(const_cast(this), IPCThreadState::self()->getCallingUid(), std::move(resyncCallback), eventRegistration); @@ -548,7 +547,7 @@ bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event, case DisplayEventReceiver::DISPLAY_EVENT_MODE_CHANGE: { return connection->mEventRegistration.test( - ISurfaceComposer::EventRegistration::modeChanged); + gui::ISurfaceComposer::EventRegistration::modeChanged); } case DisplayEventReceiver::DISPLAY_EVENT_VSYNC: @@ -581,7 +580,7 @@ bool EventThread::shouldConsumeEvent(const DisplayEventReceiver::Event& event, [[fallthrough]]; case DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH: return connection->mEventRegistration.test( - ISurfaceComposer::EventRegistration::frameRateOverride); + gui::ISurfaceComposer::EventRegistration::frameRateOverride); default: return false; diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h index c406478c17..60ab633075 100644 --- a/services/surfaceflinger/Scheduler/EventThread.h +++ b/services/surfaceflinger/Scheduler/EventThread.h @@ -92,7 +92,7 @@ public: class EventThreadConnection : public gui::BnDisplayEventConnection { public: EventThreadConnection(EventThread*, uid_t callingUid, ResyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); + EventRegistrationFlags eventRegistration = {}); virtual ~EventThreadConnection(); virtual status_t postEvent(const DisplayEventReceiver::Event& event); @@ -107,7 +107,7 @@ public: VSyncRequest vsyncRequest = VSyncRequest::None; const uid_t mOwnerUid; - const ISurfaceComposer::EventRegistrationFlags mEventRegistration; + const EventRegistrationFlags mEventRegistration; private: virtual void onFirstRef(); @@ -122,8 +122,7 @@ public: virtual ~EventThread(); virtual sp createEventConnection( - ResyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) const = 0; + ResyncCallback, EventRegistrationFlags eventRegistration = {}) const = 0; // called before the screen is turned off from main thread virtual void onScreenReleased() = 0; @@ -170,8 +169,7 @@ public: ~EventThread(); sp createEventConnection( - ResyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) const override; + ResyncCallback, EventRegistrationFlags eventRegistration = {}) const override; status_t registerDisplayEventConnection(const sp& connection) override; void setVsyncRate(uint32_t rate, const sp& connection) override; diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp index 3aa0a5f15c..8300595150 100644 --- a/services/surfaceflinger/Scheduler/Scheduler.cpp +++ b/services/surfaceflinger/Scheduler/Scheduler.cpp @@ -208,12 +208,12 @@ ConnectionHandle Scheduler::createConnection(std::unique_ptr eventT } sp Scheduler::createConnectionInternal( - EventThread* eventThread, ISurfaceComposer::EventRegistrationFlags eventRegistration) { + EventThread* eventThread, EventRegistrationFlags eventRegistration) { return eventThread->createEventConnection([&] { resync(); }, eventRegistration); } sp Scheduler::createDisplayEventConnection( - ConnectionHandle handle, ISurfaceComposer::EventRegistrationFlags eventRegistration) { + ConnectionHandle handle, EventRegistrationFlags eventRegistration) { std::lock_guard lock(mConnectionsLock); RETURN_IF_INVALID_HANDLE(handle, nullptr); return createConnectionInternal(mConnections[handle].thread.get(), eventRegistration); diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h index 0c72124119..98c0eb3bf0 100644 --- a/services/surfaceflinger/Scheduler/Scheduler.h +++ b/services/surfaceflinger/Scheduler/Scheduler.h @@ -32,6 +32,8 @@ #include #pragma clang diagnostic pop // ignored "-Wconversion -Wextra" +#include + #include #include "EventThread.h" @@ -131,7 +133,7 @@ public: impl::EventThread::InterceptVSyncsCallback); sp createDisplayEventConnection( - ConnectionHandle, ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); + ConnectionHandle, EventRegistrationFlags eventRegistration = {}); sp getEventConnection(ConnectionHandle); @@ -248,7 +250,7 @@ private: // Create a connection on the given EventThread. ConnectionHandle createConnection(std::unique_ptr); sp createConnectionInternal( - EventThread*, ISurfaceComposer::EventRegistrationFlags eventRegistration = {}); + EventThread*, EventRegistrationFlags eventRegistration = {}); // Update feature state machine to given state when corresponding timer resets or expires. void kernelIdleTimerCallback(TimerState) EXCLUDES(mRefreshRateConfigsLock); diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 46b1a60a77..5afc997ab6 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -406,7 +406,7 @@ SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipI property_get("ro.sf.blurs_are_expensive", value, "0"); mBlursAreExpensive = atoi(value); - const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS; + const size_t defaultListSize = MAX_LAYERS; auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize)); mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize; mGraphicBufferProducerListSizeLogThreshold = @@ -1789,10 +1789,11 @@ status_t SurfaceFlinger::getDisplayDecorationSupport( // ---------------------------------------------------------------------------- sp SurfaceFlinger::createDisplayEventConnection( - ISurfaceComposer::VsyncSource vsyncSource, - ISurfaceComposer::EventRegistrationFlags eventRegistration) { + gui::ISurfaceComposer::VsyncSource vsyncSource, EventRegistrationFlags eventRegistration) { const auto& handle = - vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle; + vsyncSource == gui::ISurfaceComposer::VsyncSource::eVsyncSourceSurfaceFlinger + ? mSfConnectionHandle + : mAppConnectionHandle; return mScheduler->createDisplayEventConnection(handle, eventRegistration); } @@ -3589,9 +3590,9 @@ bool SurfaceFlinger::latchBuffers() { status_t SurfaceFlinger::addClientLayer(const sp& client, const sp& handle, const sp& layer, const wp& parent, bool addToRoot, uint32_t* outTransformHint) { - if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) { + if (mNumLayers >= MAX_LAYERS) { ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(), - ISurfaceComposer::MAX_LAYERS); + MAX_LAYERS); static_cast(mScheduler->schedule([=] { ALOGE("Dumping random sampling of on-screen layers: "); mDrawingState.traverse([&](Layer *layer) { @@ -5474,7 +5475,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { switch (static_cast(code)) { // These methods should at minimum make sure that the client requested // access to SF. - case BOOT_FINISHED: case GET_HDR_CAPABILITIES: case GET_AUTO_LOW_LATENCY_MODE_SUPPORT: case GET_GAME_CONTENT_TYPE_SUPPORT: @@ -5490,8 +5490,6 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { } return OK; } - // Used by apps to hook Choreographer to SurfaceFlinger. - case CREATE_DISPLAY_EVENT_CONNECTION: // The following calls are currently used by clients that do not // request necessary permissions. However, they do not expose any secret // information, so it is OK to pass them. @@ -5505,6 +5503,9 @@ status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) { // This is not sensitive information, so should not require permission control. return OK; } + case BOOT_FINISHED: + // Used by apps to hook Choreographer to SurfaceFlinger. + case CREATE_DISPLAY_EVENT_CONNECTION: case CREATE_CONNECTION: case CREATE_DISPLAY: case DESTROY_DISPLAY: @@ -7211,6 +7212,29 @@ bool SurfaceFlinger::commitCreatedLayers() { // gui::ISurfaceComposer +binder::Status SurfaceComposerAIDL::bootFinished() { + status_t status = checkAccessPermission(); + if (status != OK) { + return binderStatusFromStatusT(status); + } + mFlinger->bootFinished(); + return binder::Status::ok(); +} + +binder::Status SurfaceComposerAIDL::createDisplayEventConnection( + VsyncSource vsyncSource, EventRegistration eventRegistration, + sp* outConnection) { + sp conn = + mFlinger->createDisplayEventConnection(vsyncSource, eventRegistration); + if (conn == nullptr) { + *outConnection = nullptr; + return binderStatusFromStatusT(BAD_VALUE); + } else { + *outConnection = conn; + return binder::Status::ok(); + } +} + binder::Status SurfaceComposerAIDL::createConnection(sp* outClient) { const sp client = new Client(mFlinger); if (client->initCheck() == NO_ERROR) { diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 353df24f7f..4bb692dda0 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -516,6 +516,8 @@ private: // Maximum allowed number of display frames that can be set through backdoor static const int MAX_ALLOWED_DISPLAY_FRAMES = 2048; + static const size_t MAX_LAYERS = 4096; + // Implements IBinder. status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override; status_t dump(int fd, const Vector& args) override { return priorityDump(fd, args); } @@ -554,11 +556,12 @@ private: const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override; - void bootFinished() override; + void bootFinished(); virtual status_t getSupportedFrameTimestamps(std::vector* outSupported) const; sp createDisplayEventConnection( - ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}) override; + gui::ISurfaceComposer::VsyncSource vsyncSource = + gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp, + EventRegistrationFlags eventRegistration = {}); status_t captureDisplay(const DisplayCaptureArgs&, const sp&); status_t captureDisplay(DisplayId, const sp&); @@ -1174,7 +1177,7 @@ private: float mGlobalSaturationFactor = 1.0f; mat4 mClientColorMatrix; - size_t mMaxGraphicBufferProducerListSize = ISurfaceComposer::MAX_LAYERS; + size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS; // If there are more GraphicBufferProducers tracked by SurfaceFlinger than // this threshold, then begin logging. size_t mGraphicBufferProducerListSizeLogThreshold = @@ -1445,6 +1448,10 @@ class SurfaceComposerAIDL : public gui::BnSurfaceComposer { public: SurfaceComposerAIDL(sp sf) : mFlinger(std::move(sf)) {} + binder::Status bootFinished() override; + binder::Status createDisplayEventConnection( + VsyncSource vsyncSource, EventRegistration eventRegistration, + sp* outConnection) override; binder::Status createConnection(sp* outClient) override; binder::Status createDisplay(const std::string& displayName, bool secure, sp* outDisplay) override; diff --git a/services/surfaceflinger/tests/DisplayEventReceiver_test.cpp b/services/surfaceflinger/tests/DisplayEventReceiver_test.cpp index 0e54664f77..0df7e2fafa 100644 --- a/services/surfaceflinger/tests/DisplayEventReceiver_test.cpp +++ b/services/surfaceflinger/tests/DisplayEventReceiver_test.cpp @@ -36,7 +36,8 @@ TEST_F(DisplayEventReceiverTest, getLatestVsyncEventData) { EXPECT_GT(vsyncEventData.frameTimelines[0].deadlineTimestamp, now) << "Deadline timestamp should be greater than frame time"; for (size_t i = 0; i < VsyncEventData::kFrameTimelinesLength; i++) { - EXPECT_NE(FrameTimelineInfo::INVALID_VSYNC_ID, vsyncEventData.frameTimelines[i].vsyncId); + EXPECT_NE(gui::FrameTimelineInfo::INVALID_VSYNC_ID, + vsyncEventData.frameTimelines[i].vsyncId); EXPECT_GT(vsyncEventData.frameTimelines[i].expectedPresentationTime, vsyncEventData.frameTimelines[i].deadlineTimestamp) << "Expected vsync timestamp should be greater than deadline"; @@ -51,4 +52,4 @@ TEST_F(DisplayEventReceiverTest, getLatestVsyncEventData) { } } -} // namespace android \ No newline at end of file +} // namespace android diff --git a/services/surfaceflinger/tests/SetFrameRateOverride_test.cpp b/services/surfaceflinger/tests/SetFrameRateOverride_test.cpp index 4efec7738a..e43ef952d6 100644 --- a/services/surfaceflinger/tests/SetFrameRateOverride_test.cpp +++ b/services/surfaceflinger/tests/SetFrameRateOverride_test.cpp @@ -14,9 +14,9 @@ * limitations under the License. */ +#include #include #include -#include #include #include #include @@ -24,12 +24,14 @@ namespace android { namespace { using FrameRateOverride = DisplayEventReceiver::Event::FrameRateOverride; +using gui::ISurfaceComposer; class SetFrameRateOverrideTest : public ::testing::Test { protected: void SetUp() override { - const ISurfaceComposer::VsyncSource vsyncSource = ISurfaceComposer::eVsyncSourceApp; - const ISurfaceComposer::EventRegistrationFlags eventRegistration = { + const ISurfaceComposer::VsyncSource vsyncSource = + ISurfaceComposer::VsyncSource::eVsyncSourceApp; + const EventRegistrationFlags eventRegistration = { ISurfaceComposer::EventRegistration::frameRateOverride}; mDisplayEventReceiver = diff --git a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp index 67df8b8d61..00845d793f 100644 --- a/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp +++ b/services/surfaceflinger/tests/fakehwc/SFFakeHwc_test.cpp @@ -245,8 +245,9 @@ protected: mComposerClient = new SurfaceComposerClient; ASSERT_EQ(NO_ERROR, mComposerClient->initCheck()); - mReceiver.reset(new DisplayEventReceiver(ISurfaceComposer::eVsyncSourceApp, - ISurfaceComposer::EventRegistration::modeChanged)); + mReceiver.reset( + new DisplayEventReceiver(gui::ISurfaceComposer::VsyncSource::eVsyncSourceApp, + gui::ISurfaceComposer::EventRegistration::modeChanged)); mLooper = new Looper(false); mLooper->addFd(mReceiver->getFd(), 0, ALOOPER_EVENT_INPUT, processDisplayEvents, this); } diff --git a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp index c033af8645..7ee04b0466 100644 --- a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp +++ b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp @@ -72,7 +72,7 @@ protected: public: MockEventThreadConnection(impl::EventThread* eventThread, uid_t callingUid, ResyncCallback&& resyncCallback, - ISurfaceComposer::EventRegistrationFlags eventRegistration) + EventRegistrationFlags eventRegistration) : EventThreadConnection(eventThread, callingUid, std::move(resyncCallback), eventRegistration) {} MOCK_METHOD1(postEvent, status_t(const DisplayEventReceiver::Event& event)); @@ -85,10 +85,9 @@ protected: ~EventThreadTest() override; void createThread(std::unique_ptr); - sp createConnection( - ConnectionEventRecorder& recorder, - ISurfaceComposer::EventRegistrationFlags eventRegistration = {}, - uid_t ownerUid = mConnectionUid); + sp createConnection(ConnectionEventRecorder& recorder, + EventRegistrationFlags eventRegistration = {}, + uid_t ownerUid = mConnectionUid); void expectVSyncSetEnabledCallReceived(bool expectedState); void expectVSyncSetDurationCallReceived(std::chrono::nanoseconds expectedDuration, @@ -149,11 +148,12 @@ EventThreadTest::EventThreadTest() { .WillRepeatedly(Invoke(mVSyncSetDurationCallRecorder.getInvocable())); createThread(std::move(vsyncSource)); - mConnection = createConnection(mConnectionEventCallRecorder, - ISurfaceComposer::EventRegistration::modeChanged | - ISurfaceComposer::EventRegistration::frameRateOverride); + mConnection = + createConnection(mConnectionEventCallRecorder, + gui::ISurfaceComposer::EventRegistration::modeChanged | + gui::ISurfaceComposer::EventRegistration::frameRateOverride); mThrottledConnection = createConnection(mThrottledConnectionEventCallRecorder, - ISurfaceComposer::EventRegistration::modeChanged, + gui::ISurfaceComposer::EventRegistration::modeChanged, mThrottledConnectionUid); // A display must be connected for VSYNC events to be delivered. @@ -190,8 +190,8 @@ void EventThreadTest::createThread(std::unique_ptr source) { } sp EventThreadTest::createConnection( - ConnectionEventRecorder& recorder, - ISurfaceComposer::EventRegistrationFlags eventRegistration, uid_t ownerUid) { + ConnectionEventRecorder& recorder, EventRegistrationFlags eventRegistration, + uid_t ownerUid) { sp connection = new MockEventThreadConnection(mThread.get(), ownerUid, mResyncCallRecorder.getInvocable(), eventRegistration); diff --git a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h index c5ca86a651..d30dc42cbb 100644 --- a/services/surfaceflinger/tests/unittests/mock/MockEventThread.h +++ b/services/surfaceflinger/tests/unittests/mock/MockEventThread.h @@ -28,8 +28,7 @@ public: ~EventThread() override; MOCK_CONST_METHOD2(createEventConnection, - sp(ResyncCallback, - ISurfaceComposer::EventRegistrationFlags)); + sp(ResyncCallback, EventRegistrationFlags)); MOCK_METHOD0(onScreenReleased, void()); MOCK_METHOD0(onScreenAcquired, void()); MOCK_METHOD2(onHotplugReceived, void(PhysicalDisplayId, bool)); -- cgit v1.2.3-59-g8ed1b From ab8ffef9fe8845e72d19bd728da5266398cba002 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Thu, 18 Aug 2022 13:02:26 -0700 Subject: Remove SurfaceInterceptor and surfacereplayer Both are no longer used and thus obsolete. Ignore-AOSP-First: depends on other changes on master Bug: 241285477 Test: atest libgui_test libsurfaceflinger_unittest SurfaceFlinger_test Change-Id: I1858826b9eca27b355edb4236510e3aad1ddb399 --- cmds/surfacereplayer/Android.bp | 13 - cmds/surfacereplayer/OWNERS | 1 - cmds/surfacereplayer/proto/Android.bp | 23 - cmds/surfacereplayer/proto/src/trace.proto | 225 ----- cmds/surfacereplayer/replayer/Android.bp | 71 -- .../replayer/BufferQueueScheduler.cpp | 109 --- .../replayer/BufferQueueScheduler.h | 82 -- cmds/surfacereplayer/replayer/Color.h | 124 --- cmds/surfacereplayer/replayer/Event.cpp | 51 -- cmds/surfacereplayer/replayer/Event.h | 57 -- cmds/surfacereplayer/replayer/Main.cpp | 116 --- cmds/surfacereplayer/replayer/README.md | 262 ------ cmds/surfacereplayer/replayer/Replayer.h | 170 ---- .../replayer/trace_creator/trace_creator.py | 285 ------ libs/gui/Android.bp | 1 - libs/gui/ISurfaceComposer.cpp | 1 - libs/gui/TransactionTracing.cpp | 53 -- libs/gui/aidl/android/gui/ISurfaceComposer.aidl | 6 - .../android/gui/ITransactionTraceListener.aidl | 6 - libs/gui/fuzzer/libgui_fuzzer_utils.h | 2 - libs/gui/include/gui/ISurfaceComposer.h | 1 - libs/gui/include/gui/TransactionTracing.h | 41 - libs/gui/tests/Surface_test.cpp | 5 - services/surfaceflinger/Android.bp | 3 - .../surfaceflinger/CompositionEngine/Android.bp | 1 - services/surfaceflinger/Layer.h | 6 - services/surfaceflinger/Scheduler/EventThread.cpp | 25 +- services/surfaceflinger/Scheduler/EventThread.h | 6 +- services/surfaceflinger/Scheduler/Scheduler.cpp | 10 +- services/surfaceflinger/Scheduler/Scheduler.h | 3 +- services/surfaceflinger/SurfaceFlinger.cpp | 61 +- services/surfaceflinger/SurfaceFlinger.h | 5 - .../SurfaceFlingerDefaultFactory.cpp | 5 - .../surfaceflinger/SurfaceFlingerDefaultFactory.h | 1 - services/surfaceflinger/SurfaceFlingerFactory.h | 2 - services/surfaceflinger/SurfaceInterceptor.cpp | 711 --------------- services/surfaceflinger/SurfaceInterceptor.h | 211 ----- .../Tracing/tools/LayerTraceGenerator.cpp | 4 - .../fuzzer/surfaceflinger_fuzzers_utils.h | 9 - .../fuzzer/surfaceflinger_scheduler_fuzzer.cpp | 2 +- services/surfaceflinger/tests/Android.bp | 2 - .../tests/SurfaceInterceptor_test.cpp | 961 --------------------- services/surfaceflinger/tests/fakehwc/Android.bp | 1 - services/surfaceflinger/tests/unittests/Android.bp | 2 - .../tests/unittests/DisplayTransactionTest.cpp | 1 - .../unittests/DisplayTransactionTestHelpers.h | 2 - .../tests/unittests/EventThreadTest.cpp | 69 +- .../unittests/SurfaceFlinger_CreateDisplayTest.cpp | 6 - .../SurfaceFlinger_DestroyDisplayTest.cpp | 3 - ...SurfaceFlinger_DisplayTransactionCommitTest.cpp | 3 - .../SurfaceFlinger_OnInitializeDisplaysTest.cpp | 5 - .../SurfaceFlinger_SetPowerModeInternalTest.cpp | 8 - .../tests/unittests/TestableSurfaceFlinger.h | 7 - .../unittests/mock/MockSurfaceInterceptor.cpp | 32 - .../tests/unittests/mock/MockSurfaceInterceptor.h | 50 -- 55 files changed, 37 insertions(+), 3885 deletions(-) delete mode 100644 cmds/surfacereplayer/Android.bp delete mode 100644 cmds/surfacereplayer/OWNERS delete mode 100644 cmds/surfacereplayer/proto/Android.bp delete mode 100644 cmds/surfacereplayer/proto/src/trace.proto delete mode 100644 cmds/surfacereplayer/replayer/Android.bp delete mode 100644 cmds/surfacereplayer/replayer/BufferQueueScheduler.cpp delete mode 100644 cmds/surfacereplayer/replayer/BufferQueueScheduler.h delete mode 100644 cmds/surfacereplayer/replayer/Color.h delete mode 100644 cmds/surfacereplayer/replayer/Event.cpp delete mode 100644 cmds/surfacereplayer/replayer/Event.h delete mode 100644 cmds/surfacereplayer/replayer/Main.cpp delete mode 100644 cmds/surfacereplayer/replayer/README.md delete mode 100644 cmds/surfacereplayer/replayer/Replayer.h delete mode 100644 cmds/surfacereplayer/replayer/trace_creator/trace_creator.py delete mode 100644 libs/gui/TransactionTracing.cpp delete mode 100644 libs/gui/aidl/android/gui/ITransactionTraceListener.aidl delete mode 100644 libs/gui/include/gui/TransactionTracing.h delete mode 100644 services/surfaceflinger/SurfaceInterceptor.cpp delete mode 100644 services/surfaceflinger/SurfaceInterceptor.h delete mode 100644 services/surfaceflinger/tests/SurfaceInterceptor_test.cpp delete mode 100644 services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.cpp delete mode 100644 services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/cmds/surfacereplayer/Android.bp b/cmds/surfacereplayer/Android.bp deleted file mode 100644 index 34fc8b10ea..0000000000 --- a/cmds/surfacereplayer/Android.bp +++ /dev/null @@ -1,13 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -subdirs = [ - "proto", - "replayer", -] diff --git a/cmds/surfacereplayer/OWNERS b/cmds/surfacereplayer/OWNERS deleted file mode 100644 index 32bcc83468..0000000000 --- a/cmds/surfacereplayer/OWNERS +++ /dev/null @@ -1 +0,0 @@ -include platform/frameworks/native:/services/surfaceflinger/OWNERS diff --git a/cmds/surfacereplayer/proto/Android.bp b/cmds/surfacereplayer/proto/Android.bp deleted file mode 100644 index 23b54ee5b0..0000000000 --- a/cmds/surfacereplayer/proto/Android.bp +++ /dev/null @@ -1,23 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_static { - name: "libtrace_proto", - srcs: [ - "src/trace.proto", - ], - cflags: [ - "-Wall", - "-Werror", - ], - proto: { - type: "lite", - export_proto_headers: true, - }, -} diff --git a/cmds/surfacereplayer/proto/src/trace.proto b/cmds/surfacereplayer/proto/src/trace.proto deleted file mode 100644 index a177027e5c..0000000000 --- a/cmds/surfacereplayer/proto/src/trace.proto +++ /dev/null @@ -1,225 +0,0 @@ -syntax = "proto2"; -option optimize_for = LITE_RUNTIME; -package android.surfaceflinger; - -message Trace { - repeated Increment increment = 1; -} - -message Increment { - required int64 time_stamp = 1; - - oneof increment { - Transaction transaction = 2; - SurfaceCreation surface_creation = 3; - SurfaceDeletion surface_deletion = 4; - BufferUpdate buffer_update = 5; - VSyncEvent vsync_event = 6; - DisplayCreation display_creation = 7; - DisplayDeletion display_deletion = 8; - PowerModeUpdate power_mode_update = 9; - } -} - -message Transaction { - repeated SurfaceChange surface_change = 1; - repeated DisplayChange display_change = 2; - - required bool synchronous = 3; - required bool animation = 4; - optional Origin origin = 5; - optional uint64 id = 6; -} - -message SurfaceChange { - required int32 id = 1; - reserved 7; - oneof SurfaceChange { - PositionChange position = 2; - SizeChange size = 3; - AlphaChange alpha = 4; - LayerChange layer = 5; - CropChange crop = 6; - MatrixChange matrix = 8; - TransparentRegionHintChange transparent_region_hint = 10; - LayerStackChange layer_stack = 11; - HiddenFlagChange hidden_flag = 12; - OpaqueFlagChange opaque_flag = 13; - SecureFlagChange secure_flag = 14; - CornerRadiusChange corner_radius = 16; - ReparentChange reparent = 17; - RelativeParentChange relative_parent = 18; - BackgroundBlurRadiusChange background_blur_radius = 20; - ShadowRadiusChange shadow_radius = 21; - BlurRegionsChange blur_regions = 22; - TrustedOverlayChange trusted_overlay = 23; - } -} - -message PositionChange { - required float x = 1; - required float y = 2; -} - -message SizeChange { - required uint32 w = 1; - required uint32 h = 2; -} - -message AlphaChange { - required float alpha = 1; -} - -message CornerRadiusChange { - required float corner_radius = 1; -} - -message BackgroundBlurRadiusChange { - required float background_blur_radius = 1; -} - -message LayerChange { - required uint32 layer = 1; -} - -message CropChange { - required Rectangle rectangle = 1; -} - -message MatrixChange { - required float dsdx = 1; - required float dtdx = 2; - required float dsdy = 3; - required float dtdy = 4; -} - -message TransparentRegionHintChange { - repeated Rectangle region = 1; -} - -message LayerStackChange { - required uint32 layer_stack = 1; -} - -message DisplayFlagsChange { - required uint32 flags = 1; -} - -message HiddenFlagChange { - required bool hidden_flag = 1; -} - -message OpaqueFlagChange { - required bool opaque_flag = 1; -} - -message SecureFlagChange { - required bool secure_flag = 1; -} - -message DisplayChange { - required int32 id = 1; - - oneof DisplayChange { - DispSurfaceChange surface = 2; - LayerStackChange layer_stack = 3; - SizeChange size = 4; - ProjectionChange projection = 5; - DisplayFlagsChange flags = 6; - } -} - -message DispSurfaceChange { - required uint64 buffer_queue_id = 1; - required string buffer_queue_name = 2; -} - -message ProjectionChange { - required int32 orientation = 1; - required Rectangle viewport = 2; - required Rectangle frame = 3; -} - -message Rectangle { - required int32 left = 1; - required int32 top = 2; - required int32 right = 3; - required int32 bottom = 4; -} - -message SurfaceCreation { - required int32 id = 1; - required string name = 2; - required uint32 w = 3; - required uint32 h = 4; -} - -message SurfaceDeletion { - required int32 id = 1; -} - -message BufferUpdate { - required int32 id = 1; - required uint32 w = 2; - required uint32 h = 3; - required uint64 frame_number = 4; -} - -message VSyncEvent { - required int64 when = 1; -} - -message DisplayCreation { - required int32 id = 1; - required string name = 2; - optional uint64 display_id = 3; - required bool is_secure = 4; -} - -message DisplayDeletion { - required int32 id = 1; -} - -message PowerModeUpdate { - required int32 id = 1; - required int32 mode = 2; -} - -message ReparentChange { - required int32 parent_id = 1; -} - -message RelativeParentChange { - required int32 relative_parent_id = 1; - required int32 z = 2; -} - -message ShadowRadiusChange { - required float radius = 1; -} - -message TrustedOverlayChange { - required float is_trusted_overlay = 1; -} - -message BlurRegionsChange { - repeated BlurRegionChange blur_regions = 1; -} - -message BlurRegionChange { - required uint32 blur_radius = 1; - required float corner_radius_tl = 2; - required float corner_radius_tr = 3; - required float corner_radius_bl = 4; - required float corner_radius_br = 5; - required float alpha = 6; - required int32 left = 7; - required int32 top = 8; - required int32 right = 9; - required int32 bottom = 10; -} - -message Origin { - required int32 pid = 1; - required int32 uid = 2; -} diff --git a/cmds/surfacereplayer/replayer/Android.bp b/cmds/surfacereplayer/replayer/Android.bp deleted file mode 100644 index 3985230f08..0000000000 --- a/cmds/surfacereplayer/replayer/Android.bp +++ /dev/null @@ -1,71 +0,0 @@ -package { - // See: http://go/android-license-faq - // A large-scale-change added 'default_applicable_licenses' to import - // all of the 'license_kinds' from "frameworks_native_license" - // to get the below license kinds: - // SPDX-license-identifier-Apache-2.0 - default_applicable_licenses: ["frameworks_native_license"], -} - -cc_library_shared { - name: "libsurfacereplayer", - srcs: [ - "BufferQueueScheduler.cpp", - "Event.cpp", - "Replayer.cpp", - ], - cppflags: [ - "-Werror", - "-Wno-unused-parameter", - "-Wno-format", - "-Wno-c++98-compat-pedantic", - "-Wno-float-conversion", - "-Wno-disabled-macro-expansion", - "-Wno-float-equal", - "-Wno-sign-conversion", - "-Wno-padded", - ], - static_libs: [ - "libtrace_proto", - ], - shared_libs: [ - "libEGL", - "libGLESv2", - "libbinder", - "liblog", - "libcutils", - "libgui", - "libui", - "libutils", - "libprotobuf-cpp-lite", - "libbase", - "libnativewindow", - ], - export_include_dirs: [ - ".", - ], -} - -cc_binary { - name: "surfacereplayer", - srcs: [ - "Main.cpp", - ], - shared_libs: [ - "libprotobuf-cpp-lite", - "libsurfacereplayer", - "libutils", - "libgui", - ], - static_libs: [ - "libtrace_proto", - ], - cppflags: [ - "-Werror", - "-Wno-unused-parameter", - "-Wno-c++98-compat-pedantic", - "-Wno-float-conversion", - "-Wno-disabled-macro-expansion", - "-Wno-float-equal", - ], -} diff --git a/cmds/surfacereplayer/replayer/BufferQueueScheduler.cpp b/cmds/surfacereplayer/replayer/BufferQueueScheduler.cpp deleted file mode 100644 index 77de8dc44c..0000000000 --- a/cmds/surfacereplayer/replayer/BufferQueueScheduler.cpp +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#define LOG_TAG "BufferQueueScheduler" - -#include "BufferQueueScheduler.h" - -#include -#include - -using namespace android; - -BufferQueueScheduler::BufferQueueScheduler( - const sp& surfaceControl, const HSV& color, int id) - : mSurfaceControl(surfaceControl), mColor(color), mSurfaceId(id), mContinueScheduling(true) {} - -void BufferQueueScheduler::startScheduling() { - ALOGV("Starting Scheduler for %d Layer", mSurfaceId); - std::unique_lock lock(mMutex); - if (mSurfaceControl == nullptr) { - mCondition.wait(lock, [&] { return (mSurfaceControl != nullptr); }); - } - - while (mContinueScheduling) { - while (true) { - if (mBufferEvents.empty()) { - break; - } - - BufferEvent event = mBufferEvents.front(); - lock.unlock(); - - bufferUpdate(event.dimensions); - fillSurface(event.event); - mColor.modulate(); - lock.lock(); - mBufferEvents.pop(); - } - mCondition.wait(lock); - } -} - -void BufferQueueScheduler::addEvent(const BufferEvent& event) { - std::lock_guard lock(mMutex); - mBufferEvents.push(event); - mCondition.notify_one(); -} - -void BufferQueueScheduler::stopScheduling() { - std::lock_guard lock(mMutex); - mContinueScheduling = false; - mCondition.notify_one(); -} - -void BufferQueueScheduler::setSurfaceControl( - const sp& surfaceControl, const HSV& color) { - std::lock_guard lock(mMutex); - mSurfaceControl = surfaceControl; - mColor = color; - mCondition.notify_one(); -} - -void BufferQueueScheduler::bufferUpdate(const Dimensions& dimensions) { - sp s = mSurfaceControl->getSurface(); - s->setBuffersDimensions(dimensions.width, dimensions.height); -} - -void BufferQueueScheduler::fillSurface(const std::shared_ptr& event) { - ANativeWindow_Buffer outBuffer; - sp s = mSurfaceControl->getSurface(); - - status_t status = s->lock(&outBuffer, nullptr); - - if (status != NO_ERROR) { - ALOGE("fillSurface: failed to lock buffer, (%d)", status); - return; - } - - auto color = mColor.getRGB(); - - auto img = reinterpret_cast(outBuffer.bits); - for (int y = 0; y < outBuffer.height; y++) { - for (int x = 0; x < outBuffer.width; x++) { - uint8_t* pixel = img + (4 * (y * outBuffer.stride + x)); - pixel[0] = color.r; - pixel[1] = color.g; - pixel[2] = color.b; - pixel[3] = LAYER_ALPHA; - } - } - - event->readyToExecute(); - - status = s->unlockAndPost(); - - ALOGE_IF(status != NO_ERROR, "fillSurface: failed to unlock and post buffer, (%d)", status); -} diff --git a/cmds/surfacereplayer/replayer/BufferQueueScheduler.h b/cmds/surfacereplayer/replayer/BufferQueueScheduler.h deleted file mode 100644 index cb20fcc798..0000000000 --- a/cmds/surfacereplayer/replayer/BufferQueueScheduler.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_SURFACEREPLAYER_BUFFERQUEUESCHEDULER_H -#define ANDROID_SURFACEREPLAYER_BUFFERQUEUESCHEDULER_H - -#include "Color.h" -#include "Event.h" - -#include - -#include - -#include -#include -#include -#include -#include - -namespace android { - -auto constexpr LAYER_ALPHA = 190; - -struct Dimensions { - Dimensions() = default; - Dimensions(int w, int h) : width(w), height(h) {} - - int width = 0; - int height = 0; -}; - -struct BufferEvent { - BufferEvent() = default; - BufferEvent(std::shared_ptr e, Dimensions d) : event(e), dimensions(d) {} - - std::shared_ptr event; - Dimensions dimensions; -}; - -class BufferQueueScheduler { - public: - BufferQueueScheduler(const sp& surfaceControl, const HSV& color, int id); - - void startScheduling(); - void addEvent(const BufferEvent&); - void stopScheduling(); - - void setSurfaceControl(const sp& surfaceControl, const HSV& color); - - private: - void bufferUpdate(const Dimensions& dimensions); - - // Lock and fill the surface, block until the event is signaled by the main loop, - // then unlock and post the buffer. - void fillSurface(const std::shared_ptr& event); - - sp mSurfaceControl; - HSV mColor; - const int mSurfaceId; - - bool mContinueScheduling; - - std::queue mBufferEvents; - std::mutex mMutex; - std::condition_variable mCondition; -}; - -} // namespace android -#endif diff --git a/cmds/surfacereplayer/replayer/Color.h b/cmds/surfacereplayer/replayer/Color.h deleted file mode 100644 index ce644be7be..0000000000 --- a/cmds/surfacereplayer/replayer/Color.h +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_SURFACEREPLAYER_COLOR_H -#define ANDROID_SURFACEREPLAYER_COLOR_H - -#include -#include - -namespace android { - -constexpr double modulateFactor = .0001; -constexpr double modulateLimit = .80; - -struct RGB { - RGB(uint8_t rIn, uint8_t gIn, uint8_t bIn) : r(rIn), g(gIn), b(bIn) {} - - uint8_t r = 0; - uint8_t g = 0; - uint8_t b = 0; -}; - -struct HSV { - HSV() = default; - HSV(double hIn, double sIn, double vIn) : h(hIn), s(sIn), v(vIn) {} - - double h = 0; - double s = 0; - double v = 0; - - RGB getRGB() const; - - bool modulateUp = false; - - void modulate(); -}; - -void inline HSV::modulate() { - if(modulateUp) { - v += modulateFactor; - } else { - v -= modulateFactor; - } - - if(v <= modulateLimit || v >= 1) { - modulateUp = !modulateUp; - } -} - -inline RGB HSV::getRGB() const { - using namespace std; - double r = 0, g = 0, b = 0; - - if (s == 0) { - r = v; - g = v; - b = v; - } else { - auto tempHue = static_cast(h) % 360; - tempHue = tempHue / 60; - - int i = static_cast(trunc(tempHue)); - double f = h - i; - - double x = v * (1.0 - s); - double y = v * (1.0 - (s * f)); - double z = v * (1.0 - (s * (1.0 - f))); - - switch (i) { - case 0: - r = v; - g = z; - b = x; - break; - - case 1: - r = y; - g = v; - b = x; - break; - - case 2: - r = x; - g = v; - b = z; - break; - - case 3: - r = x; - g = y; - b = v; - break; - - case 4: - r = z; - g = x; - b = v; - break; - - default: - r = v; - g = x; - b = y; - break; - } - } - - return RGB(round(r * 255), round(g * 255), round(b * 255)); -} -} -#endif diff --git a/cmds/surfacereplayer/replayer/Event.cpp b/cmds/surfacereplayer/replayer/Event.cpp deleted file mode 100644 index 64db5f07b1..0000000000 --- a/cmds/surfacereplayer/replayer/Event.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "Event.h" - -using namespace android; -using Increment = surfaceflinger::Increment; - -Event::Event(Increment::IncrementCase type) : mIncrementType(type) {} - -void Event::readyToExecute() { - changeState(Event::EventState::Waiting); - waitUntil(Event::EventState::Signaled); - changeState(Event::EventState::Running); -} - -void Event::complete() { - waitUntil(Event::EventState::Waiting); - changeState(Event::EventState::Signaled); - waitUntil(Event::EventState::Running); -} - -void Event::waitUntil(Event::EventState state) { - std::unique_lock lock(mLock); - mCond.wait(lock, [this, state] { return (mState == state); }); -} - -void Event::changeState(Event::EventState state) { - std::unique_lock lock(mLock); - mState = state; - lock.unlock(); - - mCond.notify_one(); -} - -Increment::IncrementCase Event::getIncrementType() { - return mIncrementType; -} diff --git a/cmds/surfacereplayer/replayer/Event.h b/cmds/surfacereplayer/replayer/Event.h deleted file mode 100644 index 09a7c248d5..0000000000 --- a/cmds/surfacereplayer/replayer/Event.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_SURFACEREPLAYER_EVENT_H -#define ANDROID_SURFACEREPLAYER_EVENT_H - -#include - -#include -#include - -namespace android { - -using Increment = surfaceflinger::Increment; - -class Event { - public: - Event(Increment::IncrementCase); - - enum class EventState { - SettingUp, // Completing as much time-independent work as possible - Waiting, // Waiting for signal from main thread to finish execution - Signaled, // Signaled by main thread, about to immediately switch to Running - Running // Finishing execution of rest of work - }; - - void readyToExecute(); - void complete(); - - Increment::IncrementCase getIncrementType(); - - private: - void waitUntil(EventState state); - void changeState(EventState state); - - std::mutex mLock; - std::condition_variable mCond; - - EventState mState = EventState::SettingUp; - - Increment::IncrementCase mIncrementType; -}; -} -#endif diff --git a/cmds/surfacereplayer/replayer/Main.cpp b/cmds/surfacereplayer/replayer/Main.cpp deleted file mode 100644 index fbfcacf1aa..0000000000 --- a/cmds/surfacereplayer/replayer/Main.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - * Replayer - Main.cpp - * - * 1. Get flags from command line - * 2. Commit actions or settings based on the flags - * 3. Initalize a replayer object with the filename passed in - * 4. Replay - * 5. Exit successfully or print error statement - */ - -#include - -#include -#include -#include -#include - -using namespace android; - -void printHelpMenu() { - std::cout << "SurfaceReplayer options:\n"; - std::cout << "Usage: surfacereplayer [OPTIONS...] \n"; - std::cout << " File path must be absolute" << std::endl << std::endl; - - std::cout << " -m Stops the replayer at the start of the trace and switches "; - "to manual replay\n"; - - std::cout << "\n -t [Number of Threads] Specifies the number of threads to be used while " - "replaying (default is " << android::DEFAULT_THREADS << ")\n"; - - std::cout << "\n -s [Timestamp] Specify at what timestamp should the replayer switch " - "to manual replay\n"; - - std::cout << " -n Ignore timestamps and run through trace as fast as possible\n"; - - std::cout << " -l Indefinitely loop the replayer\n"; - - std::cout << " -h Display help menu\n"; - - std::cout << std::endl; -} - -int main(int argc, char** argv) { - std::string filename; - bool loop = false; - bool wait = true; - bool pauseBeginning = false; - int numThreads = DEFAULT_THREADS; - long stopHere = -1; - - int opt = 0; - while ((opt = getopt(argc, argv, "mt:s:nlh?")) != -1) { - switch (opt) { - case 'm': - pauseBeginning = true; - break; - case 't': - numThreads = atoi(optarg); - break; - case 's': - stopHere = atol(optarg); - break; - case 'n': - wait = false; - break; - case 'l': - loop = true; - break; - case 'h': - case '?': - printHelpMenu(); - exit(0); - default: - std::cerr << "Invalid argument...exiting" << std::endl; - printHelpMenu(); - exit(0); - } - } - - char** input = argv + optind; - if (input[0] == nullptr) { - std::cerr << "No trace file provided...exiting" << std::endl; - abort(); - } - filename.assign(input[0]); - - status_t status = NO_ERROR; - do { - android::Replayer r(filename, pauseBeginning, numThreads, wait, stopHere); - status = r.replay(); - } while(loop); - - if (status == NO_ERROR) { - std::cout << "Successfully finished replaying trace" << std::endl; - } else { - std::cerr << "Trace replayer returned error: " << status << std::endl; - } - - return 0; -} diff --git a/cmds/surfacereplayer/replayer/README.md b/cmds/surfacereplayer/replayer/README.md deleted file mode 100644 index 893f0dc0f6..0000000000 --- a/cmds/surfacereplayer/replayer/README.md +++ /dev/null @@ -1,262 +0,0 @@ -SurfaceReplayer Documentation -=================== - -[go/SurfaceReplayer](go/SurfaceReplayer) - -SurfaceReplayer is a playback mechanism that allows the replaying of traces recorded by -[SurfaceInterceptor](go/SurfaceInterceptor) from SurfaceFlinger. It specifically replays - -* Creation and deletion of surfaces/displays -* Alterations to the surfaces/displays called Transactions -* Buffer Updates to surfaces -* VSync events - -At their specified times to be as close to the original trace. - -Usage --------- - -###Creating a trace - -SurfaceInterceptor is the mechanism used to create traces. The device needs to be rooted in order to -utilize it. To allow it to write to the device, run - -`setenforce 0` - -To start recording a trace, run - -`service call SurfaceFlinger 1020 i32 1` - -To stop recording, run - -`service call SurfaceFlinger 1020 i32 0` - -The default location for the trace is `/data/SurfaceTrace.dat` - -###Executable - -To replay a specific trace, execute - -`/data/local/tmp/surfacereplayer /absolute/path/to/trace` - -inside the android shell. This will replay the full trace and then exit. Running this command -outside of the shell by prepending `adb shell` will not allow for manual control and will not turn -off VSync injections if it interrupted in any way other than fully replaying the trace - -The replay will not fill surfaces with their contents during the capture. Rather they are given a -random color which will be the same every time the trace is replayed. Surfaces modulate their color -at buffer updates. - -**Options:** - -- -m pause the replayer at the start of the trace for manual replay -- -t [Number of Threads] uses specified number of threads to queue up actions (default is 3) -- -s [Timestamp] switches to manual replay at specified timestamp -- -n Ignore timestamps and run through trace as fast as possible -- -l Indefinitely loop the replayer -- -h displays help menu - -**Manual Replay:** -When replaying, if the user presses CTRL-C, the replay will stop and can be manually controlled -by the user. Pressing CTRL-C again will exit the replayer. - -Manual replaying is similar to debugging in gdb. A prompt is presented and the user is able to -input commands to choose how to proceed by hitting enter after inputting a command. Pressing enter -without inputting a command repeats the previous command. - -- n - steps the replayer to the next VSync event -- ni - steps the replayer to the next increment -- c - continues normal replaying -- c [milliseconds] - continue until specified number of milliseconds have passed -- s [timestamp] - continue and stop at specified timestamp -- l - list out timestamp of current increment -- h - displays help menu - -###Shared Library - -To use the shared library include these shared libraries - -`libsurfacereplayer` -`libprotobuf-cpp-full` -`libutils` - -And the static library - -`libtrace_proto` - -Include the replayer header at the top of your file - -`#include ` - -There are two constructors for the replayer - -`Replayer(std::string& filename, bool replayManually, int numThreads, bool wait, nsecs_t stopHere)` -`Replayer(Trace& trace, ... ditto ...)` - -The first constructor takes in the filepath where the trace is located and loads in the trace -object internally. -- replayManually - **True**: if the replayer will immediately switch to manual replay at the start -- numThreads - Number of worker threads the replayer will use. -- wait - **False**: Replayer ignores waits in between increments -- stopHere - Time stamp of where the replayer should run to then switch to manual replay - -The second constructor includes all of the same parameters but takes in a preloaded trace object. -To use add - -`#include ` - -To your file - -After initializing the Replayer call - - replayer.replay(); - -And the trace will start replaying. Once the trace is finished replaying, the function will return. -The layers that are visible at the end of the trace will remain on screen until the program -terminates. - - -**If VSyncs are broken after running the replayer** that means `enableVSyncInjections(false)` was -never executed. This can be fixed by executing - -`service call SurfaceFlinger 23 i32 0` - -in the android shell - -Code Breakdown -------------- - -The Replayer is composed of 5 components. - -- The data format of the trace (Trace.proto) -- The Replayer object (Replayer.cpp) -- The synchronization mechanism to signal threads within the Replayer (Event.cpp) -- The scheduler for buffer updates per surface (BufferQueueScheduler.cpp) -- The Main executable (Main.cpp) - -### Traces - -Traces are represented as a protobuf message located in surfacereplayer/proto/src. - -**Traces** contain *repeated* **Increments** (events that have occurred in SurfaceFlinger). -**Increments** contain the time stamp of when it occurred and a *oneof* which can be a - - - Transaction - - SurfaceCreation - - SurfaceDeletion - - DisplayCreation - - DisplayDeleteion - - BufferUpdate - - VSyncEvent - - PowerModeUpdate - -**Transactions** contain whether the transaction was synchronous or animated and *repeated* -**SurfaceChanges** and **DisplayChanges** - -- **SurfaceChanges** contain an id of the surface being manipulated and can be changes such as -position, alpha, hidden, size, etc. -- **DisplayChanges** contain the id of the display being manipulated and can be changes such as -size, layer stack, projection, etc. - -**Surface/Display Creation** contain the id of the surface/display and the name of the -surface/display - -**Surface/Display Deletion** contain the id of the surface/display to be deleted - -**Buffer Updates** contain the id of the surface who's buffer is being updated, the size of the -buffer, and the frame number. - -**VSyncEvents** contain when the VSync event has occurred. - -**PowerModeUpdates** contain the id of the display being updated and what mode it is being -changed to. - -To output the contents of a trace in a readable format, execute - -`**aprotoc** --decode=Trace \ --I=$ANDROID_BUILD_TOP/frameworks/native/cmds/surfacereplayer/proto/src \ -$ANDROID_BUILD_TOP/frameworks/native/cmds/surfacereplayer/proto/src/trace.proto \ - < **YourTraceFile.dat** > **YourOutputName.txt**` - - -###Replayer - -Fundamentally the replayer loads a trace and iterates through each increment, waiting the required -amount of time until the increment should be executed, then executing the increment. The first -increment in a trace does not start at 0, rather the replayer treats its time stamp as time 0 and -goes from there. - -Increments from the trace are played asynchronously rather than one by one, being dispatched by -the main thread, queued up in a thread pool and completed when the main thread deems they are -ready to finish execution. - -When an increment is dispatched, it completes as much work as it can before it has to be -synchronized (e.g. prebaking a buffer for a BufferUpdate). When it gets to a critical action -(e.g. locking and pushing a buffer), it waits for the main thread to complete it using an Event -object. The main thread holds a queue of these Event objects and completes the -corresponding Event base on its time stamp. After completing an increment, the main thread will -dispatch another increment and continue. - -The main thread's execution flow is outlined below - - initReplay() //queue up the initial increments - while(!pendingIncrements.empty()) { //while increments remaining - event = pendingIncrement.pop(); - wait(event.time_stamp(); //waitUntil it is time to complete this increment - - event.complete() //signal to let event finish - if(increments remaing()) { - dispatchEvent() //queue up another increment - } - } - -A worker thread's flow looks like so - - //dispatched! - Execute non-time sensitive work here - ... - event.readyToExecute() //time sensitive point...waiting for Main Thread - ... - Finish execution - - -### Event - -An Event is a simple synchronization mechanism used to facilitate communication between the main -and worker threads. Every time an increment is dispatched, an Event object is also created. - -An Event can be in 4 different states: - -- **SettingUp** - The worker is in the process of completing all non-time sensitive work -- **Waiting** - The worker is waiting on the main thread to signal it. -- **Signaled** - The worker has just been signaled by the main thread -- **Running** - The worker is running again and finishing the rest of its work. - -When the main thread wants to finish the execution of a worker, the worker can either still be -**SettingUp**, in which the main thread will wait, or the worker will be **Waiting**, in which the -main thread will **Signal** it to complete. The worker thread changes itself to the **Running** -state once **Signaled**. This last step exists in order to communicate back to the main thread that -the worker thread has actually started completing its execution, rather than being preempted right -after signalling. Once this happens, the main thread schedules the next worker. This makes sure -there is a constant amount of workers running at one time. - -This activity is encapsulated in the `readyToExecute()` and `complete()` functions called by the -worker and main thread respectively. - -### BufferQueueScheduler - -During a **BuferUpdate**, the worker thread will wait until **Signaled** to unlock and post a -buffer that has been prefilled during the **SettingUp** phase. However if there are two sequential -**BufferUpdates** that act on the same surface, both threads will try to lock a buffer and fill it, -which isn't possible and will cause a deadlock. The BufferQueueScheduler solves this problem by -handling when **BufferUpdates** should be scheduled, making sure that they don't overlap. - -When a surface is created, a BufferQueueScheduler is also created along side it. Whenever a -**BufferUpdate** is read, it schedules the event onto its own internal queue and then schedules one -every time an Event is completed. - -### Main - -The main exectuable reads in the command line arguments. Creates the Replayer using those -arguments. Executes `replay()` on the Replayer. If there are no errors while replaying it will exit -gracefully, if there are then it will report the error and then exit. diff --git a/cmds/surfacereplayer/replayer/Replayer.h b/cmds/surfacereplayer/replayer/Replayer.h deleted file mode 100644 index d62522a497..0000000000 --- a/cmds/surfacereplayer/replayer/Replayer.h +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_SURFACEREPLAYER_H -#define ANDROID_SURFACEREPLAYER_H - -#include "BufferQueueScheduler.h" -#include "Color.h" -#include "Event.h" - -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -using namespace android::surfaceflinger; - -namespace android { - -const auto DEFAULT_PATH = "/data/local/tmp/SurfaceTrace.dat"; -const auto RAND_COLOR_SEED = 700; -const auto DEFAULT_THREADS = 3; - -typedef int32_t layer_id; -typedef int32_t display_id; - -typedef google::protobuf::RepeatedPtrField SurfaceChanges; -typedef google::protobuf::RepeatedPtrField DisplayChanges; - -class Replayer { - public: - Replayer(const std::string& filename, bool replayManually = false, - int numThreads = DEFAULT_THREADS, bool wait = true, nsecs_t stopHere = -1); - Replayer(const Trace& trace, bool replayManually = false, int numThreads = DEFAULT_THREADS, - bool wait = true, nsecs_t stopHere = -1); - - status_t replay(); - - private: - status_t initReplay(); - - void waitForConsoleCommmand(); - static void stopAutoReplayHandler(int signal); - - status_t dispatchEvent(int index); - - status_t doTransaction(const Transaction& transaction, const std::shared_ptr& event); - status_t createSurfaceControl(const SurfaceCreation& create, - const std::shared_ptr& event); - status_t injectVSyncEvent(const VSyncEvent& vsyncEvent, const std::shared_ptr& event); - void createDisplay(const DisplayCreation& create, const std::shared_ptr& event); - void deleteDisplay(const DisplayDeletion& delete_, const std::shared_ptr& event); - void updatePowerMode(const PowerModeUpdate& update, const std::shared_ptr& event); - - status_t doSurfaceTransaction(SurfaceComposerClient::Transaction& transaction, - const SurfaceChanges& surfaceChange); - void doDisplayTransaction(SurfaceComposerClient::Transaction& transaction, - const DisplayChanges& displayChange); - - void setPosition(SurfaceComposerClient::Transaction& t, - layer_id id, const PositionChange& pc); - void setSize(SurfaceComposerClient::Transaction& t, - layer_id id, const SizeChange& sc); - void setAlpha(SurfaceComposerClient::Transaction& t, - layer_id id, const AlphaChange& ac); - void setLayer(SurfaceComposerClient::Transaction& t, - layer_id id, const LayerChange& lc); - void setCrop(SurfaceComposerClient::Transaction& t, - layer_id id, const CropChange& cc); - void setCornerRadius(SurfaceComposerClient::Transaction& t, - layer_id id, const CornerRadiusChange& cc); - void setBackgroundBlurRadius(SurfaceComposerClient::Transaction& t, - layer_id id, const BackgroundBlurRadiusChange& cc); - void setBlurRegions(SurfaceComposerClient::Transaction& t, - layer_id id, const BlurRegionsChange& cc); - void setMatrix(SurfaceComposerClient::Transaction& t, - layer_id id, const MatrixChange& mc); - void setTransparentRegionHint(SurfaceComposerClient::Transaction& t, - layer_id id, const TransparentRegionHintChange& trgc); - void setLayerStack(SurfaceComposerClient::Transaction& t, - layer_id id, const LayerStackChange& lsc); - void setHiddenFlag(SurfaceComposerClient::Transaction& t, - layer_id id, const HiddenFlagChange& hfc); - void setOpaqueFlag(SurfaceComposerClient::Transaction& t, - layer_id id, const OpaqueFlagChange& ofc); - void setSecureFlag(SurfaceComposerClient::Transaction& t, - layer_id id, const SecureFlagChange& sfc); - void setReparentChange(SurfaceComposerClient::Transaction& t, - layer_id id, const ReparentChange& c); - void setRelativeParentChange(SurfaceComposerClient::Transaction& t, - layer_id id, const RelativeParentChange& c); - void setShadowRadiusChange(SurfaceComposerClient::Transaction& t, - layer_id id, const ShadowRadiusChange& c); - void setBlurRegionsChange(SurfaceComposerClient::Transaction& t, - layer_id id, const BlurRegionsChange& c); - - void setDisplaySurface(SurfaceComposerClient::Transaction& t, - display_id id, const DispSurfaceChange& dsc); - void setDisplayLayerStack(SurfaceComposerClient::Transaction& t, - display_id id, const LayerStackChange& lsc); - void setDisplaySize(SurfaceComposerClient::Transaction& t, - display_id id, const SizeChange& sc); - void setDisplayProjection(SurfaceComposerClient::Transaction& t, - display_id id, const ProjectionChange& pc); - - void waitUntilTimestamp(int64_t timestamp); - status_t loadSurfaceComposerClient(); - - Trace mTrace; - bool mLoaded = false; - int32_t mIncrementIndex = 0; - int64_t mCurrentTime = 0; - int32_t mNumThreads = DEFAULT_THREADS; - - Increment mCurrentIncrement; - - std::string mLastInput; - - static atomic_bool sReplayingManually; - bool mWaitingForNextVSync; - bool mWaitForTimeStamps; - nsecs_t mStopTimeStamp; - bool mHasStopped; - - std::mutex mLayerLock; - std::condition_variable mLayerCond; - std::unordered_map> mLayers; - std::unordered_map mColors; - - std::mutex mPendingLayersLock; - std::vector mLayersPendingRemoval; - - std::mutex mBufferQueueSchedulerLock; - std::unordered_map> mBufferQueueSchedulers; - - std::mutex mDisplayLock; - std::condition_variable mDisplayCond; - std::unordered_map> mDisplays; - - sp mComposerClient; - std::queue> mPendingIncrements; -}; - -} // namespace android -#endif diff --git a/cmds/surfacereplayer/replayer/trace_creator/trace_creator.py b/cmds/surfacereplayer/replayer/trace_creator/trace_creator.py deleted file mode 100644 index 58bfbf3c43..0000000000 --- a/cmds/surfacereplayer/replayer/trace_creator/trace_creator.py +++ /dev/null @@ -1,285 +0,0 @@ -#!/usr/bin/python -from subprocess import call -import os -proto_path = os.environ['ANDROID_BUILD_TOP'] + "/frameworks/native/cmds/surfacereplayer/proto/src/" -call(["aprotoc", "-I=" + proto_path, "--python_out=.", proto_path + "trace.proto"]) - -from trace_pb2 import * - -trace = Trace() - -def main(): - global trace - while(1): - option = main_menu() - - if option == 0: - break - - increment = trace.increment.add() - increment.time_stamp = int(input("Time stamp of action: ")) - - if option == 1: - transaction(increment) - elif option == 2: - surface_create(increment) - elif option == 3: - surface_delete(increment) - elif option == 4: - display_create(increment) - elif option == 5: - display_delete(increment) - elif option == 6: - buffer_update(increment) - elif option == 7: - vsync_event(increment) - elif option == 8: - power_mode_update(increment) - - seralizeTrace() - -def seralizeTrace(): - with open("trace.dat", 'wb') as f: - f.write(trace.SerializeToString()) - - -def main_menu(): - print ("") - print ("What would you like to do?") - print ("1. Add transaction") - print ("2. Add surface creation") - print ("3. Add surface deletion") - print ("4. Add display creation") - print ("5. Add display deletion") - print ("6. Add buffer update") - print ("7. Add VSync event") - print ("8. Add power mode update") - print ("0. Finish and serialize") - print ("") - - return int(input("> ")) - -def transaction_menu(): - print ("") - print ("What kind of transaction?") - print ("1. Position Change") - print ("2. Size Change") - print ("3. Alpha Change") - print ("4. Layer Change") - print ("5. Crop Change") - print ("6. Final Crop Change") - print ("7. Matrix Change") - print ("9. Transparent Region Hint Change") - print ("10. Layer Stack Change") - print ("11. Hidden Flag Change") - print ("12. Opaque Flag Change") - print ("13. Secure Flag Change") - print ("14. Deferred Transaction Change") - print ("15. Display - Surface Change") - print ("16. Display - Layer Stack Change") - print ("17. Display - Size Change") - print ("18. Display - Projection Change") - print ("0. Finished adding Changes to this transaction") - print ("") - - return int(input("> ")) - -def transaction(increment): - global trace - - increment.transaction.synchronous \ - = bool(input("Is transaction synchronous (True/False): ")) - increment.transaction.animation \ - = bool(input("Is transaction animated (True/False): ")) - - while(1): - option = transaction_menu() - - if option == 0: - break - - change = None - if option <= 14: - change = increment.transaction.surface_change.add() - elif option >= 15 and option <= 18: - change = increment.transaction.display_change.add() - - change.id = int(input("ID of layer/display to undergo a change: ")) - - if option == 1: - change.position.x, change.position.y = position() - elif option == 2: - change.size.w, change.size.h = size() - elif option == 3: - change.alpha.alpha = alpha() - elif option == 4: - change.layer.layer = layer() - elif option == 5: - change.crop.rectangle.left, change.crop.rectangle.top, \ - change.crop.rectangle.right, change.crop.rectangle.bottom = crop() - elif option == 6: - change.final_crop.rectangle.left, \ - change.final_crop.rectangle.top, \ - change.final_crop.rectangle.right,\ - change.final_crop.rectangle.bottom = final_crop() - elif option == 7: - change.matrix.dsdx,\ - change.matrix.dtdx,\ - change.matrix.dsdy,\ - change.matrix.dtdy = layer() - elif option == 9: - for rect in transparent_region_hint(): - new = increment.transparent_region_hint.region.add() - new.left = rect[0] - new.top = rect[1] - new.right = rect[2] - new.bottom = rect[3] - elif option == 10: - change.layer_stack.layer_stack = layer_stack() - elif option == 11: - change.hidden_flag.hidden_flag = hidden_flag() - elif option == 12: - change.opaque_flag.opaque_flag = opaque_flag() - elif option == 13: - change.secure_flag.secure_flag = secure_flag() - elif option == 14: - change.deferred_transaction.layer_id, \ - change.deferred_transaction.frame_number = deferred_transaction() - elif option == 15: - change.surface.buffer_queue_id, \ - change.surface.buffer_queue_name = surface() - elif option == 16: - change.layer_stack.layer_stack = layer_stack() - elif option == 17: - change.size.w, change.size.h = size() - elif option == 18: - projection(change) - -def surface_create(increment): - increment.surface_creation.id = int(input("Enter id: ")) - n = str(raw_input("Enter name: ")) - increment.surface_creation.name = n - increment.surface_creation.w = input("Enter w: ") - increment.surface_creation.h = input("Enter h: ") - -def surface_delete(increment): - increment.surface_deletion.id = int(input("Enter id: ")) - -def display_create(increment): - increment.display_creation.id = int(input("Enter id: ")) - increment.display_creation.name = str(raw_input("Enter name: ")) - increment.display_creation.display_id = int(input("Enter display ID: ")) - increment.display_creation.is_secure = bool(input("Enter if secure: ")) - -def display_delete(increment): - increment.surface_deletion.id = int(input("Enter id: ")) - -def buffer_update(increment): - increment.buffer_update.id = int(input("Enter id: ")) - increment.buffer_update.w = int(input("Enter w: ")) - increment.buffer_update.h = int(input("Enter h: ")) - increment.buffer_update.frame_number = int(input("Enter frame_number: ")) - -def vsync_event(increment): - increment.vsync_event.when = int(input("Enter when: ")) - -def power_mode_update(increment): - increment.power_mode_update.id = int(input("Enter id: ")) - increment.power_mode_update.mode = int(input("Enter mode: ")) - -def position(): - x = input("Enter x: ") - y = input("Enter y: ") - - return float(x), float(y) - -def size(): - w = input("Enter w: ") - h = input("Enter h: ") - - return int(w), int(h) - -def alpha(): - alpha = input("Enter alpha: ") - - return float(alpha) - -def layer(): - layer = input("Enter layer: ") - - return int(layer) - -def crop(): - return rectangle() - -def final_crop(): - return rectangle() - -def matrix(): - dsdx = input("Enter dsdx: ") - dtdx = input("Enter dtdx: ") - dsdy = input("Enter dsdy: ") - dtdy = input("Enter dtdy: ") - - return float(dsdx) - -def transparent_region_hint(): - num = input("Enter number of rectangles in region: ") - - return [rectangle() in range(x)] - -def layer_stack(): - layer_stack = input("Enter layer stack: ") - - return int(layer_stack) - -def hidden_flag(): - flag = input("Enter hidden flag state (True/False): ") - - return bool(flag) - -def opaque_flag(): - flag = input("Enter opaque flag state (True/False): ") - - return bool(flag) - -def secure_flag(): - flag = input("Enter secure flag state (True/False): ") - - return bool(flag) - -def deferred_transaction(): - layer_id = input("Enter layer_id: ") - frame_number = input("Enter frame_number: ") - - return int(layer_id), int(frame_number) - -def surface(): - id = input("Enter id: ") - name = raw_input("Enter name: ") - - return int(id), str(name) - -def projection(change): - change.projection.orientation = input("Enter orientation: ") - print("Enter rectangle for viewport") - change.projection.viewport.left, \ - change.projection.viewport.top, \ - change.projection.viewport.right,\ - change.projection.viewport.bottom = rectangle() - print("Enter rectangle for frame") - change.projection.frame.left, \ - change.projection.frame.top, \ - change.projection.frame.right,\ - change.projection.frame.bottom = rectangle() - -def rectangle(): - left = input("Enter left: ") - top = input("Enter top: ") - right = input("Enter right: ") - bottom = input("Enter bottom: ") - - return int(left), int(top), int(right), int(bottom) - -if __name__ == "__main__": - main() diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index d3144bb6c1..23a2181e59 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -217,7 +217,6 @@ cc_library_shared { "SurfaceControl.cpp", "SurfaceComposerClient.cpp", "SyncFeatures.cpp", - "TransactionTracing.cpp", "VsyncEventData.cpp", "view/Surface.cpp", "WindowInfosListenerReporter.cpp", diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index af64b3bd32..4c887ec96d 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -19,7 +19,6 @@ #include #include -#include #include #include #include diff --git a/libs/gui/TransactionTracing.cpp b/libs/gui/TransactionTracing.cpp deleted file mode 100644 index 59450fb411..0000000000 --- a/libs/gui/TransactionTracing.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "gui/TransactionTracing.h" -#include "android/gui/ISurfaceComposer.h" - -#include - -namespace android { - -sp TransactionTraceListener::sInstance = nullptr; -std::mutex TransactionTraceListener::sMutex; - -TransactionTraceListener::TransactionTraceListener() {} - -sp TransactionTraceListener::getInstance() { - const std::lock_guard lock(sMutex); - - if (sInstance == nullptr) { - sInstance = new TransactionTraceListener; - - sp sf(ComposerServiceAIDL::getComposerService()); - sf->addTransactionTraceListener(sInstance); - } - - return sInstance; -} - -binder::Status TransactionTraceListener::onToggled(bool enabled) { - ALOGD("TransactionTraceListener: onToggled listener called"); - mTracingEnabled = enabled; - - return binder::Status::ok(); -} - -bool TransactionTraceListener::isTracingEnabled() { - return mTracingEnabled; -} - -} // namespace android diff --git a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl index 3c220fcc66..ac1442b73e 100644 --- a/libs/gui/aidl/android/gui/ISurfaceComposer.aidl +++ b/libs/gui/aidl/android/gui/ISurfaceComposer.aidl @@ -36,7 +36,6 @@ import android.gui.IHdrLayerInfoListener; import android.gui.IRegionSamplingListener; import android.gui.IScreenCaptureListener; import android.gui.ISurfaceComposerClient; -import android.gui.ITransactionTraceListener; import android.gui.ITunnelModeEnabledListener; import android.gui.IWindowInfosListener; import android.gui.LayerCaptureArgs; @@ -452,11 +451,6 @@ interface ISurfaceComposer { */ void setOverrideFrameRate(int uid, float frameRate); - /** - * Adds a TransactionTraceListener to listen for transaction tracing state updates. - */ - void addTransactionTraceListener(ITransactionTraceListener listener); - /** * Gets priority of the RenderEngine in SurfaceFlinger. */ diff --git a/libs/gui/aidl/android/gui/ITransactionTraceListener.aidl b/libs/gui/aidl/android/gui/ITransactionTraceListener.aidl deleted file mode 100644 index 5cd12fdc2b..0000000000 --- a/libs/gui/aidl/android/gui/ITransactionTraceListener.aidl +++ /dev/null @@ -1,6 +0,0 @@ -package android.gui; - -/** @hide */ -interface ITransactionTraceListener { - void onToggled(boolean enabled); -} \ No newline at end of file diff --git a/libs/gui/fuzzer/libgui_fuzzer_utils.h b/libs/gui/fuzzer/libgui_fuzzer_utils.h index d51f6850c0..a5527484c9 100644 --- a/libs/gui/fuzzer/libgui_fuzzer_utils.h +++ b/libs/gui/fuzzer/libgui_fuzzer_utils.h @@ -148,8 +148,6 @@ public: MOCK_METHOD(binder::Status, getDisplayDecorationSupport, (const sp&, std::optional*), (override)); MOCK_METHOD(binder::Status, setOverrideFrameRate, (int32_t, float), (override)); - MOCK_METHOD(binder::Status, addTransactionTraceListener, - (const sp&), (override)); MOCK_METHOD(binder::Status, getGpuContextPriority, (int32_t*), (override)); MOCK_METHOD(binder::Status, getMaxAcquiredBufferCount, (int32_t*), (override)); MOCK_METHOD(binder::Status, addWindowInfosListener, (const sp&), diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index d46c2e7e24..e91d75467d 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -23,7 +23,6 @@ #include #include #include -#include #include #include #include diff --git a/libs/gui/include/gui/TransactionTracing.h b/libs/gui/include/gui/TransactionTracing.h deleted file mode 100644 index 9efba47a18..0000000000 --- a/libs/gui/include/gui/TransactionTracing.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2020 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include - -namespace android { - -class TransactionTraceListener : public gui::BnTransactionTraceListener { - static std::mutex sMutex; - static sp sInstance; - - TransactionTraceListener(); - -public: - static sp getInstance(); - - binder::Status onToggled(bool enabled) override; - - bool isTracingEnabled(); - -private: - bool mTracingEnabled = false; -}; - -} // namespace android diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index c078378118..d5cc55f7fd 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -977,11 +977,6 @@ public: return binder::Status::ok(); } - binder::Status addTransactionTraceListener( - const sp& /*listener*/) override { - return binder::Status::ok(); - } - binder::Status getGpuContextPriority(int32_t* /*outPriority*/) override { return binder::Status::ok(); } diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp index 809c80be0d..8a76d7c3f8 100644 --- a/services/surfaceflinger/Android.bp +++ b/services/surfaceflinger/Android.bp @@ -84,7 +84,6 @@ cc_defaults { "libserviceutils", "libshaders", "libtonemap", - "libtrace_proto", ], header_libs: [ "android.hardware.graphics.composer@2.1-command-buffer", @@ -189,7 +188,6 @@ filegroup { "StartPropertySetThread.cpp", "SurfaceFlinger.cpp", "SurfaceFlingerDefaultFactory.cpp", - "SurfaceInterceptor.cpp", "Tracing/LayerTracing.cpp", "Tracing/TransactionTracing.cpp", "Tracing/TransactionProtoParser.cpp", @@ -225,7 +223,6 @@ cc_defaults { ], static_libs: [ "libserviceutils", - "libtrace_proto", ], } diff --git a/services/surfaceflinger/CompositionEngine/Android.bp b/services/surfaceflinger/CompositionEngine/Android.bp index b5d2ad0f74..0ae8bf98bf 100644 --- a/services/surfaceflinger/CompositionEngine/Android.bp +++ b/services/surfaceflinger/CompositionEngine/Android.bp @@ -42,7 +42,6 @@ cc_defaults { "libmath", "librenderengine", "libtonemap", - "libtrace_proto", "libaidlcommonsupport", "libprocessgroup", "libcgrouprc", diff --git a/services/surfaceflinger/Layer.h b/services/surfaceflinger/Layer.h index 418056c22c..8ace8123f9 100644 --- a/services/surfaceflinger/Layer.h +++ b/services/surfaceflinger/Layer.h @@ -77,10 +77,6 @@ namespace gui { class LayerDebugInfo; } -namespace impl { -class SurfaceInterceptor; -} - namespace frametimeline { class SurfaceFrame; } // namespace frametimeline @@ -916,8 +912,6 @@ public: std::unordered_set& visited); protected: - friend class impl::SurfaceInterceptor; - // For unit tests friend class TestableSurfaceFlinger; friend class FpsReporterTest; diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp index d3f53c11e4..a6cd47b253 100644 --- a/services/surfaceflinger/Scheduler/EventThread.cpp +++ b/services/surfaceflinger/Scheduler/EventThread.cpp @@ -237,16 +237,13 @@ namespace impl { EventThread::EventThread(std::unique_ptr vsyncSource, android::frametimeline::TokenManager* tokenManager, - InterceptVSyncsCallback interceptVSyncsCallback, ThrottleVsyncCallback throttleVsyncCallback, GetVsyncPeriodFunction getVsyncPeriodFunction) : mVSyncSource(std::move(vsyncSource)), mTokenManager(tokenManager), - mInterceptVSyncsCallback(std::move(interceptVSyncsCallback)), mThrottleVsyncCallback(std::move(throttleVsyncCallback)), mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)), mThreadName(mVSyncSource->getName()) { - LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr, "getVsyncPeriodFunction must not be null"); @@ -443,21 +440,13 @@ void EventThread::threadMain(std::unique_lock& lock) { event = mPendingEvents.front(); mPendingEvents.pop_front(); - switch (event->header.type) { - case DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG: - if (event->hotplug.connected && !mVSyncState) { - mVSyncState.emplace(event->header.displayId); - } else if (!event->hotplug.connected && mVSyncState && - mVSyncState->displayId == event->header.displayId) { - mVSyncState.reset(); - } - break; - - case DisplayEventReceiver::DISPLAY_EVENT_VSYNC: - if (mInterceptVSyncsCallback) { - mInterceptVSyncsCallback(event->header.timestamp); - } - break; + if (event->header.type == DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG) { + if (event->hotplug.connected && !mVSyncState) { + mVSyncState.emplace(event->header.displayId); + } else if (!event->hotplug.connected && mVSyncState && + mVSyncState->displayId == event->header.displayId) { + mVSyncState.reset(); + } } } diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h index d85d140fc0..7a5a348db9 100644 --- a/services/surfaceflinger/Scheduler/EventThread.h +++ b/services/surfaceflinger/Scheduler/EventThread.h @@ -161,12 +161,11 @@ namespace impl { class EventThread : public android::EventThread, private VSyncSource::Callback { public: - using InterceptVSyncsCallback = std::function; using ThrottleVsyncCallback = std::function; using GetVsyncPeriodFunction = std::function; - EventThread(std::unique_ptr, frametimeline::TokenManager*, InterceptVSyncsCallback, - ThrottleVsyncCallback, GetVsyncPeriodFunction); + EventThread(std::unique_ptr, frametimeline::TokenManager*, ThrottleVsyncCallback, + GetVsyncPeriodFunction); ~EventThread(); sp createEventConnection( @@ -225,7 +224,6 @@ private: const std::unique_ptr mVSyncSource GUARDED_BY(mMutex); frametimeline::TokenManager* const mTokenManager; - const InterceptVSyncsCallback mInterceptVSyncsCallback; const ThrottleVsyncCallback mThrottleVsyncCallback; const GetVsyncPeriodFunction mGetVsyncPeriodFunction; const char* const mThreadName; diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp index 7f04a4de85..72b65455b0 100644 --- a/services/surfaceflinger/Scheduler/Scheduler.cpp +++ b/services/surfaceflinger/Scheduler/Scheduler.cpp @@ -231,15 +231,14 @@ impl::EventThread::GetVsyncPeriodFunction Scheduler::makeGetVsyncPeriodFunction( }; } -ConnectionHandle Scheduler::createConnection( - const char* connectionName, frametimeline::TokenManager* tokenManager, - std::chrono::nanoseconds workDuration, std::chrono::nanoseconds readyDuration, - impl::EventThread::InterceptVSyncsCallback interceptCallback) { +ConnectionHandle Scheduler::createConnection(const char* connectionName, + frametimeline::TokenManager* tokenManager, + std::chrono::nanoseconds workDuration, + std::chrono::nanoseconds readyDuration) { auto vsyncSource = makePrimaryDispSyncSource(connectionName, workDuration, readyDuration); auto throttleVsync = makeThrottleVsyncCallback(); auto getVsyncPeriod = makeGetVsyncPeriodFunction(); auto eventThread = std::make_unique(std::move(vsyncSource), tokenManager, - std::move(interceptCallback), std::move(throttleVsync), std::move(getVsyncPeriod)); return createConnection(std::move(eventThread)); @@ -418,7 +417,6 @@ ConnectionHandle Scheduler::enableVSyncInjection(bool enable) { auto eventThread = std::make_unique(std::move(vsyncSource), /*tokenManager=*/nullptr, - impl::EventThread::InterceptVSyncsCallback(), impl::EventThread::ThrottleVsyncCallback(), impl::EventThread::GetVsyncPeriodFunction()); diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h index d6f62ca898..4c4956291d 100644 --- a/services/surfaceflinger/Scheduler/Scheduler.h +++ b/services/surfaceflinger/Scheduler/Scheduler.h @@ -162,8 +162,7 @@ public: ConnectionHandle createConnection(const char* connectionName, frametimeline::TokenManager*, std::chrono::nanoseconds workDuration, - std::chrono::nanoseconds readyDuration, - android::impl::EventThread::InterceptVSyncsCallback); + std::chrono::nanoseconds readyDuration); sp createDisplayEventConnection( ConnectionHandle, EventRegistrationFlags eventRegistration = {}); diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 2d29e4cf2b..d21b0fafda 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -136,7 +136,6 @@ #include "Scheduler/VsyncConfiguration.h" #include "StartPropertySetThread.h" #include "SurfaceFlingerProperties.h" -#include "SurfaceInterceptor.h" #include "TimeStats/TimeStats.h" #include "TunnelModeEnabledReporter.h" #include "Utils/Dumper.h" @@ -300,7 +299,6 @@ bool callingThreadHasInternalSystemWindowAccess() { SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag) : mFactory(factory), mPid(getpid()), - mInterceptor(mFactory.createSurfaceInterceptor()), mTimeStats(std::make_shared()), mFrameTracer(mFactory.createFrameTracer()), mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)), @@ -495,7 +493,6 @@ sp SurfaceFlinger::createDisplay(const String8& displayName, bool secur state.isSecure = secure; state.displayName = displayName; mCurrentState.displays.add(token, state); - mInterceptor->saveDisplayCreation(state); return token; } @@ -513,7 +510,6 @@ void SurfaceFlinger::destroyDisplay(const sp& displayToken) { ALOGE("%s: Invalid operation on physical display", __func__); return; } - mInterceptor->saveDisplayDeletion(state.sequenceId); mCurrentState.displays.removeItemsAt(index); setTransactionFlags(eDisplayTransactionNeeded); } @@ -2690,8 +2686,6 @@ const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId, const auto& display = displayOpt->get(); if (const ssize_t index = mCurrentState.displays.indexOfKey(display.token()); index >= 0) { - const DisplayDeviceState& state = mCurrentState.displays.valueAt(index); - mInterceptor->saveDisplayDeletion(state.sequenceId); mCurrentState.displays.removeItemsAt(index); } @@ -2746,7 +2740,6 @@ const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId, state.displayName = std::move(info.name); mCurrentState.displays.add(token, state); - mInterceptor->saveDisplayCreation(state); return "Connecting"; } @@ -3408,15 +3401,11 @@ void SurfaceFlinger::initScheduler(const sp& display) { mAppConnectionHandle = mScheduler->createConnection("app", mFrameTimeline->getTokenManager(), /*workDuration=*/configs.late.appWorkDuration, - /*readyDuration=*/configs.late.sfWorkDuration, - impl::EventThread::InterceptVSyncsCallback()); + /*readyDuration=*/configs.late.sfWorkDuration); mSfConnectionHandle = mScheduler->createConnection("appSf", mFrameTimeline->getTokenManager(), /*workDuration=*/std::chrono::nanoseconds(vsyncPeriod), - /*readyDuration=*/configs.late.sfWorkDuration, - [this](nsecs_t timestamp) { - mInterceptor->saveVSyncEvent(timestamp); - }); + /*readyDuration=*/configs.late.sfWorkDuration); mScheduler->initVsync(mScheduler->getVsyncSchedule().getDispatch(), *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration); @@ -3991,11 +3980,6 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin bool needsTraversal = false; if (transactionFlags) { - if (mInterceptor->isEnabled()) { - mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags, - originPid, originUid, transactionId); - } - // We are on the main thread, we are about to preform a traversal. Clear the traversal bit // so we don't have to wake up again next frame to preform an unnecessary traversal. if (transactionFlags & eTraversalNeeded) { @@ -4641,9 +4625,6 @@ void SurfaceFlinger::setPowerModeInternal(const sp& display, hal: display->setPowerMode(mode); - if (mInterceptor->isEnabled()) { - mInterceptor->savePowerModeUpdate(display->getSequenceId(), static_cast(mode)); - } const auto refreshRate = display->refreshRateConfigs().getActiveMode().getFps(); if (*currentMode == hal::PowerMode::OFF) { // Turn on the display @@ -5533,17 +5514,8 @@ status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* r mScheduler->setDuration(mSfConnectionHandle, std::chrono::nanoseconds(n), 0ns); return NO_ERROR; } - case 1020: { // Layer updates interceptor - n = data.readInt32(); - if (n) { - ALOGV("Interceptor enabled"); - mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays); - } - else{ - ALOGV("Interceptor disabled"); - mInterceptor->disable(); - } - return NO_ERROR; + case 1020: { // Unused + return NAME_NOT_FOUND; } case 1021: { // Disable HWC virtual displays const bool enable = data.readInt32() != 0; @@ -6816,17 +6788,6 @@ void SurfaceFlinger::enableRefreshRateOverlay(bool enable) { } } -status_t SurfaceFlinger::addTransactionTraceListener( - const sp& listener) { - if (!listener) { - return BAD_VALUE; - } - - mInterceptor->addTransactionTraceListener(listener); - - return NO_ERROR; -} - int SurfaceFlinger::getGpuContextPriority() { return getRenderEngine().getContextPriority(); } @@ -6906,7 +6867,6 @@ void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, Vs if (mTransactionTracing) { mTransactionTracing->onLayerAddedToDrawingState(layer->getSequence(), vsyncId.value); } - mInterceptor->saveSurfaceCreation(layer); } void SurfaceFlinger::sample() { @@ -7758,19 +7718,6 @@ binder::Status SurfaceComposerAIDL::setOverrideFrameRate(int32_t uid, float fram return binderStatusFromStatusT(status); } -binder::Status SurfaceComposerAIDL::addTransactionTraceListener( - const sp& listener) { - status_t status; - IPCThreadState* ipc = IPCThreadState::self(); - const int uid = ipc->getCallingUid(); - if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) { - status = mFlinger->addTransactionTraceListener(listener); - } else { - status = PERMISSION_DENIED; - } - return binderStatusFromStatusT(status); -} - binder::Status SurfaceComposerAIDL::getGpuContextPriority(int32_t* outPriority) { *outPriority = mFlinger->getGpuContextPriority(); return binder::Status::ok(); diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 426e7886ec..ac23c12c85 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -588,8 +588,6 @@ private: status_t setOverrideFrameRate(uid_t uid, float frameRate); - status_t addTransactionTraceListener(const sp& listener); - int getGpuContextPriority(); status_t getMaxAcquiredBufferCount(int* buffers) const; @@ -1198,7 +1196,6 @@ private: bool mLayerCachingEnabled = false; bool mPropagateBackpressureClientComposition = false; - sp mInterceptor; LayerTracing mLayerTracing{*this}; bool mLayerTracingEnabled = false; @@ -1489,8 +1486,6 @@ public: const sp& displayToken, std::optional* outSupport) override; binder::Status setOverrideFrameRate(int32_t uid, float frameRate) override; - binder::Status addTransactionTraceListener( - const sp& listener) override; binder::Status getGpuContextPriority(int32_t* outPriority) override; binder::Status getMaxAcquiredBufferCount(int32_t* buffers) override; binder::Status addWindowInfosListener( diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp index 3e30dcb817..2f1f263afa 100644 --- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp +++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.cpp @@ -29,7 +29,6 @@ #include "StartPropertySetThread.h" #include "SurfaceFlingerDefaultFactory.h" #include "SurfaceFlingerProperties.h" -#include "SurfaceInterceptor.h" #include "DisplayHardware/ComposerHal.h" #include "FrameTimeline/FrameTimeline.h" @@ -54,10 +53,6 @@ std::unique_ptr DefaultFactory::createVsyncConfig } } -sp DefaultFactory::createSurfaceInterceptor() { - return sp::make(); -} - sp DefaultFactory::createStartPropertySetThread( bool timestampPropertyValue) { return sp::make(timestampPropertyValue); diff --git a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h index 6fca402641..447a02fc0c 100644 --- a/services/surfaceflinger/SurfaceFlingerDefaultFactory.h +++ b/services/surfaceflinger/SurfaceFlingerDefaultFactory.h @@ -29,7 +29,6 @@ public: std::unique_ptr createHWComposer(const std::string& serviceName) override; std::unique_ptr createVsyncConfiguration( Fps currentRefreshRate) override; - sp createSurfaceInterceptor() override; sp createStartPropertySetThread(bool timestampPropertyValue) override; sp createDisplayDevice(DisplayDeviceCreationArgs&) override; sp createGraphicBuffer(uint32_t width, uint32_t height, PixelFormat format, diff --git a/services/surfaceflinger/SurfaceFlingerFactory.h b/services/surfaceflinger/SurfaceFlingerFactory.h index 6d18adea39..9c4d5c82ea 100644 --- a/services/surfaceflinger/SurfaceFlingerFactory.h +++ b/services/surfaceflinger/SurfaceFlingerFactory.h @@ -40,7 +40,6 @@ class IGraphicBufferProducer; class Layer; class StartPropertySetThread; class SurfaceFlinger; -class SurfaceInterceptor; class TimeStats; struct DisplayDeviceCreationArgs; @@ -71,7 +70,6 @@ public: virtual std::unique_ptr createHWComposer(const std::string& serviceName) = 0; virtual std::unique_ptr createVsyncConfiguration( Fps currentRefreshRate) = 0; - virtual sp createSurfaceInterceptor() = 0; virtual sp createStartPropertySetThread( bool timestampPropertyValue) = 0; diff --git a/services/surfaceflinger/SurfaceInterceptor.cpp b/services/surfaceflinger/SurfaceInterceptor.cpp deleted file mode 100644 index c90ae4cd83..0000000000 --- a/services/surfaceflinger/SurfaceInterceptor.cpp +++ /dev/null @@ -1,711 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wconversion" -#undef LOG_TAG -#define LOG_TAG "SurfaceInterceptor" -#define ATRACE_TAG ATRACE_TAG_GRAPHICS - -#include "Layer.h" -#include "SurfaceFlinger.h" -#include "SurfaceInterceptor.h" - -#include - -#include -#include -#include - -namespace android { - -// ---------------------------------------------------------------------------- -// TODO(marissaw): add new layer state values to SurfaceInterceptor - -SurfaceInterceptor::~SurfaceInterceptor() = default; - -namespace impl { - -void SurfaceInterceptor::addTransactionTraceListener( - const sp& listener) { - sp asBinder = IInterface::asBinder(listener); - - std::scoped_lock lock(mListenersMutex); - - asBinder->linkToDeath(sp::fromExisting(this)); - - listener->onToggled(mEnabled); // notifies of current state - - mTraceToggledListeners.emplace(asBinder, listener); -} - -void SurfaceInterceptor::binderDied(const wp& who) { - std::scoped_lock lock(mListenersMutex); - mTraceToggledListeners.erase(who); -} - -void SurfaceInterceptor::enable(const SortedVector>& layers, - const DefaultKeyedVector< wp, DisplayDeviceState>& displays) -{ - if (mEnabled) { - return; - } - ATRACE_CALL(); - { - std::scoped_lock lock(mListenersMutex); - for (const auto& [_, listener] : mTraceToggledListeners) { - listener->onToggled(true); - } - } - mEnabled = true; - std::scoped_lock protoGuard(mTraceMutex); - saveExistingDisplaysLocked(displays); - saveExistingSurfacesLocked(layers); -} - -void SurfaceInterceptor::disable() { - if (!mEnabled) { - return; - } - ATRACE_CALL(); - { - std::scoped_lock lock(mListenersMutex); - for (const auto& [_, listener] : mTraceToggledListeners) { - listener->onToggled(false); - } - } - mEnabled = false; - std::scoped_lock protoGuard(mTraceMutex); - status_t err(writeProtoFileLocked()); - ALOGE_IF(err == PERMISSION_DENIED, "Could not save the proto file! Permission denied"); - ALOGE_IF(err == NOT_ENOUGH_DATA, "Could not save the proto file! There are missing fields"); - mTrace.Clear(); -} - -bool SurfaceInterceptor::isEnabled() { - return mEnabled; -} - -void SurfaceInterceptor::saveExistingDisplaysLocked( - const DefaultKeyedVector< wp, DisplayDeviceState>& displays) -{ - // Caveat: The initial snapshot does not capture the power mode of the existing displays - ATRACE_CALL(); - for (size_t i = 0 ; i < displays.size() ; i++) { - addDisplayCreationLocked(createTraceIncrementLocked(), displays[i]); - addInitialDisplayStateLocked(createTraceIncrementLocked(), displays[i]); - } -} - -void SurfaceInterceptor::saveExistingSurfacesLocked(const SortedVector>& layers) { - ATRACE_CALL(); - for (const auto& l : layers) { - l->traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* layer) { - addSurfaceCreationLocked(createTraceIncrementLocked(), sp::fromExisting(layer)); - addInitialSurfaceStateLocked(createTraceIncrementLocked(), - sp::fromExisting(layer)); - }); - } -} - -void SurfaceInterceptor::addInitialSurfaceStateLocked(Increment* increment, - const sp& layer) -{ - Transaction* transaction(increment->mutable_transaction()); - const uint32_t layerFlags = layer->getTransactionFlags(); - transaction->set_animation(layerFlags & BnSurfaceComposer::eAnimation); - - const int32_t layerId(getLayerId(layer)); - addPositionLocked(transaction, layerId, layer->mDrawingState.transform.tx(), - layer->mDrawingState.transform.ty()); - addDepthLocked(transaction, layerId, layer->mDrawingState.z); - addAlphaLocked(transaction, layerId, layer->mDrawingState.color.a); - addLayerStackLocked(transaction, layerId, layer->mDrawingState.layerStack); - addCropLocked(transaction, layerId, layer->mDrawingState.crop); - addCornerRadiusLocked(transaction, layerId, layer->mDrawingState.cornerRadius); - addBackgroundBlurRadiusLocked(transaction, layerId, layer->mDrawingState.backgroundBlurRadius); - addBlurRegionsLocked(transaction, layerId, layer->mDrawingState.blurRegions); - addFlagsLocked(transaction, layerId, layer->mDrawingState.flags, - layer_state_t::eLayerHidden | layer_state_t::eLayerOpaque | - layer_state_t::eLayerSecure); - addReparentLocked(transaction, layerId, getLayerIdFromWeakRef(layer->mDrawingParent)); - addRelativeParentLocked(transaction, layerId, - getLayerIdFromWeakRef(layer->mDrawingState.zOrderRelativeOf), - layer->mDrawingState.z); - addShadowRadiusLocked(transaction, layerId, layer->mDrawingState.shadowRadius); - addTrustedOverlayLocked(transaction, layerId, layer->mDrawingState.isTrustedOverlay); -} - -void SurfaceInterceptor::addInitialDisplayStateLocked(Increment* increment, - const DisplayDeviceState& display) -{ - Transaction* transaction(increment->mutable_transaction()); - transaction->set_synchronous(false); - transaction->set_animation(false); - - addDisplaySurfaceLocked(transaction, display.sequenceId, display.surface); - addDisplayLayerStackLocked(transaction, display.sequenceId, display.layerStack); - addDisplayFlagsLocked(transaction, display.sequenceId, display.flags); - addDisplaySizeLocked(transaction, display.sequenceId, display.width, display.height); - addDisplayProjectionLocked(transaction, display.sequenceId, toRotationInt(display.orientation), - display.layerStackSpaceRect, display.orientedDisplaySpaceRect); -} - -status_t SurfaceInterceptor::writeProtoFileLocked() { - ATRACE_CALL(); - std::string output; - - if (!mTrace.IsInitialized()) { - return NOT_ENOUGH_DATA; - } - if (!mTrace.SerializeToString(&output)) { - return PERMISSION_DENIED; - } - if (!android::base::WriteStringToFile(output, mOutputFileName, true)) { - return PERMISSION_DENIED; - } - - return NO_ERROR; -} - -const sp SurfaceInterceptor::getLayer(const wp& weakHandle) const { - sp handle = weakHandle.promote(); - return Layer::fromHandle(handle).promote(); -} - -int32_t SurfaceInterceptor::getLayerId(const sp& layer) const { - return layer->sequence; -} - -int32_t SurfaceInterceptor::getLayerIdFromWeakRef(const wp& layer) const { - if (layer == nullptr) { - return -1; - } - auto strongLayer = layer.promote(); - return strongLayer == nullptr ? -1 : getLayerId(strongLayer); -} - -int32_t SurfaceInterceptor::getLayerIdFromHandle(const sp& handle) const { - if (handle == nullptr) { - return -1; - } - const sp layer = Layer::fromHandle(handle).promote(); - return layer == nullptr ? -1 : getLayerId(layer); -} - -Increment* SurfaceInterceptor::createTraceIncrementLocked() { - Increment* increment(mTrace.add_increment()); - increment->set_time_stamp(elapsedRealtimeNano()); - return increment; -} - -SurfaceChange* SurfaceInterceptor::createSurfaceChangeLocked(Transaction* transaction, - int32_t layerId) -{ - SurfaceChange* change(transaction->add_surface_change()); - change->set_id(layerId); - return change; -} - -DisplayChange* SurfaceInterceptor::createDisplayChangeLocked(Transaction* transaction, - int32_t sequenceId) -{ - DisplayChange* dispChange(transaction->add_display_change()); - dispChange->set_id(sequenceId); - return dispChange; -} - -void SurfaceInterceptor::setProtoRectLocked(Rectangle* protoRect, const Rect& rect) { - protoRect->set_left(rect.left); - protoRect->set_top(rect.top); - protoRect->set_right(rect.right); - protoRect->set_bottom(rect.bottom); -} - -void SurfaceInterceptor::setTransactionOriginLocked(Transaction* transaction, int32_t pid, - int32_t uid) { - Origin* origin(transaction->mutable_origin()); - origin->set_pid(pid); - origin->set_uid(uid); -} - -void SurfaceInterceptor::addPositionLocked(Transaction* transaction, int32_t layerId, - float x, float y) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - PositionChange* posChange(change->mutable_position()); - posChange->set_x(x); - posChange->set_y(y); -} - -void SurfaceInterceptor::addDepthLocked(Transaction* transaction, int32_t layerId, - uint32_t z) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - LayerChange* depthChange(change->mutable_layer()); - depthChange->set_layer(z); -} - -void SurfaceInterceptor::addSizeLocked(Transaction* transaction, int32_t layerId, uint32_t w, - uint32_t h) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - SizeChange* sizeChange(change->mutable_size()); - sizeChange->set_w(w); - sizeChange->set_h(h); -} - -void SurfaceInterceptor::addAlphaLocked(Transaction* transaction, int32_t layerId, - float alpha) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - AlphaChange* alphaChange(change->mutable_alpha()); - alphaChange->set_alpha(alpha); -} - -void SurfaceInterceptor::addMatrixLocked(Transaction* transaction, int32_t layerId, - const layer_state_t::matrix22_t& matrix) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - MatrixChange* matrixChange(change->mutable_matrix()); - matrixChange->set_dsdx(matrix.dsdx); - matrixChange->set_dtdx(matrix.dtdx); - matrixChange->set_dsdy(matrix.dsdy); - matrixChange->set_dtdy(matrix.dtdy); -} - -void SurfaceInterceptor::addTransparentRegionLocked(Transaction* transaction, - int32_t layerId, const Region& transRegion) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - TransparentRegionHintChange* transparentChange(change->mutable_transparent_region_hint()); - - for (const auto& rect : transRegion) { - Rectangle* protoRect(transparentChange->add_region()); - setProtoRectLocked(protoRect, rect); - } -} - -void SurfaceInterceptor::addFlagsLocked(Transaction* transaction, int32_t layerId, uint8_t flags, - uint8_t mask) { - // There can be multiple flags changed - if (mask & layer_state_t::eLayerHidden) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - HiddenFlagChange* flagChange(change->mutable_hidden_flag()); - flagChange->set_hidden_flag(flags & layer_state_t::eLayerHidden); - } - if (mask & layer_state_t::eLayerOpaque) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - OpaqueFlagChange* flagChange(change->mutable_opaque_flag()); - flagChange->set_opaque_flag(flags & layer_state_t::eLayerOpaque); - } - if (mask & layer_state_t::eLayerSecure) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - SecureFlagChange* flagChange(change->mutable_secure_flag()); - flagChange->set_secure_flag(flags & layer_state_t::eLayerSecure); - } -} - -void SurfaceInterceptor::addLayerStackLocked(Transaction* transaction, int32_t layerId, - ui::LayerStack layerStack) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - LayerStackChange* layerStackChange(change->mutable_layer_stack()); - layerStackChange->set_layer_stack(layerStack.id); -} - -void SurfaceInterceptor::addCropLocked(Transaction* transaction, int32_t layerId, - const Rect& rect) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - CropChange* cropChange(change->mutable_crop()); - Rectangle* protoRect(cropChange->mutable_rectangle()); - setProtoRectLocked(protoRect, rect); -} - -void SurfaceInterceptor::addCornerRadiusLocked(Transaction* transaction, int32_t layerId, - float cornerRadius) -{ - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - CornerRadiusChange* cornerRadiusChange(change->mutable_corner_radius()); - cornerRadiusChange->set_corner_radius(cornerRadius); -} - -void SurfaceInterceptor::addBackgroundBlurRadiusLocked(Transaction* transaction, int32_t layerId, - int32_t backgroundBlurRadius) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - BackgroundBlurRadiusChange* blurRadiusChange(change->mutable_background_blur_radius()); - blurRadiusChange->set_background_blur_radius(backgroundBlurRadius); -} - -void SurfaceInterceptor::addBlurRegionsLocked(Transaction* transaction, int32_t layerId, - const std::vector& blurRegions) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - BlurRegionsChange* blurRegionsChange(change->mutable_blur_regions()); - for (const auto blurRegion : blurRegions) { - const auto blurRegionChange = blurRegionsChange->add_blur_regions(); - blurRegionChange->set_blur_radius(blurRegion.blurRadius); - blurRegionChange->set_corner_radius_tl(blurRegion.cornerRadiusTL); - blurRegionChange->set_corner_radius_tr(blurRegion.cornerRadiusTR); - blurRegionChange->set_corner_radius_bl(blurRegion.cornerRadiusBL); - blurRegionChange->set_corner_radius_br(blurRegion.cornerRadiusBR); - blurRegionChange->set_alpha(blurRegion.alpha); - blurRegionChange->set_left(blurRegion.left); - blurRegionChange->set_top(blurRegion.top); - blurRegionChange->set_right(blurRegion.right); - blurRegionChange->set_bottom(blurRegion.bottom); - } -} - -void SurfaceInterceptor::addReparentLocked(Transaction* transaction, int32_t layerId, - int32_t parentId) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - ReparentChange* overrideChange(change->mutable_reparent()); - overrideChange->set_parent_id(parentId); -} - -void SurfaceInterceptor::addRelativeParentLocked(Transaction* transaction, int32_t layerId, - int32_t parentId, int z) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - RelativeParentChange* overrideChange(change->mutable_relative_parent()); - overrideChange->set_relative_parent_id(parentId); - overrideChange->set_z(z); -} - -void SurfaceInterceptor::addShadowRadiusLocked(Transaction* transaction, int32_t layerId, - float shadowRadius) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - ShadowRadiusChange* overrideChange(change->mutable_shadow_radius()); - overrideChange->set_radius(shadowRadius); -} - -void SurfaceInterceptor::addTrustedOverlayLocked(Transaction* transaction, int32_t layerId, - bool isTrustedOverlay) { - SurfaceChange* change(createSurfaceChangeLocked(transaction, layerId)); - TrustedOverlayChange* overrideChange(change->mutable_trusted_overlay()); - overrideChange->set_is_trusted_overlay(isTrustedOverlay); -} - -void SurfaceInterceptor::addSurfaceChangesLocked(Transaction* transaction, - const layer_state_t& state) -{ - const sp layer(getLayer(state.surface)); - if (layer == nullptr) { - ALOGE("An existing layer could not be retrieved with the surface " - "from the layer_state_t surface in the update transaction"); - return; - } - - const int32_t layerId(getLayerId(layer)); - - if (state.what & layer_state_t::ePositionChanged) { - addPositionLocked(transaction, layerId, state.x, state.y); - } - if (state.what & layer_state_t::eLayerChanged) { - addDepthLocked(transaction, layerId, state.z); - } - if (state.what & layer_state_t::eAlphaChanged) { - addAlphaLocked(transaction, layerId, state.alpha); - } - if (state.what & layer_state_t::eMatrixChanged) { - addMatrixLocked(transaction, layerId, state.matrix); - } - if (state.what & layer_state_t::eTransparentRegionChanged) { - addTransparentRegionLocked(transaction, layerId, state.transparentRegion); - } - if (state.what & layer_state_t::eFlagsChanged) { - addFlagsLocked(transaction, layerId, state.flags, state.mask); - } - if (state.what & layer_state_t::eLayerStackChanged) { - addLayerStackLocked(transaction, layerId, state.layerStack); - } - if (state.what & layer_state_t::eCropChanged) { - addCropLocked(transaction, layerId, state.crop); - } - if (state.what & layer_state_t::eCornerRadiusChanged) { - addCornerRadiusLocked(transaction, layerId, state.cornerRadius); - } - if (state.what & layer_state_t::eBackgroundBlurRadiusChanged) { - addBackgroundBlurRadiusLocked(transaction, layerId, state.backgroundBlurRadius); - } - if (state.what & layer_state_t::eBlurRegionsChanged) { - addBlurRegionsLocked(transaction, layerId, state.blurRegions); - } - if (state.what & layer_state_t::eReparent) { - auto parentHandle = (state.parentSurfaceControlForChild) - ? state.parentSurfaceControlForChild->getHandle() - : nullptr; - addReparentLocked(transaction, layerId, getLayerIdFromHandle(parentHandle)); - } - if (state.what & layer_state_t::eRelativeLayerChanged) { - addRelativeParentLocked(transaction, layerId, - getLayerIdFromHandle( - state.relativeLayerSurfaceControl->getHandle()), - state.z); - } - if (state.what & layer_state_t::eShadowRadiusChanged) { - addShadowRadiusLocked(transaction, layerId, state.shadowRadius); - } - if (state.what & layer_state_t::eTrustedOverlayChanged) { - addTrustedOverlayLocked(transaction, layerId, state.isTrustedOverlay); - } - if (state.what & layer_state_t::eStretchChanged) { - ALOGW("SurfaceInterceptor not implemented for eStretchChanged"); - } -} - -void SurfaceInterceptor::addDisplayChangesLocked(Transaction* transaction, - const DisplayState& state, int32_t sequenceId) -{ - if (state.what & DisplayState::eSurfaceChanged) { - addDisplaySurfaceLocked(transaction, sequenceId, state.surface); - } - if (state.what & DisplayState::eLayerStackChanged) { - addDisplayLayerStackLocked(transaction, sequenceId, state.layerStack); - } - if (state.what & DisplayState::eFlagsChanged) { - addDisplayFlagsLocked(transaction, sequenceId, state.flags); - } - if (state.what & DisplayState::eDisplaySizeChanged) { - addDisplaySizeLocked(transaction, sequenceId, state.width, state.height); - } - if (state.what & DisplayState::eDisplayProjectionChanged) { - addDisplayProjectionLocked(transaction, sequenceId, toRotationInt(state.orientation), - state.layerStackSpaceRect, state.orientedDisplaySpaceRect); - } -} - -void SurfaceInterceptor::addTransactionLocked( - Increment* increment, const Vector& stateUpdates, - const DefaultKeyedVector, DisplayDeviceState>& displays, - const Vector& changedDisplays, uint32_t transactionFlags, int originPid, - int originUid, uint64_t transactionId) { - Transaction* transaction(increment->mutable_transaction()); - transaction->set_animation(transactionFlags & BnSurfaceComposer::eAnimation); - setTransactionOriginLocked(transaction, originPid, originUid); - transaction->set_id(transactionId); - for (const auto& compState: stateUpdates) { - addSurfaceChangesLocked(transaction, compState.state); - } - for (const auto& disp: changedDisplays) { - ssize_t dpyIdx = displays.indexOfKey(disp.token); - if (dpyIdx >= 0) { - const DisplayDeviceState& dispState(displays.valueAt(dpyIdx)); - addDisplayChangesLocked(transaction, disp, dispState.sequenceId); - } - } -} - -void SurfaceInterceptor::addSurfaceCreationLocked(Increment* increment, - const sp& layer) -{ - SurfaceCreation* creation(increment->mutable_surface_creation()); - creation->set_id(getLayerId(layer)); - creation->set_name(layer->getName()); -} - -void SurfaceInterceptor::addSurfaceDeletionLocked(Increment* increment, - const sp& layer) -{ - SurfaceDeletion* deletion(increment->mutable_surface_deletion()); - deletion->set_id(getLayerId(layer)); -} - -void SurfaceInterceptor::addBufferUpdateLocked(Increment* increment, int32_t layerId, - uint32_t width, uint32_t height, uint64_t frameNumber) -{ - BufferUpdate* update(increment->mutable_buffer_update()); - update->set_id(layerId); - update->set_w(width); - update->set_h(height); - update->set_frame_number(frameNumber); -} - -void SurfaceInterceptor::addVSyncUpdateLocked(Increment* increment, nsecs_t timestamp) { - VSyncEvent* event(increment->mutable_vsync_event()); - event->set_when(timestamp); -} - -void SurfaceInterceptor::addDisplaySurfaceLocked(Transaction* transaction, int32_t sequenceId, - const sp& surface) -{ - if (surface == nullptr) { - return; - } - uint64_t bufferQueueId = 0; - status_t err(surface->getUniqueId(&bufferQueueId)); - if (err == NO_ERROR) { - DisplayChange* dispChange(createDisplayChangeLocked(transaction, sequenceId)); - DispSurfaceChange* surfaceChange(dispChange->mutable_surface()); - surfaceChange->set_buffer_queue_id(bufferQueueId); - surfaceChange->set_buffer_queue_name(surface->getConsumerName().string()); - } - else { - ALOGE("invalid graphic buffer producer received while tracing a display change (%s)", - strerror(-err)); - } -} - -void SurfaceInterceptor::addDisplayLayerStackLocked(Transaction* transaction, int32_t sequenceId, - ui::LayerStack layerStack) { - DisplayChange* dispChange(createDisplayChangeLocked(transaction, sequenceId)); - LayerStackChange* layerStackChange(dispChange->mutable_layer_stack()); - layerStackChange->set_layer_stack(layerStack.id); -} - -void SurfaceInterceptor::addDisplayFlagsLocked(Transaction* transaction, int32_t sequenceId, - uint32_t flags) { - DisplayChange* dispChange(createDisplayChangeLocked(transaction, sequenceId)); - DisplayFlagsChange* flagsChange(dispChange->mutable_flags()); - flagsChange->set_flags(flags); -} - -void SurfaceInterceptor::addDisplaySizeLocked(Transaction* transaction, int32_t sequenceId, - uint32_t w, uint32_t h) -{ - DisplayChange* dispChange(createDisplayChangeLocked(transaction, sequenceId)); - SizeChange* sizeChange(dispChange->mutable_size()); - sizeChange->set_w(w); - sizeChange->set_h(h); -} - -void SurfaceInterceptor::addDisplayProjectionLocked(Transaction* transaction, - int32_t sequenceId, int32_t orientation, const Rect& viewport, const Rect& frame) -{ - DisplayChange* dispChange(createDisplayChangeLocked(transaction, sequenceId)); - ProjectionChange* projectionChange(dispChange->mutable_projection()); - projectionChange->set_orientation(orientation); - Rectangle* viewportRect(projectionChange->mutable_viewport()); - setProtoRectLocked(viewportRect, viewport); - Rectangle* frameRect(projectionChange->mutable_frame()); - setProtoRectLocked(frameRect, frame); -} - -void SurfaceInterceptor::addDisplayCreationLocked(Increment* increment, - const DisplayDeviceState& info) -{ - DisplayCreation* creation(increment->mutable_display_creation()); - creation->set_id(info.sequenceId); - creation->set_name(info.displayName); - creation->set_is_secure(info.isSecure); - if (info.physical) { - creation->set_display_id(info.physical->id.value); - } -} - -void SurfaceInterceptor::addDisplayDeletionLocked(Increment* increment, int32_t sequenceId) { - DisplayDeletion* deletion(increment->mutable_display_deletion()); - deletion->set_id(sequenceId); -} - -void SurfaceInterceptor::addPowerModeUpdateLocked(Increment* increment, int32_t sequenceId, - int32_t mode) -{ - PowerModeUpdate* powerModeUpdate(increment->mutable_power_mode_update()); - powerModeUpdate->set_id(sequenceId); - powerModeUpdate->set_mode(mode); -} - -void SurfaceInterceptor::saveTransaction( - const Vector& stateUpdates, - const DefaultKeyedVector, DisplayDeviceState>& displays, - const Vector& changedDisplays, uint32_t flags, int originPid, int originUid, - uint64_t transactionId) { - if (!mEnabled || (stateUpdates.size() <= 0 && changedDisplays.size() <= 0)) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addTransactionLocked(createTraceIncrementLocked(), stateUpdates, displays, changedDisplays, - flags, originPid, originUid, transactionId); -} - -void SurfaceInterceptor::saveSurfaceCreation(const sp& layer) { - if (!mEnabled || layer == nullptr) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addSurfaceCreationLocked(createTraceIncrementLocked(), layer); -} - -void SurfaceInterceptor::saveSurfaceDeletion(const sp& layer) { - if (!mEnabled || layer == nullptr) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addSurfaceDeletionLocked(createTraceIncrementLocked(), layer); -} - -/** - * Here we pass the layer by ID instead of by sp<> since this is called without - * holding the state-lock from a Binder thread. If we required the caller - * to pass 'this' by sp<> the temporary sp<> constructed could end up - * being the last reference and we might accidentally destroy the Layer - * from this binder thread. - */ -void SurfaceInterceptor::saveBufferUpdate(int32_t layerId, uint32_t width, - uint32_t height, uint64_t frameNumber) -{ - if (!mEnabled) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addBufferUpdateLocked(createTraceIncrementLocked(), layerId, width, height, frameNumber); -} - -void SurfaceInterceptor::saveVSyncEvent(nsecs_t timestamp) { - if (!mEnabled) { - return; - } - std::lock_guard protoGuard(mTraceMutex); - addVSyncUpdateLocked(createTraceIncrementLocked(), timestamp); -} - -void SurfaceInterceptor::saveDisplayCreation(const DisplayDeviceState& info) { - if (!mEnabled) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addDisplayCreationLocked(createTraceIncrementLocked(), info); -} - -void SurfaceInterceptor::saveDisplayDeletion(int32_t sequenceId) { - if (!mEnabled) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addDisplayDeletionLocked(createTraceIncrementLocked(), sequenceId); -} - -void SurfaceInterceptor::savePowerModeUpdate(int32_t sequenceId, int32_t mode) { - if (!mEnabled) { - return; - } - ATRACE_CALL(); - std::lock_guard protoGuard(mTraceMutex); - addPowerModeUpdateLocked(createTraceIncrementLocked(), sequenceId, mode); -} - -} // namespace impl -} // namespace android - -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic pop // ignored "-Wconversion" diff --git a/services/surfaceflinger/SurfaceInterceptor.h b/services/surfaceflinger/SurfaceInterceptor.h deleted file mode 100644 index 970c3e5c27..0000000000 --- a/services/surfaceflinger/SurfaceInterceptor.h +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef ANDROID_SURFACEINTERCEPTOR_H -#define ANDROID_SURFACEINTERCEPTOR_H - -#include - -#include - -#include - -#include - -#include -#include -#include -#include - -#include "DisplayDevice.h" - -namespace android { - -class BufferItem; -class Layer; -class SurfaceFlinger; -struct ComposerState; -struct DisplayDeviceState; -struct DisplayState; -struct layer_state_t; -using Transaction = surfaceflinger::Transaction; -using Trace = surfaceflinger::Trace; -using Rectangle = surfaceflinger::Rectangle; -using SurfaceChange = surfaceflinger::SurfaceChange; -using Increment = surfaceflinger::Increment; -using DisplayChange = surfaceflinger::DisplayChange; - -constexpr auto DEFAULT_FILENAME = "/data/misc/wmtrace/transaction_trace.winscope"; - -class SurfaceInterceptor : public IBinder::DeathRecipient { -public: - virtual ~SurfaceInterceptor(); - - // Both vectors are used to capture the current state of SF as the initial snapshot in the trace - virtual void enable(const SortedVector>& layers, - const DefaultKeyedVector, DisplayDeviceState>& displays) = 0; - virtual void disable() = 0; - virtual bool isEnabled() = 0; - - virtual void addTransactionTraceListener( - const sp& listener) = 0; - virtual void binderDied(const wp& who) = 0; - - // Intercept display and surface transactions - virtual void saveTransaction( - const Vector& stateUpdates, - const DefaultKeyedVector, DisplayDeviceState>& displays, - const Vector& changedDisplays, uint32_t flags, int originPid, - int originUid, uint64_t transactionId) = 0; - - // Intercept surface data - virtual void saveSurfaceCreation(const sp& layer) = 0; - virtual void saveSurfaceDeletion(const sp& layer) = 0; - virtual void saveBufferUpdate(int32_t layerId, uint32_t width, uint32_t height, - uint64_t frameNumber) = 0; - - // Intercept display data - virtual void saveDisplayCreation(const DisplayDeviceState& info) = 0; - virtual void saveDisplayDeletion(int32_t sequenceId) = 0; - virtual void savePowerModeUpdate(int32_t sequenceId, int32_t mode) = 0; - virtual void saveVSyncEvent(nsecs_t timestamp) = 0; -}; - -namespace impl { - -/* - * SurfaceInterceptor intercepts and stores incoming streams of window - * properties on SurfaceFlinger. - */ -class SurfaceInterceptor final : public android::SurfaceInterceptor { -public: - SurfaceInterceptor() = default; - ~SurfaceInterceptor() override = default; - - // Both vectors are used to capture the current state of SF as the initial snapshot in the trace - void enable(const SortedVector>& layers, - const DefaultKeyedVector, DisplayDeviceState>& displays) override; - void disable() override; - bool isEnabled() override; - - void addTransactionTraceListener(const sp& listener) override; - void binderDied(const wp& who) override; - - // Intercept display and surface transactions - void saveTransaction(const Vector& stateUpdates, - const DefaultKeyedVector, DisplayDeviceState>& displays, - const Vector& changedDisplays, uint32_t flags, int originPid, - int originUid, uint64_t transactionId) override; - - // Intercept surface data - void saveSurfaceCreation(const sp& layer) override; - void saveSurfaceDeletion(const sp& layer) override; - void saveBufferUpdate(int32_t layerId, uint32_t width, uint32_t height, - uint64_t frameNumber) override; - - // Intercept display data - void saveDisplayCreation(const DisplayDeviceState& info) override; - void saveDisplayDeletion(int32_t sequenceId) override; - void savePowerModeUpdate(int32_t sequenceId, int32_t mode) override; - void saveVSyncEvent(nsecs_t timestamp) override; - -private: - // The creation increments of Surfaces and Displays do not contain enough information to capture - // the initial state of each object, so a transaction with all of the missing properties is - // performed at the initial snapshot for each display and surface. - void saveExistingDisplaysLocked( - const DefaultKeyedVector< wp, DisplayDeviceState>& displays); - void saveExistingSurfacesLocked(const SortedVector>& layers); - void addInitialSurfaceStateLocked(Increment* increment, const sp& layer); - void addInitialDisplayStateLocked(Increment* increment, const DisplayDeviceState& display); - - status_t writeProtoFileLocked(); - const sp getLayer(const wp& weakHandle) const; - int32_t getLayerId(const sp& layer) const; - int32_t getLayerIdFromWeakRef(const wp& layer) const; - int32_t getLayerIdFromHandle(const sp& weakHandle) const; - - Increment* createTraceIncrementLocked(); - void addSurfaceCreationLocked(Increment* increment, const sp& layer); - void addSurfaceDeletionLocked(Increment* increment, const sp& layer); - void addBufferUpdateLocked(Increment* increment, int32_t layerId, uint32_t width, - uint32_t height, uint64_t frameNumber); - void addVSyncUpdateLocked(Increment* increment, nsecs_t timestamp); - void addDisplayCreationLocked(Increment* increment, const DisplayDeviceState& info); - void addDisplayDeletionLocked(Increment* increment, int32_t sequenceId); - void addPowerModeUpdateLocked(Increment* increment, int32_t sequenceId, int32_t mode); - - // Add surface transactions to the trace - SurfaceChange* createSurfaceChangeLocked(Transaction* transaction, int32_t layerId); - void setProtoRectLocked(Rectangle* protoRect, const Rect& rect); - void addPositionLocked(Transaction* transaction, int32_t layerId, float x, float y); - void addDepthLocked(Transaction* transaction, int32_t layerId, uint32_t z); - void addSizeLocked(Transaction* transaction, int32_t layerId, uint32_t w, uint32_t h); - void addAlphaLocked(Transaction* transaction, int32_t layerId, float alpha); - void addMatrixLocked(Transaction* transaction, int32_t layerId, - const layer_state_t::matrix22_t& matrix); - void addTransparentRegionLocked(Transaction* transaction, int32_t layerId, - const Region& transRegion); - void addFlagsLocked(Transaction* transaction, int32_t layerId, uint8_t flags, uint8_t mask); - void addLayerStackLocked(Transaction* transaction, int32_t layerId, ui::LayerStack); - void addCropLocked(Transaction* transaction, int32_t layerId, const Rect& rect); - void addCornerRadiusLocked(Transaction* transaction, int32_t layerId, float cornerRadius); - void addBackgroundBlurRadiusLocked(Transaction* transaction, int32_t layerId, - int32_t backgroundBlurRadius); - void addBlurRegionsLocked(Transaction* transaction, int32_t layerId, - const std::vector& effectRegions); - void addSurfaceChangesLocked(Transaction* transaction, const layer_state_t& state); - void addTransactionLocked(Increment* increment, const Vector& stateUpdates, - const DefaultKeyedVector, DisplayDeviceState>& displays, - const Vector& changedDisplays, - uint32_t transactionFlags, int originPid, int originUid, - uint64_t transactionId); - void addReparentLocked(Transaction* transaction, int32_t layerId, int32_t parentId); - void addRelativeParentLocked(Transaction* transaction, int32_t layerId, int32_t parentId, - int z); - void addShadowRadiusLocked(Transaction* transaction, int32_t layerId, float shadowRadius); - void addTrustedOverlayLocked(Transaction* transaction, int32_t layerId, bool isTrustedOverlay); - - // Add display transactions to the trace - DisplayChange* createDisplayChangeLocked(Transaction* transaction, int32_t sequenceId); - void addDisplaySurfaceLocked(Transaction* transaction, int32_t sequenceId, - const sp& surface); - void addDisplayLayerStackLocked(Transaction* transaction, int32_t sequenceId, ui::LayerStack); - void addDisplayFlagsLocked(Transaction* transaction, int32_t sequenceId, uint32_t flags); - void addDisplaySizeLocked(Transaction* transaction, int32_t sequenceId, uint32_t w, - uint32_t h); - void addDisplayProjectionLocked(Transaction* transaction, int32_t sequenceId, - int32_t orientation, const Rect& viewport, const Rect& frame); - void addDisplayChangesLocked(Transaction* transaction, - const DisplayState& state, int32_t sequenceId); - - // Add transaction origin to trace - void setTransactionOriginLocked(Transaction* transaction, int32_t pid, int32_t uid); - - bool mEnabled {false}; - std::string mOutputFileName {DEFAULT_FILENAME}; - std::mutex mTraceMutex {}; - Trace mTrace {}; - std::mutex mListenersMutex; - std::map, sp> mTraceToggledListeners - GUARDED_BY(mListenersMutex); -}; - -} // namespace impl - -} // namespace android - -#endif // ANDROID_SURFACEINTERCEPTOR_H diff --git a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp index 88171785c7..963f7b6aff 100644 --- a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp +++ b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp @@ -47,10 +47,6 @@ public: return std::make_unique(); } - sp createSurfaceInterceptor() override { - return sp::make(); - } - sp createStartPropertySetThread( bool /* timestampPropertyValue */) override { return sp(); diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 2f8062ec2f..03630c9db5 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -46,7 +46,6 @@ #include "StartPropertySetThread.h" #include "SurfaceFlinger.h" #include "SurfaceFlingerDefaultFactory.h" -#include "SurfaceInterceptor.h" #include "ThreadContext.h" #include "TimeStats/TimeStats.h" @@ -60,7 +59,6 @@ #include "tests/unittests/mock/MockFrameTimeline.h" #include "tests/unittests/mock/MockFrameTracer.h" #include "tests/unittests/mock/MockNativeWindowSurface.h" -#include "tests/unittests/mock/MockSurfaceInterceptor.h" #include "tests/unittests/mock/MockTimeStats.h" #include "tests/unittests/mock/MockVSyncTracker.h" #include "tests/unittests/mock/MockVsyncController.h" @@ -316,10 +314,6 @@ public: return nullptr; } - sp createSurfaceInterceptor() override { - return sp::make(); - } - sp createStartPropertySetThread(bool timestampPropertyValue) override { return sp::make(timestampPropertyValue); } @@ -765,12 +759,10 @@ public: /* Read-write access to private data to set up preconditions and assert * post-conditions. */ - auto& mutableSupportsWideColor() { return mFlinger->mSupportsWideColor; } auto& mutableCurrentState() { return mFlinger->mCurrentState; } auto& mutableDisplays() { return mFlinger->mDisplays; } auto& mutableDrawingState() { return mFlinger->mDrawingState; } - auto& mutableInterceptor() { return mFlinger->mInterceptor; } auto fromHandle(const sp &handle) { return mFlinger->fromHandle(handle); } @@ -778,7 +770,6 @@ public: mutableDisplays().clear(); mutableCurrentState().displays.clear(); mutableDrawingState().displays.clear(); - mutableInterceptor().clear(); mFlinger->mScheduler.reset(); mFlinger->mCompositionEngine->setHwComposer(std::unique_ptr()); mFlinger->mCompositionEngine->setRenderEngine( diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp index a949440f41..2614288016 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_scheduler_fuzzer.cpp @@ -92,7 +92,7 @@ void SchedulerFuzzer::fuzzEventThread() { const auto getVsyncPeriod = [](uid_t /* uid */) { return kSyncPeriod.count(); }; std::unique_ptr thread = std::make_unique< android::impl::EventThread>(std::move(std::make_unique()), nullptr, - nullptr, nullptr, getVsyncPeriod); + nullptr, getVsyncPeriod); thread->onHotplugReceived(getPhysicalDisplayId(), mFdp.ConsumeBool()); sp connection = diff --git a/services/surfaceflinger/tests/Android.bp b/services/surfaceflinger/tests/Android.bp index 13ce65d4af..71b1c0eeb1 100644 --- a/services/surfaceflinger/tests/Android.bp +++ b/services/surfaceflinger/tests/Android.bp @@ -56,13 +56,11 @@ cc_test { "SetFrameRateOverride_test.cpp", "SetGeometry_test.cpp", "Stress_test.cpp", - "SurfaceInterceptor_test.cpp", "VirtualDisplay_test.cpp", "WindowInfosListener_test.cpp", ], data: ["SurfaceFlinger_test.filter"], static_libs: [ - "libtrace_proto", "liblayers_proto", "android.hardware.graphics.composer@2.1", ], diff --git a/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp b/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp deleted file mode 100644 index 7166d413f1..0000000000 --- a/services/surfaceflinger/tests/SurfaceInterceptor_test.cpp +++ /dev/null @@ -1,961 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wconversion" -#pragma clang diagnostic ignored "-Wextra" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace android { - -using Transaction = SurfaceComposerClient::Transaction; -using SurfaceChange = surfaceflinger::SurfaceChange; -using Trace = surfaceflinger::Trace; -using Increment = surfaceflinger::Increment; - -constexpr uint32_t BUFFER_UPDATES = 18; -constexpr uint32_t LAYER_UPDATE = INT_MAX - 2; -constexpr uint32_t SIZE_UPDATE = 134; -constexpr uint32_t STACK_UPDATE = 1; -constexpr int32_t RELATIVE_Z = 42; -constexpr float ALPHA_UPDATE = 0.29f; -constexpr float CORNER_RADIUS_UPDATE = 0.2f; -constexpr int BACKGROUND_BLUR_RADIUS_UPDATE = 24; -constexpr float POSITION_UPDATE = 121; -const Rect CROP_UPDATE(16, 16, 32, 32); -const float SHADOW_RADIUS_UPDATE = 35.0f; -std::vector BLUR_REGIONS_UPDATE; - -const String8 DISPLAY_NAME("SurfaceInterceptor Display Test"); -constexpr auto TEST_BG_SURFACE_NAME = "BG Interceptor Test Surface"; -constexpr auto TEST_FG_SURFACE_NAME = "FG Interceptor Test Surface"; -constexpr auto LAYER_NAME = "Layer Create and Delete Test"; - -constexpr auto DEFAULT_FILENAME = "/data/misc/wmtrace/transaction_trace.winscope"; - -// Fill an RGBA_8888 formatted surface with a single color. -static void fillSurfaceRGBA8(const sp& sc, uint8_t r, uint8_t g, uint8_t b) { - ANativeWindow_Buffer outBuffer; - sp s = sc->getSurface(); - ASSERT_TRUE(s != nullptr); - ASSERT_EQ(NO_ERROR, s->lock(&outBuffer, nullptr)); - uint8_t* img = reinterpret_cast(outBuffer.bits); - for (int y = 0; y < outBuffer.height; y++) { - for (int x = 0; x < outBuffer.width; x++) { - uint8_t* pixel = img + (4 * (y*outBuffer.stride + x)); - pixel[0] = r; - pixel[1] = g; - pixel[2] = b; - pixel[3] = 255; - } - } - ASSERT_EQ(NO_ERROR, s->unlockAndPost()); -} - -static status_t readProtoFile(Trace* trace) { - status_t err = NO_ERROR; - - int fd = open(DEFAULT_FILENAME, O_RDONLY); - { - google::protobuf::io::FileInputStream f(fd); - if (fd && !trace->ParseFromZeroCopyStream(&f)) { - err = PERMISSION_DENIED; - } - } - close(fd); - - return err; -} - -static void enableInterceptor() { - system("service call SurfaceFlinger 1020 i32 1 > /dev/null"); -} - -static void disableInterceptor() { - system("service call SurfaceFlinger 1020 i32 0 > /dev/null"); -} - -std::string getUniqueName(const std::string& name, const Increment& increment) { - return base::StringPrintf("%s#%d", name.c_str(), increment.surface_creation().id()); -} - -int32_t getSurfaceId(const Trace& capturedTrace, const std::string& surfaceName) { - int32_t layerId = 0; - for (const auto& increment : capturedTrace.increment()) { - if (increment.increment_case() == increment.kSurfaceCreation) { - if (increment.surface_creation().name() == getUniqueName(surfaceName, increment)) { - layerId = increment.surface_creation().id(); - } - } - } - return layerId; -} - -int32_t getDisplayId(const Trace& capturedTrace, const std::string& displayName) { - int32_t displayId = 0; - for (const auto& increment : capturedTrace.increment()) { - if (increment.increment_case() == increment.kDisplayCreation) { - if (increment.display_creation().name() == displayName) { - displayId = increment.display_creation().id(); - break; - } - } - } - return displayId; -} - -class SurfaceInterceptorTest : public ::testing::Test { -protected: - void SetUp() override { - // Allow SurfaceInterceptor write to /data - system("setenforce 0"); - - mComposerClient = sp::make(); - ASSERT_EQ(NO_ERROR, mComposerClient->initCheck()); - GTEST_SKIP(); - } - - void TearDown() override { - mComposerClient->dispose(); - mBGSurfaceControl.clear(); - mFGSurfaceControl.clear(); - mComposerClient.clear(); - system("setenforce 1"); - } - - sp mComposerClient; - sp mBGSurfaceControl; - sp mFGSurfaceControl; - int32_t mBGLayerId; - int32_t mFGLayerId; - -public: - using TestTransactionAction = void (SurfaceInterceptorTest::*)(Transaction&); - using TestAction = void (SurfaceInterceptorTest::*)(); - using TestBooleanVerification = bool (SurfaceInterceptorTest::*)(const Trace&); - using TestVerification = void (SurfaceInterceptorTest::*)(const Trace&); - - void setupBackgroundSurface(); - void preProcessTrace(const Trace& trace); - - // captureTest will enable SurfaceInterceptor, setup background surface, - // disable SurfaceInterceptor, collect the trace and process the trace for - // id of background surface before further verification. - void captureTest(TestTransactionAction action, TestBooleanVerification verification); - void captureTest(TestTransactionAction action, SurfaceChange::SurfaceChangeCase changeCase); - void captureTest(TestTransactionAction action, Increment::IncrementCase incrementCase); - void captureTest(TestAction action, TestBooleanVerification verification); - void captureTest(TestAction action, TestVerification verification); - void runInTransaction(TestTransactionAction action); - - // Verification of changes to a surface - bool positionUpdateFound(const SurfaceChange& change, bool foundPosition); - bool sizeUpdateFound(const SurfaceChange& change, bool foundSize); - bool alphaUpdateFound(const SurfaceChange& change, bool foundAlpha); - bool layerUpdateFound(const SurfaceChange& change, bool foundLayer); - bool cropUpdateFound(const SurfaceChange& change, bool foundCrop); - bool cornerRadiusUpdateFound(const SurfaceChange& change, bool foundCornerRadius); - bool backgroundBlurRadiusUpdateFound(const SurfaceChange& change, - bool foundBackgroundBlurRadius); - bool blurRegionsUpdateFound(const SurfaceChange& change, bool foundBlurRegions); - bool matrixUpdateFound(const SurfaceChange& change, bool foundMatrix); - bool scalingModeUpdateFound(const SurfaceChange& change, bool foundScalingMode); - bool transparentRegionHintUpdateFound(const SurfaceChange& change, bool foundTransparentRegion); - bool layerStackUpdateFound(const SurfaceChange& change, bool foundLayerStack); - bool hiddenFlagUpdateFound(const SurfaceChange& change, bool foundHiddenFlag); - bool opaqueFlagUpdateFound(const SurfaceChange& change, bool foundOpaqueFlag); - bool secureFlagUpdateFound(const SurfaceChange& change, bool foundSecureFlag); - bool reparentUpdateFound(const SurfaceChange& change, bool found); - bool relativeParentUpdateFound(const SurfaceChange& change, bool found); - bool shadowRadiusUpdateFound(const SurfaceChange& change, bool found); - bool trustedOverlayUpdateFound(const SurfaceChange& change, bool found); - bool surfaceUpdateFound(const Trace& trace, SurfaceChange::SurfaceChangeCase changeCase); - - // Find all of the updates in the single trace - void assertAllUpdatesFound(const Trace& trace); - - // Verification of creation and deletion of a surface - bool surfaceCreationFound(const Increment& increment, bool foundSurface); - bool surfaceDeletionFound(const Increment& increment, const int32_t targetId, - bool foundSurface); - bool displayCreationFound(const Increment& increment, bool foundDisplay); - bool displayDeletionFound(const Increment& increment, const int32_t targetId, - bool foundDisplay); - bool singleIncrementFound(const Trace& trace, Increment::IncrementCase incrementCase); - - // Verification of buffer updates - bool bufferUpdatesFound(const Trace& trace); - - // Perform each of the possible changes to a surface - void positionUpdate(Transaction&); - void sizeUpdate(Transaction&); - void alphaUpdate(Transaction&); - void layerUpdate(Transaction&); - void cropUpdate(Transaction&); - void cornerRadiusUpdate(Transaction&); - void backgroundBlurRadiusUpdate(Transaction&); - void blurRegionsUpdate(Transaction&); - void matrixUpdate(Transaction&); - void transparentRegionHintUpdate(Transaction&); - void layerStackUpdate(Transaction&); - void hiddenFlagUpdate(Transaction&); - void opaqueFlagUpdate(Transaction&); - void secureFlagUpdate(Transaction&); - void reparentUpdate(Transaction&); - void relativeParentUpdate(Transaction&); - void shadowRadiusUpdate(Transaction&); - void trustedOverlayUpdate(Transaction&); - void surfaceCreation(Transaction&); - void displayCreation(Transaction&); - void displayDeletion(Transaction&); - - void nBufferUpdates(); - void runAllUpdates(); - -private: - void captureInTransaction(TestTransactionAction action, Trace*); - void capture(TestAction action, Trace*); -}; - -void SurfaceInterceptorTest::captureInTransaction(TestTransactionAction action, Trace* outTrace) { - enableInterceptor(); - setupBackgroundSurface(); - runInTransaction(action); - disableInterceptor(); - ASSERT_EQ(NO_ERROR, readProtoFile(outTrace)); - preProcessTrace(*outTrace); -} - -void SurfaceInterceptorTest::capture(TestAction action, Trace* outTrace) { - enableInterceptor(); - setupBackgroundSurface(); - (this->*action)(); - disableInterceptor(); - ASSERT_EQ(NO_ERROR, readProtoFile(outTrace)); - preProcessTrace(*outTrace); -} - -void SurfaceInterceptorTest::setupBackgroundSurface() { - const auto ids = SurfaceComposerClient::getPhysicalDisplayIds(); - ASSERT_FALSE(ids.empty()); - const auto display = SurfaceComposerClient::getPhysicalDisplayToken(ids.front()); - ASSERT_FALSE(display == nullptr); - - ui::DisplayMode mode; - ASSERT_EQ(NO_ERROR, SurfaceComposerClient::getActiveDisplayMode(display, &mode)); - const ui::Size& resolution = mode.resolution; - - // Background surface - mBGSurfaceControl = - mComposerClient->createSurface(String8(TEST_BG_SURFACE_NAME), resolution.getWidth(), - resolution.getHeight(), PIXEL_FORMAT_RGBA_8888, 0); - ASSERT_TRUE(mBGSurfaceControl != nullptr); - ASSERT_TRUE(mBGSurfaceControl->isValid()); - - // Foreground surface - mFGSurfaceControl = - mComposerClient->createSurface(String8(TEST_FG_SURFACE_NAME), resolution.getWidth(), - resolution.getHeight(), PIXEL_FORMAT_RGBA_8888, 0); - ASSERT_TRUE(mFGSurfaceControl != nullptr); - ASSERT_TRUE(mFGSurfaceControl->isValid()); - - Transaction t; - t.setDisplayLayerStack(display, ui::DEFAULT_LAYER_STACK); - ASSERT_EQ(NO_ERROR, - t.setLayer(mBGSurfaceControl, INT_MAX - 3) - .show(mBGSurfaceControl) - .setLayer(mFGSurfaceControl, INT_MAX - 3) - .show(mFGSurfaceControl) - .apply()); -} - -void SurfaceInterceptorTest::preProcessTrace(const Trace& trace) { - mBGLayerId = getSurfaceId(trace, TEST_BG_SURFACE_NAME); - mFGLayerId = getSurfaceId(trace, TEST_FG_SURFACE_NAME); -} - -void SurfaceInterceptorTest::captureTest(TestTransactionAction action, - TestBooleanVerification verification) { - Trace capturedTrace; - captureInTransaction(action, &capturedTrace); - ASSERT_TRUE((this->*verification)(capturedTrace)); -} - -void SurfaceInterceptorTest::captureTest(TestTransactionAction action, - Increment::IncrementCase incrementCase) { - Trace capturedTrace; - captureInTransaction(action, &capturedTrace); - ASSERT_TRUE(singleIncrementFound(capturedTrace, incrementCase)); -} - -void SurfaceInterceptorTest::captureTest(TestTransactionAction action, - SurfaceChange::SurfaceChangeCase changeCase) { - Trace capturedTrace; - captureInTransaction(action, &capturedTrace); - ASSERT_TRUE(surfaceUpdateFound(capturedTrace, changeCase)); -} - -void SurfaceInterceptorTest::captureTest(TestAction action, TestBooleanVerification verification) { - Trace capturedTrace; - capture(action, &capturedTrace); - ASSERT_TRUE((this->*verification)(capturedTrace)); -} - -void SurfaceInterceptorTest::captureTest(TestAction action, TestVerification verification) { - Trace capturedTrace; - capture(action, &capturedTrace); - (this->*verification)(capturedTrace); -} - -void SurfaceInterceptorTest::runInTransaction(TestTransactionAction action) { - Transaction t; - (this->*action)(t); - t.apply(true); -} - -void SurfaceInterceptorTest::positionUpdate(Transaction& t) { - t.setPosition(mBGSurfaceControl, POSITION_UPDATE, POSITION_UPDATE); -} - -void SurfaceInterceptorTest::sizeUpdate(Transaction&) {} - -void SurfaceInterceptorTest::alphaUpdate(Transaction& t) { - t.setAlpha(mBGSurfaceControl, ALPHA_UPDATE); -} - -void SurfaceInterceptorTest::cornerRadiusUpdate(Transaction& t) { - t.setCornerRadius(mBGSurfaceControl, CORNER_RADIUS_UPDATE); -} - -void SurfaceInterceptorTest::backgroundBlurRadiusUpdate(Transaction& t) { - t.setBackgroundBlurRadius(mBGSurfaceControl, BACKGROUND_BLUR_RADIUS_UPDATE); -} - -void SurfaceInterceptorTest::blurRegionsUpdate(Transaction& t) { - BLUR_REGIONS_UPDATE.empty(); - BLUR_REGIONS_UPDATE.push_back(BlurRegion()); - t.setBlurRegions(mBGSurfaceControl, BLUR_REGIONS_UPDATE); -} - -void SurfaceInterceptorTest::layerUpdate(Transaction& t) { - t.setLayer(mBGSurfaceControl, LAYER_UPDATE); -} - -void SurfaceInterceptorTest::cropUpdate(Transaction& t) { - t.setCrop(mBGSurfaceControl, CROP_UPDATE); -} - -void SurfaceInterceptorTest::matrixUpdate(Transaction& t) { - t.setMatrix(mBGSurfaceControl, M_SQRT1_2, M_SQRT1_2, -M_SQRT1_2, M_SQRT1_2); -} - -void SurfaceInterceptorTest::transparentRegionHintUpdate(Transaction& t) { - Region region(CROP_UPDATE); - t.setTransparentRegionHint(mBGSurfaceControl, region); -} - -void SurfaceInterceptorTest::layerStackUpdate(Transaction& t) { - t.setLayerStack(mBGSurfaceControl, ui::LayerStack::fromValue(STACK_UPDATE)); -} - -void SurfaceInterceptorTest::hiddenFlagUpdate(Transaction& t) { - t.setFlags(mBGSurfaceControl, layer_state_t::eLayerHidden, layer_state_t::eLayerHidden); -} - -void SurfaceInterceptorTest::opaqueFlagUpdate(Transaction& t) { - t.setFlags(mBGSurfaceControl, layer_state_t::eLayerOpaque, layer_state_t::eLayerOpaque); -} - -void SurfaceInterceptorTest::secureFlagUpdate(Transaction& t) { - t.setFlags(mBGSurfaceControl, layer_state_t::eLayerSecure, layer_state_t::eLayerSecure); -} - -void SurfaceInterceptorTest::reparentUpdate(Transaction& t) { - t.reparent(mBGSurfaceControl, mFGSurfaceControl); -} - -void SurfaceInterceptorTest::relativeParentUpdate(Transaction& t) { - t.setRelativeLayer(mBGSurfaceControl, mFGSurfaceControl, RELATIVE_Z); -} - -void SurfaceInterceptorTest::shadowRadiusUpdate(Transaction& t) { - t.setShadowRadius(mBGSurfaceControl, SHADOW_RADIUS_UPDATE); -} - -void SurfaceInterceptorTest::trustedOverlayUpdate(Transaction& t) { - t.setTrustedOverlay(mBGSurfaceControl, true); -} - -void SurfaceInterceptorTest::displayCreation(Transaction&) { - sp testDisplay = SurfaceComposerClient::createDisplay(DISPLAY_NAME, false); - SurfaceComposerClient::destroyDisplay(testDisplay); -} - -void SurfaceInterceptorTest::displayDeletion(Transaction&) { - sp testDisplay = SurfaceComposerClient::createDisplay(DISPLAY_NAME, false); - SurfaceComposerClient::destroyDisplay(testDisplay); -} - -void SurfaceInterceptorTest::runAllUpdates() { - runInTransaction(&SurfaceInterceptorTest::positionUpdate); - runInTransaction(&SurfaceInterceptorTest::sizeUpdate); - runInTransaction(&SurfaceInterceptorTest::alphaUpdate); - runInTransaction(&SurfaceInterceptorTest::cornerRadiusUpdate); - runInTransaction(&SurfaceInterceptorTest::backgroundBlurRadiusUpdate); - runInTransaction(&SurfaceInterceptorTest::blurRegionsUpdate); - runInTransaction(&SurfaceInterceptorTest::layerUpdate); - runInTransaction(&SurfaceInterceptorTest::cropUpdate); - runInTransaction(&SurfaceInterceptorTest::matrixUpdate); - runInTransaction(&SurfaceInterceptorTest::transparentRegionHintUpdate); - runInTransaction(&SurfaceInterceptorTest::layerStackUpdate); - runInTransaction(&SurfaceInterceptorTest::hiddenFlagUpdate); - runInTransaction(&SurfaceInterceptorTest::opaqueFlagUpdate); - runInTransaction(&SurfaceInterceptorTest::secureFlagUpdate); - runInTransaction(&SurfaceInterceptorTest::reparentUpdate); - runInTransaction(&SurfaceInterceptorTest::relativeParentUpdate); - runInTransaction(&SurfaceInterceptorTest::shadowRadiusUpdate); - runInTransaction(&SurfaceInterceptorTest::trustedOverlayUpdate); -} - -void SurfaceInterceptorTest::surfaceCreation(Transaction&) { - mComposerClient->createSurface(String8(LAYER_NAME), SIZE_UPDATE, SIZE_UPDATE, - PIXEL_FORMAT_RGBA_8888, 0); -} - -void SurfaceInterceptorTest::nBufferUpdates() { - std::random_device rd; - std::mt19937_64 gen(rd()); - // This makes testing fun - std::uniform_int_distribution dis; - for (uint32_t i = 0; i < BUFFER_UPDATES; ++i) { - fillSurfaceRGBA8(mBGSurfaceControl, dis(gen), dis(gen), dis(gen)); - } -} - -bool SurfaceInterceptorTest::positionUpdateFound(const SurfaceChange& change, bool foundPosition) { - // There should only be one position transaction with x and y = POSITION_UPDATE - bool hasX(change.position().x() == POSITION_UPDATE); - bool hasY(change.position().y() == POSITION_UPDATE); - if (hasX && hasY && !foundPosition) { - foundPosition = true; - } else if (hasX && hasY && foundPosition) { - // Failed because the position update was found a second time - [] () { FAIL(); }(); - } - return foundPosition; -} - -bool SurfaceInterceptorTest::sizeUpdateFound(const SurfaceChange&, bool) { - return true; -} - -bool SurfaceInterceptorTest::alphaUpdateFound(const SurfaceChange& change, bool foundAlpha) { - bool hasAlpha(change.alpha().alpha() == ALPHA_UPDATE); - if (hasAlpha && !foundAlpha) { - foundAlpha = true; - } else if (hasAlpha && foundAlpha) { - [] () { FAIL(); }(); - } - return foundAlpha; -} - -bool SurfaceInterceptorTest::cornerRadiusUpdateFound(const SurfaceChange &change, - bool foundCornerRadius) { - bool hasCornerRadius(change.corner_radius().corner_radius() == CORNER_RADIUS_UPDATE); - if (hasCornerRadius && !foundCornerRadius) { - foundCornerRadius = true; - } else if (hasCornerRadius && foundCornerRadius) { - [] () { FAIL(); }(); - } - return foundCornerRadius; -} - -bool SurfaceInterceptorTest::backgroundBlurRadiusUpdateFound(const SurfaceChange& change, - bool foundBackgroundBlur) { - bool hasBackgroundBlur(change.background_blur_radius().background_blur_radius() == - BACKGROUND_BLUR_RADIUS_UPDATE); - if (hasBackgroundBlur && !foundBackgroundBlur) { - foundBackgroundBlur = true; - } else if (hasBackgroundBlur && foundBackgroundBlur) { - []() { FAIL(); }(); - } - return foundBackgroundBlur; -} - -bool SurfaceInterceptorTest::blurRegionsUpdateFound(const SurfaceChange& change, - bool foundBlurRegions) { - bool hasBlurRegions(change.blur_regions().blur_regions_size() == BLUR_REGIONS_UPDATE.size()); - if (hasBlurRegions && !foundBlurRegions) { - foundBlurRegions = true; - } else if (hasBlurRegions && foundBlurRegions) { - []() { FAIL(); }(); - } - return foundBlurRegions; -} - -bool SurfaceInterceptorTest::layerUpdateFound(const SurfaceChange& change, bool foundLayer) { - bool hasLayer(change.layer().layer() == LAYER_UPDATE); - if (hasLayer && !foundLayer) { - foundLayer = true; - } else if (hasLayer && foundLayer) { - [] () { FAIL(); }(); - } - return foundLayer; -} - -bool SurfaceInterceptorTest::cropUpdateFound(const SurfaceChange& change, bool foundCrop) { - bool hasLeft(change.crop().rectangle().left() == CROP_UPDATE.left); - bool hasTop(change.crop().rectangle().top() == CROP_UPDATE.top); - bool hasRight(change.crop().rectangle().right() == CROP_UPDATE.right); - bool hasBottom(change.crop().rectangle().bottom() == CROP_UPDATE.bottom); - if (hasLeft && hasRight && hasTop && hasBottom && !foundCrop) { - foundCrop = true; - } else if (hasLeft && hasRight && hasTop && hasBottom && foundCrop) { - [] () { FAIL(); }(); - } - return foundCrop; -} - -bool SurfaceInterceptorTest::matrixUpdateFound(const SurfaceChange& change, bool foundMatrix) { - bool hasSx((float)change.matrix().dsdx() == (float)M_SQRT1_2); - bool hasTx((float)change.matrix().dtdx() == (float)M_SQRT1_2); - bool hasSy((float)change.matrix().dsdy() == (float)M_SQRT1_2); - bool hasTy((float)change.matrix().dtdy() == (float)-M_SQRT1_2); - if (hasSx && hasTx && hasSy && hasTy && !foundMatrix) { - foundMatrix = true; - } else if (hasSx && hasTx && hasSy && hasTy && foundMatrix) { - [] () { FAIL(); }(); - } - return foundMatrix; -} - -bool SurfaceInterceptorTest::transparentRegionHintUpdateFound(const SurfaceChange& change, - bool foundTransparentRegion) { - auto traceRegion = change.transparent_region_hint().region(0); - bool hasLeft(traceRegion.left() == CROP_UPDATE.left); - bool hasTop(traceRegion.top() == CROP_UPDATE.top); - bool hasRight(traceRegion.right() == CROP_UPDATE.right); - bool hasBottom(traceRegion.bottom() == CROP_UPDATE.bottom); - if (hasLeft && hasRight && hasTop && hasBottom && !foundTransparentRegion) { - foundTransparentRegion = true; - } else if (hasLeft && hasRight && hasTop && hasBottom && foundTransparentRegion) { - [] () { FAIL(); }(); - } - return foundTransparentRegion; -} - -bool SurfaceInterceptorTest::layerStackUpdateFound(const SurfaceChange& change, - bool foundLayerStack) { - bool hasLayerStackUpdate(change.layer_stack().layer_stack() == STACK_UPDATE); - if (hasLayerStackUpdate && !foundLayerStack) { - foundLayerStack = true; - } else if (hasLayerStackUpdate && foundLayerStack) { - [] () { FAIL(); }(); - } - return foundLayerStack; -} - -bool SurfaceInterceptorTest::hiddenFlagUpdateFound(const SurfaceChange& change, - bool foundHiddenFlag) { - bool hasHiddenFlag(change.hidden_flag().hidden_flag()); - if (hasHiddenFlag && !foundHiddenFlag) { - foundHiddenFlag = true; - } else if (hasHiddenFlag && foundHiddenFlag) { - [] () { FAIL(); }(); - } - return foundHiddenFlag; -} - -bool SurfaceInterceptorTest::opaqueFlagUpdateFound(const SurfaceChange& change, - bool foundOpaqueFlag) { - bool hasOpaqueFlag(change.opaque_flag().opaque_flag()); - if (hasOpaqueFlag && !foundOpaqueFlag) { - foundOpaqueFlag = true; - } else if (hasOpaqueFlag && foundOpaqueFlag) { - [] () { FAIL(); }(); - } - return foundOpaqueFlag; -} - -bool SurfaceInterceptorTest::secureFlagUpdateFound(const SurfaceChange& change, - bool foundSecureFlag) { - bool hasSecureFlag(change.secure_flag().secure_flag()); - if (hasSecureFlag && !foundSecureFlag) { - foundSecureFlag = true; - } else if (hasSecureFlag && foundSecureFlag) { - [] () { FAIL(); }(); - } - return foundSecureFlag; -} - -bool SurfaceInterceptorTest::reparentUpdateFound(const SurfaceChange& change, bool found) { - bool hasId(change.reparent().parent_id() == mFGLayerId); - if (hasId && !found) { - found = true; - } else if (hasId && found) { - []() { FAIL(); }(); - } - return found; -} - -bool SurfaceInterceptorTest::relativeParentUpdateFound(const SurfaceChange& change, bool found) { - bool hasId(change.relative_parent().relative_parent_id() == mFGLayerId); - if (hasId && !found) { - found = true; - } else if (hasId && found) { - []() { FAIL(); }(); - } - return found; -} - -bool SurfaceInterceptorTest::shadowRadiusUpdateFound(const SurfaceChange& change, - bool foundShadowRadius) { - bool hasShadowRadius(change.shadow_radius().radius() == SHADOW_RADIUS_UPDATE); - if (hasShadowRadius && !foundShadowRadius) { - foundShadowRadius = true; - } else if (hasShadowRadius && foundShadowRadius) { - []() { FAIL(); }(); - } - return foundShadowRadius; -} - -bool SurfaceInterceptorTest::trustedOverlayUpdateFound(const SurfaceChange& change, - bool foundTrustedOverlay) { - bool hasTrustedOverlay(change.trusted_overlay().is_trusted_overlay()); - if (hasTrustedOverlay && !foundTrustedOverlay) { - foundTrustedOverlay = true; - } else if (hasTrustedOverlay && foundTrustedOverlay) { - []() { FAIL(); }(); - } - return foundTrustedOverlay; -} - -bool SurfaceInterceptorTest::surfaceUpdateFound(const Trace& trace, - SurfaceChange::SurfaceChangeCase changeCase) { - bool foundUpdate = false; - for (const auto& increment : trace.increment()) { - if (increment.increment_case() == increment.kTransaction) { - for (const auto& change : increment.transaction().surface_change()) { - if (change.id() == mBGLayerId && change.SurfaceChange_case() == changeCase) { - switch (changeCase) { - case SurfaceChange::SurfaceChangeCase::kPosition: - // foundUpdate is sent for the tests to fail on duplicated increments - foundUpdate = positionUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kSize: - foundUpdate = sizeUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kAlpha: - foundUpdate = alphaUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kLayer: - foundUpdate = layerUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kCrop: - foundUpdate = cropUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kCornerRadius: - foundUpdate = cornerRadiusUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kBackgroundBlurRadius: - foundUpdate = backgroundBlurRadiusUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kBlurRegions: - foundUpdate = blurRegionsUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kMatrix: - foundUpdate = matrixUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kTransparentRegionHint: - foundUpdate = transparentRegionHintUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kLayerStack: - foundUpdate = layerStackUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kHiddenFlag: - foundUpdate = hiddenFlagUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kOpaqueFlag: - foundUpdate = opaqueFlagUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kSecureFlag: - foundUpdate = secureFlagUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kReparent: - foundUpdate = reparentUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kRelativeParent: - foundUpdate = relativeParentUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kShadowRadius: - foundUpdate = shadowRadiusUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::kTrustedOverlay: - foundUpdate = trustedOverlayUpdateFound(change, foundUpdate); - break; - case SurfaceChange::SurfaceChangeCase::SURFACECHANGE_NOT_SET: - break; - } - } - } - } - } - return foundUpdate; -} - -void SurfaceInterceptorTest::assertAllUpdatesFound(const Trace& trace) { - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kPosition)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kSize)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kAlpha)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kLayer)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kCrop)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kMatrix)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kTransparentRegionHint)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kLayerStack)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kHiddenFlag)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kOpaqueFlag)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kSecureFlag)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kReparent)); - ASSERT_TRUE(surfaceUpdateFound(trace, SurfaceChange::SurfaceChangeCase::kRelativeParent)); -} - -bool SurfaceInterceptorTest::surfaceCreationFound(const Increment& increment, bool foundSurface) { - bool isMatch(increment.surface_creation().name() == getUniqueName(LAYER_NAME, increment)); - if (isMatch && !foundSurface) { - foundSurface = true; - } else if (isMatch && foundSurface) { - [] () { FAIL(); }(); - } - return foundSurface; -} - -bool SurfaceInterceptorTest::surfaceDeletionFound(const Increment& increment, - const int32_t targetId, bool foundSurface) { - bool isMatch(increment.surface_deletion().id() == targetId); - if (isMatch && !foundSurface) { - foundSurface = true; - } else if (isMatch && foundSurface) { - [] () { FAIL(); }(); - } - return foundSurface; -} - -bool SurfaceInterceptorTest::displayCreationFound(const Increment& increment, bool foundDisplay) { - bool isMatch(increment.display_creation().name() == DISPLAY_NAME.string() && - !increment.display_creation().is_secure()); - if (isMatch && !foundDisplay) { - foundDisplay = true; - } else if (isMatch && foundDisplay) { - [] () { FAIL(); }(); - } - return foundDisplay; -} - -bool SurfaceInterceptorTest::displayDeletionFound(const Increment& increment, - const int32_t targetId, bool foundDisplay) { - bool isMatch(increment.display_deletion().id() == targetId); - if (isMatch && !foundDisplay) { - foundDisplay = true; - } else if (isMatch && foundDisplay) { - [] () { FAIL(); }(); - } - return foundDisplay; -} - -bool SurfaceInterceptorTest::singleIncrementFound(const Trace& trace, - Increment::IncrementCase incrementCase) { - bool foundIncrement = false; - for (const auto& increment : trace.increment()) { - if (increment.increment_case() == incrementCase) { - int32_t targetId = 0; - switch (incrementCase) { - case Increment::IncrementCase::kSurfaceCreation: - foundIncrement = surfaceCreationFound(increment, foundIncrement); - break; - case Increment::IncrementCase::kSurfaceDeletion: - // Find the id of created surface. - targetId = getSurfaceId(trace, LAYER_NAME); - foundIncrement = surfaceDeletionFound(increment, targetId, foundIncrement); - break; - case Increment::IncrementCase::kDisplayCreation: - foundIncrement = displayCreationFound(increment, foundIncrement); - break; - case Increment::IncrementCase::kDisplayDeletion: - // Find the id of created display. - targetId = getDisplayId(trace, DISPLAY_NAME.string()); - foundIncrement = displayDeletionFound(increment, targetId, foundIncrement); - break; - default: - /* code */ - break; - } - } - } - return foundIncrement; -} - -bool SurfaceInterceptorTest::bufferUpdatesFound(const Trace& trace) { - uint32_t updates = 0; - for (const auto& inc : trace.increment()) { - if (inc.increment_case() == inc.kBufferUpdate && inc.buffer_update().id() == mBGLayerId) { - updates++; - } - } - return updates == BUFFER_UPDATES; -} - -TEST_F(SurfaceInterceptorTest, InterceptPositionUpdateWorks) { - captureTest(&SurfaceInterceptorTest::positionUpdate, - SurfaceChange::SurfaceChangeCase::kPosition); -} - -TEST_F(SurfaceInterceptorTest, InterceptSizeUpdateWorks) { - captureTest(&SurfaceInterceptorTest::sizeUpdate, SurfaceChange::SurfaceChangeCase::kSize); -} - -TEST_F(SurfaceInterceptorTest, InterceptAlphaUpdateWorks) { - captureTest(&SurfaceInterceptorTest::alphaUpdate, SurfaceChange::SurfaceChangeCase::kAlpha); -} - -TEST_F(SurfaceInterceptorTest, InterceptLayerUpdateWorks) { - captureTest(&SurfaceInterceptorTest::layerUpdate, SurfaceChange::SurfaceChangeCase::kLayer); -} - -TEST_F(SurfaceInterceptorTest, InterceptCropUpdateWorks) { - captureTest(&SurfaceInterceptorTest::cropUpdate, SurfaceChange::SurfaceChangeCase::kCrop); -} - -TEST_F(SurfaceInterceptorTest, InterceptCornerRadiusUpdateWorks) { - captureTest(&SurfaceInterceptorTest::cornerRadiusUpdate, - SurfaceChange::SurfaceChangeCase::kCornerRadius); -} - -TEST_F(SurfaceInterceptorTest, InterceptBackgroundBlurRadiusUpdateWorks) { - captureTest(&SurfaceInterceptorTest::backgroundBlurRadiusUpdate, - SurfaceChange::SurfaceChangeCase::kBackgroundBlurRadius); -} - -TEST_F(SurfaceInterceptorTest, InterceptBlurRegionsUpdateWorks) { - captureTest(&SurfaceInterceptorTest::blurRegionsUpdate, - SurfaceChange::SurfaceChangeCase::kBlurRegions); -} - -TEST_F(SurfaceInterceptorTest, InterceptMatrixUpdateWorks) { - captureTest(&SurfaceInterceptorTest::matrixUpdate, SurfaceChange::SurfaceChangeCase::kMatrix); -} - -TEST_F(SurfaceInterceptorTest, InterceptTransparentRegionHintUpdateWorks) { - captureTest(&SurfaceInterceptorTest::transparentRegionHintUpdate, - SurfaceChange::SurfaceChangeCase::kTransparentRegionHint); -} - -TEST_F(SurfaceInterceptorTest, InterceptLayerStackUpdateWorks) { - captureTest(&SurfaceInterceptorTest::layerStackUpdate, - SurfaceChange::SurfaceChangeCase::kLayerStack); -} - -TEST_F(SurfaceInterceptorTest, InterceptHiddenFlagUpdateWorks) { - captureTest(&SurfaceInterceptorTest::hiddenFlagUpdate, - SurfaceChange::SurfaceChangeCase::kHiddenFlag); -} - -TEST_F(SurfaceInterceptorTest, InterceptOpaqueFlagUpdateWorks) { - captureTest(&SurfaceInterceptorTest::opaqueFlagUpdate, - SurfaceChange::SurfaceChangeCase::kOpaqueFlag); -} - -TEST_F(SurfaceInterceptorTest, InterceptSecureFlagUpdateWorks) { - captureTest(&SurfaceInterceptorTest::secureFlagUpdate, - SurfaceChange::SurfaceChangeCase::kSecureFlag); -} - -TEST_F(SurfaceInterceptorTest, InterceptReparentUpdateWorks) { - captureTest(&SurfaceInterceptorTest::reparentUpdate, - SurfaceChange::SurfaceChangeCase::kReparent); -} - -TEST_F(SurfaceInterceptorTest, InterceptRelativeParentUpdateWorks) { - captureTest(&SurfaceInterceptorTest::relativeParentUpdate, - SurfaceChange::SurfaceChangeCase::kRelativeParent); -} - -TEST_F(SurfaceInterceptorTest, InterceptShadowRadiusUpdateWorks) { - captureTest(&SurfaceInterceptorTest::shadowRadiusUpdate, - SurfaceChange::SurfaceChangeCase::kShadowRadius); -} - -TEST_F(SurfaceInterceptorTest, InterceptTrustedOverlayUpdateWorks) { - captureTest(&SurfaceInterceptorTest::trustedOverlayUpdate, - SurfaceChange::SurfaceChangeCase::kTrustedOverlay); -} - -TEST_F(SurfaceInterceptorTest, InterceptAllUpdatesWorks) { - captureTest(&SurfaceInterceptorTest::runAllUpdates, - &SurfaceInterceptorTest::assertAllUpdatesFound); -} - -TEST_F(SurfaceInterceptorTest, InterceptSurfaceCreationWorks) { - captureTest(&SurfaceInterceptorTest::surfaceCreation, - Increment::IncrementCase::kSurfaceCreation); -} - -TEST_F(SurfaceInterceptorTest, InterceptDisplayCreationWorks) { - captureTest(&SurfaceInterceptorTest::displayCreation, - Increment::IncrementCase::kDisplayCreation); -} - -TEST_F(SurfaceInterceptorTest, InterceptDisplayDeletionWorks) { - enableInterceptor(); - runInTransaction(&SurfaceInterceptorTest::displayDeletion); - disableInterceptor(); - Trace capturedTrace; - ASSERT_EQ(NO_ERROR, readProtoFile(&capturedTrace)); - ASSERT_TRUE(singleIncrementFound(capturedTrace, Increment::IncrementCase::kDisplayDeletion)); -} - -// If the interceptor is enabled while buffer updates are being pushed, the interceptor should -// first create a snapshot of the existing displays and surfaces and then start capturing -// the buffer updates -TEST_F(SurfaceInterceptorTest, InterceptWhileBufferUpdatesWorks) { - setupBackgroundSurface(); - std::thread bufferUpdates(&SurfaceInterceptorTest::nBufferUpdates, this); - enableInterceptor(); - disableInterceptor(); - bufferUpdates.join(); - - Trace capturedTrace; - ASSERT_EQ(NO_ERROR, readProtoFile(&capturedTrace)); - const auto& firstIncrement = capturedTrace.mutable_increment(0); - ASSERT_EQ(firstIncrement->increment_case(), Increment::IncrementCase::kDisplayCreation); -} -} -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic pop // ignored "-Wconversion -Wextra" diff --git a/services/surfaceflinger/tests/fakehwc/Android.bp b/services/surfaceflinger/tests/fakehwc/Android.bp index 06afdb10cc..0d40e7085a 100644 --- a/services/surfaceflinger/tests/fakehwc/Android.bp +++ b/services/surfaceflinger/tests/fakehwc/Android.bp @@ -53,7 +53,6 @@ cc_test { "libgmock", "libperfetto_client_experimental", "librenderengine", - "libtrace_proto", "libaidlcommonsupport", ], header_libs: [ diff --git a/services/surfaceflinger/tests/unittests/Android.bp b/services/surfaceflinger/tests/unittests/Android.bp index 4469df007a..d2b58137f0 100644 --- a/services/surfaceflinger/tests/unittests/Android.bp +++ b/services/surfaceflinger/tests/unittests/Android.bp @@ -34,7 +34,6 @@ filegroup { "mock/MockFrameTimeline.cpp", "mock/MockFrameTracer.cpp", "mock/MockNativeWindowSurface.cpp", - "mock/MockSurfaceInterceptor.cpp", "mock/MockTimeStats.cpp", "mock/MockVsyncController.cpp", "mock/MockVSyncTracker.cpp", @@ -168,7 +167,6 @@ cc_defaults { "libtimestats_atoms_proto", "libtimestats_proto", "libtonemap", - "libtrace_proto", "perfetto_trace_protos", ], shared_libs: [ diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp index abe32c9794..8b91c67982 100644 --- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp +++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp @@ -50,7 +50,6 @@ DisplayTransactionTest::DisplayTransactionTest() { injectMockScheduler(); mFlinger.setupRenderEngine(std::unique_ptr(mRenderEngine)); - mFlinger.mutableInterceptor() = mSurfaceInterceptor; injectMockComposer(0); } diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h index 20e776f1f2..9cceb5e4df 100644 --- a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h +++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h @@ -49,7 +49,6 @@ #include "mock/DisplayHardware/MockPowerAdvisor.h" #include "mock/MockEventThread.h" #include "mock/MockNativeWindowSurface.h" -#include "mock/MockSurfaceInterceptor.h" #include "mock/MockVsyncController.h" #include "mock/system/window/MockNativeWindow.h" @@ -120,7 +119,6 @@ public: // to keep a reference to them for use in setting up call expectations. renderengine::mock::RenderEngine* mRenderEngine = new renderengine::mock::RenderEngine(); Hwc2::mock::Composer* mComposer = nullptr; - sp mSurfaceInterceptor = sp::make(); mock::VsyncController* mVsyncController = new mock::VsyncController; mock::VSyncTracker* mVSyncTracker = new mock::VSyncTracker; diff --git a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp index 978afc510a..a5beaba286 100644 --- a/services/surfaceflinger/tests/unittests/EventThreadTest.cpp +++ b/services/surfaceflinger/tests/unittests/EventThreadTest.cpp @@ -93,7 +93,6 @@ protected: void expectVSyncSetDurationCallReceived(std::chrono::nanoseconds expectedDuration, std::chrono::nanoseconds expectedReadyDuration); VSyncSource::Callback* expectVSyncSetCallbackCallReceived(); - void expectInterceptCallReceived(nsecs_t expectedTimestamp); void expectVsyncEventReceivedByConnection(const char* name, ConnectionEventRecorder& connectionEventRecorder, nsecs_t expectedTimestamp, unsigned expectedCount); @@ -114,7 +113,6 @@ protected: AsyncCallRecorder mVSyncSetDurationCallRecorder; AsyncCallRecorder mResyncCallRecorder; - AsyncCallRecorder mInterceptVSyncCallRecorder; AsyncCallRecorder mThrottleVsyncCallRecorder; ConnectionEventRecorder mConnectionEventCallRecorder{0}; ConnectionEventRecorder mThrottledConnectionEventCallRecorder{0}; @@ -181,7 +179,6 @@ void EventThreadTest::createThread(std::unique_ptr source) { mTokenManager = std::make_unique(); mThread = std::make_unique(std::move(source), mTokenManager.get(), - mInterceptVSyncCallRecorder.getInvocable(), throttleVsync, getVsyncPeriod); // EventThread should register itself as VSyncSource callback. @@ -219,12 +216,6 @@ VSyncSource::Callback* EventThreadTest::expectVSyncSetCallbackCallReceived() { return callbackSet.has_value() ? std::get<0>(callbackSet.value()) : nullptr; } -void EventThreadTest::expectInterceptCallReceived(nsecs_t expectedTimestamp) { - auto args = mInterceptVSyncCallRecorder.waitForCall(); - ASSERT_TRUE(args.has_value()); - EXPECT_EQ(expectedTimestamp, std::get<0>(args.value())); -} - void EventThreadTest::expectThrottleVsyncReceived(nsecs_t expectedTimestamp, uid_t uid) { auto args = mThrottleVsyncCallRecorder.waitForCall(); ASSERT_TRUE(args.has_value()); @@ -348,7 +339,6 @@ TEST_F(EventThreadTest, canCreateAndDestroyThreadWithNoEventsSent) { EXPECT_FALSE(mVSyncSetCallbackCallRecorder.waitForCall(0us).has_value()); EXPECT_FALSE(mVSyncSetDurationCallRecorder.waitForCall(0us).has_value()); EXPECT_FALSE(mResyncCallRecorder.waitForCall(0us).has_value()); - EXPECT_FALSE(mInterceptVSyncCallRecorder.waitForCall(0us).has_value()); EXPECT_FALSE(mConnectionEventCallRecorder.waitForCall(0us).has_value()); } @@ -374,17 +364,15 @@ TEST_F(EventThreadTest, requestNextVsyncPostsASingleVSyncEventToTheConnection) { expectVSyncSetEnabledCallReceived(true); // Use the received callback to signal a first vsync event. - // The interceptor should receive the event, as well as the connection. + // The throttler should receive the event, as well as the connection. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectThrottleVsyncReceived(456, mConnectionUid); expectVsyncEventReceivedByConnection(123, 1u); // Use the received callback to signal a second vsync event. - // The interceptor should receive the event, but the connection should + // The throttler should receive the event, but the connection should // not as it was only interested in the first. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); EXPECT_FALSE(mThrottleVsyncCallRecorder.waitForUnexpectedCall().has_value()); EXPECT_FALSE(mConnectionEventCallRecorder.waitForUnexpectedCall().has_value()); @@ -400,10 +388,9 @@ TEST_F(EventThreadTest, requestNextVsyncEventFrameTimelinesCorrect) { expectVSyncSetEnabledCallReceived(true); // Use the received callback to signal a vsync event. - // The interceptor should receive the event, as well as the connection. + // The throttler should receive the event, as well as the connection. VSyncSource::VSyncData vsyncData = {456, 789}; mCallback->onVSyncEvent(123, vsyncData); - expectInterceptCallReceived(123); expectVsyncEventFrameTimelinesCorrect(123, vsyncData); } @@ -477,10 +464,9 @@ TEST_F(EventThreadTest, setVsyncRateZeroPostsNoVSyncEventsToThatConnection) { expectVSyncSetEnabledCallReceived(true); // Send a vsync event. EventThread should then make a call to the - // interceptor, and the second connection. The first connection should not + // the second connection. The first connection should not // get the event. mCallback->onVSyncEvent(123, {456, 0}); - expectInterceptCallReceived(123); EXPECT_FALSE(firstConnectionEventRecorder.waitForUnexpectedCall().has_value()); expectVsyncEventReceivedByConnection("secondConnection", secondConnectionEventRecorder, 123, 1u); @@ -493,21 +479,18 @@ TEST_F(EventThreadTest, setVsyncRateOnePostsAllEventsToThatConnection) { expectVSyncSetEnabledCallReceived(true); // Send a vsync event. EventThread should then make a call to the - // interceptor, and the connection. + // throttler, and the connection. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectThrottleVsyncReceived(456, mConnectionUid); expectVsyncEventReceivedByConnection(123, 1u); // A second event should go to the same places. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); expectThrottleVsyncReceived(123, mConnectionUid); expectVsyncEventReceivedByConnection(456, 2u); // A third event should go to the same places. mCallback->onVSyncEvent(789, {777, 111}); - expectInterceptCallReceived(789); expectThrottleVsyncReceived(777, mConnectionUid); expectVsyncEventReceivedByConnection(789, 3u); } @@ -518,27 +501,23 @@ TEST_F(EventThreadTest, setVsyncRateTwoPostsEveryOtherEventToThatConnection) { // EventThread should enable vsync callbacks. expectVSyncSetEnabledCallReceived(true); - // The first event will be seen by the interceptor, and not the connection. + // The first event will not be seen by the connection. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); EXPECT_FALSE(mConnectionEventCallRecorder.waitForUnexpectedCall().has_value()); EXPECT_FALSE(mThrottleVsyncCallRecorder.waitForUnexpectedCall().has_value()); - // The second event will be seen by the interceptor and the connection. + // The second event will be seen by the connection. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); expectVsyncEventReceivedByConnection(456, 2u); EXPECT_FALSE(mThrottleVsyncCallRecorder.waitForUnexpectedCall().has_value()); - // The third event will be seen by the interceptor, and not the connection. + // The third event will not be seen by the connection. mCallback->onVSyncEvent(789, {777, 744}); - expectInterceptCallReceived(789); EXPECT_FALSE(mConnectionEventCallRecorder.waitForUnexpectedCall().has_value()); EXPECT_FALSE(mThrottleVsyncCallRecorder.waitForUnexpectedCall().has_value()); - // The fourth event will be seen by the interceptor and the connection. + // The fourth event will be seen by the connection. mCallback->onVSyncEvent(101112, {7847, 86}); - expectInterceptCallReceived(101112); expectVsyncEventReceivedByConnection(101112, 4u); } @@ -551,9 +530,8 @@ TEST_F(EventThreadTest, connectionsRemovedIfInstanceDestroyed) { // Destroy the only (strong) reference to the connection. mConnection = nullptr; - // The first event will be seen by the interceptor, and not the connection. + // The first event will not be seen by the connection. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); EXPECT_FALSE(mConnectionEventCallRecorder.waitForUnexpectedCall().has_value()); // EventThread should disable vsync callbacks @@ -568,16 +546,12 @@ TEST_F(EventThreadTest, connectionsRemovedIfEventDeliveryError) { // EventThread should enable vsync callbacks. expectVSyncSetEnabledCallReceived(true); - // The first event will be seen by the interceptor, and by the connection, - // which then returns an error. + // The first event will be seen by the connection, which then returns an error. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectVsyncEventReceivedByConnection("errorConnection", errorConnectionEventRecorder, 123, 1u); - // A subsequent event will be seen by the interceptor and not by the - // connection. + // A subsequent event will not be seen by the connection. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); EXPECT_FALSE(errorConnectionEventRecorder.waitForUnexpectedCall().has_value()); // EventThread should disable vsync callbacks with the second event @@ -599,10 +573,8 @@ TEST_F(EventThreadTest, tracksEventConnections) { // EventThread should enable vsync callbacks. expectVSyncSetEnabledCallReceived(true); - // The first event will be seen by the interceptor, and by the connection, - // which then returns an error. + // The first event will be seen by the connection, which then returns an error. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectVsyncEventReceivedByConnection("errorConnection", errorConnectionEventRecorder, 123, 1u); expectVsyncEventReceivedByConnection("successConnection", secondConnectionEventRecorder, 123, 1u); @@ -617,16 +589,13 @@ TEST_F(EventThreadTest, eventsDroppedIfNonfatalEventDeliveryError) { // EventThread should enable vsync callbacks. expectVSyncSetEnabledCallReceived(true); - // The first event will be seen by the interceptor, and by the connection, - // which then returns an non-fatal error. + // The first event will be seen by the connection, which then returns a non-fatal error. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectVsyncEventReceivedByConnection("errorConnection", errorConnectionEventRecorder, 123, 1u); - // A subsequent event will be seen by the interceptor, and by the connection, - // which still then returns an non-fatal error. + // A subsequent event will be seen by the connection, which still then returns a non-fatal + // error. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); expectVsyncEventReceivedByConnection("errorConnection", errorConnectionEventRecorder, 456, 2u); // EventThread will not disable vsync callbacks as the errors are non-fatal. @@ -748,17 +717,15 @@ TEST_F(EventThreadTest, requestNextVsyncWithThrottleVsyncDoesntPostVSync) { expectVSyncSetEnabledCallReceived(true); // Use the received callback to signal a first vsync event. - // The interceptor should receive the event, but not the connection. + // The throttler should receive the event, but not the connection. mCallback->onVSyncEvent(123, {456, 789}); - expectInterceptCallReceived(123); expectThrottleVsyncReceived(456, mThrottledConnectionUid); mThrottledConnectionEventCallRecorder.waitForUnexpectedCall(); // Use the received callback to signal a second vsync event. - // The interceptor should receive the event, but the connection should + // The throttler should receive the event, but the connection should // not as it was only interested in the first. mCallback->onVSyncEvent(456, {123, 0}); - expectInterceptCallReceived(456); expectThrottleVsyncReceived(123, mThrottledConnectionUid); EXPECT_FALSE(mConnectionEventCallRecorder.waitForUnexpectedCall().has_value()); diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_CreateDisplayTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_CreateDisplayTest.cpp index f7d34ac5da..6a9c970bc3 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_CreateDisplayTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_CreateDisplayTest.cpp @@ -30,9 +30,6 @@ TEST_F(CreateDisplayTest, createDisplaySetsCurrentStateForNonsecureDisplay) { // -------------------------------------------------------------------- // Call Expectations - // The call should notify the interceptor that a display was created. - EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1); - // -------------------------------------------------------------------- // Invocation @@ -61,9 +58,6 @@ TEST_F(CreateDisplayTest, createDisplaySetsCurrentStateForSecureDisplay) { // -------------------------------------------------------------------- // Call Expectations - // The call should notify the interceptor that a display was created. - EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1); - // -------------------------------------------------------------------- // Invocation int64_t oldId = IPCThreadState::self()->clearCallingIdentity(); diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp index 40ef949468..93a3811172 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DestroyDisplayTest.cpp @@ -37,9 +37,6 @@ TEST_F(DestroyDisplayTest, destroyDisplayClearsCurrentStateForDisplay) { // -------------------------------------------------------------------- // Call Expectations - // The call should notify the interceptor that a display was created. - EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1); - // Destroying the display commits a display transaction. EXPECT_CALL(*mFlinger.scheduler(), scheduleFrame()).Times(1); diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp index 73f654ba87..94d517a3c3 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_DisplayTransactionCommitTest.cpp @@ -90,15 +90,12 @@ void DisplayTransactionCommitTest::setupCommonCallExpectationsForConnectProcessi Case::HdrSupport::setupComposerCallExpectations(this); Case::PerFrameMetadataSupport::setupComposerCallExpectations(this); - EXPECT_CALL(*mSurfaceInterceptor, saveDisplayCreation(_)).Times(1); expectHotplugReceived(mEventThread); expectHotplugReceived(mSFEventThread); } template void DisplayTransactionCommitTest::setupCommonCallExpectationsForDisconnectProcessing() { - EXPECT_CALL(*mSurfaceInterceptor, saveDisplayDeletion(_)).Times(1); - expectHotplugReceived(mEventThread); expectHotplugReceived(mSFEventThread); } diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp index 98249bf104..f553a23f3c 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_OnInitializeDisplaysTest.cpp @@ -38,11 +38,6 @@ TEST_F(OnInitializeDisplaysTest, onInitializeDisplaysSetsUpPrimaryDisplay) { // -------------------------------------------------------------------- // Call Expectations - // We expect the surface interceptor to possibly be used, but we treat it as - // disabled since it is called as a side effect rather than directly by this - // function. - EXPECT_CALL(*mSurfaceInterceptor, isEnabled()).WillOnce(Return(false)); - // We expect a call to get the active display config. Case::Display::setupHwcGetActiveConfigCallExpectations(this); diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp index 6f84437372..25857ecb4e 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetPowerModeInternalTest.cpp @@ -276,13 +276,6 @@ struct DisplayPowerCase { EXPECT_CALL(*test->mFlinger.scheduler(), scheduleFrame()).Times(1); } - static void setupSurfaceInterceptorCallExpectations(DisplayTransactionTest* test, - PowerMode mode) { - EXPECT_CALL(*test->mSurfaceInterceptor, isEnabled()).WillOnce(Return(true)); - EXPECT_CALL(*test->mSurfaceInterceptor, savePowerModeUpdate(_, static_cast(mode))) - .Times(1); - } - static void setupComposerCallExpectations(DisplayTransactionTest* test, PowerMode mode) { // Any calls to get the active config will return a default value. EXPECT_CALL(*test->mComposer, getActiveConfig(Display::HWC_DISPLAY_ID, _)) @@ -349,7 +342,6 @@ void SetPowerModeInternalTest::transitionDisplayCommon() { // -------------------------------------------------------------------- // Call Expectations - Case::setupSurfaceInterceptorCallExpectations(this, Case::Transition::TARGET_POWER_MODE); Case::Transition::template setupCallExpectations(this); // -------------------------------------------------------------------- diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index f5042d301d..e0784eec06 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -40,7 +40,6 @@ #include "StartPropertySetThread.h" #include "SurfaceFlinger.h" #include "SurfaceFlingerDefaultFactory.h" -#include "SurfaceInterceptor.h" #include "TestableScheduler.h" #include "mock/DisplayHardware/MockComposer.h" #include "mock/DisplayHardware/MockDisplayMode.h" @@ -81,10 +80,6 @@ public: return std::make_unique(); } - sp createSurfaceInterceptor() override { - return sp::make(); - } - sp createStartPropertySetThread(bool timestampPropertyValue) override { return sp::make(timestampPropertyValue); } @@ -518,7 +513,6 @@ public: auto& mutablePhysicalDisplays() { return mFlinger->mPhysicalDisplays; } auto& mutableDrawingState() { return mFlinger->mDrawingState; } auto& mutableGeometryDirty() { return mFlinger->mGeometryDirty; } - auto& mutableInterceptor() { return mFlinger->mInterceptor; } auto& mutableMainThreadId() { return mFlinger->mMainThreadId; } auto& mutablePendingHotplugEvents() { return mFlinger->mPendingHotplugEvents; } auto& mutableTexturePool() { return mFlinger->mTexturePool; } @@ -543,7 +537,6 @@ public: mutableDisplays().clear(); mutableCurrentState().displays.clear(); mutableDrawingState().displays.clear(); - mutableInterceptor().clear(); mFlinger->mScheduler.reset(); mFlinger->mCompositionEngine->setHwComposer(std::unique_ptr()); mFlinger->mCompositionEngine->setRenderEngine( diff --git a/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.cpp b/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.cpp deleted file mode 100644 index 0a0e7b5861..0000000000 --- a/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.cpp +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic push -#pragma clang diagnostic ignored "-Wconversion" - -#include "mock/MockSurfaceInterceptor.h" - -namespace android::mock { - -// Explicit default instantiation is recommended. -SurfaceInterceptor::SurfaceInterceptor() = default; -SurfaceInterceptor::~SurfaceInterceptor() = default; - -} // namespace android::mock - -// TODO(b/129481165): remove the #pragma below and fix conversion issues -#pragma clang diagnostic pop // ignored "-Wconversion" diff --git a/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.h b/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.h deleted file mode 100644 index b085027397..0000000000 --- a/services/surfaceflinger/tests/unittests/mock/MockSurfaceInterceptor.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include - -#include "SurfaceInterceptor.h" - -namespace android::mock { - -class SurfaceInterceptor : public android::SurfaceInterceptor { -public: - SurfaceInterceptor(); - ~SurfaceInterceptor() override; - - MOCK_METHOD2(enable, - void(const SortedVector>&, - const DefaultKeyedVector, DisplayDeviceState>&)); - MOCK_METHOD0(disable, void()); - MOCK_METHOD0(isEnabled, bool()); - MOCK_METHOD1(addTransactionTraceListener, void(const sp&)); - MOCK_METHOD1(binderDied, void(const wp&)); - MOCK_METHOD7(saveTransaction, - void(const Vector&, - const DefaultKeyedVector, DisplayDeviceState>&, - const Vector&, uint32_t, int, int, uint64_t)); - MOCK_METHOD1(saveSurfaceCreation, void(const sp&)); - MOCK_METHOD1(saveSurfaceDeletion, void(const sp&)); - MOCK_METHOD4(saveBufferUpdate, void(int32_t, uint32_t, uint32_t, uint64_t)); - MOCK_METHOD1(saveDisplayCreation, void(const DisplayDeviceState&)); - MOCK_METHOD1(saveDisplayDeletion, void(int32_t)); - MOCK_METHOD2(savePowerModeUpdate, void(int32_t, int32_t)); - MOCK_METHOD1(saveVSyncEvent, void(nsecs_t)); -}; - -} // namespace android::mock -- cgit v1.2.3-59-g8ed1b From 40fff5cdf1db782c04b1bae6c9f45d56797f1b02 Mon Sep 17 00:00:00 2001 From: Vishnu Nair Date: Fri, 4 Nov 2022 02:46:28 +0000 Subject: SF: Look up buffer caches in binder thread Avoid locking inside the main thread and contention with binder thread (via client token binder died). Test: presubmit Bug: 238781169 Change-Id: I8a440e9fe3e6f41761d90196ec6128d756735eee --- libs/gui/ISurfaceComposer.cpp | 10 ++-- libs/gui/SurfaceComposerClient.cpp | 8 +-- libs/gui/include/gui/ISurfaceComposer.h | 4 +- libs/gui/include/gui/LayerState.h | 3 +- libs/gui/tests/Surface_test.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 61 +++++++++++++--------- services/surfaceflinger/SurfaceFlinger.h | 10 ++-- .../Tracing/TransactionProtoParser.cpp | 4 +- .../Tracing/tools/LayerTraceGenerator.cpp | 8 +-- services/surfaceflinger/TransactionState.h | 33 ++++++++---- .../fuzzer/surfaceflinger_fuzzers_utils.h | 14 ++--- .../tests/unittests/TestableSurfaceFlinger.h | 18 ++++--- .../tests/unittests/TransactionApplicationTest.cpp | 25 ++++++--- .../tests/unittests/TransactionProtoParserTest.cpp | 4 +- .../tests/unittests/TransactionTracingTest.cpp | 20 +++---- 15 files changed, 131 insertions(+), 93 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index 4c887ec96d..a77ca04943 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -60,11 +60,11 @@ public: virtual ~BpSurfaceComposer(); status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - const Vector& state, - const Vector& displays, uint32_t flags, - const sp& applyToken, const InputWindowCommands& commands, - int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + Vector& state, const Vector& displays, + uint32_t flags, const sp& applyToken, + const InputWindowCommands& commands, int64_t desiredPresentTime, + bool isAutoTimestamp, const client_cache_t& uncacheBuffer, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override { Parcel data, reply; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 9c2ce0f242..b60e195c81 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -912,11 +912,11 @@ void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { client_cache_t uncacheBuffer; uncacheBuffer.token = BufferCache::getInstance().getToken(); uncacheBuffer.id = cacheId; - + Vector composerStates; status_t status = - sf->setTransactionState(FrameTimelineInfo{}, {}, {}, ISurfaceComposer::eOneWay, - Transaction::getDefaultApplyToken(), {}, systemTime(), true, - uncacheBuffer, false, {}, generateId()); + sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, + ISurfaceComposer::eOneWay, Transaction::getDefaultApplyToken(), + {}, systemTime(), true, uncacheBuffer, false, {}, generateId()); if (status != NO_ERROR) { ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s", strerror(-status)); diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index e91d75467d..d517e99fda 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -55,7 +55,7 @@ namespace android { struct client_cache_t; -struct ComposerState; +class ComposerState; struct DisplayStatInfo; struct DisplayState; struct InputWindowCommands; @@ -110,7 +110,7 @@ public: /* open/close transactions. requires ACCESS_SURFACE_FLINGER permission */ virtual status_t setTransactionState( - const FrameTimelineInfo& frameTimelineInfo, const Vector& state, + const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h index 45272e7431..09f171db04 100644 --- a/libs/gui/include/gui/LayerState.h +++ b/libs/gui/include/gui/LayerState.h @@ -311,7 +311,8 @@ struct layer_state_t { bool dimmingEnabled; }; -struct ComposerState { +class ComposerState { +public: layer_state_t state; status_t write(Parcel& output) const; status_t read(const Parcel& input); diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 346b686466..54fc578ac7 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -696,7 +696,7 @@ public: } status_t setTransactionState(const FrameTimelineInfo& /*frameTimelineInfo*/, - const Vector& /*state*/, + Vector& /*state*/, const Vector& /*displays*/, uint32_t /*flags*/, const sp& /*applyToken*/, const InputWindowCommands& /*inputWindowCommands*/, diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index cfebec70cb..849fd9c7ce 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -104,6 +104,7 @@ #include #include #include +#include #include #include "BackgroundExecutor.h" @@ -3878,7 +3879,7 @@ bool SurfaceFlinger::shouldLatchUnsignaled(const sp& layer, const layer_s } status_t SurfaceFlinger::setTransactionState( - const FrameTimelineInfo& frameTimelineInfo, const Vector& states, + const FrameTimelineInfo& frameTimelineInfo, Vector& states, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, @@ -3910,7 +3911,24 @@ status_t SurfaceFlinger::setTransactionState( IPCThreadState* ipc = IPCThreadState::self(); const int originPid = ipc->getCallingPid(); const int originUid = ipc->getCallingUid(); - TransactionState state{frameTimelineInfo, states, + + std::vector resolvedStates; + resolvedStates.reserve(states.size()); + for (auto& state : states) { + resolvedStates.emplace_back(std::move(state)); + auto& resolvedState = resolvedStates.back(); + if (resolvedState.state.hasBufferChanges() && resolvedState.state.hasValidBuffer() && + resolvedState.state.surface) { + resolvedState.externalTexture = + getExternalTextureFromBufferData(*resolvedState.state.bufferData, + std::to_string(resolvedState.state.layerId) + .c_str(), + transactionId); + mBufferCountTracker.increment(resolvedState.state.surface->localBinder()); + } + } + + TransactionState state{frameTimelineInfo, resolvedStates, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, @@ -3919,11 +3937,6 @@ status_t SurfaceFlinger::setTransactionState( listenerCallbacks, originPid, originUid, transactionId}; - // Check for incoming buffer updates and increment the pending buffer count. - state.traverseStatesWithBuffers([&](const layer_state_t& state) { - mBufferCountTracker.increment(state.surface->localBinder()); - }); - if (mTransactionTracing) { mTransactionTracing->addQueuedTransaction(state); } @@ -3942,7 +3955,7 @@ status_t SurfaceFlinger::setTransactionState( } bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& states, + std::vector& states, const Vector& displays, uint32_t flags, const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, @@ -3964,13 +3977,12 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin } uint32_t clientStateFlags = 0; - for (int i = 0; i < states.size(); i++) { - ComposerState& state = states.editItemAt(i); + for (auto& resolvedState : states) { clientStateFlags |= - setClientStateLocked(frameTimelineInfo, state, desiredPresentTime, isAutoTimestamp, - postTime, permissions, transactionId); - if ((flags & eAnimation) && state.state.surface) { - if (const auto layer = LayerHandle::getLayer(state.state.surface)) { + setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime, + isAutoTimestamp, postTime, permissions, transactionId); + if ((flags & eAnimation) && resolvedState.state.surface) { + if (const auto layer = LayerHandle::getLayer(resolvedState.state.surface)) { using LayerUpdateType = scheduler::LayerHistory::LayerUpdateType; mScheduler->recordLayerHistory(layer.get(), isAutoTimestamp ? 0 : desiredPresentTime, @@ -4082,7 +4094,7 @@ bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermis } uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo, - ComposerState& composerState, + ResolvedComposerState& composerState, int64_t desiredPresentTime, bool isAutoTimestamp, int64_t postTime, uint32_t permissions, uint64_t transactionId) { @@ -4377,11 +4389,9 @@ uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTime } if (what & layer_state_t::eBufferChanged) { - std::shared_ptr buffer = - getExternalTextureFromBufferData(*s.bufferData, layer->getDebugName(), - transactionId); - if (layer->setBuffer(buffer, *s.bufferData, postTime, desiredPresentTime, isAutoTimestamp, - dequeueBufferTimestamp, frameTimelineInfo)) { + if (layer->setBuffer(composerState.externalTexture, *s.bufferData, postTime, + desiredPresentTime, isAutoTimestamp, dequeueBufferTimestamp, + frameTimelineInfo)) { flags |= eTraversalNeeded; } } else if (frameTimelineInfo.vsyncId != FrameTimelineInfo::INVALID_VSYNC_ID) { @@ -4589,7 +4599,7 @@ void SurfaceFlinger::onInitializeDisplays() { LOG_ALWAYS_FATAL_IF(token == nullptr); // reset screen orientation and use primary layer stack - Vector state; + std::vector state; Vector displays; DisplayState d; d.what = DisplayState::eDisplayProjectionChanged | @@ -6974,9 +6984,12 @@ std::shared_ptr SurfaceFlinger::getExternalTextur } if (result.error() == ClientCache::AddError::CacheFull) { - mTransactionHandler - .onTransactionQueueStalled(transactionId, bufferData.releaseBufferListener, - "Buffer processing hung due to full buffer cache"); + ALOGE("Attempted to create an ExternalTexture for layer %s but CacheFull", layerName); + + if (bufferData.releaseBufferListener) { + bufferData.releaseBufferListener->onTransactionQueueStalled( + String8("Buffer processing hung due to full buffer cache")); + } } return nullptr; diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 85c194bbb5..e09d2b5e5c 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -490,9 +490,8 @@ private: sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const; status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - const Vector& state, - const Vector& displays, uint32_t flags, - const sp& applyToken, + Vector& state, const Vector& displays, + uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, @@ -702,7 +701,8 @@ private: /* * Transactions */ - bool applyTransactionState(const FrameTimelineInfo& info, Vector& state, + bool applyTransactionState(const FrameTimelineInfo& info, + std::vector& state, const Vector& displays, uint32_t flags, const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, @@ -723,7 +723,7 @@ private: const TransactionHandler::TransactionFlushState& flushState) REQUIRES(kMainThreadContext); - uint32_t setClientStateLocked(const FrameTimelineInfo&, ComposerState&, + uint32_t setClientStateLocked(const FrameTimelineInfo&, ResolvedComposerState&, int64_t desiredPresentTime, bool isAutoTimestamp, int64_t postTime, uint32_t permissions, uint64_t transactionId) REQUIRES(mStateLock); diff --git a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp index 3418c82f9e..2f464873ea 100644 --- a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp +++ b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp @@ -310,10 +310,10 @@ TransactionState TransactionProtoParser::fromProto(const proto::TransactionState int32_t layerCount = proto.layer_changes_size(); t.states.reserve(static_cast(layerCount)); for (int i = 0; i < layerCount; i++) { - ComposerState s; + ResolvedComposerState s; s.state.what = 0; fromProto(proto.layer_changes(i), s.state); - t.states.add(s); + t.states.emplace_back(s); } int32_t displayCount = proto.display_changes_size(); diff --git a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp index 25fdd26ef1..f1a6c0e2fa 100644 --- a/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp +++ b/services/surfaceflinger/Tracing/tools/LayerTraceGenerator.cpp @@ -240,13 +240,7 @@ bool LayerTraceGenerator::generate(const proto::TransactionTraceFile& traceFile, for (int j = 0; j < entry.transactions_size(); j++) { // apply transactions TransactionState transaction = parser.fromProto(entry.transactions(j)); - mFlinger.setTransactionState(transaction.frameTimelineInfo, transaction.states, - transaction.displays, transaction.flags, - transaction.applyToken, transaction.inputWindowCommands, - transaction.desiredPresentTime, - transaction.isAutoTimestamp, {}, - transaction.hasListenerCallbacks, - transaction.listenerCallbacks, transaction.id); + mFlinger.setTransactionStateInternal(transaction); } const auto frameTime = TimePoint::fromNs(entry.elapsed_realtime_nanos()); diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 3cbfe811ea..f1ef31d81c 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -20,17 +20,26 @@ #include #include #include +#include "renderengine/ExternalTexture.h" #include #include namespace android { +// Extends the client side composer state by resolving buffer cache ids. +class ResolvedComposerState : public ComposerState { +public: + ResolvedComposerState() = default; + ResolvedComposerState(ComposerState&& source) { state = std::move(source.state); } + std::shared_ptr externalTexture; +}; + struct TransactionState { TransactionState() = default; TransactionState(const FrameTimelineInfo& frameTimelineInfo, - const Vector& composerStates, + std::vector& composerStates, const Vector& displayStates, uint32_t transactionFlags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, @@ -38,7 +47,7 @@ struct TransactionState { bool hasListenerCallbacks, std::vector listenerCallbacks, int originPid, int originUid, uint64_t transactionId) : frameTimelineInfo(frameTimelineInfo), - states(composerStates), + states(std::move(composerStates)), displays(displayStates), flags(transactionFlags), applyToken(applyToken), @@ -57,18 +66,20 @@ struct TransactionState { // Invokes `void(const layer_state_t&)` visitor for matching layers. template void traverseStatesWithBuffers(Visitor&& visitor) const { - for (const auto& [state] : states) { - if (state.hasBufferChanges() && state.hasValidBuffer() && state.surface) { - visitor(state); + for (const auto& state : states) { + if (state.state.hasBufferChanges() && state.state.hasValidBuffer() && + state.state.surface) { + visitor(state.state); } } } template void traverseStatesWithBuffersWhileTrue(Visitor&& visitor) const { - for (const auto& [state] : states) { - if (state.hasBufferChanges() && state.hasValidBuffer() && state.surface) { - if (!visitor(state)) return; + for (const auto& state : states) { + if (state.state.hasBufferChanges() && state.state.hasValidBuffer() && + state.state.surface) { + if (!visitor(state.state)) return; } } } @@ -79,8 +90,8 @@ struct TransactionState { bool isFrameActive() const { if (!displays.empty()) return true; - for (const auto& [state] : states) { - if (state.frameRateCompatibility != ANATIVEWINDOW_FRAME_RATE_NO_VOTE) { + for (const auto& state : states) { + if (state.state.frameRateCompatibility != ANATIVEWINDOW_FRAME_RATE_NO_VOTE) { return true; } } @@ -89,7 +100,7 @@ struct TransactionState { } FrameTimelineInfo frameTimelineInfo; - Vector states; + std::vector states; Vector displays; uint32_t flags; sp applyToken; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index e55586774f..cc0b012391 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -736,12 +736,14 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionQueues; } - auto setTransactionState( - const FrameTimelineInfo &frameTimelineInfo, const Vector &states, - const Vector &displays, uint32_t flags, const sp &applyToken, - const InputWindowCommands &inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t &uncacheBuffer, bool hasListenerCallbacks, - std::vector &listenerCallbacks, uint64_t transactionId) { + auto setTransactionState(const FrameTimelineInfo &frameTimelineInfo, + Vector &states, const Vector &displays, + uint32_t flags, const sp &applyToken, + const InputWindowCommands &inputWindowCommands, + int64_t desiredPresentTime, bool isAutoTimestamp, + const client_cache_t &uncacheBuffer, bool hasListenerCallbacks, + std::vector &listenerCallbacks, + uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index 7f471bc8b8..935d95339f 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -427,18 +427,24 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionCount.load(); } - auto setTransactionState( - const FrameTimelineInfo& frameTimelineInfo, const Vector& states, - const Vector& displays, uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, - std::vector& listenerCallbacks, uint64_t transactionId) { + auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, + Vector& states, const Vector& displays, + uint32_t flags, const sp& applyToken, + const InputWindowCommands& inputWindowCommands, + int64_t desiredPresentTime, bool isAutoTimestamp, + const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + std::vector& listenerCallbacks, + uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, listenerCallbacks, transactionId); } + auto setTransactionStateInternal(TransactionState& transaction) { + return mFlinger->mTransactionHandler.queueTransaction(std::move(transaction)); + } + auto flushTransactionQueues() { return FTL_FAKE_GUARD(kMainThreadContext, mFlinger->flushTransactionQueues(kVsyncId)); } diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index 9888f002fb..488d4a9c58 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -32,6 +32,7 @@ #include "FrontEnd/TransactionHandler.h" #include "TestableSurfaceFlinger.h" +#include "TransactionState.h" #include "mock/MockEventThread.h" #include "mock/MockVsyncController.h" @@ -359,13 +360,23 @@ public: EXPECT_TRUE(mFlinger.getTransactionQueue().isEmpty()); EXPECT_EQ(0u, mFlinger.getPendingTransactionQueue().size()); - for (const auto& transaction : transactions) { - mFlinger.setTransactionState(transaction.frameTimelineInfo, transaction.states, - transaction.displays, transaction.flags, - transaction.applyToken, transaction.inputWindowCommands, - transaction.desiredPresentTime, - transaction.isAutoTimestamp, transaction.uncacheBuffer, - mHasListenerCallbacks, mCallbacks, transaction.id); + for (auto transaction : transactions) { + std::vector resolvedStates; + resolvedStates.reserve(transaction.states.size()); + for (auto& state : transaction.states) { + resolvedStates.emplace_back(std::move(state)); + } + + TransactionState transactionState(transaction.frameTimelineInfo, resolvedStates, + transaction.displays, transaction.flags, + transaction.applyToken, + transaction.inputWindowCommands, + transaction.desiredPresentTime, + transaction.isAutoTimestamp, + transaction.uncacheBuffer, systemTime(), 0, + mHasListenerCallbacks, mCallbacks, getpid(), + static_cast(getuid()), transaction.id); + mFlinger.setTransactionStateInternal(transactionState); } mFlinger.flushTransactionQueues(); EXPECT_TRUE(mFlinger.getTransactionQueue().isEmpty()); diff --git a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp index 14e1aac793..b6427c0ffb 100644 --- a/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionProtoParserTest.cpp @@ -46,14 +46,14 @@ TEST(TransactionProtoParserTest, parse) { size_t layerCount = 2; t1.states.reserve(layerCount); for (uint32_t i = 0; i < layerCount; i++) { - ComposerState s; + ResolvedComposerState s; if (i == 1) { layer.parentSurfaceControlForChild = sp::make(SurfaceComposerClient::getDefault(), layerHandle, 42, "#42"); } s.state = layer; - t1.states.add(s); + t1.states.emplace_back(s); } size_t displayCount = 2; diff --git a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp index 2dbcfbdb18..482c3a8e50 100644 --- a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp @@ -112,16 +112,16 @@ protected: { TransactionState transaction; transaction.id = 50; - ComposerState layerState; + ResolvedComposerState layerState; layerState.state.surface = fakeLayerHandle; layerState.state.what = layer_state_t::eLayerChanged; layerState.state.z = 42; - transaction.states.add(layerState); - ComposerState childState; + transaction.states.emplace_back(layerState); + ResolvedComposerState childState; childState.state.surface = fakeChildLayerHandle; childState.state.what = layer_state_t::eLayerChanged; childState.state.z = 43; - transaction.states.add(childState); + transaction.states.emplace_back(childState); mTracing.addQueuedTransaction(transaction); std::vector transactions; @@ -138,12 +138,12 @@ protected: { TransactionState transaction; transaction.id = 51; - ComposerState layerState; + ResolvedComposerState layerState; layerState.state.surface = fakeLayerHandle; layerState.state.what = layer_state_t::eLayerChanged | layer_state_t::ePositionChanged; layerState.state.z = 41; layerState.state.x = 22; - transaction.states.add(layerState); + transaction.states.emplace_back(layerState); mTracing.addQueuedTransaction(transaction); std::vector transactions; @@ -247,16 +247,16 @@ protected: { TransactionState transaction; transaction.id = 50; - ComposerState layerState; + ResolvedComposerState layerState; layerState.state.surface = fakeLayerHandle; layerState.state.what = layer_state_t::eLayerChanged; layerState.state.z = 42; - transaction.states.add(layerState); - ComposerState mirrorState; + transaction.states.emplace_back(layerState); + ResolvedComposerState mirrorState; mirrorState.state.surface = fakeMirrorLayerHandle; mirrorState.state.what = layer_state_t::eLayerChanged; mirrorState.state.z = 43; - transaction.states.add(mirrorState); + transaction.states.emplace_back(mirrorState); mTracing.addQueuedTransaction(transaction); std::vector transactions; -- cgit v1.2.3-59-g8ed1b From c50b4988e93872bfe023a4e099548f84bdfd998d Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Wed, 24 Nov 2021 12:34:52 -0800 Subject: Migrate ITransactionCompletedListener to AIDL This migrates the c++ interface to aidl. Bug: 225250470 Test: atest libsurfaceflinger_unittest libgui_test SurfaceFlinger_test Change-Id: I997e302ac8c6a23bedefaa5b8272677f3dce54df --- libs/binder/include/binder/IInterface.h | 1 - libs/gui/ISurfaceComposer.cpp | 1 + libs/gui/ITransactionCompletedListener.cpp | 71 +----- libs/gui/LayerState.cpp | 1 + libs/gui/SurfaceComposerClient.cpp | 33 ++- .../android/gui/ITransactionCompletedListener.aidl | 31 +++ libs/gui/aidl/android/gui/ListenerStats.aidl | 19 ++ libs/gui/aidl/android/gui/ReleaseCallbackId.aidl | 19 ++ libs/gui/include/gui/ISurfaceComposer.h | 3 +- .../include/gui/ITransactionCompletedListener.h | 271 --------------------- libs/gui/include/gui/LayerState.h | 6 +- libs/gui/include/gui/ListenerStats.h | 225 +++++++++++++++++ libs/gui/include/gui/ReleaseCallbackId.h | 50 ++++ libs/gui/include/gui/SurfaceComposerClient.h | 25 +- .../surfaceflinger/FrontEnd/TransactionHandler.cpp | 2 +- .../surfaceflinger/FrontEnd/TransactionHandler.h | 1 + services/surfaceflinger/Layer.cpp | 9 +- services/surfaceflinger/SurfaceFlinger.cpp | 5 +- services/surfaceflinger/SurfaceFlinger.h | 5 +- .../surfaceflinger/TransactionCallbackInvoker.h | 17 +- 20 files changed, 428 insertions(+), 367 deletions(-) create mode 100644 libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl create mode 100644 libs/gui/aidl/android/gui/ListenerStats.aidl create mode 100644 libs/gui/aidl/android/gui/ReleaseCallbackId.aidl delete mode 100644 libs/gui/include/gui/ITransactionCompletedListener.h create mode 100644 libs/gui/include/gui/ListenerStats.h create mode 100644 libs/gui/include/gui/ReleaseCallbackId.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/binder/include/binder/IInterface.h b/libs/binder/include/binder/IInterface.h index dc572ac953..8cc8105ff9 100644 --- a/libs/binder/include/binder/IInterface.h +++ b/libs/binder/include/binder/IInterface.h @@ -230,7 +230,6 @@ constexpr const char* const kManualInterfaces[] = { "android.graphicsenv.IGpuService", "android.gui.IConsumerListener", "android.gui.IGraphicBufferConsumer", - "android.gui.ITransactionComposerListener", "android.gui.SensorEventConnection", "android.gui.SensorServer", "android.hardware.ICamera", diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a77ca04943..a0e75ffe49 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -42,6 +42,7 @@ using namespace aidl::android::hardware::graphics; namespace android { +using gui::CallbackId; using gui::DisplayCaptureArgs; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; diff --git a/libs/gui/ITransactionCompletedListener.cpp b/libs/gui/ITransactionCompletedListener.cpp index 2b25b614e9..23d7d500c8 100644 --- a/libs/gui/ITransactionCompletedListener.cpp +++ b/libs/gui/ITransactionCompletedListener.cpp @@ -21,22 +21,11 @@ #include #include -#include #include +#include #include -namespace android { - -namespace { // Anonymous - -enum class Tag : uint32_t { - ON_TRANSACTION_COMPLETED = IBinder::FIRST_CALL_TRANSACTION, - ON_RELEASE_BUFFER, - ON_TRANSACTION_QUEUE_STALLED, - LAST = ON_TRANSACTION_QUEUE_STALLED, -}; - -} // Anonymous namespace +namespace android::gui { status_t FrameEventHistoryStats::writeToParcel(Parcel* output) const { status_t err = output->writeUint64(frameNumber); @@ -274,60 +263,6 @@ ListenerStats ListenerStats::createEmpty( return listenerStats; } -class BpTransactionCompletedListener : public SafeBpInterface { -public: - explicit BpTransactionCompletedListener(const sp& impl) - : SafeBpInterface(impl, "BpTransactionCompletedListener") { - } - - ~BpTransactionCompletedListener() override; - - void onTransactionCompleted(ListenerStats stats) override { - callRemoteAsync(Tag::ON_TRANSACTION_COMPLETED, - stats); - } - - void onReleaseBuffer(ReleaseCallbackId callbackId, sp releaseFence, - uint32_t currentMaxAcquiredBufferCount) override { - callRemoteAsync(Tag::ON_RELEASE_BUFFER, callbackId, - releaseFence, - currentMaxAcquiredBufferCount); - } - - void onTransactionQueueStalled(const String8& reason) override { - callRemoteAsync< - decltype(&ITransactionCompletedListener:: - onTransactionQueueStalled)>(Tag::ON_TRANSACTION_QUEUE_STALLED, - reason); - } -}; - -// Out-of-line virtual method definitions to trigger vtable emission in this translation unit (see -// clang warning -Wweak-vtables) -BpTransactionCompletedListener::~BpTransactionCompletedListener() = default; - -IMPLEMENT_META_INTERFACE(TransactionCompletedListener, "android.gui.ITransactionComposerListener"); - -status_t BnTransactionCompletedListener::onTransact(uint32_t code, const Parcel& data, - Parcel* reply, uint32_t flags) { - if (code < IBinder::FIRST_CALL_TRANSACTION || code > static_cast(Tag::LAST)) { - return BBinder::onTransact(code, data, reply, flags); - } - auto tag = static_cast(code); - switch (tag) { - case Tag::ON_TRANSACTION_COMPLETED: - return callLocalAsync(data, reply, - &ITransactionCompletedListener::onTransactionCompleted); - case Tag::ON_RELEASE_BUFFER: - return callLocalAsync(data, reply, &ITransactionCompletedListener::onReleaseBuffer); - case Tag::ON_TRANSACTION_QUEUE_STALLED: - return callLocalAsync(data, reply, - &ITransactionCompletedListener::onTransactionQueueStalled); - } -} - ListenerCallbacks ListenerCallbacks::filter(CallbackId::Type type) const { std::vector filteredCallbackIds; for (const auto& callbackId : callbackIds) { @@ -366,4 +301,4 @@ status_t ReleaseCallbackId::readFromParcel(const Parcel* input) { const ReleaseCallbackId ReleaseCallbackId::INVALID_ID = ReleaseCallbackId(0, 0); -}; // namespace android +}; // namespace android::gui diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp index 59b62fe58c..0d1a69b898 100644 --- a/libs/gui/LayerState.cpp +++ b/libs/gui/LayerState.cpp @@ -51,6 +51,7 @@ namespace android { +using gui::CallbackId; using gui::FocusRequest; using gui::WindowInfoHandle; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 7085e8a349..d741c99d01 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -314,7 +314,8 @@ void TransactionCompletedListener::addSurfaceControlToCallbacks( } } -void TransactionCompletedListener::onTransactionCompleted(ListenerStats listenerStats) { +binder::Status TransactionCompletedListener::onTransactionCompleted( + const ListenerStats& listenerStats) { std::unordered_map callbacksMap; std::multimap> jankListenersMap; { @@ -454,9 +455,10 @@ void TransactionCompletedListener::onTransactionCompleted(ListenerStats listener } } } + return binder::Status::ok(); } -void TransactionCompletedListener::onTransactionQueueStalled(const String8& reason) { +binder::Status TransactionCompletedListener::onTransactionQueueStalled(const std::string& reason) { std::unordered_map> callbackCopy; { std::scoped_lock lock(mMutex); @@ -465,6 +467,7 @@ void TransactionCompletedListener::onTransactionQueueStalled(const String8& reas for (auto const& it : callbackCopy) { it.second(reason.c_str()); } + return binder::Status::ok(); } void TransactionCompletedListener::addQueueStallListener( @@ -478,9 +481,12 @@ void TransactionCompletedListener::removeQueueStallListener(void* id) { mQueueStallListeners.erase(id); } -void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId, - sp releaseFence, - uint32_t currentMaxAcquiredBufferCount) { +binder::Status TransactionCompletedListener::onReleaseBuffer( + const ReleaseCallbackId& callbackId, + const std::optional& releaseFenceFd, + int32_t currentMaxAcquiredBufferCount) { + sp releaseFence(releaseFenceFd ? new Fence(::dup(releaseFenceFd->get())) + : Fence::NO_FENCE); ReleaseBufferCallback callback; { std::scoped_lock lock(mMutex); @@ -489,13 +495,14 @@ void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId, if (!callback) { ALOGE("Could not call release buffer callback, buffer not found %s", callbackId.to_string().c_str()); - return; + return binder::Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT); } std::optional optionalMaxAcquiredBufferCount = - currentMaxAcquiredBufferCount == UINT_MAX + static_cast(currentMaxAcquiredBufferCount) == UINT_MAX ? std::nullopt : std::make_optional(currentMaxAcquiredBufferCount); callback(callbackId, releaseFence, optionalMaxAcquiredBufferCount); + return binder::Status::ok(); } ReleaseBufferCallback TransactionCompletedListener::popReleaseBufferCallbackLocked( @@ -825,7 +832,11 @@ void SurfaceComposerClient::Transaction::releaseBufferIfOverwriting(const layer_ ->mReleaseCallbackThread .addReleaseCallback(state.bufferData->generateReleaseCallbackId(), fence); } else { - listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fence, UINT_MAX); + std::optional fenceFd; + if (fence != Fence::NO_FENCE) { + fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(fence->get()))); + } + listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fenceFd, UINT_MAX); } } @@ -2846,7 +2857,11 @@ void ReleaseCallbackThread::threadMain() { while (!callbackInfos.empty()) { auto [callbackId, releaseFence] = callbackInfos.front(); - listener->onReleaseBuffer(callbackId, std::move(releaseFence), UINT_MAX); + std::optional fenceFd; + if (releaseFence != Fence::NO_FENCE) { + fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(releaseFence->get()))); + } + listener->onReleaseBuffer(callbackId, fenceFd, UINT_MAX); callbackInfos.pop(); } diff --git a/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl b/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl new file mode 100644 index 0000000000..dde4d38cba --- /dev/null +++ b/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl @@ -0,0 +1,31 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +import android.gui.ListenerStats; +import android.gui.ReleaseCallbackId; + +/** @hide */ +oneway interface ITransactionCompletedListener { + void onTransactionCompleted(in ListenerStats stats); + + void onReleaseBuffer(in ReleaseCallbackId callbackId, + in @nullable ParcelFileDescriptor releaseFenceFd, + int currentMaxAcquiredBufferCount); + + void onTransactionQueueStalled(@utf8InCpp String name); +} diff --git a/libs/gui/aidl/android/gui/ListenerStats.aidl b/libs/gui/aidl/android/gui/ListenerStats.aidl new file mode 100644 index 0000000000..63248b2bf3 --- /dev/null +++ b/libs/gui/aidl/android/gui/ListenerStats.aidl @@ -0,0 +1,19 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +parcelable ListenerStats cpp_header "gui/ListenerStats.h"; diff --git a/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl b/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl new file mode 100644 index 0000000000..c86de34de9 --- /dev/null +++ b/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl @@ -0,0 +1,19 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.gui; + +parcelable ReleaseCallbackId cpp_header "gui/ReleaseCallbackId.h"; diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index d517e99fda..d70a7f0f1b 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -23,11 +23,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -66,6 +66,7 @@ using gui::FrameTimelineInfo; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; using gui::IScreenCaptureListener; +using gui::ListenerCallbacks; using gui::SpHash; namespace gui { diff --git a/libs/gui/include/gui/ITransactionCompletedListener.h b/libs/gui/include/gui/ITransactionCompletedListener.h deleted file mode 100644 index 453e8f3ef5..0000000000 --- a/libs/gui/include/gui/ITransactionCompletedListener.h +++ /dev/null @@ -1,271 +0,0 @@ -/* - * Copyright 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "JankInfo.h" - -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include - -namespace android { - -class ITransactionCompletedListener; -class ListenerCallbacks; - -class CallbackId : public Parcelable { -public: - int64_t id; - enum class Type : int32_t { ON_COMPLETE, ON_COMMIT } type; - - CallbackId() {} - CallbackId(int64_t id, Type type) : id(id), type(type) {} - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - bool operator==(const CallbackId& rhs) const { return id == rhs.id && type == rhs.type; } -}; - -struct CallbackIdHash { - std::size_t operator()(const CallbackId& key) const { return std::hash()(key.id); } -}; - -class ReleaseCallbackId : public Parcelable { -public: - static const ReleaseCallbackId INVALID_ID; - - uint64_t bufferId; - uint64_t framenumber; - ReleaseCallbackId() {} - ReleaseCallbackId(uint64_t bufferId, uint64_t framenumber) - : bufferId(bufferId), framenumber(framenumber) {} - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - bool operator==(const ReleaseCallbackId& rhs) const { - return bufferId == rhs.bufferId && framenumber == rhs.framenumber; - } - bool operator!=(const ReleaseCallbackId& rhs) const { return !operator==(rhs); } - std::string to_string() const { - if (*this == INVALID_ID) return "INVALID_ID"; - - return "bufferId:" + std::to_string(bufferId) + - " framenumber:" + std::to_string(framenumber); - } -}; - -struct ReleaseBufferCallbackIdHash { - std::size_t operator()(const ReleaseCallbackId& key) const { - return std::hash()(key.bufferId); - } -}; - -class FrameEventHistoryStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - FrameEventHistoryStats() = default; - FrameEventHistoryStats(uint64_t fn, const sp& gpuCompFence, CompositorTiming compTiming, - nsecs_t refreshTime, nsecs_t dequeueReadyTime) - : frameNumber(fn), - gpuCompositionDoneFence(gpuCompFence), - compositorTiming(compTiming), - refreshStartTime(refreshTime), - dequeueReadyTime(dequeueReadyTime) {} - - uint64_t frameNumber; - sp gpuCompositionDoneFence; - CompositorTiming compositorTiming; - nsecs_t refreshStartTime; - nsecs_t dequeueReadyTime; -}; - -/** - * Jank information representing SurfaceFlinger's jank classification about frames for a specific - * surface. - */ -class JankData : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - JankData(); - JankData(int64_t frameVsyncId, int32_t jankType) - : frameVsyncId(frameVsyncId), jankType(jankType) {} - - // Identifier for the frame submitted with Transaction.setFrameTimelineVsyncId - int64_t frameVsyncId; - - // Bitmask of janks that occurred - int32_t jankType; -}; - -class SurfaceStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - SurfaceStats() = default; - SurfaceStats(const sp& sc, std::variant> acquireTimeOrFence, - const sp& prevReleaseFence, std::optional hint, - uint32_t currentMaxAcquiredBuffersCount, FrameEventHistoryStats frameEventStats, - std::vector jankData, ReleaseCallbackId previousReleaseCallbackId) - : surfaceControl(sc), - acquireTimeOrFence(std::move(acquireTimeOrFence)), - previousReleaseFence(prevReleaseFence), - transformHint(hint), - currentMaxAcquiredBufferCount(currentMaxAcquiredBuffersCount), - eventStats(frameEventStats), - jankData(std::move(jankData)), - previousReleaseCallbackId(previousReleaseCallbackId) {} - - sp surfaceControl; - std::variant> acquireTimeOrFence = -1; - sp previousReleaseFence; - std::optional transformHint = 0; - uint32_t currentMaxAcquiredBufferCount = 0; - FrameEventHistoryStats eventStats; - std::vector jankData; - ReleaseCallbackId previousReleaseCallbackId; -}; - -class TransactionStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - TransactionStats() = default; - TransactionStats(const std::vector& ids) : callbackIds(ids) {} - TransactionStats(const std::unordered_set& ids) - : callbackIds(ids.begin(), ids.end()) {} - TransactionStats(const std::vector& ids, nsecs_t latch, const sp& present, - const std::vector& surfaces) - : callbackIds(ids), latchTime(latch), presentFence(present), surfaceStats(surfaces) {} - - std::vector callbackIds; - nsecs_t latchTime = -1; - sp presentFence = nullptr; - std::vector surfaceStats; -}; - -class ListenerStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - static ListenerStats createEmpty( - const sp& listener, - const std::unordered_set& callbackIds); - - sp listener; - std::vector transactionStats; -}; - -class ITransactionCompletedListener : public IInterface { -public: - DECLARE_META_INTERFACE(TransactionCompletedListener) - - virtual void onTransactionCompleted(ListenerStats stats) = 0; - - virtual void onReleaseBuffer(ReleaseCallbackId callbackId, sp releaseFence, - uint32_t currentMaxAcquiredBufferCount) = 0; - - virtual void onTransactionQueueStalled(const String8& name) = 0; -}; - -class BnTransactionCompletedListener : public SafeBnInterface { -public: - BnTransactionCompletedListener() - : SafeBnInterface("BnTransactionCompletedListener") {} - - status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, - uint32_t flags = 0) override; -}; - -class ListenerCallbacks { -public: - ListenerCallbacks(const sp& listener, - const std::unordered_set& callbacks) - : transactionCompletedListener(listener), - callbackIds(callbacks.begin(), callbacks.end()) {} - - ListenerCallbacks(const sp& listener, const std::vector& ids) - : transactionCompletedListener(listener), callbackIds(ids) {} - - bool operator==(const ListenerCallbacks& rhs) const { - if (transactionCompletedListener != rhs.transactionCompletedListener) { - return false; - } - if (callbackIds.empty()) { - return rhs.callbackIds.empty(); - } - return callbackIds.front().id == rhs.callbackIds.front().id; - } - - // Returns a new ListenerCallbacks filtered by type - ListenerCallbacks filter(CallbackId::Type type) const; - - sp transactionCompletedListener; - std::vector callbackIds; -}; - -struct IListenerHash { - std::size_t operator()(const sp& strongPointer) const { - return std::hash{}(strongPointer.get()); - } -}; - -struct CallbackIdsHash { - // CallbackId vectors have several properties that let us get away with this simple hash. - // 1) CallbackIds are never 0 so if something has gone wrong and our CallbackId vector is - // empty we can still hash 0. - // 2) CallbackId vectors for the same listener either are identical or contain none of the - // same members. It is sufficient to just check the first CallbackId in the vectors. If - // they match, they are the same. If they do not match, they are not the same. - std::size_t operator()(const std::vector& callbackIds) const { - return std::hash{}((callbackIds.empty()) ? 0 : callbackIds.front().id); - } -}; - -struct ListenerCallbacksHash { - std::size_t HashCombine(size_t value1, size_t value2) const { - return value1 ^ (value2 + 0x9e3779b9 + (value1 << 6) + (value1 >> 2)); - } - - std::size_t operator()(const ListenerCallbacks& listenerCallbacks) const { - struct IListenerHash listenerHasher; - struct CallbackIdsHash callbackIdsHasher; - - std::size_t listenerHash = listenerHasher(listenerCallbacks.transactionCompletedListener); - std::size_t callbackIdsHash = callbackIdsHasher(listenerCallbacks.callbackIds); - - return HashCombine(listenerHash, callbackIdsHash); - } -}; - -} // namespace android diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h index 45a84f6c66..c5fdf82d4f 100644 --- a/libs/gui/include/gui/LayerState.h +++ b/libs/gui/include/gui/LayerState.h @@ -21,10 +21,10 @@ #include #include +#include #include #include #include -#include #include #include @@ -35,6 +35,7 @@ #include #include #include +#include #include #include #include @@ -56,6 +57,9 @@ class Parcel; using gui::ISurfaceComposerClient; using gui::LayerMetadata; +using gui::ITransactionCompletedListener; +using gui::ReleaseCallbackId; + struct client_cache_t { wp token = nullptr; uint64_t id; diff --git a/libs/gui/include/gui/ListenerStats.h b/libs/gui/include/gui/ListenerStats.h new file mode 100644 index 0000000000..3a12802146 --- /dev/null +++ b/libs/gui/include/gui/ListenerStats.h @@ -0,0 +1,225 @@ +/* + * Copyright 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "JankInfo.h" + +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include + +namespace android::gui { + +class CallbackId : public Parcelable { +public: + int64_t id; + enum class Type : int32_t { ON_COMPLETE, ON_COMMIT } type; + + CallbackId() {} + CallbackId(int64_t id, Type type) : id(id), type(type) {} + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + bool operator==(const CallbackId& rhs) const { return id == rhs.id && type == rhs.type; } +}; + +struct CallbackIdHash { + std::size_t operator()(const CallbackId& key) const { return std::hash()(key.id); } +}; + +struct ReleaseBufferCallbackIdHash { + std::size_t operator()(const ReleaseCallbackId& key) const { + return std::hash()(key.bufferId); + } +}; + +class FrameEventHistoryStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + FrameEventHistoryStats() = default; + FrameEventHistoryStats(uint64_t fn, const sp& gpuCompFence, CompositorTiming compTiming, + nsecs_t refreshTime, nsecs_t dequeueReadyTime) + : frameNumber(fn), + gpuCompositionDoneFence(gpuCompFence), + compositorTiming(compTiming), + refreshStartTime(refreshTime), + dequeueReadyTime(dequeueReadyTime) {} + + uint64_t frameNumber; + sp gpuCompositionDoneFence; + CompositorTiming compositorTiming; + nsecs_t refreshStartTime; + nsecs_t dequeueReadyTime; +}; + +/** + * Jank information representing SurfaceFlinger's jank classification about frames for a specific + * surface. + */ +class JankData : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + JankData(); + JankData(int64_t frameVsyncId, int32_t jankType) + : frameVsyncId(frameVsyncId), jankType(jankType) {} + + // Identifier for the frame submitted with Transaction.setFrameTimelineVsyncId + int64_t frameVsyncId; + + // Bitmask of janks that occurred + int32_t jankType; +}; + +class SurfaceStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + SurfaceStats() = default; + SurfaceStats(const sp& sc, std::variant> acquireTimeOrFence, + const sp& prevReleaseFence, std::optional hint, + uint32_t currentMaxAcquiredBuffersCount, FrameEventHistoryStats frameEventStats, + std::vector jankData, ReleaseCallbackId previousReleaseCallbackId) + : surfaceControl(sc), + acquireTimeOrFence(std::move(acquireTimeOrFence)), + previousReleaseFence(prevReleaseFence), + transformHint(hint), + currentMaxAcquiredBufferCount(currentMaxAcquiredBuffersCount), + eventStats(frameEventStats), + jankData(std::move(jankData)), + previousReleaseCallbackId(previousReleaseCallbackId) {} + + sp surfaceControl; + std::variant> acquireTimeOrFence = -1; + sp previousReleaseFence; + std::optional transformHint = 0; + uint32_t currentMaxAcquiredBufferCount = 0; + FrameEventHistoryStats eventStats; + std::vector jankData; + ReleaseCallbackId previousReleaseCallbackId; +}; + +class TransactionStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + TransactionStats() = default; + TransactionStats(const std::vector& ids) : callbackIds(ids) {} + TransactionStats(const std::unordered_set& ids) + : callbackIds(ids.begin(), ids.end()) {} + TransactionStats(const std::vector& ids, nsecs_t latch, const sp& present, + const std::vector& surfaces) + : callbackIds(ids), latchTime(latch), presentFence(present), surfaceStats(surfaces) {} + + std::vector callbackIds; + nsecs_t latchTime = -1; + sp presentFence = nullptr; + std::vector surfaceStats; +}; + +class ListenerStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + static ListenerStats createEmpty( + const sp& listener, + const std::unordered_set& callbackIds); + + sp listener; + std::vector transactionStats; +}; + +class ListenerCallbacks { +public: + ListenerCallbacks(const sp& listener, + const std::unordered_set& callbacks) + : transactionCompletedListener(listener), + callbackIds(callbacks.begin(), callbacks.end()) {} + + ListenerCallbacks(const sp& listener, const std::vector& ids) + : transactionCompletedListener(listener), callbackIds(ids) {} + + bool operator==(const ListenerCallbacks& rhs) const { + if (transactionCompletedListener != rhs.transactionCompletedListener) { + return false; + } + if (callbackIds.empty()) { + return rhs.callbackIds.empty(); + } + return callbackIds.front().id == rhs.callbackIds.front().id; + } + + // Returns a new ListenerCallbacks filtered by type + ListenerCallbacks filter(CallbackId::Type type) const; + + sp transactionCompletedListener; + std::vector callbackIds; +}; + +struct IListenerHash { + std::size_t operator()(const sp& strongPointer) const { + return std::hash{}(strongPointer.get()); + } +}; + +struct CallbackIdsHash { + // CallbackId vectors have several properties that let us get away with this simple hash. + // 1) CallbackIds are never 0 so if something has gone wrong and our CallbackId vector is + // empty we can still hash 0. + // 2) CallbackId vectors for the same listener either are identical or contain none of the + // same members. It is sufficient to just check the first CallbackId in the vectors. If + // they match, they are the same. If they do not match, they are not the same. + std::size_t operator()(const std::vector& callbackIds) const { + return std::hash{}((callbackIds.empty()) ? 0 : callbackIds.front().id); + } +}; + +struct ListenerCallbacksHash { + std::size_t HashCombine(size_t value1, size_t value2) const { + return value1 ^ (value2 + 0x9e3779b9 + (value1 << 6) + (value1 >> 2)); + } + + std::size_t operator()(const ListenerCallbacks& listenerCallbacks) const { + struct IListenerHash listenerHasher; + struct CallbackIdsHash callbackIdsHasher; + + std::size_t listenerHash = listenerHasher(listenerCallbacks.transactionCompletedListener); + std::size_t callbackIdsHash = callbackIdsHasher(listenerCallbacks.callbackIds); + + return HashCombine(listenerHash, callbackIdsHash); + } +}; + +} // namespace android::gui diff --git a/libs/gui/include/gui/ReleaseCallbackId.h b/libs/gui/include/gui/ReleaseCallbackId.h new file mode 100644 index 0000000000..142ee5a727 --- /dev/null +++ b/libs/gui/include/gui/ReleaseCallbackId.h @@ -0,0 +1,50 @@ +/* + * Copyright 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include +#include + +#include + +namespace android::gui { + +class ReleaseCallbackId : public Parcelable { +public: + static const ReleaseCallbackId INVALID_ID; + + uint64_t bufferId; + uint64_t framenumber; + ReleaseCallbackId() {} + ReleaseCallbackId(uint64_t bufferId, uint64_t framenumber) + : bufferId(bufferId), framenumber(framenumber) {} + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + bool operator==(const ReleaseCallbackId& rhs) const { + return bufferId == rhs.bufferId && framenumber == rhs.framenumber; + } + bool operator!=(const ReleaseCallbackId& rhs) const { return !operator==(rhs); } + std::string to_string() const { + if (*this == INVALID_ID) return "INVALID_ID"; + + return "bufferId:" + std::to_string(bufferId) + + " framenumber:" + std::to_string(framenumber); + } +}; + +} // namespace android::gui diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index df47002b3b..96d3a23bec 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -42,10 +42,13 @@ #include +#include + #include #include -#include #include +#include +#include #include #include #include @@ -59,11 +62,21 @@ class IGraphicBufferProducer; class ITunnelModeEnabledListener; class Region; +using gui::BnTransactionCompletedListener; +using gui::CallbackId; +using gui::CallbackIdHash; using gui::DisplayCaptureArgs; +using gui::FrameEventHistoryStats; using gui::IRegionSamplingListener; using gui::ISurfaceComposerClient; +using gui::ITransactionCompletedListener; +using gui::JankData; using gui::LayerCaptureArgs; using gui::LayerMetadata; +using gui::ListenerStats; +using gui::ReleaseBufferCallbackIdHash; +using gui::ReleaseCallbackId; +using gui::SurfaceStats; struct SurfaceControlStats { SurfaceControlStats(const sp& sc, nsecs_t latchTime, @@ -825,17 +838,17 @@ public: void setReleaseBufferCallback(const ReleaseCallbackId&, ReleaseBufferCallback); // BnTransactionCompletedListener overrides - void onTransactionCompleted(ListenerStats stats) override; - void onReleaseBuffer(ReleaseCallbackId, sp releaseFence, - uint32_t currentMaxAcquiredBufferCount) override; + binder::Status onTransactionCompleted(const ListenerStats& stats) override; + binder::Status onReleaseBuffer(const ReleaseCallbackId& callbackId, + const std::optional& releaseFenceFd, + int32_t currentMaxAcquiredBufferCount) override; + binder::Status onTransactionQueueStalled(const std::string& reason) override; void removeReleaseBufferCallback(const ReleaseCallbackId& callbackId); // For Testing Only static void setInstance(const sp&); - void onTransactionQueueStalled(const String8& reason) override; - private: ReleaseBufferCallback popReleaseBufferCallbackLocked(const ReleaseCallbackId&); static sp sInstance; diff --git a/services/surfaceflinger/FrontEnd/TransactionHandler.cpp b/services/surfaceflinger/FrontEnd/TransactionHandler.cpp index 8629671214..c2109b3aa5 100644 --- a/services/surfaceflinger/FrontEnd/TransactionHandler.cpp +++ b/services/surfaceflinger/FrontEnd/TransactionHandler.cpp @@ -177,7 +177,7 @@ void TransactionHandler::onTransactionQueueStalled(uint64_t transactionId, } mStalledTransactions.push_back(transactionId); - listener->onTransactionQueueStalled(String8(reason.c_str())); + listener->onTransactionQueueStalled(reason); } void TransactionHandler::removeFromStalledTransactions(uint64_t id) { diff --git a/services/surfaceflinger/FrontEnd/TransactionHandler.h b/services/surfaceflinger/FrontEnd/TransactionHandler.h index a06b870549..475ff1b1dc 100644 --- a/services/surfaceflinger/FrontEnd/TransactionHandler.h +++ b/services/surfaceflinger/FrontEnd/TransactionHandler.h @@ -29,6 +29,7 @@ namespace android { class TestableSurfaceFlinger; +using gui::IListenerHash; namespace surfaceflinger::frontend { class TransactionHandler { diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index 0017af0476..56abc516fd 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -2604,9 +2604,12 @@ void Layer::callReleaseBufferCallback(const sp& l return; } ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber); - listener->onReleaseBuffer({buffer->getId(), framenumber}, - releaseFence ? releaseFence : Fence::NO_FENCE, - currentMaxAcquiredBufferCount); + std::optional fenceFd; + if (releaseFence) { + fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(releaseFence->get()))); + } + listener->onReleaseBuffer({buffer->getId(), framenumber}, fenceFd, + static_cast(currentMaxAcquiredBufferCount)); } void Layer::onLayerDisplayed(ftl::SharedFuture futureFenceResult) { diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index d4c4fb28f5..55644e2a41 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -7113,8 +7113,7 @@ std::shared_ptr SurfaceFlinger::getExternalTextur layerName, static_cast(mMaxRenderTargetSize)); ALOGD("%s", errorMessage.c_str()); if (bufferData.releaseBufferListener) { - bufferData.releaseBufferListener->onTransactionQueueStalled( - String8(errorMessage.c_str())); + bufferData.releaseBufferListener->onTransactionQueueStalled(errorMessage); } return nullptr; } @@ -7132,7 +7131,7 @@ std::shared_ptr SurfaceFlinger::getExternalTextur if (bufferData.releaseBufferListener) { bufferData.releaseBufferListener->onTransactionQueueStalled( - String8("Buffer processing hung due to full buffer cache")); + "Buffer processing hung due to full buffer cache"); } } diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 3354b24bbb..8fa427843b 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -26,6 +26,7 @@ #include #include #include +#include #include #include #include @@ -34,8 +35,8 @@ #include #include #include -#include #include + #include #include #include @@ -125,7 +126,9 @@ using frontend::TransactionHandler; using gui::CaptureArgs; using gui::DisplayCaptureArgs; using gui::IRegionSamplingListener; +using gui::ITransactionCompletedListener; using gui::LayerCaptureArgs; + using gui::ScreenCaptureResults; namespace frametimeline { diff --git a/services/surfaceflinger/TransactionCallbackInvoker.h b/services/surfaceflinger/TransactionCallbackInvoker.h index 61ff9bce98..c09bcce067 100644 --- a/services/surfaceflinger/TransactionCallbackInvoker.h +++ b/services/surfaceflinger/TransactionCallbackInvoker.h @@ -26,14 +26,27 @@ #include #include +#include + #include -#include -#include +#include +#include +#include #include #include namespace android { +using gui::CallbackId; +using gui::FrameEventHistoryStats; +using gui::IListenerHash; +using gui::ITransactionCompletedListener; +using gui::JankData; +using gui::ListenerCallbacks; +using gui::ListenerStats; +using gui::ReleaseCallbackId; +using gui::TransactionStats; + class CallbackHandle : public RefBase { public: CallbackHandle(const sp& transactionListener, const std::vector& ids, -- cgit v1.2.3-59-g8ed1b From ffee3bc5ba2b696721a86b615c1f0ef5ee2afa55 Mon Sep 17 00:00:00 2001 From: Huihong Luo Date: Tue, 17 Jan 2023 16:14:35 +0000 Subject: Revert "Migrate ITransactionCompletedListener to AIDL" This reverts commit c50b4988e93872bfe023a4e099548f84bdfd998d. Reason for revert: CTS failures, b/262211898 Change-Id: Iaff863f8af98c11dbf852cccad50e55148d87cee --- libs/binder/include/binder/IInterface.h | 1 + libs/gui/ISurfaceComposer.cpp | 1 - libs/gui/ITransactionCompletedListener.cpp | 71 +++++- libs/gui/LayerState.cpp | 1 - libs/gui/SurfaceComposerClient.cpp | 33 +-- .../android/gui/ITransactionCompletedListener.aidl | 31 --- libs/gui/aidl/android/gui/ListenerStats.aidl | 19 -- libs/gui/aidl/android/gui/ReleaseCallbackId.aidl | 19 -- libs/gui/include/gui/ISurfaceComposer.h | 3 +- .../include/gui/ITransactionCompletedListener.h | 271 +++++++++++++++++++++ libs/gui/include/gui/LayerState.h | 6 +- libs/gui/include/gui/ListenerStats.h | 225 ----------------- libs/gui/include/gui/ReleaseCallbackId.h | 50 ---- libs/gui/include/gui/SurfaceComposerClient.h | 25 +- .../surfaceflinger/FrontEnd/TransactionHandler.cpp | 2 +- .../surfaceflinger/FrontEnd/TransactionHandler.h | 1 - services/surfaceflinger/Layer.cpp | 9 +- services/surfaceflinger/SurfaceFlinger.cpp | 5 +- services/surfaceflinger/SurfaceFlinger.h | 5 +- .../surfaceflinger/TransactionCallbackInvoker.h | 17 +- 20 files changed, 367 insertions(+), 428 deletions(-) delete mode 100644 libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl delete mode 100644 libs/gui/aidl/android/gui/ListenerStats.aidl delete mode 100644 libs/gui/aidl/android/gui/ReleaseCallbackId.aidl create mode 100644 libs/gui/include/gui/ITransactionCompletedListener.h delete mode 100644 libs/gui/include/gui/ListenerStats.h delete mode 100644 libs/gui/include/gui/ReleaseCallbackId.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/binder/include/binder/IInterface.h b/libs/binder/include/binder/IInterface.h index 8cc8105ff9..dc572ac953 100644 --- a/libs/binder/include/binder/IInterface.h +++ b/libs/binder/include/binder/IInterface.h @@ -230,6 +230,7 @@ constexpr const char* const kManualInterfaces[] = { "android.graphicsenv.IGpuService", "android.gui.IConsumerListener", "android.gui.IGraphicBufferConsumer", + "android.gui.ITransactionComposerListener", "android.gui.SensorEventConnection", "android.gui.SensorServer", "android.hardware.ICamera", diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a0e75ffe49..a77ca04943 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -42,7 +42,6 @@ using namespace aidl::android::hardware::graphics; namespace android { -using gui::CallbackId; using gui::DisplayCaptureArgs; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; diff --git a/libs/gui/ITransactionCompletedListener.cpp b/libs/gui/ITransactionCompletedListener.cpp index 23d7d500c8..2b25b614e9 100644 --- a/libs/gui/ITransactionCompletedListener.cpp +++ b/libs/gui/ITransactionCompletedListener.cpp @@ -21,11 +21,22 @@ #include #include +#include #include -#include #include -namespace android::gui { +namespace android { + +namespace { // Anonymous + +enum class Tag : uint32_t { + ON_TRANSACTION_COMPLETED = IBinder::FIRST_CALL_TRANSACTION, + ON_RELEASE_BUFFER, + ON_TRANSACTION_QUEUE_STALLED, + LAST = ON_TRANSACTION_QUEUE_STALLED, +}; + +} // Anonymous namespace status_t FrameEventHistoryStats::writeToParcel(Parcel* output) const { status_t err = output->writeUint64(frameNumber); @@ -263,6 +274,60 @@ ListenerStats ListenerStats::createEmpty( return listenerStats; } +class BpTransactionCompletedListener : public SafeBpInterface { +public: + explicit BpTransactionCompletedListener(const sp& impl) + : SafeBpInterface(impl, "BpTransactionCompletedListener") { + } + + ~BpTransactionCompletedListener() override; + + void onTransactionCompleted(ListenerStats stats) override { + callRemoteAsync(Tag::ON_TRANSACTION_COMPLETED, + stats); + } + + void onReleaseBuffer(ReleaseCallbackId callbackId, sp releaseFence, + uint32_t currentMaxAcquiredBufferCount) override { + callRemoteAsync(Tag::ON_RELEASE_BUFFER, callbackId, + releaseFence, + currentMaxAcquiredBufferCount); + } + + void onTransactionQueueStalled(const String8& reason) override { + callRemoteAsync< + decltype(&ITransactionCompletedListener:: + onTransactionQueueStalled)>(Tag::ON_TRANSACTION_QUEUE_STALLED, + reason); + } +}; + +// Out-of-line virtual method definitions to trigger vtable emission in this translation unit (see +// clang warning -Wweak-vtables) +BpTransactionCompletedListener::~BpTransactionCompletedListener() = default; + +IMPLEMENT_META_INTERFACE(TransactionCompletedListener, "android.gui.ITransactionComposerListener"); + +status_t BnTransactionCompletedListener::onTransact(uint32_t code, const Parcel& data, + Parcel* reply, uint32_t flags) { + if (code < IBinder::FIRST_CALL_TRANSACTION || code > static_cast(Tag::LAST)) { + return BBinder::onTransact(code, data, reply, flags); + } + auto tag = static_cast(code); + switch (tag) { + case Tag::ON_TRANSACTION_COMPLETED: + return callLocalAsync(data, reply, + &ITransactionCompletedListener::onTransactionCompleted); + case Tag::ON_RELEASE_BUFFER: + return callLocalAsync(data, reply, &ITransactionCompletedListener::onReleaseBuffer); + case Tag::ON_TRANSACTION_QUEUE_STALLED: + return callLocalAsync(data, reply, + &ITransactionCompletedListener::onTransactionQueueStalled); + } +} + ListenerCallbacks ListenerCallbacks::filter(CallbackId::Type type) const { std::vector filteredCallbackIds; for (const auto& callbackId : callbackIds) { @@ -301,4 +366,4 @@ status_t ReleaseCallbackId::readFromParcel(const Parcel* input) { const ReleaseCallbackId ReleaseCallbackId::INVALID_ID = ReleaseCallbackId(0, 0); -}; // namespace android::gui +}; // namespace android diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp index 0d1a69b898..59b62fe58c 100644 --- a/libs/gui/LayerState.cpp +++ b/libs/gui/LayerState.cpp @@ -51,7 +51,6 @@ namespace android { -using gui::CallbackId; using gui::FocusRequest; using gui::WindowInfoHandle; diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index d741c99d01..7085e8a349 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -314,8 +314,7 @@ void TransactionCompletedListener::addSurfaceControlToCallbacks( } } -binder::Status TransactionCompletedListener::onTransactionCompleted( - const ListenerStats& listenerStats) { +void TransactionCompletedListener::onTransactionCompleted(ListenerStats listenerStats) { std::unordered_map callbacksMap; std::multimap> jankListenersMap; { @@ -455,10 +454,9 @@ binder::Status TransactionCompletedListener::onTransactionCompleted( } } } - return binder::Status::ok(); } -binder::Status TransactionCompletedListener::onTransactionQueueStalled(const std::string& reason) { +void TransactionCompletedListener::onTransactionQueueStalled(const String8& reason) { std::unordered_map> callbackCopy; { std::scoped_lock lock(mMutex); @@ -467,7 +465,6 @@ binder::Status TransactionCompletedListener::onTransactionQueueStalled(const std for (auto const& it : callbackCopy) { it.second(reason.c_str()); } - return binder::Status::ok(); } void TransactionCompletedListener::addQueueStallListener( @@ -481,12 +478,9 @@ void TransactionCompletedListener::removeQueueStallListener(void* id) { mQueueStallListeners.erase(id); } -binder::Status TransactionCompletedListener::onReleaseBuffer( - const ReleaseCallbackId& callbackId, - const std::optional& releaseFenceFd, - int32_t currentMaxAcquiredBufferCount) { - sp releaseFence(releaseFenceFd ? new Fence(::dup(releaseFenceFd->get())) - : Fence::NO_FENCE); +void TransactionCompletedListener::onReleaseBuffer(ReleaseCallbackId callbackId, + sp releaseFence, + uint32_t currentMaxAcquiredBufferCount) { ReleaseBufferCallback callback; { std::scoped_lock lock(mMutex); @@ -495,14 +489,13 @@ binder::Status TransactionCompletedListener::onReleaseBuffer( if (!callback) { ALOGE("Could not call release buffer callback, buffer not found %s", callbackId.to_string().c_str()); - return binder::Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT); + return; } std::optional optionalMaxAcquiredBufferCount = - static_cast(currentMaxAcquiredBufferCount) == UINT_MAX + currentMaxAcquiredBufferCount == UINT_MAX ? std::nullopt : std::make_optional(currentMaxAcquiredBufferCount); callback(callbackId, releaseFence, optionalMaxAcquiredBufferCount); - return binder::Status::ok(); } ReleaseBufferCallback TransactionCompletedListener::popReleaseBufferCallbackLocked( @@ -832,11 +825,7 @@ void SurfaceComposerClient::Transaction::releaseBufferIfOverwriting(const layer_ ->mReleaseCallbackThread .addReleaseCallback(state.bufferData->generateReleaseCallbackId(), fence); } else { - std::optional fenceFd; - if (fence != Fence::NO_FENCE) { - fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(fence->get()))); - } - listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fenceFd, UINT_MAX); + listener->onReleaseBuffer(state.bufferData->generateReleaseCallbackId(), fence, UINT_MAX); } } @@ -2857,11 +2846,7 @@ void ReleaseCallbackThread::threadMain() { while (!callbackInfos.empty()) { auto [callbackId, releaseFence] = callbackInfos.front(); - std::optional fenceFd; - if (releaseFence != Fence::NO_FENCE) { - fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(releaseFence->get()))); - } - listener->onReleaseBuffer(callbackId, fenceFd, UINT_MAX); + listener->onReleaseBuffer(callbackId, std::move(releaseFence), UINT_MAX); callbackInfos.pop(); } diff --git a/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl b/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl deleted file mode 100644 index dde4d38cba..0000000000 --- a/libs/gui/aidl/android/gui/ITransactionCompletedListener.aidl +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.gui; - -import android.gui.ListenerStats; -import android.gui.ReleaseCallbackId; - -/** @hide */ -oneway interface ITransactionCompletedListener { - void onTransactionCompleted(in ListenerStats stats); - - void onReleaseBuffer(in ReleaseCallbackId callbackId, - in @nullable ParcelFileDescriptor releaseFenceFd, - int currentMaxAcquiredBufferCount); - - void onTransactionQueueStalled(@utf8InCpp String name); -} diff --git a/libs/gui/aidl/android/gui/ListenerStats.aidl b/libs/gui/aidl/android/gui/ListenerStats.aidl deleted file mode 100644 index 63248b2bf3..0000000000 --- a/libs/gui/aidl/android/gui/ListenerStats.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.gui; - -parcelable ListenerStats cpp_header "gui/ListenerStats.h"; diff --git a/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl b/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl deleted file mode 100644 index c86de34de9..0000000000 --- a/libs/gui/aidl/android/gui/ReleaseCallbackId.aidl +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package android.gui; - -parcelable ReleaseCallbackId cpp_header "gui/ReleaseCallbackId.h"; diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index d70a7f0f1b..d517e99fda 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -23,11 +23,11 @@ #include #include #include -#include #include #include #include #include +#include #include #include #include @@ -66,7 +66,6 @@ using gui::FrameTimelineInfo; using gui::IDisplayEventConnection; using gui::IRegionSamplingListener; using gui::IScreenCaptureListener; -using gui::ListenerCallbacks; using gui::SpHash; namespace gui { diff --git a/libs/gui/include/gui/ITransactionCompletedListener.h b/libs/gui/include/gui/ITransactionCompletedListener.h new file mode 100644 index 0000000000..453e8f3ef5 --- /dev/null +++ b/libs/gui/include/gui/ITransactionCompletedListener.h @@ -0,0 +1,271 @@ +/* + * Copyright 2018 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#pragma once + +#include "JankInfo.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +namespace android { + +class ITransactionCompletedListener; +class ListenerCallbacks; + +class CallbackId : public Parcelable { +public: + int64_t id; + enum class Type : int32_t { ON_COMPLETE, ON_COMMIT } type; + + CallbackId() {} + CallbackId(int64_t id, Type type) : id(id), type(type) {} + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + bool operator==(const CallbackId& rhs) const { return id == rhs.id && type == rhs.type; } +}; + +struct CallbackIdHash { + std::size_t operator()(const CallbackId& key) const { return std::hash()(key.id); } +}; + +class ReleaseCallbackId : public Parcelable { +public: + static const ReleaseCallbackId INVALID_ID; + + uint64_t bufferId; + uint64_t framenumber; + ReleaseCallbackId() {} + ReleaseCallbackId(uint64_t bufferId, uint64_t framenumber) + : bufferId(bufferId), framenumber(framenumber) {} + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + bool operator==(const ReleaseCallbackId& rhs) const { + return bufferId == rhs.bufferId && framenumber == rhs.framenumber; + } + bool operator!=(const ReleaseCallbackId& rhs) const { return !operator==(rhs); } + std::string to_string() const { + if (*this == INVALID_ID) return "INVALID_ID"; + + return "bufferId:" + std::to_string(bufferId) + + " framenumber:" + std::to_string(framenumber); + } +}; + +struct ReleaseBufferCallbackIdHash { + std::size_t operator()(const ReleaseCallbackId& key) const { + return std::hash()(key.bufferId); + } +}; + +class FrameEventHistoryStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + FrameEventHistoryStats() = default; + FrameEventHistoryStats(uint64_t fn, const sp& gpuCompFence, CompositorTiming compTiming, + nsecs_t refreshTime, nsecs_t dequeueReadyTime) + : frameNumber(fn), + gpuCompositionDoneFence(gpuCompFence), + compositorTiming(compTiming), + refreshStartTime(refreshTime), + dequeueReadyTime(dequeueReadyTime) {} + + uint64_t frameNumber; + sp gpuCompositionDoneFence; + CompositorTiming compositorTiming; + nsecs_t refreshStartTime; + nsecs_t dequeueReadyTime; +}; + +/** + * Jank information representing SurfaceFlinger's jank classification about frames for a specific + * surface. + */ +class JankData : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + JankData(); + JankData(int64_t frameVsyncId, int32_t jankType) + : frameVsyncId(frameVsyncId), jankType(jankType) {} + + // Identifier for the frame submitted with Transaction.setFrameTimelineVsyncId + int64_t frameVsyncId; + + // Bitmask of janks that occurred + int32_t jankType; +}; + +class SurfaceStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + SurfaceStats() = default; + SurfaceStats(const sp& sc, std::variant> acquireTimeOrFence, + const sp& prevReleaseFence, std::optional hint, + uint32_t currentMaxAcquiredBuffersCount, FrameEventHistoryStats frameEventStats, + std::vector jankData, ReleaseCallbackId previousReleaseCallbackId) + : surfaceControl(sc), + acquireTimeOrFence(std::move(acquireTimeOrFence)), + previousReleaseFence(prevReleaseFence), + transformHint(hint), + currentMaxAcquiredBufferCount(currentMaxAcquiredBuffersCount), + eventStats(frameEventStats), + jankData(std::move(jankData)), + previousReleaseCallbackId(previousReleaseCallbackId) {} + + sp surfaceControl; + std::variant> acquireTimeOrFence = -1; + sp previousReleaseFence; + std::optional transformHint = 0; + uint32_t currentMaxAcquiredBufferCount = 0; + FrameEventHistoryStats eventStats; + std::vector jankData; + ReleaseCallbackId previousReleaseCallbackId; +}; + +class TransactionStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + TransactionStats() = default; + TransactionStats(const std::vector& ids) : callbackIds(ids) {} + TransactionStats(const std::unordered_set& ids) + : callbackIds(ids.begin(), ids.end()) {} + TransactionStats(const std::vector& ids, nsecs_t latch, const sp& present, + const std::vector& surfaces) + : callbackIds(ids), latchTime(latch), presentFence(present), surfaceStats(surfaces) {} + + std::vector callbackIds; + nsecs_t latchTime = -1; + sp presentFence = nullptr; + std::vector surfaceStats; +}; + +class ListenerStats : public Parcelable { +public: + status_t writeToParcel(Parcel* output) const override; + status_t readFromParcel(const Parcel* input) override; + + static ListenerStats createEmpty( + const sp& listener, + const std::unordered_set& callbackIds); + + sp listener; + std::vector transactionStats; +}; + +class ITransactionCompletedListener : public IInterface { +public: + DECLARE_META_INTERFACE(TransactionCompletedListener) + + virtual void onTransactionCompleted(ListenerStats stats) = 0; + + virtual void onReleaseBuffer(ReleaseCallbackId callbackId, sp releaseFence, + uint32_t currentMaxAcquiredBufferCount) = 0; + + virtual void onTransactionQueueStalled(const String8& name) = 0; +}; + +class BnTransactionCompletedListener : public SafeBnInterface { +public: + BnTransactionCompletedListener() + : SafeBnInterface("BnTransactionCompletedListener") {} + + status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, + uint32_t flags = 0) override; +}; + +class ListenerCallbacks { +public: + ListenerCallbacks(const sp& listener, + const std::unordered_set& callbacks) + : transactionCompletedListener(listener), + callbackIds(callbacks.begin(), callbacks.end()) {} + + ListenerCallbacks(const sp& listener, const std::vector& ids) + : transactionCompletedListener(listener), callbackIds(ids) {} + + bool operator==(const ListenerCallbacks& rhs) const { + if (transactionCompletedListener != rhs.transactionCompletedListener) { + return false; + } + if (callbackIds.empty()) { + return rhs.callbackIds.empty(); + } + return callbackIds.front().id == rhs.callbackIds.front().id; + } + + // Returns a new ListenerCallbacks filtered by type + ListenerCallbacks filter(CallbackId::Type type) const; + + sp transactionCompletedListener; + std::vector callbackIds; +}; + +struct IListenerHash { + std::size_t operator()(const sp& strongPointer) const { + return std::hash{}(strongPointer.get()); + } +}; + +struct CallbackIdsHash { + // CallbackId vectors have several properties that let us get away with this simple hash. + // 1) CallbackIds are never 0 so if something has gone wrong and our CallbackId vector is + // empty we can still hash 0. + // 2) CallbackId vectors for the same listener either are identical or contain none of the + // same members. It is sufficient to just check the first CallbackId in the vectors. If + // they match, they are the same. If they do not match, they are not the same. + std::size_t operator()(const std::vector& callbackIds) const { + return std::hash{}((callbackIds.empty()) ? 0 : callbackIds.front().id); + } +}; + +struct ListenerCallbacksHash { + std::size_t HashCombine(size_t value1, size_t value2) const { + return value1 ^ (value2 + 0x9e3779b9 + (value1 << 6) + (value1 >> 2)); + } + + std::size_t operator()(const ListenerCallbacks& listenerCallbacks) const { + struct IListenerHash listenerHasher; + struct CallbackIdsHash callbackIdsHasher; + + std::size_t listenerHash = listenerHasher(listenerCallbacks.transactionCompletedListener); + std::size_t callbackIdsHash = callbackIdsHasher(listenerCallbacks.callbackIds); + + return HashCombine(listenerHash, callbackIdsHash); + } +}; + +} // namespace android diff --git a/libs/gui/include/gui/LayerState.h b/libs/gui/include/gui/LayerState.h index c5fdf82d4f..45a84f6c66 100644 --- a/libs/gui/include/gui/LayerState.h +++ b/libs/gui/include/gui/LayerState.h @@ -21,10 +21,10 @@ #include #include -#include #include #include #include +#include #include #include @@ -35,7 +35,6 @@ #include #include #include -#include #include #include #include @@ -57,9 +56,6 @@ class Parcel; using gui::ISurfaceComposerClient; using gui::LayerMetadata; -using gui::ITransactionCompletedListener; -using gui::ReleaseCallbackId; - struct client_cache_t { wp token = nullptr; uint64_t id; diff --git a/libs/gui/include/gui/ListenerStats.h b/libs/gui/include/gui/ListenerStats.h deleted file mode 100644 index 3a12802146..0000000000 --- a/libs/gui/include/gui/ListenerStats.h +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2018 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include "JankInfo.h" - -#include -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include -#include -#include - -namespace android::gui { - -class CallbackId : public Parcelable { -public: - int64_t id; - enum class Type : int32_t { ON_COMPLETE, ON_COMMIT } type; - - CallbackId() {} - CallbackId(int64_t id, Type type) : id(id), type(type) {} - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - bool operator==(const CallbackId& rhs) const { return id == rhs.id && type == rhs.type; } -}; - -struct CallbackIdHash { - std::size_t operator()(const CallbackId& key) const { return std::hash()(key.id); } -}; - -struct ReleaseBufferCallbackIdHash { - std::size_t operator()(const ReleaseCallbackId& key) const { - return std::hash()(key.bufferId); - } -}; - -class FrameEventHistoryStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - FrameEventHistoryStats() = default; - FrameEventHistoryStats(uint64_t fn, const sp& gpuCompFence, CompositorTiming compTiming, - nsecs_t refreshTime, nsecs_t dequeueReadyTime) - : frameNumber(fn), - gpuCompositionDoneFence(gpuCompFence), - compositorTiming(compTiming), - refreshStartTime(refreshTime), - dequeueReadyTime(dequeueReadyTime) {} - - uint64_t frameNumber; - sp gpuCompositionDoneFence; - CompositorTiming compositorTiming; - nsecs_t refreshStartTime; - nsecs_t dequeueReadyTime; -}; - -/** - * Jank information representing SurfaceFlinger's jank classification about frames for a specific - * surface. - */ -class JankData : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - JankData(); - JankData(int64_t frameVsyncId, int32_t jankType) - : frameVsyncId(frameVsyncId), jankType(jankType) {} - - // Identifier for the frame submitted with Transaction.setFrameTimelineVsyncId - int64_t frameVsyncId; - - // Bitmask of janks that occurred - int32_t jankType; -}; - -class SurfaceStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - SurfaceStats() = default; - SurfaceStats(const sp& sc, std::variant> acquireTimeOrFence, - const sp& prevReleaseFence, std::optional hint, - uint32_t currentMaxAcquiredBuffersCount, FrameEventHistoryStats frameEventStats, - std::vector jankData, ReleaseCallbackId previousReleaseCallbackId) - : surfaceControl(sc), - acquireTimeOrFence(std::move(acquireTimeOrFence)), - previousReleaseFence(prevReleaseFence), - transformHint(hint), - currentMaxAcquiredBufferCount(currentMaxAcquiredBuffersCount), - eventStats(frameEventStats), - jankData(std::move(jankData)), - previousReleaseCallbackId(previousReleaseCallbackId) {} - - sp surfaceControl; - std::variant> acquireTimeOrFence = -1; - sp previousReleaseFence; - std::optional transformHint = 0; - uint32_t currentMaxAcquiredBufferCount = 0; - FrameEventHistoryStats eventStats; - std::vector jankData; - ReleaseCallbackId previousReleaseCallbackId; -}; - -class TransactionStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - TransactionStats() = default; - TransactionStats(const std::vector& ids) : callbackIds(ids) {} - TransactionStats(const std::unordered_set& ids) - : callbackIds(ids.begin(), ids.end()) {} - TransactionStats(const std::vector& ids, nsecs_t latch, const sp& present, - const std::vector& surfaces) - : callbackIds(ids), latchTime(latch), presentFence(present), surfaceStats(surfaces) {} - - std::vector callbackIds; - nsecs_t latchTime = -1; - sp presentFence = nullptr; - std::vector surfaceStats; -}; - -class ListenerStats : public Parcelable { -public: - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - static ListenerStats createEmpty( - const sp& listener, - const std::unordered_set& callbackIds); - - sp listener; - std::vector transactionStats; -}; - -class ListenerCallbacks { -public: - ListenerCallbacks(const sp& listener, - const std::unordered_set& callbacks) - : transactionCompletedListener(listener), - callbackIds(callbacks.begin(), callbacks.end()) {} - - ListenerCallbacks(const sp& listener, const std::vector& ids) - : transactionCompletedListener(listener), callbackIds(ids) {} - - bool operator==(const ListenerCallbacks& rhs) const { - if (transactionCompletedListener != rhs.transactionCompletedListener) { - return false; - } - if (callbackIds.empty()) { - return rhs.callbackIds.empty(); - } - return callbackIds.front().id == rhs.callbackIds.front().id; - } - - // Returns a new ListenerCallbacks filtered by type - ListenerCallbacks filter(CallbackId::Type type) const; - - sp transactionCompletedListener; - std::vector callbackIds; -}; - -struct IListenerHash { - std::size_t operator()(const sp& strongPointer) const { - return std::hash{}(strongPointer.get()); - } -}; - -struct CallbackIdsHash { - // CallbackId vectors have several properties that let us get away with this simple hash. - // 1) CallbackIds are never 0 so if something has gone wrong and our CallbackId vector is - // empty we can still hash 0. - // 2) CallbackId vectors for the same listener either are identical or contain none of the - // same members. It is sufficient to just check the first CallbackId in the vectors. If - // they match, they are the same. If they do not match, they are not the same. - std::size_t operator()(const std::vector& callbackIds) const { - return std::hash{}((callbackIds.empty()) ? 0 : callbackIds.front().id); - } -}; - -struct ListenerCallbacksHash { - std::size_t HashCombine(size_t value1, size_t value2) const { - return value1 ^ (value2 + 0x9e3779b9 + (value1 << 6) + (value1 >> 2)); - } - - std::size_t operator()(const ListenerCallbacks& listenerCallbacks) const { - struct IListenerHash listenerHasher; - struct CallbackIdsHash callbackIdsHasher; - - std::size_t listenerHash = listenerHasher(listenerCallbacks.transactionCompletedListener); - std::size_t callbackIdsHash = callbackIdsHasher(listenerCallbacks.callbackIds); - - return HashCombine(listenerHash, callbackIdsHash); - } -}; - -} // namespace android::gui diff --git a/libs/gui/include/gui/ReleaseCallbackId.h b/libs/gui/include/gui/ReleaseCallbackId.h deleted file mode 100644 index 142ee5a727..0000000000 --- a/libs/gui/include/gui/ReleaseCallbackId.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2022 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#pragma once - -#include -#include - -#include - -namespace android::gui { - -class ReleaseCallbackId : public Parcelable { -public: - static const ReleaseCallbackId INVALID_ID; - - uint64_t bufferId; - uint64_t framenumber; - ReleaseCallbackId() {} - ReleaseCallbackId(uint64_t bufferId, uint64_t framenumber) - : bufferId(bufferId), framenumber(framenumber) {} - status_t writeToParcel(Parcel* output) const override; - status_t readFromParcel(const Parcel* input) override; - - bool operator==(const ReleaseCallbackId& rhs) const { - return bufferId == rhs.bufferId && framenumber == rhs.framenumber; - } - bool operator!=(const ReleaseCallbackId& rhs) const { return !operator==(rhs); } - std::string to_string() const { - if (*this == INVALID_ID) return "INVALID_ID"; - - return "bufferId:" + std::to_string(bufferId) + - " framenumber:" + std::to_string(framenumber); - } -}; - -} // namespace android::gui diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 96d3a23bec..df47002b3b 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -42,13 +42,10 @@ #include -#include - #include #include +#include #include -#include -#include #include #include #include @@ -62,21 +59,11 @@ class IGraphicBufferProducer; class ITunnelModeEnabledListener; class Region; -using gui::BnTransactionCompletedListener; -using gui::CallbackId; -using gui::CallbackIdHash; using gui::DisplayCaptureArgs; -using gui::FrameEventHistoryStats; using gui::IRegionSamplingListener; using gui::ISurfaceComposerClient; -using gui::ITransactionCompletedListener; -using gui::JankData; using gui::LayerCaptureArgs; using gui::LayerMetadata; -using gui::ListenerStats; -using gui::ReleaseBufferCallbackIdHash; -using gui::ReleaseCallbackId; -using gui::SurfaceStats; struct SurfaceControlStats { SurfaceControlStats(const sp& sc, nsecs_t latchTime, @@ -838,17 +825,17 @@ public: void setReleaseBufferCallback(const ReleaseCallbackId&, ReleaseBufferCallback); // BnTransactionCompletedListener overrides - binder::Status onTransactionCompleted(const ListenerStats& stats) override; - binder::Status onReleaseBuffer(const ReleaseCallbackId& callbackId, - const std::optional& releaseFenceFd, - int32_t currentMaxAcquiredBufferCount) override; - binder::Status onTransactionQueueStalled(const std::string& reason) override; + void onTransactionCompleted(ListenerStats stats) override; + void onReleaseBuffer(ReleaseCallbackId, sp releaseFence, + uint32_t currentMaxAcquiredBufferCount) override; void removeReleaseBufferCallback(const ReleaseCallbackId& callbackId); // For Testing Only static void setInstance(const sp&); + void onTransactionQueueStalled(const String8& reason) override; + private: ReleaseBufferCallback popReleaseBufferCallbackLocked(const ReleaseCallbackId&); static sp sInstance; diff --git a/services/surfaceflinger/FrontEnd/TransactionHandler.cpp b/services/surfaceflinger/FrontEnd/TransactionHandler.cpp index c2109b3aa5..8629671214 100644 --- a/services/surfaceflinger/FrontEnd/TransactionHandler.cpp +++ b/services/surfaceflinger/FrontEnd/TransactionHandler.cpp @@ -177,7 +177,7 @@ void TransactionHandler::onTransactionQueueStalled(uint64_t transactionId, } mStalledTransactions.push_back(transactionId); - listener->onTransactionQueueStalled(reason); + listener->onTransactionQueueStalled(String8(reason.c_str())); } void TransactionHandler::removeFromStalledTransactions(uint64_t id) { diff --git a/services/surfaceflinger/FrontEnd/TransactionHandler.h b/services/surfaceflinger/FrontEnd/TransactionHandler.h index 475ff1b1dc..a06b870549 100644 --- a/services/surfaceflinger/FrontEnd/TransactionHandler.h +++ b/services/surfaceflinger/FrontEnd/TransactionHandler.h @@ -29,7 +29,6 @@ namespace android { class TestableSurfaceFlinger; -using gui::IListenerHash; namespace surfaceflinger::frontend { class TransactionHandler { diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index 56abc516fd..0017af0476 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -2604,12 +2604,9 @@ void Layer::callReleaseBufferCallback(const sp& l return; } ATRACE_FORMAT_INSTANT("callReleaseBufferCallback %s - %" PRIu64, getDebugName(), framenumber); - std::optional fenceFd; - if (releaseFence) { - fenceFd = os::ParcelFileDescriptor(base::unique_fd(::dup(releaseFence->get()))); - } - listener->onReleaseBuffer({buffer->getId(), framenumber}, fenceFd, - static_cast(currentMaxAcquiredBufferCount)); + listener->onReleaseBuffer({buffer->getId(), framenumber}, + releaseFence ? releaseFence : Fence::NO_FENCE, + currentMaxAcquiredBufferCount); } void Layer::onLayerDisplayed(ftl::SharedFuture futureFenceResult) { diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 55644e2a41..d4c4fb28f5 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -7113,7 +7113,8 @@ std::shared_ptr SurfaceFlinger::getExternalTextur layerName, static_cast(mMaxRenderTargetSize)); ALOGD("%s", errorMessage.c_str()); if (bufferData.releaseBufferListener) { - bufferData.releaseBufferListener->onTransactionQueueStalled(errorMessage); + bufferData.releaseBufferListener->onTransactionQueueStalled( + String8(errorMessage.c_str())); } return nullptr; } @@ -7131,7 +7132,7 @@ std::shared_ptr SurfaceFlinger::getExternalTextur if (bufferData.releaseBufferListener) { bufferData.releaseBufferListener->onTransactionQueueStalled( - "Buffer processing hung due to full buffer cache"); + String8("Buffer processing hung due to full buffer cache")); } } diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 8fa427843b..3354b24bbb 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -26,7 +26,6 @@ #include #include #include -#include #include #include #include @@ -35,8 +34,8 @@ #include #include #include +#include #include - #include #include #include @@ -126,9 +125,7 @@ using frontend::TransactionHandler; using gui::CaptureArgs; using gui::DisplayCaptureArgs; using gui::IRegionSamplingListener; -using gui::ITransactionCompletedListener; using gui::LayerCaptureArgs; - using gui::ScreenCaptureResults; namespace frametimeline { diff --git a/services/surfaceflinger/TransactionCallbackInvoker.h b/services/surfaceflinger/TransactionCallbackInvoker.h index c09bcce067..61ff9bce98 100644 --- a/services/surfaceflinger/TransactionCallbackInvoker.h +++ b/services/surfaceflinger/TransactionCallbackInvoker.h @@ -26,27 +26,14 @@ #include #include -#include - #include -#include -#include -#include +#include +#include #include #include namespace android { -using gui::CallbackId; -using gui::FrameEventHistoryStats; -using gui::IListenerHash; -using gui::ITransactionCompletedListener; -using gui::JankData; -using gui::ListenerCallbacks; -using gui::ListenerStats; -using gui::ReleaseCallbackId; -using gui::TransactionStats; - class CallbackHandle : public RefBase { public: CallbackHandle(const sp& transactionListener, const std::vector& ids, -- cgit v1.2.3-59-g8ed1b From 75ce1ea078444100db9f9eef06a9ef35ad8a0446 Mon Sep 17 00:00:00 2001 From: Patrick Williams Date: Thu, 19 Jan 2023 15:02:30 -0600 Subject: Cache and uncache buffers in the same transaction This removes a race condition where clients may attempt to cache a buffer before an associated uncache buffer request has completed, leading to full buffer cache errors in SurfaceFlinger. GLSurfaceViewTest#testPauseResumeWithoutDelay is failing on barbet and test logs show frequent `ClientCache::add - cache is full` messages. This CL fixes the "cache is full" error but does not fix the broken test. Bug: 264892858 Test: presubmits Test: GLSurfaceViewTest#testPauseResumeWithoutDelay on barbet Change-Id: I9a075054d11c819307cd837fcfbdc03d8faf5086 --- libs/gui/ISurfaceComposer.cpp | 23 +++++--- libs/gui/SurfaceComposerClient.cpp | 62 ++++++++++++++++------ libs/gui/include/gui/ISurfaceComposer.h | 5 +- libs/gui/include/gui/SurfaceComposerClient.h | 1 + libs/gui/tests/Surface_test.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 49 +++++++++++------ services/surfaceflinger/SurfaceFlinger.h | 21 ++++---- services/surfaceflinger/TransactionState.h | 6 +-- .../fuzzer/surfaceflinger_fuzzers_utils.h | 15 +++--- .../tests/unittests/TestableSurfaceFlinger.h | 5 +- .../tests/unittests/TransactionApplicationTest.cpp | 19 ++++--- 11 files changed, 130 insertions(+), 78 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a77ca04943..cefb9a71d6 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -63,7 +63,8 @@ public: Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& commands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, + bool isAutoTimestamp, + const std::vector& uncacheBuffers, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override { @@ -87,8 +88,11 @@ public: SAFE_PARCEL(commands.write, data); SAFE_PARCEL(data.writeInt64, desiredPresentTime); SAFE_PARCEL(data.writeBool, isAutoTimestamp); - SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); - SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); + SAFE_PARCEL(data.writeUint32, static_cast(uncacheBuffers.size())); + for (const client_cache_t& uncacheBuffer : uncacheBuffers) { + SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); + SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); + } SAFE_PARCEL(data.writeBool, hasListenerCallbacks); SAFE_PARCEL(data.writeVectorSize, listenerCallbacks); @@ -158,11 +162,14 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(data.readInt64, &desiredPresentTime); SAFE_PARCEL(data.readBool, &isAutoTimestamp); - client_cache_t uncachedBuffer; + SAFE_PARCEL_READ_SIZE(data.readUint32, &count, data.dataSize()); + std::vector uncacheBuffers(count); sp tmpBinder; - SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); - uncachedBuffer.token = tmpBinder; - SAFE_PARCEL(data.readUint64, &uncachedBuffer.id); + for (size_t i = 0; i < count; i++) { + SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); + uncacheBuffers[i].token = tmpBinder; + SAFE_PARCEL(data.readUint64, &uncacheBuffers[i].id); + } bool hasListenerCallbacks = false; SAFE_PARCEL(data.readBool, &hasListenerCallbacks); @@ -182,7 +189,7 @@ status_t BnSurfaceComposer::onTransact( return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, - uncachedBuffer, hasListenerCallbacks, listenerCallbacks, + uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } default: { diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 92125ead1f..21a7f7817a 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -565,11 +565,13 @@ public: return NO_ERROR; } - uint64_t cache(const sp& buffer) { + uint64_t cache(const sp& buffer, + std::optional& outUncacheBuffer) { std::lock_guard lock(mMutex); if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) { - evictLeastRecentlyUsedBuffer(); + outUncacheBuffer = findLeastRecentlyUsedBuffer(); + mBuffers.erase(outUncacheBuffer->id); } buffer->addDeathCallback(removeDeadBufferCallback, nullptr); @@ -580,16 +582,13 @@ public: void uncache(uint64_t cacheId) { std::lock_guard lock(mMutex); - uncacheLocked(cacheId); - } - - void uncacheLocked(uint64_t cacheId) REQUIRES(mMutex) { - mBuffers.erase(cacheId); - SurfaceComposerClient::doUncacheBufferTransaction(cacheId); + if (mBuffers.erase(cacheId)) { + SurfaceComposerClient::doUncacheBufferTransaction(cacheId); + } } private: - void evictLeastRecentlyUsedBuffer() REQUIRES(mMutex) { + client_cache_t findLeastRecentlyUsedBuffer() REQUIRES(mMutex) { auto itr = mBuffers.begin(); uint64_t minCounter = itr->second; auto minBuffer = itr; @@ -603,7 +602,8 @@ private: } itr++; } - uncacheLocked(minBuffer->first); + + return {.token = getToken(), .id = minBuffer->first}; } uint64_t getCounter() REQUIRES(mMutex) { @@ -741,6 +741,18 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel InputWindowCommands inputWindowCommands; inputWindowCommands.read(*parcel); + count = static_cast(parcel->readUint32()); + if (count > parcel->dataSize()) { + return BAD_VALUE; + } + std::vector uncacheBuffers(count); + for (size_t i = 0; i < count; i++) { + sp tmpBinder; + SAFE_PARCEL(parcel->readStrongBinder, &tmpBinder); + uncacheBuffers[i].token = tmpBinder; + SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id); + } + // Parsing was successful. Update the object. mId = transactionId; mTransactionNestCount = transactionNestCount; @@ -755,6 +767,7 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel mComposerStates = composerStates; mInputWindowCommands = inputWindowCommands; mApplyToken = applyToken; + mUncacheBuffers = std::move(uncacheBuffers); return NO_ERROR; } @@ -806,6 +819,13 @@ status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const } mInputWindowCommands.write(*parcel); + + SAFE_PARCEL(parcel->writeUint32, static_cast(mUncacheBuffers.size())); + for (const client_cache_t& uncacheBuffer : mUncacheBuffers) { + SAFE_PARCEL(parcel->writeStrongBinder, uncacheBuffer.token.promote()); + SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id); + } + return NO_ERROR; } @@ -873,6 +893,10 @@ SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Tr } } + for (const auto& cacheId : other.mUncacheBuffers) { + mUncacheBuffers.push_back(cacheId); + } + mInputWindowCommands.merge(other.mInputWindowCommands); mMayContainBuffer |= other.mMayContainBuffer; @@ -891,6 +915,7 @@ void SurfaceComposerClient::Transaction::clear() { mDisplayStates.clear(); mListenerCallbacks.clear(); mInputWindowCommands.clear(); + mUncacheBuffers.clear(); mMayContainBuffer = false; mTransactionNestCount = 0; mAnimation = false; @@ -913,10 +938,10 @@ void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { uncacheBuffer.token = BufferCache::getInstance().getToken(); uncacheBuffer.id = cacheId; Vector composerStates; - status_t status = - sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, - ISurfaceComposer::eOneWay, Transaction::getDefaultApplyToken(), - {}, systemTime(), true, uncacheBuffer, false, {}, generateId()); + status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, + ISurfaceComposer::eOneWay, + Transaction::getDefaultApplyToken(), {}, systemTime(), + true, {uncacheBuffer}, false, {}, generateId()); if (status != NO_ERROR) { ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s", strerror(-status)); @@ -954,7 +979,11 @@ void SurfaceComposerClient::Transaction::cacheBuffers() { s->bufferData->buffer = nullptr; } else { // Cache-miss. Include the buffer and send the new cacheId. - cacheId = BufferCache::getInstance().cache(s->bufferData->buffer); + std::optional uncacheBuffer; + cacheId = BufferCache::getInstance().cache(s->bufferData->buffer, uncacheBuffer); + if (uncacheBuffer) { + mUncacheBuffers.push_back(*uncacheBuffer); + } } s->bufferData->flags |= BufferData::BufferDataChange::cachedBufferChanged; s->bufferData->cachedBuffer.token = BufferCache::getInstance().getToken(); @@ -1087,8 +1116,7 @@ status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay sp sf(ComposerService::getComposerService()); sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken, mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp, - {} /*uncacheBuffer - only set in doUncacheBufferTransaction*/, - hasListenerCallbacks, listenerCallbacks, mId); + mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId); mId = generateId(); // Clear the current states and flags diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 045cc2a184..ae56f9fdb5 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -113,8 +113,9 @@ public: const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, uint64_t transactionId) = 0; + bool isAutoTimestamp, const std::vector& uncacheBuffer, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, + uint64_t transactionId) = 0; }; // ---------------------------------------------------------------------------- diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 2458a40ce0..0e51dcf4d4 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -402,6 +402,7 @@ public: SortedVector mDisplayStates; std::unordered_map, CallbackInfo, TCLHash> mListenerCallbacks; + std::vector mUncacheBuffers; uint64_t mId; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 30148042fb..32d60cd5bd 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -701,7 +701,7 @@ public: const sp& /*applyToken*/, const InputWindowCommands& /*inputWindowCommands*/, int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, - const client_cache_t& /*cachedBuffer*/, + const std::vector& /*cachedBuffer*/, bool /*hasListenerCallbacks*/, const std::vector& /*listenerCallbacks*/, uint64_t /*transactionId*/) override { diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 40de4d675d..d63e2812e2 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -3973,7 +3973,7 @@ bool SurfaceFlinger::applyTransactions(std::vector& transactio transaction.displays, transaction.flags, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.buffer, transaction.postTime, + std::move(transaction.uncacheBufferIds), transaction.postTime, transaction.permissions, transaction.hasListenerCallbacks, transaction.listenerCallbacks, transaction.originPid, transaction.originUid, transaction.id); @@ -4061,8 +4061,9 @@ status_t SurfaceFlinger::setTransactionState( const FrameTimelineInfo& frameTimelineInfo, Vector& states, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, uint64_t transactionId) { + bool isAutoTimestamp, const std::vector& uncacheBuffers, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, + uint64_t transactionId) { ATRACE_CALL(); uint32_t permissions = @@ -4096,6 +4097,15 @@ status_t SurfaceFlinger::setTransactionState( const int originPid = ipc->getCallingPid(); const int originUid = ipc->getCallingUid(); + std::vector uncacheBufferIds; + uncacheBufferIds.reserve(uncacheBuffers.size()); + for (const auto& uncacheBuffer : uncacheBuffers) { + sp buffer = ClientCache::getInstance().erase(uncacheBuffer); + if (buffer != nullptr) { + uncacheBufferIds.push_back(buffer->getId()); + } + } + std::vector resolvedStates; resolvedStates.reserve(states.size()); for (auto& state : states) { @@ -4113,14 +4123,22 @@ status_t SurfaceFlinger::setTransactionState( } } - TransactionState state{frameTimelineInfo, resolvedStates, - displays, flags, - applyToken, inputWindowCommands, - desiredPresentTime, isAutoTimestamp, - uncacheBuffer, postTime, - permissions, hasListenerCallbacks, - listenerCallbacks, originPid, - originUid, transactionId}; + TransactionState state{frameTimelineInfo, + resolvedStates, + displays, + flags, + applyToken, + inputWindowCommands, + desiredPresentTime, + isAutoTimestamp, + std::move(uncacheBufferIds), + postTime, + permissions, + hasListenerCallbacks, + listenerCallbacks, + originPid, + originUid, + transactionId}; if (mTransactionTracing) { mTransactionTracing->addQueuedTransaction(state); @@ -4144,7 +4162,7 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin Vector& displays, uint32_t flags, const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, + const std::vector& uncacheBufferIds, const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, const std::vector& listenerCallbacks, @@ -4185,11 +4203,8 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin ALOGE("Only privileged callers are allowed to send input commands."); } - if (uncacheBuffer.isValid()) { - sp buffer = ClientCache::getInstance().erase(uncacheBuffer); - if (buffer != nullptr) { - mBufferIdsToUncache.push_back(buffer->getId()); - } + for (uint64_t uncacheBufferId : uncacheBufferIds) { + mBufferIdsToUncache.push_back(uncacheBufferId); } // If a synchronous transaction is explicitly requested without any changes, force a transaction diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 5457be81a5..9245399e0d 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -501,7 +501,8 @@ private: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override; void bootFinished(); @@ -714,16 +715,14 @@ private: /* * Transactions */ - bool applyTransactionState(const FrameTimelineInfo& info, - std::vector& state, - Vector& displays, uint32_t flags, - const InputWindowCommands& inputWindowCommands, - const int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, const int64_t postTime, - uint32_t permissions, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, - int originPid, int originUid, uint64_t transactionId) - REQUIRES(mStateLock); + bool applyTransactionState( + const FrameTimelineInfo& info, std::vector& state, + Vector& displays, uint32_t flags, + const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, + bool isAutoTimestamp, const std::vector& uncacheBufferIds, + const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, int originPid, int originUid, + uint64_t transactionId) REQUIRES(mStateLock); // Flush pending transactions that were presented after desiredPresentTime. bool flushTransactionQueues(VsyncId) REQUIRES(kMainThreadContext); // Returns true if there is at least one transaction that needs to be flushed diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 366b09d68b..5025c4935c 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -43,7 +43,7 @@ struct TransactionState { const Vector& displayStates, uint32_t transactionFlags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, int64_t postTime, uint32_t permissions, + std::vector uncacheBufferIds, int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, std::vector listenerCallbacks, int originPid, int originUid, uint64_t transactionId) : frameTimelineInfo(frameTimelineInfo), @@ -54,7 +54,7 @@ struct TransactionState { inputWindowCommands(inputWindowCommands), desiredPresentTime(desiredPresentTime), isAutoTimestamp(isAutoTimestamp), - buffer(uncacheBuffer), + uncacheBufferIds(std::move(uncacheBufferIds)), postTime(postTime), permissions(permissions), hasListenerCallbacks(hasListenerCallbacks), @@ -109,7 +109,7 @@ struct TransactionState { InputWindowCommands inputWindowCommands; int64_t desiredPresentTime; bool isAutoTimestamp; - client_cache_t buffer; + std::vector uncacheBufferIds; int64_t postTime; uint32_t permissions; bool hasListenerCallbacks; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 81ca659915..c22d78b86e 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -730,17 +730,18 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionQueues; } - auto setTransactionState(const FrameTimelineInfo &frameTimelineInfo, - Vector &states, const Vector &displays, - uint32_t flags, const sp &applyToken, - const InputWindowCommands &inputWindowCommands, + auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, + Vector& states, const Vector& displays, + uint32_t flags, const sp& applyToken, + const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t &uncacheBuffer, bool hasListenerCallbacks, - std::vector &listenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, + std::vector& listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index 584d52ca02..72e0c7be16 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -439,12 +439,13 @@ public: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, std::vector& listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index d84698f279..a28d1cd415 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -102,7 +102,7 @@ public: int64_t desiredPresentTime = 0; bool isAutoTimestamp = true; FrameTimelineInfo frameTimelineInfo; - client_cache_t uncacheBuffer; + std::vector uncacheBuffers; uint64_t id = static_cast(-1); static_assert(0xffffffffffffffff == static_cast(-1)); }; @@ -138,7 +138,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transaction.id); // If transaction is synchronous, SF applyTransactionState should time out (5s) wating for @@ -165,7 +165,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transaction.id); nsecs_t returnedTime = systemTime(); @@ -196,7 +196,7 @@ public: transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, - transactionA.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); // This thread should not have been blocked by the above transaction @@ -211,7 +211,7 @@ public: transactionB.displays, transactionB.flags, transactionB.applyToken, transactionB.inputWindowCommands, transactionB.desiredPresentTime, transactionB.isAutoTimestamp, - transactionB.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transactionB.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionB.id); // this thread should have been blocked by the above transaction @@ -243,7 +243,7 @@ TEST_F(TransactionApplicationTest, AddToPendingQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffer, + transactionA.isAutoTimestamp, transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -263,7 +263,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffer, + transactionA.isAutoTimestamp, transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -277,7 +277,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(empty.frameTimelineInfo, empty.states, empty.displays, empty.flags, empty.applyToken, empty.inputWindowCommands, empty.desiredPresentTime, empty.isAutoTimestamp, - empty.uncacheBuffer, mHasListenerCallbacks, mCallbacks, empty.id); + empty.uncacheBuffers, mHasListenerCallbacks, mCallbacks, empty.id); // flush transaction queue should flush as desiredPresentTime has // passed @@ -374,8 +374,7 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, - transaction.isAutoTimestamp, - transaction.uncacheBuffer, systemTime(), 0, + transaction.isAutoTimestamp, {}, systemTime(), 0, mHasListenerCallbacks, mCallbacks, getpid(), static_cast(getuid()), transaction.id); mFlinger.setTransactionStateInternal(transactionState); -- cgit v1.2.3-59-g8ed1b From 1088bbf9882d778079eaa7465c1dec2b08848f1a Mon Sep 17 00:00:00 2001 From: Patrick Williams Date: Thu, 9 Feb 2023 21:45:08 +0000 Subject: Revert "Cache and uncache buffers in the same transaction" This reverts commit 75ce1ea078444100db9f9eef06a9ef35ad8a0446. Reason for revert: b/266481887 Change-Id: I147947d55672c8f14d9bbe51df54eadfc43edeb2 --- libs/gui/ISurfaceComposer.cpp | 23 +++----- libs/gui/SurfaceComposerClient.cpp | 62 ++++++---------------- libs/gui/include/gui/ISurfaceComposer.h | 5 +- libs/gui/include/gui/SurfaceComposerClient.h | 1 - libs/gui/tests/Surface_test.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 49 ++++++----------- services/surfaceflinger/SurfaceFlinger.h | 21 ++++---- services/surfaceflinger/TransactionState.h | 6 +-- .../fuzzer/surfaceflinger_fuzzers_utils.h | 15 +++--- .../tests/unittests/TestableSurfaceFlinger.h | 5 +- .../tests/unittests/TransactionApplicationTest.cpp | 19 +++---- 11 files changed, 78 insertions(+), 130 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index cefb9a71d6..a77ca04943 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -63,8 +63,7 @@ public: Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& commands, int64_t desiredPresentTime, - bool isAutoTimestamp, - const std::vector& uncacheBuffers, + bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override { @@ -88,11 +87,8 @@ public: SAFE_PARCEL(commands.write, data); SAFE_PARCEL(data.writeInt64, desiredPresentTime); SAFE_PARCEL(data.writeBool, isAutoTimestamp); - SAFE_PARCEL(data.writeUint32, static_cast(uncacheBuffers.size())); - for (const client_cache_t& uncacheBuffer : uncacheBuffers) { - SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); - SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); - } + SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); + SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); SAFE_PARCEL(data.writeBool, hasListenerCallbacks); SAFE_PARCEL(data.writeVectorSize, listenerCallbacks); @@ -162,14 +158,11 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(data.readInt64, &desiredPresentTime); SAFE_PARCEL(data.readBool, &isAutoTimestamp); - SAFE_PARCEL_READ_SIZE(data.readUint32, &count, data.dataSize()); - std::vector uncacheBuffers(count); + client_cache_t uncachedBuffer; sp tmpBinder; - for (size_t i = 0; i < count; i++) { - SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); - uncacheBuffers[i].token = tmpBinder; - SAFE_PARCEL(data.readUint64, &uncacheBuffers[i].id); - } + SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); + uncachedBuffer.token = tmpBinder; + SAFE_PARCEL(data.readUint64, &uncachedBuffer.id); bool hasListenerCallbacks = false; SAFE_PARCEL(data.readBool, &hasListenerCallbacks); @@ -189,7 +182,7 @@ status_t BnSurfaceComposer::onTransact( return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, - uncacheBuffers, hasListenerCallbacks, listenerCallbacks, + uncachedBuffer, hasListenerCallbacks, listenerCallbacks, transactionId); } default: { diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 21a7f7817a..92125ead1f 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -565,13 +565,11 @@ public: return NO_ERROR; } - uint64_t cache(const sp& buffer, - std::optional& outUncacheBuffer) { + uint64_t cache(const sp& buffer) { std::lock_guard lock(mMutex); if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) { - outUncacheBuffer = findLeastRecentlyUsedBuffer(); - mBuffers.erase(outUncacheBuffer->id); + evictLeastRecentlyUsedBuffer(); } buffer->addDeathCallback(removeDeadBufferCallback, nullptr); @@ -582,13 +580,16 @@ public: void uncache(uint64_t cacheId) { std::lock_guard lock(mMutex); - if (mBuffers.erase(cacheId)) { - SurfaceComposerClient::doUncacheBufferTransaction(cacheId); - } + uncacheLocked(cacheId); + } + + void uncacheLocked(uint64_t cacheId) REQUIRES(mMutex) { + mBuffers.erase(cacheId); + SurfaceComposerClient::doUncacheBufferTransaction(cacheId); } private: - client_cache_t findLeastRecentlyUsedBuffer() REQUIRES(mMutex) { + void evictLeastRecentlyUsedBuffer() REQUIRES(mMutex) { auto itr = mBuffers.begin(); uint64_t minCounter = itr->second; auto minBuffer = itr; @@ -602,8 +603,7 @@ private: } itr++; } - - return {.token = getToken(), .id = minBuffer->first}; + uncacheLocked(minBuffer->first); } uint64_t getCounter() REQUIRES(mMutex) { @@ -741,18 +741,6 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel InputWindowCommands inputWindowCommands; inputWindowCommands.read(*parcel); - count = static_cast(parcel->readUint32()); - if (count > parcel->dataSize()) { - return BAD_VALUE; - } - std::vector uncacheBuffers(count); - for (size_t i = 0; i < count; i++) { - sp tmpBinder; - SAFE_PARCEL(parcel->readStrongBinder, &tmpBinder); - uncacheBuffers[i].token = tmpBinder; - SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id); - } - // Parsing was successful. Update the object. mId = transactionId; mTransactionNestCount = transactionNestCount; @@ -767,7 +755,6 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel mComposerStates = composerStates; mInputWindowCommands = inputWindowCommands; mApplyToken = applyToken; - mUncacheBuffers = std::move(uncacheBuffers); return NO_ERROR; } @@ -819,13 +806,6 @@ status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const } mInputWindowCommands.write(*parcel); - - SAFE_PARCEL(parcel->writeUint32, static_cast(mUncacheBuffers.size())); - for (const client_cache_t& uncacheBuffer : mUncacheBuffers) { - SAFE_PARCEL(parcel->writeStrongBinder, uncacheBuffer.token.promote()); - SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id); - } - return NO_ERROR; } @@ -893,10 +873,6 @@ SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Tr } } - for (const auto& cacheId : other.mUncacheBuffers) { - mUncacheBuffers.push_back(cacheId); - } - mInputWindowCommands.merge(other.mInputWindowCommands); mMayContainBuffer |= other.mMayContainBuffer; @@ -915,7 +891,6 @@ void SurfaceComposerClient::Transaction::clear() { mDisplayStates.clear(); mListenerCallbacks.clear(); mInputWindowCommands.clear(); - mUncacheBuffers.clear(); mMayContainBuffer = false; mTransactionNestCount = 0; mAnimation = false; @@ -938,10 +913,10 @@ void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { uncacheBuffer.token = BufferCache::getInstance().getToken(); uncacheBuffer.id = cacheId; Vector composerStates; - status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, - ISurfaceComposer::eOneWay, - Transaction::getDefaultApplyToken(), {}, systemTime(), - true, {uncacheBuffer}, false, {}, generateId()); + status_t status = + sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, + ISurfaceComposer::eOneWay, Transaction::getDefaultApplyToken(), + {}, systemTime(), true, uncacheBuffer, false, {}, generateId()); if (status != NO_ERROR) { ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s", strerror(-status)); @@ -979,11 +954,7 @@ void SurfaceComposerClient::Transaction::cacheBuffers() { s->bufferData->buffer = nullptr; } else { // Cache-miss. Include the buffer and send the new cacheId. - std::optional uncacheBuffer; - cacheId = BufferCache::getInstance().cache(s->bufferData->buffer, uncacheBuffer); - if (uncacheBuffer) { - mUncacheBuffers.push_back(*uncacheBuffer); - } + cacheId = BufferCache::getInstance().cache(s->bufferData->buffer); } s->bufferData->flags |= BufferData::BufferDataChange::cachedBufferChanged; s->bufferData->cachedBuffer.token = BufferCache::getInstance().getToken(); @@ -1116,7 +1087,8 @@ status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay sp sf(ComposerService::getComposerService()); sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken, mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp, - mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId); + {} /*uncacheBuffer - only set in doUncacheBufferTransaction*/, + hasListenerCallbacks, listenerCallbacks, mId); mId = generateId(); // Clear the current states and flags diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index ae56f9fdb5..045cc2a184 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -113,9 +113,8 @@ public: const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const std::vector& uncacheBuffer, - bool hasListenerCallbacks, const std::vector& listenerCallbacks, - uint64_t transactionId) = 0; + bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, uint64_t transactionId) = 0; }; // ---------------------------------------------------------------------------- diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 0e51dcf4d4..2458a40ce0 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -402,7 +402,6 @@ public: SortedVector mDisplayStates; std::unordered_map, CallbackInfo, TCLHash> mListenerCallbacks; - std::vector mUncacheBuffers; uint64_t mId; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 32d60cd5bd..30148042fb 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -701,7 +701,7 @@ public: const sp& /*applyToken*/, const InputWindowCommands& /*inputWindowCommands*/, int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, - const std::vector& /*cachedBuffer*/, + const client_cache_t& /*cachedBuffer*/, bool /*hasListenerCallbacks*/, const std::vector& /*listenerCallbacks*/, uint64_t /*transactionId*/) override { diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index d63e2812e2..40de4d675d 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -3973,7 +3973,7 @@ bool SurfaceFlinger::applyTransactions(std::vector& transactio transaction.displays, transaction.flags, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - std::move(transaction.uncacheBufferIds), transaction.postTime, + transaction.buffer, transaction.postTime, transaction.permissions, transaction.hasListenerCallbacks, transaction.listenerCallbacks, transaction.originPid, transaction.originUid, transaction.id); @@ -4061,9 +4061,8 @@ status_t SurfaceFlinger::setTransactionState( const FrameTimelineInfo& frameTimelineInfo, Vector& states, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const std::vector& uncacheBuffers, - bool hasListenerCallbacks, const std::vector& listenerCallbacks, - uint64_t transactionId) { + bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, uint64_t transactionId) { ATRACE_CALL(); uint32_t permissions = @@ -4097,15 +4096,6 @@ status_t SurfaceFlinger::setTransactionState( const int originPid = ipc->getCallingPid(); const int originUid = ipc->getCallingUid(); - std::vector uncacheBufferIds; - uncacheBufferIds.reserve(uncacheBuffers.size()); - for (const auto& uncacheBuffer : uncacheBuffers) { - sp buffer = ClientCache::getInstance().erase(uncacheBuffer); - if (buffer != nullptr) { - uncacheBufferIds.push_back(buffer->getId()); - } - } - std::vector resolvedStates; resolvedStates.reserve(states.size()); for (auto& state : states) { @@ -4123,22 +4113,14 @@ status_t SurfaceFlinger::setTransactionState( } } - TransactionState state{frameTimelineInfo, - resolvedStates, - displays, - flags, - applyToken, - inputWindowCommands, - desiredPresentTime, - isAutoTimestamp, - std::move(uncacheBufferIds), - postTime, - permissions, - hasListenerCallbacks, - listenerCallbacks, - originPid, - originUid, - transactionId}; + TransactionState state{frameTimelineInfo, resolvedStates, + displays, flags, + applyToken, inputWindowCommands, + desiredPresentTime, isAutoTimestamp, + uncacheBuffer, postTime, + permissions, hasListenerCallbacks, + listenerCallbacks, originPid, + originUid, transactionId}; if (mTransactionTracing) { mTransactionTracing->addQueuedTransaction(state); @@ -4162,7 +4144,7 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin Vector& displays, uint32_t flags, const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBufferIds, + const client_cache_t& uncacheBuffer, const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, const std::vector& listenerCallbacks, @@ -4203,8 +4185,11 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin ALOGE("Only privileged callers are allowed to send input commands."); } - for (uint64_t uncacheBufferId : uncacheBufferIds) { - mBufferIdsToUncache.push_back(uncacheBufferId); + if (uncacheBuffer.isValid()) { + sp buffer = ClientCache::getInstance().erase(uncacheBuffer); + if (buffer != nullptr) { + mBufferIdsToUncache.push_back(buffer->getId()); + } } // If a synchronous transaction is explicitly requested without any changes, force a transaction diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 9245399e0d..5457be81a5 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -501,8 +501,7 @@ private: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, + const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override; void bootFinished(); @@ -715,14 +714,16 @@ private: /* * Transactions */ - bool applyTransactionState( - const FrameTimelineInfo& info, std::vector& state, - Vector& displays, uint32_t flags, - const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, - bool isAutoTimestamp, const std::vector& uncacheBufferIds, - const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, int originPid, int originUid, - uint64_t transactionId) REQUIRES(mStateLock); + bool applyTransactionState(const FrameTimelineInfo& info, + std::vector& state, + Vector& displays, uint32_t flags, + const InputWindowCommands& inputWindowCommands, + const int64_t desiredPresentTime, bool isAutoTimestamp, + const client_cache_t& uncacheBuffer, const int64_t postTime, + uint32_t permissions, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, + int originPid, int originUid, uint64_t transactionId) + REQUIRES(mStateLock); // Flush pending transactions that were presented after desiredPresentTime. bool flushTransactionQueues(VsyncId) REQUIRES(kMainThreadContext); // Returns true if there is at least one transaction that needs to be flushed diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 5025c4935c..366b09d68b 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -43,7 +43,7 @@ struct TransactionState { const Vector& displayStates, uint32_t transactionFlags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - std::vector uncacheBufferIds, int64_t postTime, uint32_t permissions, + const client_cache_t& uncacheBuffer, int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, std::vector listenerCallbacks, int originPid, int originUid, uint64_t transactionId) : frameTimelineInfo(frameTimelineInfo), @@ -54,7 +54,7 @@ struct TransactionState { inputWindowCommands(inputWindowCommands), desiredPresentTime(desiredPresentTime), isAutoTimestamp(isAutoTimestamp), - uncacheBufferIds(std::move(uncacheBufferIds)), + buffer(uncacheBuffer), postTime(postTime), permissions(permissions), hasListenerCallbacks(hasListenerCallbacks), @@ -109,7 +109,7 @@ struct TransactionState { InputWindowCommands inputWindowCommands; int64_t desiredPresentTime; bool isAutoTimestamp; - std::vector uncacheBufferIds; + client_cache_t buffer; int64_t postTime; uint32_t permissions; bool hasListenerCallbacks; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index c22d78b86e..81ca659915 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -730,18 +730,17 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionQueues; } - auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& states, const Vector& displays, - uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, + auto setTransactionState(const FrameTimelineInfo &frameTimelineInfo, + Vector &states, const Vector &displays, + uint32_t flags, const sp &applyToken, + const InputWindowCommands &inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, - std::vector& listenerCallbacks, + const client_cache_t &uncacheBuffer, bool hasListenerCallbacks, + std::vector &listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index 72e0c7be16..584d52ca02 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -439,13 +439,12 @@ public: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, + const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, std::vector& listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index a28d1cd415..d84698f279 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -102,7 +102,7 @@ public: int64_t desiredPresentTime = 0; bool isAutoTimestamp = true; FrameTimelineInfo frameTimelineInfo; - std::vector uncacheBuffers; + client_cache_t uncacheBuffer; uint64_t id = static_cast(-1); static_assert(0xffffffffffffffff == static_cast(-1)); }; @@ -138,7 +138,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transaction.id); // If transaction is synchronous, SF applyTransactionState should time out (5s) wating for @@ -165,7 +165,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transaction.id); nsecs_t returnedTime = systemTime(); @@ -196,7 +196,7 @@ public: transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, - transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, + transactionA.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transactionA.id); // This thread should not have been blocked by the above transaction @@ -211,7 +211,7 @@ public: transactionB.displays, transactionB.flags, transactionB.applyToken, transactionB.inputWindowCommands, transactionB.desiredPresentTime, transactionB.isAutoTimestamp, - transactionB.uncacheBuffers, mHasListenerCallbacks, mCallbacks, + transactionB.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transactionB.id); // this thread should have been blocked by the above transaction @@ -243,7 +243,7 @@ TEST_F(TransactionApplicationTest, AddToPendingQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffers, + transactionA.isAutoTimestamp, transactionA.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -263,7 +263,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffers, + transactionA.isAutoTimestamp, transactionA.uncacheBuffer, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -277,7 +277,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(empty.frameTimelineInfo, empty.states, empty.displays, empty.flags, empty.applyToken, empty.inputWindowCommands, empty.desiredPresentTime, empty.isAutoTimestamp, - empty.uncacheBuffers, mHasListenerCallbacks, mCallbacks, empty.id); + empty.uncacheBuffer, mHasListenerCallbacks, mCallbacks, empty.id); // flush transaction queue should flush as desiredPresentTime has // passed @@ -374,7 +374,8 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, - transaction.isAutoTimestamp, {}, systemTime(), 0, + transaction.isAutoTimestamp, + transaction.uncacheBuffer, systemTime(), 0, mHasListenerCallbacks, mCallbacks, getpid(), static_cast(getuid()), transaction.id); mFlinger.setTransactionStateInternal(transactionState); -- cgit v1.2.3-59-g8ed1b From 6c6dd3b2ae7ae677f0448624cf8f6aeafdaffbf5 Mon Sep 17 00:00:00 2001 From: Patrick Williams Date: Mon, 13 Feb 2023 22:53:06 +0000 Subject: Cache and uncache buffers in the same transaction This removes a race condition where clients may attempt to cache a buffer before an associated uncache buffer request has completed, leading to full buffer cache errors in SurfaceFlinger. GLSurfaceViewTest#testPauseResumeWithoutDelay is failing on barbet and test logs show frequent `ClientCache::add - cache is full` messages. This CL fixes the "cache is full" error but does not fix the broken test. This reverts commit 1088bbf9882d778079eaa7465c1dec2b08848f1a. Reason for revert: b/269141832 Change-Id: I4ba8cf18a367ae6ca94992aabd695d8984fea76f --- libs/gui/ISurfaceComposer.cpp | 23 +++++--- libs/gui/SurfaceComposerClient.cpp | 62 ++++++++++++++++------ libs/gui/include/gui/ISurfaceComposer.h | 5 +- libs/gui/include/gui/SurfaceComposerClient.h | 1 + libs/gui/tests/Surface_test.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 49 +++++++++++------ services/surfaceflinger/SurfaceFlinger.h | 21 ++++---- services/surfaceflinger/TransactionState.h | 6 +-- .../fuzzer/surfaceflinger_fuzzers_utils.h | 15 +++--- .../tests/unittests/TestableSurfaceFlinger.h | 5 +- .../tests/unittests/TransactionApplicationTest.cpp | 19 ++++--- 11 files changed, 130 insertions(+), 78 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index a77ca04943..cefb9a71d6 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -63,7 +63,8 @@ public: Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& commands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, + bool isAutoTimestamp, + const std::vector& uncacheBuffers, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override { @@ -87,8 +88,11 @@ public: SAFE_PARCEL(commands.write, data); SAFE_PARCEL(data.writeInt64, desiredPresentTime); SAFE_PARCEL(data.writeBool, isAutoTimestamp); - SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); - SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); + SAFE_PARCEL(data.writeUint32, static_cast(uncacheBuffers.size())); + for (const client_cache_t& uncacheBuffer : uncacheBuffers) { + SAFE_PARCEL(data.writeStrongBinder, uncacheBuffer.token.promote()); + SAFE_PARCEL(data.writeUint64, uncacheBuffer.id); + } SAFE_PARCEL(data.writeBool, hasListenerCallbacks); SAFE_PARCEL(data.writeVectorSize, listenerCallbacks); @@ -158,11 +162,14 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(data.readInt64, &desiredPresentTime); SAFE_PARCEL(data.readBool, &isAutoTimestamp); - client_cache_t uncachedBuffer; + SAFE_PARCEL_READ_SIZE(data.readUint32, &count, data.dataSize()); + std::vector uncacheBuffers(count); sp tmpBinder; - SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); - uncachedBuffer.token = tmpBinder; - SAFE_PARCEL(data.readUint64, &uncachedBuffer.id); + for (size_t i = 0; i < count; i++) { + SAFE_PARCEL(data.readNullableStrongBinder, &tmpBinder); + uncacheBuffers[i].token = tmpBinder; + SAFE_PARCEL(data.readUint64, &uncacheBuffers[i].id); + } bool hasListenerCallbacks = false; SAFE_PARCEL(data.readBool, &hasListenerCallbacks); @@ -182,7 +189,7 @@ status_t BnSurfaceComposer::onTransact( return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, - uncachedBuffer, hasListenerCallbacks, listenerCallbacks, + uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } default: { diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 92125ead1f..21a7f7817a 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -565,11 +565,13 @@ public: return NO_ERROR; } - uint64_t cache(const sp& buffer) { + uint64_t cache(const sp& buffer, + std::optional& outUncacheBuffer) { std::lock_guard lock(mMutex); if (mBuffers.size() >= BUFFER_CACHE_MAX_SIZE) { - evictLeastRecentlyUsedBuffer(); + outUncacheBuffer = findLeastRecentlyUsedBuffer(); + mBuffers.erase(outUncacheBuffer->id); } buffer->addDeathCallback(removeDeadBufferCallback, nullptr); @@ -580,16 +582,13 @@ public: void uncache(uint64_t cacheId) { std::lock_guard lock(mMutex); - uncacheLocked(cacheId); - } - - void uncacheLocked(uint64_t cacheId) REQUIRES(mMutex) { - mBuffers.erase(cacheId); - SurfaceComposerClient::doUncacheBufferTransaction(cacheId); + if (mBuffers.erase(cacheId)) { + SurfaceComposerClient::doUncacheBufferTransaction(cacheId); + } } private: - void evictLeastRecentlyUsedBuffer() REQUIRES(mMutex) { + client_cache_t findLeastRecentlyUsedBuffer() REQUIRES(mMutex) { auto itr = mBuffers.begin(); uint64_t minCounter = itr->second; auto minBuffer = itr; @@ -603,7 +602,8 @@ private: } itr++; } - uncacheLocked(minBuffer->first); + + return {.token = getToken(), .id = minBuffer->first}; } uint64_t getCounter() REQUIRES(mMutex) { @@ -741,6 +741,18 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel InputWindowCommands inputWindowCommands; inputWindowCommands.read(*parcel); + count = static_cast(parcel->readUint32()); + if (count > parcel->dataSize()) { + return BAD_VALUE; + } + std::vector uncacheBuffers(count); + for (size_t i = 0; i < count; i++) { + sp tmpBinder; + SAFE_PARCEL(parcel->readStrongBinder, &tmpBinder); + uncacheBuffers[i].token = tmpBinder; + SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id); + } + // Parsing was successful. Update the object. mId = transactionId; mTransactionNestCount = transactionNestCount; @@ -755,6 +767,7 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel mComposerStates = composerStates; mInputWindowCommands = inputWindowCommands; mApplyToken = applyToken; + mUncacheBuffers = std::move(uncacheBuffers); return NO_ERROR; } @@ -806,6 +819,13 @@ status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const } mInputWindowCommands.write(*parcel); + + SAFE_PARCEL(parcel->writeUint32, static_cast(mUncacheBuffers.size())); + for (const client_cache_t& uncacheBuffer : mUncacheBuffers) { + SAFE_PARCEL(parcel->writeStrongBinder, uncacheBuffer.token.promote()); + SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id); + } + return NO_ERROR; } @@ -873,6 +893,10 @@ SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Tr } } + for (const auto& cacheId : other.mUncacheBuffers) { + mUncacheBuffers.push_back(cacheId); + } + mInputWindowCommands.merge(other.mInputWindowCommands); mMayContainBuffer |= other.mMayContainBuffer; @@ -891,6 +915,7 @@ void SurfaceComposerClient::Transaction::clear() { mDisplayStates.clear(); mListenerCallbacks.clear(); mInputWindowCommands.clear(); + mUncacheBuffers.clear(); mMayContainBuffer = false; mTransactionNestCount = 0; mAnimation = false; @@ -913,10 +938,10 @@ void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { uncacheBuffer.token = BufferCache::getInstance().getToken(); uncacheBuffer.id = cacheId; Vector composerStates; - status_t status = - sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, - ISurfaceComposer::eOneWay, Transaction::getDefaultApplyToken(), - {}, systemTime(), true, uncacheBuffer, false, {}, generateId()); + status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, + ISurfaceComposer::eOneWay, + Transaction::getDefaultApplyToken(), {}, systemTime(), + true, {uncacheBuffer}, false, {}, generateId()); if (status != NO_ERROR) { ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s", strerror(-status)); @@ -954,7 +979,11 @@ void SurfaceComposerClient::Transaction::cacheBuffers() { s->bufferData->buffer = nullptr; } else { // Cache-miss. Include the buffer and send the new cacheId. - cacheId = BufferCache::getInstance().cache(s->bufferData->buffer); + std::optional uncacheBuffer; + cacheId = BufferCache::getInstance().cache(s->bufferData->buffer, uncacheBuffer); + if (uncacheBuffer) { + mUncacheBuffers.push_back(*uncacheBuffer); + } } s->bufferData->flags |= BufferData::BufferDataChange::cachedBufferChanged; s->bufferData->cachedBuffer.token = BufferCache::getInstance().getToken(); @@ -1087,8 +1116,7 @@ status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay sp sf(ComposerService::getComposerService()); sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken, mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp, - {} /*uncacheBuffer - only set in doUncacheBufferTransaction*/, - hasListenerCallbacks, listenerCallbacks, mId); + mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId); mId = generateId(); // Clear the current states and flags diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 045cc2a184..ae56f9fdb5 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -113,8 +113,9 @@ public: const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, uint64_t transactionId) = 0; + bool isAutoTimestamp, const std::vector& uncacheBuffer, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, + uint64_t transactionId) = 0; }; // ---------------------------------------------------------------------------- diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 2458a40ce0..0e51dcf4d4 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -402,6 +402,7 @@ public: SortedVector mDisplayStates; std::unordered_map, CallbackInfo, TCLHash> mListenerCallbacks; + std::vector mUncacheBuffers; uint64_t mId; diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 30148042fb..32d60cd5bd 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -701,7 +701,7 @@ public: const sp& /*applyToken*/, const InputWindowCommands& /*inputWindowCommands*/, int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, - const client_cache_t& /*cachedBuffer*/, + const std::vector& /*cachedBuffer*/, bool /*hasListenerCallbacks*/, const std::vector& /*listenerCallbacks*/, uint64_t /*transactionId*/) override { diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 40de4d675d..d63e2812e2 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -3973,7 +3973,7 @@ bool SurfaceFlinger::applyTransactions(std::vector& transactio transaction.displays, transaction.flags, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.buffer, transaction.postTime, + std::move(transaction.uncacheBufferIds), transaction.postTime, transaction.permissions, transaction.hasListenerCallbacks, transaction.listenerCallbacks, transaction.originPid, transaction.originUid, transaction.id); @@ -4061,8 +4061,9 @@ status_t SurfaceFlinger::setTransactionState( const FrameTimelineInfo& frameTimelineInfo, Vector& states, const Vector& displays, uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, uint64_t transactionId) { + bool isAutoTimestamp, const std::vector& uncacheBuffers, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, + uint64_t transactionId) { ATRACE_CALL(); uint32_t permissions = @@ -4096,6 +4097,15 @@ status_t SurfaceFlinger::setTransactionState( const int originPid = ipc->getCallingPid(); const int originUid = ipc->getCallingUid(); + std::vector uncacheBufferIds; + uncacheBufferIds.reserve(uncacheBuffers.size()); + for (const auto& uncacheBuffer : uncacheBuffers) { + sp buffer = ClientCache::getInstance().erase(uncacheBuffer); + if (buffer != nullptr) { + uncacheBufferIds.push_back(buffer->getId()); + } + } + std::vector resolvedStates; resolvedStates.reserve(states.size()); for (auto& state : states) { @@ -4113,14 +4123,22 @@ status_t SurfaceFlinger::setTransactionState( } } - TransactionState state{frameTimelineInfo, resolvedStates, - displays, flags, - applyToken, inputWindowCommands, - desiredPresentTime, isAutoTimestamp, - uncacheBuffer, postTime, - permissions, hasListenerCallbacks, - listenerCallbacks, originPid, - originUid, transactionId}; + TransactionState state{frameTimelineInfo, + resolvedStates, + displays, + flags, + applyToken, + inputWindowCommands, + desiredPresentTime, + isAutoTimestamp, + std::move(uncacheBufferIds), + postTime, + permissions, + hasListenerCallbacks, + listenerCallbacks, + originPid, + originUid, + transactionId}; if (mTransactionTracing) { mTransactionTracing->addQueuedTransaction(state); @@ -4144,7 +4162,7 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin Vector& displays, uint32_t flags, const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, + const std::vector& uncacheBufferIds, const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, const std::vector& listenerCallbacks, @@ -4185,11 +4203,8 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin ALOGE("Only privileged callers are allowed to send input commands."); } - if (uncacheBuffer.isValid()) { - sp buffer = ClientCache::getInstance().erase(uncacheBuffer); - if (buffer != nullptr) { - mBufferIdsToUncache.push_back(buffer->getId()); - } + for (uint64_t uncacheBufferId : uncacheBufferIds) { + mBufferIdsToUncache.push_back(uncacheBufferId); } // If a synchronous transaction is explicitly requested without any changes, force a transaction diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 5457be81a5..9245399e0d 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -501,7 +501,8 @@ private: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) override; void bootFinished(); @@ -714,16 +715,14 @@ private: /* * Transactions */ - bool applyTransactionState(const FrameTimelineInfo& info, - std::vector& state, - Vector& displays, uint32_t flags, - const InputWindowCommands& inputWindowCommands, - const int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, const int64_t postTime, - uint32_t permissions, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, - int originPid, int originUid, uint64_t transactionId) - REQUIRES(mStateLock); + bool applyTransactionState( + const FrameTimelineInfo& info, std::vector& state, + Vector& displays, uint32_t flags, + const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, + bool isAutoTimestamp, const std::vector& uncacheBufferIds, + const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, int originPid, int originUid, + uint64_t transactionId) REQUIRES(mStateLock); // Flush pending transactions that were presented after desiredPresentTime. bool flushTransactionQueues(VsyncId) REQUIRES(kMainThreadContext); // Returns true if there is at least one transaction that needs to be flushed diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 366b09d68b..5025c4935c 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -43,7 +43,7 @@ struct TransactionState { const Vector& displayStates, uint32_t transactionFlags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, int64_t postTime, uint32_t permissions, + std::vector uncacheBufferIds, int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, std::vector listenerCallbacks, int originPid, int originUid, uint64_t transactionId) : frameTimelineInfo(frameTimelineInfo), @@ -54,7 +54,7 @@ struct TransactionState { inputWindowCommands(inputWindowCommands), desiredPresentTime(desiredPresentTime), isAutoTimestamp(isAutoTimestamp), - buffer(uncacheBuffer), + uncacheBufferIds(std::move(uncacheBufferIds)), postTime(postTime), permissions(permissions), hasListenerCallbacks(hasListenerCallbacks), @@ -109,7 +109,7 @@ struct TransactionState { InputWindowCommands inputWindowCommands; int64_t desiredPresentTime; bool isAutoTimestamp; - client_cache_t buffer; + std::vector uncacheBufferIds; int64_t postTime; uint32_t permissions; bool hasListenerCallbacks; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 81ca659915..c22d78b86e 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -730,17 +730,18 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionQueues; } - auto setTransactionState(const FrameTimelineInfo &frameTimelineInfo, - Vector &states, const Vector &displays, - uint32_t flags, const sp &applyToken, - const InputWindowCommands &inputWindowCommands, + auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, + Vector& states, const Vector& displays, + uint32_t flags, const sp& applyToken, + const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t &uncacheBuffer, bool hasListenerCallbacks, - std::vector &listenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, + std::vector& listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index 584d52ca02..72e0c7be16 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -439,12 +439,13 @@ public: uint32_t flags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - const client_cache_t& uncacheBuffer, bool hasListenerCallbacks, + const std::vector& uncacheBuffers, + bool hasListenerCallbacks, std::vector& listenerCallbacks, uint64_t transactionId) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, - isAutoTimestamp, uncacheBuffer, hasListenerCallbacks, + isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, listenerCallbacks, transactionId); } diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index d84698f279..a28d1cd415 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -102,7 +102,7 @@ public: int64_t desiredPresentTime = 0; bool isAutoTimestamp = true; FrameTimelineInfo frameTimelineInfo; - client_cache_t uncacheBuffer; + std::vector uncacheBuffers; uint64_t id = static_cast(-1); static_assert(0xffffffffffffffff == static_cast(-1)); }; @@ -138,7 +138,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transaction.id); // If transaction is synchronous, SF applyTransactionState should time out (5s) wating for @@ -165,7 +165,7 @@ public: transaction.displays, transaction.flags, transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, - transaction.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transaction.id); nsecs_t returnedTime = systemTime(); @@ -196,7 +196,7 @@ public: transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, - transactionA.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); // This thread should not have been blocked by the above transaction @@ -211,7 +211,7 @@ public: transactionB.displays, transactionB.flags, transactionB.applyToken, transactionB.inputWindowCommands, transactionB.desiredPresentTime, transactionB.isAutoTimestamp, - transactionB.uncacheBuffer, mHasListenerCallbacks, mCallbacks, + transactionB.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionB.id); // this thread should have been blocked by the above transaction @@ -243,7 +243,7 @@ TEST_F(TransactionApplicationTest, AddToPendingQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffer, + transactionA.isAutoTimestamp, transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -263,7 +263,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(transactionA.frameTimelineInfo, transactionA.states, transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, - transactionA.isAutoTimestamp, transactionA.uncacheBuffer, + transactionA.isAutoTimestamp, transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, transactionA.id); auto& transactionQueue = mFlinger.getTransactionQueue(); @@ -277,7 +277,7 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(empty.frameTimelineInfo, empty.states, empty.displays, empty.flags, empty.applyToken, empty.inputWindowCommands, empty.desiredPresentTime, empty.isAutoTimestamp, - empty.uncacheBuffer, mHasListenerCallbacks, mCallbacks, empty.id); + empty.uncacheBuffers, mHasListenerCallbacks, mCallbacks, empty.id); // flush transaction queue should flush as desiredPresentTime has // passed @@ -374,8 +374,7 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, - transaction.isAutoTimestamp, - transaction.uncacheBuffer, systemTime(), 0, + transaction.isAutoTimestamp, {}, systemTime(), 0, mHasListenerCallbacks, mCallbacks, getpid(), static_cast(getuid()), transaction.id); mFlinger.setTransactionStateInternal(transactionState); -- cgit v1.2.3-59-g8ed1b From c78f53cd0e9ce68cc52a851584b6ce5b34baef7d Mon Sep 17 00:00:00 2001 From: Chavi Weingarten Date: Fri, 14 Apr 2023 18:50:53 +0000 Subject: Cleaned up transaction sanitize calls Exposed a way for a client to invoke sanitize with a uid and pid to ensure we don't remove states when the process that added it was privileged. Added a helper function to get the permission ints based on the String permission values so SF and clients can call the same API. In SF, call sanitize as soon as setTransactionState is called since that's the point where the Transaction has been passed over binder so we can identify the calling uid. This allows us to remove the permission values passed to applyTransactionState and unifies the places that were calling sanitize. Test: CredentialsTest Bug: 267794530 Change-Id: I30c1800f0fee43df1cee82464139db7b56a7d911 --- libs/gui/Android.bp | 1 + libs/gui/ISurfaceComposer.cpp | 8 +-- libs/gui/LayerStatePermissions.cpp | 58 +++++++++++++++++ libs/gui/SurfaceComposerClient.cpp | 12 +++- libs/gui/include/gui/ISurfaceComposer.h | 2 +- libs/gui/include/gui/LayerStatePermissions.h | 29 +++++++++ libs/gui/include/gui/SurfaceComposerClient.h | 2 +- libs/gui/tests/Surface_test.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 64 ++++++++----------- services/surfaceflinger/SurfaceFlinger.h | 27 ++++---- services/surfaceflinger/TransactionState.h | 4 +- services/surfaceflinger/tests/Credentials_test.cpp | 53 ++++++++++++++++ .../tests/WindowInfosListener_test.cpp | 39 ++---------- .../tests/unittests/TransactionApplicationTest.cpp | 2 +- .../tests/utils/WindowInfosListenerUtils.h | 74 ++++++++++++++++++++++ 15 files changed, 277 insertions(+), 100 deletions(-) create mode 100644 libs/gui/LayerStatePermissions.cpp create mode 100644 libs/gui/include/gui/LayerStatePermissions.h create mode 100644 services/surfaceflinger/tests/utils/WindowInfosListenerUtils.h (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/Android.bp b/libs/gui/Android.bp index 33bb343c9d..80fed98434 100644 --- a/libs/gui/Android.bp +++ b/libs/gui/Android.bp @@ -226,6 +226,7 @@ cc_library_shared { "ITransactionCompletedListener.cpp", "LayerDebugInfo.cpp", "LayerMetadata.cpp", + "LayerStatePermissions.cpp", "LayerState.cpp", "OccupancyTracker.cpp", "StreamSplitter.cpp", diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index cefb9a71d6..d72f65eb7a 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -62,7 +62,7 @@ public: status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, - const InputWindowCommands& commands, int64_t desiredPresentTime, + InputWindowCommands commands, int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBuffers, bool hasListenerCallbacks, @@ -188,9 +188,9 @@ status_t BnSurfaceComposer::onTransact( SAFE_PARCEL(data.readUint64, &transactionId); return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken, - inputWindowCommands, desiredPresentTime, isAutoTimestamp, - uncacheBuffers, hasListenerCallbacks, listenerCallbacks, - transactionId); + std::move(inputWindowCommands), desiredPresentTime, + isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, + listenerCallbacks, transactionId); } default: { return BBinder::onTransact(code, data, reply, flags); diff --git a/libs/gui/LayerStatePermissions.cpp b/libs/gui/LayerStatePermissions.cpp new file mode 100644 index 0000000000..28697ca953 --- /dev/null +++ b/libs/gui/LayerStatePermissions.cpp @@ -0,0 +1,58 @@ +/* + * Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#ifndef __ANDROID_VNDK__ +#include +#endif // __ANDROID_VNDK__ +#include + +namespace android { +std::unordered_map LayerStatePermissions::mPermissionMap = { + // If caller has ACCESS_SURFACE_FLINGER, they automatically get ROTATE_SURFACE_FLINGER + // permission, as well + {"android.permission.ACCESS_SURFACE_FLINGER", + layer_state_t::Permission::ACCESS_SURFACE_FLINGER | + layer_state_t::Permission::ROTATE_SURFACE_FLINGER}, + {"android.permission.ROTATE_SURFACE_FLINGER", + layer_state_t::Permission::ROTATE_SURFACE_FLINGER}, + {"android.permission.INTERNAL_SYSTEM_WINDOW", + layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW}, +}; + +static bool callingThreadHasPermission(const std::string& permission __attribute__((unused)), + int pid __attribute__((unused)), + int uid __attribute__((unused))) { +#ifndef __ANDROID_VNDK__ + return uid == AID_GRAPHICS || uid == AID_SYSTEM || + PermissionCache::checkPermission(String16(permission.c_str()), pid, uid); +#endif // __ANDROID_VNDK__ + return false; +} + +uint32_t LayerStatePermissions::getTransactionPermissions(int pid, int uid) { + uint32_t permissions = 0; + for (auto [permissionName, permissionVal] : mPermissionMap) { + if (callingThreadHasPermission(permissionName, pid, uid)) { + permissions |= permissionVal; + } + } + + return permissions; +} +} // namespace android diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index eb5cc4f8ab..1b13ec1c06 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -54,6 +54,7 @@ #include #include +#include #include #include @@ -716,11 +717,16 @@ SurfaceComposerClient::Transaction::Transaction(const Transaction& other) mListenerCallbacks = other.mListenerCallbacks; } -void SurfaceComposerClient::Transaction::sanitize() { +void SurfaceComposerClient::Transaction::sanitize(int pid, int uid) { + uint32_t permissions = LayerStatePermissions::getTransactionPermissions(pid, uid); for (auto & [handle, composerState] : mComposerStates) { - composerState.state.sanitize(0 /* permissionMask */); + composerState.state.sanitize(permissions); + } + if (!mInputWindowCommands.empty() && + (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) { + ALOGE("Only privileged callers are allowed to send input commands."); + mInputWindowCommands.clear(); } - mInputWindowCommands.clear(); } std::unique_ptr diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index 1e67225a4e..bd21851c14 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -113,7 +113,7 @@ public: virtual status_t setTransactionState( const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, + InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, uint64_t transactionId) = 0; diff --git a/libs/gui/include/gui/LayerStatePermissions.h b/libs/gui/include/gui/LayerStatePermissions.h new file mode 100644 index 0000000000..a90f30c621 --- /dev/null +++ b/libs/gui/include/gui/LayerStatePermissions.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +namespace android { +class LayerStatePermissions { +public: + static uint32_t getTransactionPermissions(int pid, int uid); + +private: + static std::unordered_map mPermissionMap; +}; +} // namespace android \ No newline at end of file diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 945b164fdc..8d2cdaf5b8 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -744,7 +744,7 @@ public: * * TODO (b/213644870): Remove all permissioned things from Transaction */ - void sanitize(); + void sanitize(int pid, int uid); static sp getDefaultApplyToken(); static void setDefaultApplyToken(sp applyToken); diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index fccc408473..5bc6904563 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -699,7 +699,7 @@ public: Vector& /*state*/, const Vector& /*displays*/, uint32_t /*flags*/, const sp& /*applyToken*/, - const InputWindowCommands& /*inputWindowCommands*/, + InputWindowCommands /*inputWindowCommands*/, int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, const std::vector& /*cachedBuffer*/, bool /*hasListenerCallbacks*/, diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 2d406788cf..95159d7d2a 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -110,6 +110,7 @@ #include #include +#include #include #include "BackgroundExecutor.h" #include "Client.h" @@ -4405,7 +4406,7 @@ bool SurfaceFlinger::applyTransactionsLocked(std::vector& tran transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, std::move(transaction.uncacheBufferIds), transaction.postTime, - transaction.permissions, transaction.hasListenerCallbacks, + transaction.hasListenerCallbacks, transaction.listenerCallbacks, transaction.originPid, transaction.originUid, transaction.id); } @@ -4484,24 +4485,27 @@ bool SurfaceFlinger::shouldLatchUnsignaled(const sp& layer, const layer_s status_t SurfaceFlinger::setTransactionState( const FrameTimelineInfo& frameTimelineInfo, Vector& states, const Vector& displays, uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, - bool isAutoTimestamp, const std::vector& uncacheBuffers, - bool hasListenerCallbacks, const std::vector& listenerCallbacks, - uint64_t transactionId) { + InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, + const std::vector& uncacheBuffers, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, uint64_t transactionId) { ATRACE_CALL(); - uint32_t permissions = - callingThreadHasUnscopedSurfaceFlingerAccess() ? - layer_state_t::Permission::ACCESS_SURFACE_FLINGER : 0; - // Avoid checking for rotation permissions if the caller already has ACCESS_SURFACE_FLINGER - // permissions. - if ((permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) || - callingThreadHasPermission(sRotateSurfaceFlinger)) { - permissions |= layer_state_t::Permission::ROTATE_SURFACE_FLINGER; + IPCThreadState* ipc = IPCThreadState::self(); + const int originPid = ipc->getCallingPid(); + const int originUid = ipc->getCallingUid(); + uint32_t permissions = LayerStatePermissions::getTransactionPermissions(originPid, originUid); + for (auto composerState : states) { + composerState.state.sanitize(permissions); } - if (callingThreadHasPermission(sInternalSystemWindow)) { - permissions |= layer_state_t::Permission::INTERNAL_SYSTEM_WINDOW; + for (DisplayState display : displays) { + display.sanitize(permissions); + } + + if (!inputWindowCommands.empty() && + (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) == 0) { + ALOGE("Only privileged callers are allowed to send input commands."); + inputWindowCommands.clear(); } if (flags & (eEarlyWakeupStart | eEarlyWakeupEnd)) { @@ -4517,10 +4521,6 @@ status_t SurfaceFlinger::setTransactionState( const int64_t postTime = systemTime(); - IPCThreadState* ipc = IPCThreadState::self(); - const int originPid = ipc->getCallingPid(); - const int originUid = ipc->getCallingUid(); - std::vector uncacheBufferIds; uncacheBufferIds.reserve(uncacheBuffers.size()); for (const auto& uncacheBuffer : uncacheBuffers) { @@ -4567,12 +4567,11 @@ status_t SurfaceFlinger::setTransactionState( displays, flags, applyToken, - inputWindowCommands, + std::move(inputWindowCommands), desiredPresentTime, isAutoTimestamp, std::move(uncacheBufferIds), postTime, - permissions, hasListenerCallbacks, listenerCallbacks, originPid, @@ -4601,14 +4600,12 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBufferIds, - const int64_t postTime, uint32_t permissions, - bool hasListenerCallbacks, + const int64_t postTime, bool hasListenerCallbacks, const std::vector& listenerCallbacks, int originPid, int originUid, uint64_t transactionId) { uint32_t transactionFlags = 0; if (!mLayerLifecycleManagerEnabled) { for (DisplayState& display : displays) { - display.sanitize(permissions); transactionFlags |= setDisplayStateLocked(display); } } @@ -4625,12 +4622,12 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin if (mLegacyFrontEndEnabled) { clientStateFlags |= setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime, - isAutoTimestamp, postTime, permissions, transactionId); + isAutoTimestamp, postTime, transactionId); } else /*mLayerLifecycleManagerEnabled*/ { clientStateFlags |= updateLayerCallbacksAndStats(frameTimelineInfo, resolvedState, desiredPresentTime, isAutoTimestamp, - postTime, permissions, transactionId); + postTime, transactionId); } if ((flags & eAnimation) && resolvedState.state.surface) { if (const auto layer = LayerHandle::getLayer(resolvedState.state.surface)) { @@ -4647,12 +4644,7 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin } transactionFlags |= clientStateFlags; - - if (permissions & layer_state_t::Permission::ACCESS_SURFACE_FLINGER) { - transactionFlags |= addInputWindowCommands(inputWindowCommands); - } else if (!inputWindowCommands.empty()) { - ALOGE("Only privileged callers are allowed to send input commands."); - } + transactionFlags |= addInputWindowCommands(inputWindowCommands); for (uint64_t uncacheBufferId : uncacheBufferIds) { mBufferIdsToUncache.push_back(uncacheBufferId); @@ -4689,7 +4681,6 @@ bool SurfaceFlinger::applyAndCommitDisplayTransactionStates( uint32_t transactionFlags = 0; for (auto& transaction : transactions) { for (DisplayState& display : transaction.displays) { - display.sanitize(transaction.permissions); transactionFlags |= setDisplayStateLocked(display); } } @@ -4788,10 +4779,8 @@ bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermis uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTimelineInfo, ResolvedComposerState& composerState, int64_t desiredPresentTime, bool isAutoTimestamp, - int64_t postTime, uint32_t permissions, - uint64_t transactionId) { + int64_t postTime, uint64_t transactionId) { layer_state_t& s = composerState.state; - s.sanitize(permissions); std::vector filteredListeners; for (auto& listener : s.listeners) { @@ -5140,10 +5129,8 @@ uint32_t SurfaceFlinger::updateLayerCallbacksAndStats(const FrameTimelineInfo& f ResolvedComposerState& composerState, int64_t desiredPresentTime, bool isAutoTimestamp, int64_t postTime, - uint32_t permissions, uint64_t transactionId) { layer_state_t& s = composerState.state; - s.sanitize(permissions); std::vector filteredListeners; for (auto& listener : s.listeners) { @@ -5425,7 +5412,6 @@ void SurfaceFlinger::initializeDisplays() { const nsecs_t now = systemTime(); state.desiredPresentTime = now; state.postTime = now; - state.permissions = layer_state_t::ACCESS_SURFACE_FLINGER; state.originPid = mPid; state.originUid = static_cast(getuid()); const uint64_t transactionId = (static_cast(mPid) << 32) | mUniqueTransactionId++; diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 8cc0184e99..cfaa221a45 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -510,7 +510,7 @@ private: status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, Vector& state, const Vector& displays, uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, + InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBuffers, bool hasListenerCallbacks, @@ -731,14 +731,16 @@ private: /* * Transactions */ - bool applyTransactionState( - const FrameTimelineInfo& info, std::vector& state, - Vector& displays, uint32_t flags, - const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime, - bool isAutoTimestamp, const std::vector& uncacheBufferIds, - const int64_t postTime, uint32_t permissions, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, int originPid, int originUid, - uint64_t transactionId) REQUIRES(mStateLock); + bool applyTransactionState(const FrameTimelineInfo& info, + std::vector& state, + Vector& displays, uint32_t flags, + const InputWindowCommands& inputWindowCommands, + const int64_t desiredPresentTime, bool isAutoTimestamp, + const std::vector& uncacheBufferIds, + const int64_t postTime, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, + int originPid, int originUid, uint64_t transactionId) + REQUIRES(mStateLock); // Flush pending transactions that were presented after desiredPresentTime. // For test only bool flushTransactionQueues(VsyncId) REQUIRES(kMainThreadContext); @@ -759,12 +761,11 @@ private: uint32_t setClientStateLocked(const FrameTimelineInfo&, ResolvedComposerState&, int64_t desiredPresentTime, bool isAutoTimestamp, - int64_t postTime, uint32_t permissions, uint64_t transactionId) - REQUIRES(mStateLock); + int64_t postTime, uint64_t transactionId) REQUIRES(mStateLock); uint32_t updateLayerCallbacksAndStats(const FrameTimelineInfo&, ResolvedComposerState&, int64_t desiredPresentTime, bool isAutoTimestamp, - int64_t postTime, uint32_t permissions, - uint64_t transactionId) REQUIRES(mStateLock); + int64_t postTime, uint64_t transactionId) + REQUIRES(mStateLock); uint32_t getTransactionFlags() const; // Sets the masked bits, and schedules a commit if needed. diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 35c8b6c647..62a7dfd0f1 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -54,7 +54,7 @@ struct TransactionState { const Vector& displayStates, uint32_t transactionFlags, const sp& applyToken, const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, - std::vector uncacheBufferIds, int64_t postTime, uint32_t permissions, + std::vector uncacheBufferIds, int64_t postTime, bool hasListenerCallbacks, std::vector listenerCallbacks, int originPid, int originUid, uint64_t transactionId) : frameTimelineInfo(frameTimelineInfo), @@ -67,7 +67,6 @@ struct TransactionState { isAutoTimestamp(isAutoTimestamp), uncacheBufferIds(std::move(uncacheBufferIds)), postTime(postTime), - permissions(permissions), hasListenerCallbacks(hasListenerCallbacks), listenerCallbacks(listenerCallbacks), originPid(originPid), @@ -126,7 +125,6 @@ struct TransactionState { bool isAutoTimestamp; std::vector uncacheBufferIds; int64_t postTime; - uint32_t permissions; bool hasListenerCallbacks; std::vector listenerCallbacks; int originPid; diff --git a/services/surfaceflinger/tests/Credentials_test.cpp b/services/surfaceflinger/tests/Credentials_test.cpp index 4a45eb5586..69e9a169e3 100644 --- a/services/surfaceflinger/tests/Credentials_test.cpp +++ b/services/surfaceflinger/tests/Credentials_test.cpp @@ -31,6 +31,7 @@ #include #include #include "utils/ScreenshotUtils.h" +#include "utils/WindowInfosListenerUtils.h" namespace android { @@ -378,6 +379,58 @@ TEST_F(CredentialsTest, GetActiveColorModeBasicCorrectness) { ASSERT_NE(static_cast(BAD_VALUE), colorMode); } +TEST_F(CredentialsTest, TransactionPermissionTest) { + WindowInfosListenerUtils windowInfosListenerUtils; + std::string name = "Test Layer"; + sp token = sp::make(); + WindowInfo windowInfo; + windowInfo.name = name; + windowInfo.token = token; + sp surfaceControl = + mComposerClient->createSurface(String8(name.c_str()), 100, 100, PIXEL_FORMAT_RGBA_8888, + ISurfaceComposerClient::eFXSurfaceBufferState); + const Rect crop(0, 0, 100, 100); + { + UIDFaker f(AID_SYSTEM); + Transaction() + .setLayerStack(surfaceControl, ui::DEFAULT_LAYER_STACK) + .show(surfaceControl) + .setLayer(surfaceControl, INT32_MAX - 1) + .setCrop(surfaceControl, crop) + .setInputWindowInfo(surfaceControl, windowInfo) + .apply(); + } + + // Called from non privileged process + Transaction().setTrustedOverlay(surfaceControl, true); + { + UIDFaker f(AID_SYSTEM); + auto windowIsPresentAndNotTrusted = [&](const std::vector& windowInfos) { + auto foundWindowInfo = + WindowInfosListenerUtils::findMatchingWindowInfo(windowInfo, windowInfos); + if (!foundWindowInfo) { + return false; + } + return !foundWindowInfo->inputConfig.test(WindowInfo::InputConfig::TRUSTED_OVERLAY); + }; + windowInfosListenerUtils.waitForWindowInfosPredicate(windowIsPresentAndNotTrusted); + } + + { + UIDFaker f(AID_SYSTEM); + Transaction().setTrustedOverlay(surfaceControl, true); + auto windowIsPresentAndTrusted = [&](const std::vector& windowInfos) { + auto foundWindowInfo = + WindowInfosListenerUtils::findMatchingWindowInfo(windowInfo, windowInfos); + if (!foundWindowInfo) { + return false; + } + return foundWindowInfo->inputConfig.test(WindowInfo::InputConfig::TRUSTED_OVERLAY); + }; + windowInfosListenerUtils.waitForWindowInfosPredicate(windowIsPresentAndTrusted); + } +} + } // namespace android // TODO(b/129481165): remove the #pragma below and fix conversion issues diff --git a/services/surfaceflinger/tests/WindowInfosListener_test.cpp b/services/surfaceflinger/tests/WindowInfosListener_test.cpp index 3f27360cb7..ad9a674456 100644 --- a/services/surfaceflinger/tests/WindowInfosListener_test.cpp +++ b/services/surfaceflinger/tests/WindowInfosListener_test.cpp @@ -20,11 +20,13 @@ #include #include #include +#include "utils/WindowInfosListenerUtils.h" namespace android { using Transaction = SurfaceComposerClient::Transaction; using gui::DisplayInfo; using gui::WindowInfo; +constexpr auto findMatchingWindowInfo = WindowInfosListenerUtils::findMatchingWindowInfo; using WindowInfosPredicate = std::function&)>; @@ -37,45 +39,14 @@ protected: void TearDown() override { seteuid(AID_ROOT); } - struct WindowInfosListener : public gui::WindowInfosListener { - public: - WindowInfosListener(WindowInfosPredicate predicate, std::promise& promise) - : mPredicate(std::move(predicate)), mPromise(promise) {} - - void onWindowInfosChanged(const gui::WindowInfosUpdate& update) override { - if (mPredicate(update.windowInfos)) { - mPromise.set_value(); - } - } - - private: - WindowInfosPredicate mPredicate; - std::promise& mPromise; - }; - sp mClient; + WindowInfosListenerUtils mWindowInfosListenerUtils; - bool waitForWindowInfosPredicate(WindowInfosPredicate predicate) { - std::promise promise; - auto listener = sp::make(std::move(predicate), promise); - mClient->addWindowInfosListener(listener); - auto future = promise.get_future(); - bool satisfied = future.wait_for(std::chrono::seconds{1}) == std::future_status::ready; - mClient->removeWindowInfosListener(listener); - return satisfied; + bool waitForWindowInfosPredicate(const WindowInfosPredicate& predicate) { + return mWindowInfosListenerUtils.waitForWindowInfosPredicate(std::move(predicate)); } }; -const WindowInfo* findMatchingWindowInfo(const WindowInfo& targetWindowInfo, - const std::vector& windowInfos) { - for (const WindowInfo& windowInfo : windowInfos) { - if (windowInfo.token == targetWindowInfo.token) { - return &windowInfo; - } - } - return nullptr; -} - TEST_F(WindowInfosListenerTest, WindowInfoAddedAndRemoved) { std::string name = "Test Layer"; sp token = sp::make(); diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index dbb7c6ce63..6a641b3926 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -386,7 +386,7 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, - transaction.isAutoTimestamp, {}, systemTime(), 0, + transaction.isAutoTimestamp, {}, systemTime(), mHasListenerCallbacks, mCallbacks, getpid(), static_cast(getuid()), transaction.id); mFlinger.setTransactionStateInternal(transactionState); diff --git a/services/surfaceflinger/tests/utils/WindowInfosListenerUtils.h b/services/surfaceflinger/tests/utils/WindowInfosListenerUtils.h new file mode 100644 index 0000000000..8e28a75ed4 --- /dev/null +++ b/services/surfaceflinger/tests/utils/WindowInfosListenerUtils.h @@ -0,0 +1,74 @@ +/* + * Copyright 2023 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include + +namespace android { +using Transaction = SurfaceComposerClient::Transaction; +using gui::DisplayInfo; +using gui::WindowInfo; + +using WindowInfosPredicate = std::function&)>; + +class WindowInfosListenerUtils { +public: + WindowInfosListenerUtils() { mClient = sp::make(); } + + bool waitForWindowInfosPredicate(const WindowInfosPredicate& predicate) { + std::promise promise; + auto listener = sp::make(std::move(predicate), promise); + mClient->addWindowInfosListener(listener); + auto future = promise.get_future(); + bool satisfied = future.wait_for(std::chrono::seconds{1}) == std::future_status::ready; + mClient->removeWindowInfosListener(listener); + return satisfied; + } + + static const WindowInfo* findMatchingWindowInfo(const WindowInfo& targetWindowInfo, + const std::vector& windowInfos) { + for (const WindowInfo& windowInfo : windowInfos) { + if (windowInfo.token == targetWindowInfo.token) { + return &windowInfo; + } + } + return nullptr; + } + +private: + struct WindowInfosListener : public gui::WindowInfosListener { + public: + WindowInfosListener(WindowInfosPredicate predicate, std::promise& promise) + : mPredicate(std::move(predicate)), mPromise(promise) {} + + void onWindowInfosChanged(const gui::WindowInfosUpdate& update) override { + if (mPredicate(update.windowInfos)) { + mPromise.set_value(); + } + } + + private: + WindowInfosPredicate mPredicate; + std::promise& mPromise; + }; + + sp mClient; +}; + +} // namespace android -- cgit v1.2.3-59-g8ed1b From 23780be14df464f815d3fab7466d216cfbb2eae3 Mon Sep 17 00:00:00 2001 From: Pablo Gamito Date: Tue, 18 Apr 2023 08:30:00 +0000 Subject: Track transaction merges through transaction trace Bug: 233371599 Bug: 278663063 Test: dump a transaction trace and ensure transactions have the list of merged transaction ids in the proto Change-Id: I3edf8f1443a2573ef2086f221ceeef57172ecdbe --- libs/gui/ISurfaceComposer.cpp | 29 ++-- libs/gui/SurfaceComposerClient.cpp | 41 +++++- libs/gui/include/gui/ISurfaceComposer.h | 2 +- libs/gui/include/gui/SurfaceComposerClient.h | 7 + libs/gui/tests/Surface_test.cpp | 18 ++- services/surfaceflinger/SurfaceFlinger.cpp | 6 +- services/surfaceflinger/SurfaceFlinger.h | 16 +-- .../Tracing/TransactionProtoParser.cpp | 7 + services/surfaceflinger/TransactionState.h | 7 +- .../fuzzer/surfaceflinger_fuzzer.cpp | 5 +- .../fuzzer/surfaceflinger_fuzzers_utils.h | 19 ++- .../surfaceflinger/layerproto/transactions.proto | 1 + .../tests/unittests/TestableSurfaceFlinger.h | 19 ++- .../tests/unittests/TransactionApplicationTest.cpp | 154 +++++++++++++++++++-- .../tests/unittests/TransactionTracingTest.cpp | 11 +- 15 files changed, 274 insertions(+), 68 deletions(-) (limited to 'libs/gui/ISurfaceComposer.cpp') diff --git a/libs/gui/ISurfaceComposer.cpp b/libs/gui/ISurfaceComposer.cpp index d72f65eb7a..b526a6c92c 100644 --- a/libs/gui/ISurfaceComposer.cpp +++ b/libs/gui/ISurfaceComposer.cpp @@ -59,15 +59,13 @@ public: virtual ~BpSurfaceComposer(); - status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& state, const Vector& displays, - uint32_t flags, const sp& applyToken, - InputWindowCommands commands, int64_t desiredPresentTime, - bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, - const std::vector& listenerCallbacks, - uint64_t transactionId) override { + status_t setTransactionState( + const FrameTimelineInfo& frameTimelineInfo, Vector& state, + const Vector& displays, uint32_t flags, const sp& applyToken, + InputWindowCommands commands, int64_t desiredPresentTime, bool isAutoTimestamp, + const std::vector& uncacheBuffers, bool hasListenerCallbacks, + const std::vector& listenerCallbacks, uint64_t transactionId, + const std::vector& mergedTransactionIds) override { Parcel data, reply; data.writeInterfaceToken(ISurfaceComposer::getInterfaceDescriptor()); @@ -103,6 +101,11 @@ public: SAFE_PARCEL(data.writeUint64, transactionId); + SAFE_PARCEL(data.writeUint32, static_cast(mergedTransactionIds.size())); + for (auto mergedTransactionId : mergedTransactionIds) { + SAFE_PARCEL(data.writeUint64, mergedTransactionId); + } + if (flags & ISurfaceComposer::eOneWay) { return remote()->transact(BnSurfaceComposer::SET_TRANSACTION_STATE, data, &reply, IBinder::FLAG_ONEWAY); @@ -187,10 +190,16 @@ status_t BnSurfaceComposer::onTransact( uint64_t transactionId = -1; SAFE_PARCEL(data.readUint64, &transactionId); + SAFE_PARCEL_READ_SIZE(data.readUint32, &count, data.dataSize()); + std::vector mergedTransactions(count); + for (size_t i = 0; i < count; i++) { + SAFE_PARCEL(data.readUint64, &mergedTransactions[i]); + } + return setTransactionState(frameTimelineInfo, state, displays, stateFlags, applyToken, std::move(inputWindowCommands), desiredPresentTime, isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, - listenerCallbacks, transactionId); + listenerCallbacks, transactionId, mergedTransactions); } default: { return BBinder::onTransact(code, data, reply, flags); diff --git a/libs/gui/SurfaceComposerClient.cpp b/libs/gui/SurfaceComposerClient.cpp index 1b13ec1c06..08a1a058e1 100644 --- a/libs/gui/SurfaceComposerClient.cpp +++ b/libs/gui/SurfaceComposerClient.cpp @@ -827,6 +827,15 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel SAFE_PARCEL(parcel->readUint64, &uncacheBuffers[i].id); } + count = static_cast(parcel->readUint32()); + if (count > parcel->dataSize()) { + return BAD_VALUE; + } + std::vector mergedTransactionIds(count); + for (size_t i = 0; i < count; i++) { + SAFE_PARCEL(parcel->readUint64, &mergedTransactionIds[i]); + } + // Parsing was successful. Update the object. mId = transactionId; mTransactionNestCount = transactionNestCount; @@ -842,6 +851,7 @@ status_t SurfaceComposerClient::Transaction::readFromParcel(const Parcel* parcel mInputWindowCommands = inputWindowCommands; mApplyToken = applyToken; mUncacheBuffers = std::move(uncacheBuffers); + mMergedTransactionIds = std::move(mergedTransactionIds); return NO_ERROR; } @@ -900,6 +910,11 @@ status_t SurfaceComposerClient::Transaction::writeToParcel(Parcel* parcel) const SAFE_PARCEL(parcel->writeUint64, uncacheBuffer.id); } + SAFE_PARCEL(parcel->writeUint32, static_cast(mMergedTransactionIds.size())); + for (auto mergedTransactionId : mMergedTransactionIds) { + SAFE_PARCEL(parcel->writeUint64, mergedTransactionId); + } + return NO_ERROR; } @@ -924,6 +939,22 @@ void SurfaceComposerClient::Transaction::releaseBufferIfOverwriting(const layer_ } SurfaceComposerClient::Transaction& SurfaceComposerClient::Transaction::merge(Transaction&& other) { + while (mMergedTransactionIds.size() + other.mMergedTransactionIds.size() > + MAX_MERGE_HISTORY_LENGTH - 1 && + mMergedTransactionIds.size() > 0) { + mMergedTransactionIds.pop_back(); + } + if (other.mMergedTransactionIds.size() == MAX_MERGE_HISTORY_LENGTH) { + mMergedTransactionIds.insert(mMergedTransactionIds.begin(), + other.mMergedTransactionIds.begin(), + other.mMergedTransactionIds.end() - 1); + } else if (other.mMergedTransactionIds.size() > 0u) { + mMergedTransactionIds.insert(mMergedTransactionIds.begin(), + other.mMergedTransactionIds.begin(), + other.mMergedTransactionIds.end()); + } + mMergedTransactionIds.insert(mMergedTransactionIds.begin(), other.mId); + for (auto const& [handle, composerState] : other.mComposerStates) { if (mComposerStates.count(handle) == 0) { mComposerStates[handle] = composerState; @@ -998,12 +1029,17 @@ void SurfaceComposerClient::Transaction::clear() { mIsAutoTimestamp = true; clearFrameTimelineInfo(mFrameTimelineInfo); mApplyToken = nullptr; + mMergedTransactionIds.clear(); } uint64_t SurfaceComposerClient::Transaction::getId() { return mId; } +std::vector SurfaceComposerClient::Transaction::getMergedTransactionIds() { + return mMergedTransactionIds; +} + void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { sp sf(ComposerService::getComposerService()); @@ -1014,7 +1050,7 @@ void SurfaceComposerClient::doUncacheBufferTransaction(uint64_t cacheId) { status_t status = sf->setTransactionState(FrameTimelineInfo{}, composerStates, {}, ISurfaceComposer::eOneWay, Transaction::getDefaultApplyToken(), {}, systemTime(), - true, {uncacheBuffer}, false, {}, generateId()); + true, {uncacheBuffer}, false, {}, generateId(), {}); if (status != NO_ERROR) { ALOGE_AND_TRACE("SurfaceComposerClient::doUncacheBufferTransaction - %s", strerror(-status)); @@ -1189,7 +1225,8 @@ status_t SurfaceComposerClient::Transaction::apply(bool synchronous, bool oneWay sp sf(ComposerService::getComposerService()); sf->setTransactionState(mFrameTimelineInfo, composerStates, displayStates, flags, applyToken, mInputWindowCommands, mDesiredPresentTime, mIsAutoTimestamp, - mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId); + mUncacheBuffers, hasListenerCallbacks, listenerCallbacks, mId, + mMergedTransactionIds); mId = generateId(); // Clear the current states and flags diff --git a/libs/gui/include/gui/ISurfaceComposer.h b/libs/gui/include/gui/ISurfaceComposer.h index bd21851c14..7c150d53d9 100644 --- a/libs/gui/include/gui/ISurfaceComposer.h +++ b/libs/gui/include/gui/ISurfaceComposer.h @@ -116,7 +116,7 @@ public: InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBuffer, bool hasListenerCallbacks, const std::vector& listenerCallbacks, - uint64_t transactionId) = 0; + uint64_t transactionId, const std::vector& mergedTransactionIds) = 0; }; // ---------------------------------------------------------------------------- diff --git a/libs/gui/include/gui/SurfaceComposerClient.h b/libs/gui/include/gui/SurfaceComposerClient.h index 8d2cdaf5b8..fb57f63dad 100644 --- a/libs/gui/include/gui/SurfaceComposerClient.h +++ b/libs/gui/include/gui/SurfaceComposerClient.h @@ -419,6 +419,11 @@ public: mListenerCallbacks; std::vector mUncacheBuffers; + // We keep track of the last MAX_MERGE_HISTORY_LENGTH merged transaction ids. + // Ordered most recently merged to least recently merged. + static const size_t MAX_MERGE_HISTORY_LENGTH = 10u; + std::vector mMergedTransactionIds; + uint64_t mId; uint32_t mTransactionNestCount = 0; @@ -482,6 +487,8 @@ public: // The id is updated every time the transaction is applied. uint64_t getId(); + std::vector getMergedTransactionIds(); + status_t apply(bool synchronous = false, bool oneWay = false); // Merge another transaction in to this one, clearing other // as if it had been applied. diff --git a/libs/gui/tests/Surface_test.cpp b/libs/gui/tests/Surface_test.cpp index 5bc6904563..096a43cd95 100644 --- a/libs/gui/tests/Surface_test.cpp +++ b/libs/gui/tests/Surface_test.cpp @@ -695,16 +695,14 @@ public: mSupportsPresent = supportsPresent; } - status_t setTransactionState(const FrameTimelineInfo& /*frameTimelineInfo*/, - Vector& /*state*/, - const Vector& /*displays*/, uint32_t /*flags*/, - const sp& /*applyToken*/, - InputWindowCommands /*inputWindowCommands*/, - int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, - const std::vector& /*cachedBuffer*/, - bool /*hasListenerCallbacks*/, - const std::vector& /*listenerCallbacks*/, - uint64_t /*transactionId*/) override { + status_t setTransactionState( + const FrameTimelineInfo& /*frameTimelineInfo*/, Vector& /*state*/, + const Vector& /*displays*/, uint32_t /*flags*/, + const sp& /*applyToken*/, InputWindowCommands /*inputWindowCommands*/, + int64_t /*desiredPresentTime*/, bool /*isAutoTimestamp*/, + const std::vector& /*cachedBuffer*/, bool /*hasListenerCallbacks*/, + const std::vector& /*listenerCallbacks*/, uint64_t /*transactionId*/, + const std::vector& /*mergedTransactionIds*/) override { return NO_ERROR; } diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index dfe8c72bca..b87b36f7db 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -4474,7 +4474,8 @@ status_t SurfaceFlinger::setTransactionState( const Vector& displays, uint32_t flags, const sp& applyToken, InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, bool isAutoTimestamp, const std::vector& uncacheBuffers, bool hasListenerCallbacks, - const std::vector& listenerCallbacks, uint64_t transactionId) { + const std::vector& listenerCallbacks, uint64_t transactionId, + const std::vector& mergedTransactionIds) { ATRACE_CALL(); IPCThreadState* ipc = IPCThreadState::self(); @@ -4563,7 +4564,8 @@ status_t SurfaceFlinger::setTransactionState( listenerCallbacks, originPid, originUid, - transactionId}; + transactionId, + mergedTransactionIds}; if (mTransactionTracing) { mTransactionTracing->addQueuedTransaction(state); diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index d92ec7a3b6..45a82ed23e 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -508,15 +508,13 @@ private: } sp getPhysicalDisplayToken(PhysicalDisplayId displayId) const; - status_t setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& state, const Vector& displays, - uint32_t flags, const sp& applyToken, - InputWindowCommands inputWindowCommands, - int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, - const std::vector& listenerCallbacks, - uint64_t transactionId) override; + status_t setTransactionState( + const FrameTimelineInfo& frameTimelineInfo, Vector& state, + const Vector& displays, uint32_t flags, const sp& applyToken, + InputWindowCommands inputWindowCommands, int64_t desiredPresentTime, + bool isAutoTimestamp, const std::vector& uncacheBuffers, + bool hasListenerCallbacks, const std::vector& listenerCallbacks, + uint64_t transactionId, const std::vector& mergedTransactionIds) override; void bootFinished(); virtual status_t getSupportedFrameTimestamps(std::vector* outSupported) const; sp createDisplayEventConnection( diff --git a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp index 57d927b6bb..06941809ba 100644 --- a/services/surfaceflinger/Tracing/TransactionProtoParser.cpp +++ b/services/surfaceflinger/Tracing/TransactionProtoParser.cpp @@ -69,6 +69,13 @@ proto::TransactionState TransactionProtoParser::toProto(const TransactionState& for (auto& displayState : t.displays) { proto.mutable_display_changes()->Add(std::move(toProto(displayState))); } + + proto.mutable_merged_transaction_ids()->Reserve( + static_cast(t.mergedTransactionIds.size())); + for (auto& mergedTransactionId : t.mergedTransactionIds) { + proto.mutable_merged_transaction_ids()->Add(mergedTransactionId); + } + return proto; } diff --git a/services/surfaceflinger/TransactionState.h b/services/surfaceflinger/TransactionState.h index 62a7dfd0f1..7132a59016 100644 --- a/services/surfaceflinger/TransactionState.h +++ b/services/surfaceflinger/TransactionState.h @@ -56,7 +56,8 @@ struct TransactionState { int64_t desiredPresentTime, bool isAutoTimestamp, std::vector uncacheBufferIds, int64_t postTime, bool hasListenerCallbacks, std::vector listenerCallbacks, - int originPid, int originUid, uint64_t transactionId) + int originPid, int originUid, uint64_t transactionId, + std::vector mergedTransactionIds) : frameTimelineInfo(frameTimelineInfo), states(std::move(composerStates)), displays(displayStates), @@ -71,7 +72,8 @@ struct TransactionState { listenerCallbacks(listenerCallbacks), originPid(originPid), originUid(originUid), - id(transactionId) {} + id(transactionId), + mergedTransactionIds(std::move(mergedTransactionIds)) {} // Invokes `void(const layer_state_t&)` visitor for matching layers. template @@ -131,6 +133,7 @@ struct TransactionState { int originUid; uint64_t id; bool sentFenceTimeoutWarning = false; + std::vector mergedTransactionIds; }; } // namespace android diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp index ce4d18fbe1..80943b5b63 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp @@ -185,11 +185,12 @@ void SurfaceFlingerFuzzer::setTransactionState() { bool hasListenerCallbacks = mFdp.ConsumeBool(); std::vector listenerCallbacks{}; uint64_t transactionId = mFdp.ConsumeIntegral(); + std::vector mergedTransactionIds{}; mTestableFlinger.setTransactionState(FrameTimelineInfo{}, states, displays, flags, applyToken, InputWindowCommands{}, desiredPresentTime, isAutoTimestamp, - {}, hasListenerCallbacks, listenerCallbacks, - transactionId); + {}, hasListenerCallbacks, listenerCallbacks, transactionId, + mergedTransactionIds); } void SurfaceFlingerFuzzer::setDisplayStateLocked() { diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 4d13aca5bb..da5ec480cc 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -737,19 +737,18 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionQueues; } - auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& states, const Vector& displays, - uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, - int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, - std::vector& listenerCallbacks, - uint64_t transactionId) { + auto setTransactionState( + const FrameTimelineInfo& frameTimelineInfo, Vector& states, + const Vector& displays, uint32_t flags, const sp& applyToken, + const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, + bool isAutoTimestamp, const std::vector& uncacheBuffers, + bool hasListenerCallbacks, std::vector& listenerCallbacks, + uint64_t transactionId, const std::vector& mergedTransactionIds) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, - listenerCallbacks, transactionId); + listenerCallbacks, transactionId, + mergedTransactionIds); } auto flushTransactionQueues() { diff --git a/services/surfaceflinger/layerproto/transactions.proto b/services/surfaceflinger/layerproto/transactions.proto index 2c4eb101e6..b0cee9b398 100644 --- a/services/surfaceflinger/layerproto/transactions.proto +++ b/services/surfaceflinger/layerproto/transactions.proto @@ -100,6 +100,7 @@ message TransactionState { uint64 transaction_id = 6; repeated LayerState layer_changes = 7; repeated DisplayState display_changes = 8; + repeated uint64 merged_transaction_ids = 9; } // Keep insync with layer_state_t diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index a189c002c9..856606488b 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -466,19 +466,18 @@ public: return mFlinger->mTransactionHandler.mPendingTransactionCount.load(); } - auto setTransactionState(const FrameTimelineInfo& frameTimelineInfo, - Vector& states, const Vector& displays, - uint32_t flags, const sp& applyToken, - const InputWindowCommands& inputWindowCommands, - int64_t desiredPresentTime, bool isAutoTimestamp, - const std::vector& uncacheBuffers, - bool hasListenerCallbacks, - std::vector& listenerCallbacks, - uint64_t transactionId) { + auto setTransactionState( + const FrameTimelineInfo& frameTimelineInfo, Vector& states, + const Vector& displays, uint32_t flags, const sp& applyToken, + const InputWindowCommands& inputWindowCommands, int64_t desiredPresentTime, + bool isAutoTimestamp, const std::vector& uncacheBuffers, + bool hasListenerCallbacks, std::vector& listenerCallbacks, + uint64_t transactionId, const std::vector& mergedTransactionIds) { return mFlinger->setTransactionState(frameTimelineInfo, states, displays, flags, applyToken, inputWindowCommands, desiredPresentTime, isAutoTimestamp, uncacheBuffers, hasListenerCallbacks, - listenerCallbacks, transactionId); + listenerCallbacks, transactionId, + mergedTransactionIds); } auto setTransactionStateInternal(TransactionState& transaction) { diff --git a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp index 6a641b3926..afb8efbfff 100644 --- a/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionApplicationTest.cpp @@ -73,6 +73,7 @@ public: FrameTimelineInfo frameTimelineInfo; std::vector uncacheBuffers; uint64_t id = static_cast(-1); + std::vector mergedTransactionIds; static_assert(0xffffffffffffffff == static_cast(-1)); }; @@ -108,7 +109,7 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, - transaction.id); + transaction.id, transaction.mergedTransactionIds); // If transaction is synchronous, SF applyTransactionState should time out (5s) wating for // SF to commit the transaction. If this is animation, it should not time out waiting. @@ -135,7 +136,7 @@ public: transaction.applyToken, transaction.inputWindowCommands, transaction.desiredPresentTime, transaction.isAutoTimestamp, transaction.uncacheBuffers, mHasListenerCallbacks, mCallbacks, - transaction.id); + transaction.id, transaction.mergedTransactionIds); nsecs_t returnedTime = systemTime(); EXPECT_LE(returnedTime, applicationSentTime + TRANSACTION_TIMEOUT); @@ -166,7 +167,7 @@ public: transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, transactionA.uncacheBuffers, mHasListenerCallbacks, mCallbacks, - transactionA.id); + transactionA.id, transactionA.mergedTransactionIds); // This thread should not have been blocked by the above transaction // (5s is the timeout period that applyTransactionState waits for SF to @@ -181,7 +182,7 @@ public: transactionB.applyToken, transactionB.inputWindowCommands, transactionB.desiredPresentTime, transactionB.isAutoTimestamp, transactionB.uncacheBuffers, mHasListenerCallbacks, mCallbacks, - transactionB.id); + transactionB.id, transactionB.mergedTransactionIds); // this thread should have been blocked by the above transaction // if this is an animation, this thread should be blocked for 5s @@ -218,7 +219,8 @@ TEST_F(TransactionApplicationTest, AddToPendingQueue) { transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, transactionA.uncacheBuffers, - mHasListenerCallbacks, mCallbacks, transactionA.id); + mHasListenerCallbacks, mCallbacks, transactionA.id, + transactionA.mergedTransactionIds); auto& transactionQueue = mFlinger.getTransactionQueue(); ASSERT_FALSE(transactionQueue.isEmpty()); @@ -238,7 +240,8 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { transactionA.displays, transactionA.flags, transactionA.applyToken, transactionA.inputWindowCommands, transactionA.desiredPresentTime, transactionA.isAutoTimestamp, transactionA.uncacheBuffers, - mHasListenerCallbacks, mCallbacks, transactionA.id); + mHasListenerCallbacks, mCallbacks, transactionA.id, + transactionA.mergedTransactionIds); auto& transactionQueue = mFlinger.getTransactionQueue(); ASSERT_FALSE(transactionQueue.isEmpty()); @@ -251,7 +254,8 @@ TEST_F(TransactionApplicationTest, Flush_RemovesFromQueue) { mFlinger.setTransactionState(empty.frameTimelineInfo, empty.states, empty.displays, empty.flags, empty.applyToken, empty.inputWindowCommands, empty.desiredPresentTime, empty.isAutoTimestamp, - empty.uncacheBuffers, mHasListenerCallbacks, mCallbacks, empty.id); + empty.uncacheBuffers, mHasListenerCallbacks, mCallbacks, empty.id, + empty.mergedTransactionIds); // flush transaction queue should flush as desiredPresentTime has // passed @@ -388,7 +392,8 @@ public: transaction.desiredPresentTime, transaction.isAutoTimestamp, {}, systemTime(), mHasListenerCallbacks, mCallbacks, getpid(), - static_cast(getuid()), transaction.id); + static_cast(getuid()), transaction.id, + transaction.mergedTransactionIds); mFlinger.setTransactionStateInternal(transactionState); } mFlinger.flushTransactionQueues(); @@ -1083,4 +1088,137 @@ TEST(TransactionHandlerTest, QueueTransaction) { EXPECT_EQ(transactionsReadyToBeApplied.front().id, 42u); } +TEST(TransactionHandlerTest, TransactionsKeepTrackOfDirectMerges) { + SurfaceComposerClient::Transaction transaction1, transaction2, transaction3, transaction4; + + uint64_t transaction2Id = transaction2.getId(); + uint64_t transaction3Id = transaction3.getId(); + EXPECT_NE(transaction2Id, transaction3Id); + + transaction1.merge(std::move(transaction2)); + transaction1.merge(std::move(transaction3)); + + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 2u); + EXPECT_EQ(transaction1.getMergedTransactionIds()[0], transaction3Id); + EXPECT_EQ(transaction1.getMergedTransactionIds()[1], transaction2Id); +} + +TEST(TransactionHandlerTest, TransactionsKeepTrackOfIndirectMerges) { + SurfaceComposerClient::Transaction transaction1, transaction2, transaction3, transaction4; + + uint64_t transaction2Id = transaction2.getId(); + uint64_t transaction3Id = transaction3.getId(); + uint64_t transaction4Id = transaction4.getId(); + EXPECT_NE(transaction2Id, transaction3Id); + EXPECT_NE(transaction2Id, transaction4Id); + EXPECT_NE(transaction3Id, transaction4Id); + + transaction4.merge(std::move(transaction2)); + transaction4.merge(std::move(transaction3)); + + EXPECT_EQ(transaction4.getMergedTransactionIds().size(), 2u); + EXPECT_EQ(transaction4.getMergedTransactionIds()[0], transaction3Id); + EXPECT_EQ(transaction4.getMergedTransactionIds()[1], transaction2Id); + + transaction1.merge(std::move(transaction4)); + + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 3u); + EXPECT_EQ(transaction1.getMergedTransactionIds()[0], transaction4Id); + EXPECT_EQ(transaction1.getMergedTransactionIds()[1], transaction3Id); + EXPECT_EQ(transaction1.getMergedTransactionIds()[2], transaction2Id); +} + +TEST(TransactionHandlerTest, TransactionMergesAreCleared) { + SurfaceComposerClient::Transaction transaction1, transaction2, transaction3; + + transaction1.merge(std::move(transaction2)); + transaction1.merge(std::move(transaction3)); + + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 2u); + + transaction1.clear(); + + EXPECT_EQ(transaction1.getMergedTransactionIds().empty(), true); +} + +TEST(TransactionHandlerTest, TransactionMergesAreCapped) { + SurfaceComposerClient::Transaction transaction; + std::vector mergedTransactionIds; + + for (uint i = 0; i < 20u; i++) { + SurfaceComposerClient::Transaction transactionToMerge; + mergedTransactionIds.push_back(transactionToMerge.getId()); + transaction.merge(std::move(transactionToMerge)); + } + + // Keeps latest 10 merges in order of merge recency + EXPECT_EQ(transaction.getMergedTransactionIds().size(), 10u); + for (uint i = 0; i < 10u; i++) { + EXPECT_EQ(transaction.getMergedTransactionIds()[i], + mergedTransactionIds[mergedTransactionIds.size() - 1 - i]); + } +} + +TEST(TransactionHandlerTest, KeepsMergesFromMoreRecentMerge) { + SurfaceComposerClient::Transaction transaction1, transaction2, transaction3; + std::vector mergedTransactionIds1, mergedTransactionIds2, mergedTransactionIds3; + uint64_t transaction2Id = transaction2.getId(); + uint64_t transaction3Id = transaction3.getId(); + + for (uint i = 0; i < 20u; i++) { + SurfaceComposerClient::Transaction transactionToMerge; + mergedTransactionIds1.push_back(transactionToMerge.getId()); + transaction1.merge(std::move(transactionToMerge)); + } + + for (uint i = 0; i < 5u; i++) { + SurfaceComposerClient::Transaction transactionToMerge; + mergedTransactionIds2.push_back(transactionToMerge.getId()); + transaction2.merge(std::move(transactionToMerge)); + } + + transaction1.merge(std::move(transaction2)); + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 10u); + EXPECT_EQ(transaction1.getMergedTransactionIds()[0], transaction2Id); + for (uint i = 0; i < 5u; i++) { + EXPECT_EQ(transaction1.getMergedTransactionIds()[i + 1u], + mergedTransactionIds2[mergedTransactionIds2.size() - 1 - i]); + } + for (uint i = 0; i < 4u; i++) { + EXPECT_EQ(transaction1.getMergedTransactionIds()[i + 6u], + mergedTransactionIds1[mergedTransactionIds1.size() - 1 - i]); + } + + for (uint i = 0; i < 20u; i++) { + SurfaceComposerClient::Transaction transactionToMerge; + mergedTransactionIds3.push_back(transactionToMerge.getId()); + transaction3.merge(std::move(transactionToMerge)); + } + + transaction1.merge(std::move(transaction3)); + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 10u); + EXPECT_EQ(transaction1.getMergedTransactionIds()[0], transaction3Id); + for (uint i = 0; i < 9u; i++) { + EXPECT_EQ(transaction1.getMergedTransactionIds()[i + 1], + mergedTransactionIds3[mergedTransactionIds3.size() - 1 - i]); + } +} + +TEST(TransactionHandlerTest, CanAddTransactionWithFullMergedIds) { + SurfaceComposerClient::Transaction transaction1, transaction2; + for (uint i = 0; i < 20u; i++) { + SurfaceComposerClient::Transaction transactionToMerge; + transaction1.merge(std::move(transactionToMerge)); + } + + EXPECT_EQ(transaction1.getMergedTransactionIds().size(), 10u); + + auto transaction1Id = transaction1.getId(); + transaction2.merge(std::move(transaction1)); + EXPECT_EQ(transaction2.getMergedTransactionIds().size(), 10u); + auto mergedTransactionIds = transaction2.getMergedTransactionIds(); + EXPECT_TRUE(std::count(mergedTransactionIds.begin(), mergedTransactionIds.end(), + transaction1Id) > 0); +} + } // namespace android diff --git a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp index 82aac7e4bf..92411a7ba9 100644 --- a/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp +++ b/services/surfaceflinger/tests/unittests/TransactionTracingTest.cpp @@ -67,8 +67,14 @@ protected: ASSERT_EQ(actualProto.transactions().size(), static_cast(expectedTransactions.size())); for (uint32_t i = 0; i < expectedTransactions.size(); i++) { - EXPECT_EQ(actualProto.transactions(static_cast(i)).pid(), - expectedTransactions[i].originPid); + const auto expectedTransaction = expectedTransactions[i]; + const auto protoTransaction = actualProto.transactions(static_cast(i)); + EXPECT_EQ(protoTransaction.transaction_id(), expectedTransaction.id); + EXPECT_EQ(protoTransaction.pid(), expectedTransaction.originPid); + for (uint32_t i = 0; i < expectedTransaction.mergedTransactionIds.size(); i++) { + EXPECT_EQ(protoTransaction.merged_transaction_ids(static_cast(i)), + expectedTransaction.mergedTransactionIds[i]); + } } } @@ -92,6 +98,7 @@ TEST_F(TransactionTracingTest, addTransactions) { TransactionState transaction; transaction.id = i; transaction.originPid = static_cast(i); + transaction.mergedTransactionIds = std::vector{i + 100, i + 102}; transactions.emplace_back(transaction); mTracing.addQueuedTransaction(transaction); } -- cgit v1.2.3-59-g8ed1b