[SF] Introduce VirtualDisplayId

This change introduces a new class VirtualDisplayId which is
inherited by HwcVirtualDisplayId and GpuVirtualDisplayId.
HwcVirtualDisplayId replaces the current ids assigned to
virtual displays backed by HWC. GpuVirtualDisplayIds are random
generated IDs assigned to non HWC virtual displays, which currently
don't have IDs. This way all compositionengine/Display and
DisplayDevice objects have a DisplayId.

The logic for ID generation is encapsulated in DisplayIdGenerator.h.

Bug: 162916145
Bug: 160679868
Bug: 137375833
Test: scrcpy on device
Test: atest DisplayIdGeneratorTest
Test: atest libsurfaceflinger_unittest
Change-Id: I550b1f4714fcad0c3328d0cad93fc601ea7593c2
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
index a38d1f3..01dd534 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/Display.h
@@ -34,8 +34,8 @@
  */
 class Display : public virtual Output {
 public:
-    // Gets the HWC DisplayId for the display if there is one
-    virtual const std::optional<DisplayId>& getId() const = 0;
+    // Gets the DisplayId for the display
+    virtual DisplayId getId() const = 0;
 
     // True if the display is secure
     virtual bool isSecure() const = 0;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h
index 6bc677d..95ba9f0 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h
@@ -20,12 +20,14 @@
 #include <optional>
 #include <string>
 
+#include <ui/DisplayId.h>
 #include <ui/DisplayInfo.h>
 #include <ui/PixelFormat.h>
 #include <ui/Size.h>
 
 #include "DisplayHardware/DisplayIdentification.h"
 #include "DisplayHardware/PowerAdvisor.h"
+#include "DisplayIdGenerator.h"
 
 namespace android::compositionengine {
 
@@ -65,6 +67,9 @@
 
     // Debugging. Human readable name for the display.
     std::string name;
+
+    // Generator for IDs of virtual displays, which are backed by the GPU.
+    DisplayIdGenerator<GpuVirtualDisplayId>* gpuVirtualDisplayIdGenerator;
 };
 
 /**
@@ -95,6 +100,12 @@
         return *this;
     }
 
+    DisplayCreationArgsBuilder& setGpuVirtualDisplayIdGenerator(
+            DisplayIdGenerator<GpuVirtualDisplayId>& generator) {
+        mArgs.gpuVirtualDisplayIdGenerator = &generator;
+        return *this;
+    }
+
     DisplayCreationArgsBuilder& setIsSecure(bool isSecure) {
         mArgs.isSecure = isSecure;
         return *this;
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
index 7a4f738..54e91ae 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/Display.h
@@ -57,7 +57,7 @@
     void finishFrame(const CompositionRefreshArgs&) override;
 
     // compositionengine::Display overrides
-    const std::optional<DisplayId>& getId() const override;
+    DisplayId getId() const override;
     bool isSecure() const override;
     bool isVirtual() const override;
     void disconnect() override;
@@ -85,12 +85,14 @@
     std::unique_ptr<compositionengine::OutputLayer> createOutputLayer(const sp<LayerFE>&) const;
 
     // Testing
-    void setDisplayIdForTesting(std::optional<DisplayId> displayId);
+    void setDisplayIdForTesting(DisplayId displayId);
 
 private:
     bool mIsVirtual = false;
-    std::optional<DisplayId> mId;
+    bool mIsDisconnected = false;
+    DisplayId mId;
     Hwc2::PowerAdvisor* mPowerAdvisor = nullptr;
+    DisplayIdGenerator<GpuVirtualDisplayId>* mGpuVirtualDisplayIdGenerator;
 };
 
 // This template factory function standardizes the implementation details of the
diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
index 3a4c70f..08a8b84 100644
--- a/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
+++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/mock/Display.h
@@ -32,7 +32,7 @@
     Display();
     virtual ~Display();
 
-    MOCK_CONST_METHOD0(getId, const std::optional<DisplayId>&());
+    MOCK_CONST_METHOD0(getId, DisplayId());
     MOCK_CONST_METHOD0(isSecure, bool());
     MOCK_CONST_METHOD0(isVirtual, bool());
 
diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp
index 5459861..0b0b8d5 100644
--- a/services/surfaceflinger/CompositionEngine/src/Display.cpp
+++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp
@@ -51,19 +51,26 @@
 
 void Display::setConfiguration(const compositionengine::DisplayCreationArgs& args) {
     mIsVirtual = !args.physical;
-    mId = args.physical ? std::make_optional(args.physical->id) : std::nullopt;
     mPowerAdvisor = args.powerAdvisor;
-
     editState().isSecure = args.isSecure;
     editState().displaySpace.bounds = Rect(args.pixels);
-
     setLayerStackFilter(args.layerStackId,
-                        args.physical ? args.physical->type == DisplayConnectionType::Internal
-                                      : false);
+                        args.physical && args.physical->type == DisplayConnectionType::Internal);
     setName(args.name);
+    mGpuVirtualDisplayIdGenerator = args.gpuVirtualDisplayIdGenerator;
 
-    if (!args.physical && args.useHwcVirtualDisplays) {
-        mId = maybeAllocateDisplayIdForVirtualDisplay(args.pixels, args.pixelFormat);
+    if (args.physical) {
+        mId = args.physical->id;
+    } else {
+        std::optional<DisplayId> id;
+        if (args.useHwcVirtualDisplays) {
+            id = maybeAllocateDisplayIdForVirtualDisplay(args.pixels, args.pixelFormat);
+        }
+        if (!id) {
+            id = mGpuVirtualDisplayIdGenerator->nextId();
+        }
+        LOG_ALWAYS_FATAL_IF(!id, "Failed to generate display ID");
+        mId = *id;
     }
 }
 
@@ -78,7 +85,7 @@
     return Output::isValid() && mPowerAdvisor;
 }
 
-const std::optional<DisplayId>& Display::getId() const {
+DisplayId Display::getId() const {
     return mId;
 }
 
@@ -94,31 +101,36 @@
     return mId;
 }
 
-void Display::setDisplayIdForTesting(std::optional<DisplayId> displayId) {
+void Display::setDisplayIdForTesting(DisplayId displayId) {
     mId = displayId;
 }
 
 void Display::disconnect() {
-    if (!mId) {
+    if (mIsDisconnected) {
         return;
     }
 
-    auto& hwc = getCompositionEngine().getHwComposer();
-    hwc.disconnectDisplay(*mId);
-    mId.reset();
+    mIsDisconnected = true;
+    if (const auto id = GpuVirtualDisplayId::tryCast(mId)) {
+        mGpuVirtualDisplayIdGenerator->markUnused(*id);
+        return;
+    }
+    const auto halDisplayId = HalDisplayId::tryCast(mId);
+    LOG_FATAL_IF(!halDisplayId);
+    getCompositionEngine().getHwComposer().disconnectDisplay(*halDisplayId);
 }
 
 void Display::setColorTransform(const compositionengine::CompositionRefreshArgs& args) {
     Output::setColorTransform(args);
-
-    if (!mId || CC_LIKELY(!args.colorTransformMatrix)) {
+    const auto halDisplayId = HalDisplayId::tryCast(mId);
+    if (mIsDisconnected || !halDisplayId || CC_LIKELY(!args.colorTransformMatrix)) {
         return;
     }
 
     auto& hwc = getCompositionEngine().getHwComposer();
-    status_t result = hwc.setColorTransform(*mId, *args.colorTransformMatrix);
+    status_t result = hwc.setColorTransform(*halDisplayId, *args.colorTransformMatrix);
     ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display \"%s\": %d",
-             mId ? to_string(*mId).c_str() : "", result);
+             to_string(mId).c_str(), result);
 }
 
 void Display::setColorProfile(const ColorProfile& colorProfile) {
@@ -140,8 +152,10 @@
 
     Output::setColorProfile(colorProfile);
 
-    auto& hwc = getCompositionEngine().getHwComposer();
-    hwc.setActiveColorMode(*mId, colorProfile.mode, colorProfile.renderIntent);
+    const auto physicalId = PhysicalDisplayId::tryCast(mId);
+    LOG_FATAL_IF(!physicalId);
+    getCompositionEngine().getHwComposer().setActiveColorMode(*physicalId, colorProfile.mode,
+                                                              colorProfile.renderIntent);
 }
 
 void Display::dump(std::string& out) const {
@@ -150,14 +164,8 @@
     StringAppendF(&out, "   Composition Display State: [\"%s\"]", getName().c_str());
 
     out.append("\n   ");
-
     dumpVal(out, "isVirtual", mIsVirtual);
-    if (mId) {
-        dumpVal(out, "hwcId", to_string(*mId));
-    } else {
-        StringAppendF(&out, "no hwcId, ");
-    }
-
+    dumpVal(out, "DisplayId", to_string(mId));
     out.append("\n");
 
     Output::dumpBase(out);
@@ -178,31 +186,33 @@
 
 std::unique_ptr<compositionengine::OutputLayer> Display::createOutputLayer(
         const sp<compositionengine::LayerFE>& layerFE) const {
-    auto result = impl::createOutputLayer(*this, layerFE);
+    auto outputLayer = impl::createOutputLayer(*this, layerFE);
 
-    if (result && mId) {
+    if (const auto halDisplayId = HalDisplayId::tryCast(mId);
+        outputLayer && !mIsDisconnected && halDisplayId) {
         auto& hwc = getCompositionEngine().getHwComposer();
-        auto displayId = *mId;
         // Note: For the moment we ensure it is safe to take a reference to the
         // HWComposer implementation by destroying all the OutputLayers (and
         // hence the HWC2::Layers they own) before setting a new HWComposer. See
         // for example SurfaceFlinger::updateVrFlinger().
         // TODO(b/121291683): Make this safer.
-        auto hwcLayer = std::shared_ptr<HWC2::Layer>(hwc.createLayer(displayId),
-                                                     [&hwc, displayId](HWC2::Layer* layer) {
-                                                         hwc.destroyLayer(displayId, layer);
-                                                     });
+        auto hwcLayer =
+                std::shared_ptr<HWC2::Layer>(hwc.createLayer(*halDisplayId),
+                                             [&hwc, id = *halDisplayId](HWC2::Layer* layer) {
+                                                 hwc.destroyLayer(id, layer);
+                                             });
         ALOGE_IF(!hwcLayer, "Failed to create a HWC layer for a HWC supported display %s",
                  getName().c_str());
-        result->setHwcLayer(std::move(hwcLayer));
+        outputLayer->setHwcLayer(std::move(hwcLayer));
     }
-    return result;
+    return outputLayer;
 }
 
 void Display::setReleasedLayers(const compositionengine::CompositionRefreshArgs& refreshArgs) {
     Output::setReleasedLayers(refreshArgs);
 
-    if (!mId || refreshArgs.layersWithQueuedFrames.empty()) {
+    if (mIsDisconnected || GpuVirtualDisplayId::tryCast(mId) ||
+        refreshArgs.layersWithQueuedFrames.empty()) {
         return;
     }
 
@@ -238,19 +248,25 @@
     ATRACE_CALL();
     ALOGV(__FUNCTION__);
 
+    if (mIsDisconnected) {
+        return;
+    }
+
     // Default to the base settings -- client composition only.
     Output::chooseCompositionStrategy();
 
-    // If we don't have a HWC display, then we are done
-    if (!mId) {
+    // If we don't have a HWC display, then we are done.
+    const auto halDisplayId = HalDisplayId::tryCast(mId);
+    if (!halDisplayId) {
         return;
     }
 
     // Get any composition changes requested by the HWC device, and apply them.
     std::optional<android::HWComposer::DeviceRequestedChanges> changes;
     auto& hwc = getCompositionEngine().getHwComposer();
-    if (status_t result = hwc.getDeviceCompositionChanges(*mId, anyLayersRequireClientComposition(),
-                                                          &changes);
+    if (status_t result =
+                hwc.getDeviceCompositionChanges(*halDisplayId, anyLayersRequireClientComposition(),
+                                                &changes);
         result != NO_ERROR) {
         ALOGE("chooseCompositionStrategy failed for %s: %d (%s)", getName().c_str(), result,
               strerror(-result));
@@ -271,8 +287,12 @@
 
 bool Display::getSkipColorTransform() const {
     const auto& hwc = getCompositionEngine().getHwComposer();
-    return mId ? hwc.hasDisplayCapability(*mId, hal::DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM)
-               : hwc.hasCapability(hal::Capability::SKIP_CLIENT_COLOR_TRANSFORM);
+    if (const auto halDisplayId = HalDisplayId::tryCast(mId)) {
+        return hwc.hasDisplayCapability(*halDisplayId,
+                                        hal::DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM);
+    }
+
+    return hwc.hasCapability(hal::Capability::SKIP_CLIENT_COLOR_TRANSFORM);
 }
 
 bool Display::anyLayersRequireClientComposition() const {
@@ -339,16 +359,17 @@
 }
 
 compositionengine::Output::FrameFences Display::presentAndGetFrameFences() {
-    auto result = impl::Output::presentAndGetFrameFences();
+    auto fences = impl::Output::presentAndGetFrameFences();
 
-    if (!mId) {
-        return result;
+    const auto halDisplayIdOpt = HalDisplayId::tryCast(mId);
+    if (mIsDisconnected || !halDisplayIdOpt) {
+        return fences;
     }
 
     auto& hwc = getCompositionEngine().getHwComposer();
-    hwc.presentAndGetReleaseFences(*mId);
+    hwc.presentAndGetReleaseFences(*halDisplayIdOpt);
 
-    result.presentFence = hwc.getPresentFence(*mId);
+    fences.presentFence = hwc.getPresentFence(*halDisplayIdOpt);
 
     // TODO(b/121291683): Change HWComposer call to return entire map
     for (const auto* layer : getOutputLayersOrderedByZ()) {
@@ -357,19 +378,19 @@
             continue;
         }
 
-        result.layerFences.emplace(hwcLayer, hwc.getLayerReleaseFence(*mId, hwcLayer));
+        fences.layerFences.emplace(hwcLayer, hwc.getLayerReleaseFence(*halDisplayIdOpt, hwcLayer));
     }
 
-    hwc.clearReleaseFences(*mId);
+    hwc.clearReleaseFences(*halDisplayIdOpt);
 
-    return result;
+    return fences;
 }
 
 void Display::setExpensiveRenderingExpected(bool enabled) {
     Output::setExpensiveRenderingExpected(enabled);
 
-    if (mPowerAdvisor && mId) {
-        mPowerAdvisor->setExpensiveRenderingExpected(*mId, enabled);
+    if (mPowerAdvisor && !GpuVirtualDisplayId::tryCast(mId)) {
+        mPowerAdvisor->setExpensiveRenderingExpected(mId, enabled);
     }
 }
 
@@ -378,11 +399,10 @@
     // 1) It is being handled by hardware composer, which may need this to
     //    keep its virtual display state machine in sync, or
     // 2) There is work to be done (the dirty region isn't empty)
-    if (!mId) {
-        if (getDirtyRegion(refreshArgs.repaintEverything).isEmpty()) {
-            ALOGV("Skipping display composition");
-            return;
-        }
+    if (GpuVirtualDisplayId::tryCast(mId) &&
+        getDirtyRegion(refreshArgs.repaintEverything).isEmpty()) {
+        ALOGV("Skipping display composition");
+        return;
     }
 
     impl::Output::finishFrame(refreshArgs);
diff --git a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
index 4519a9d..6d01bf1 100644
--- a/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/DisplayTest.cpp
@@ -176,6 +176,7 @@
     DisplayCreationArgs getDisplayCreationArgsForNonHWCVirtualDisplay() {
         return DisplayCreationArgsBuilder()
                 .setUseHwcVirtualDisplays(false)
+                .setGpuVirtualDisplayIdGenerator(mGpuDisplayIdGenerator)
                 .setPixels({DEFAULT_DISPLAY_WIDTH, DEFAULT_DISPLAY_HEIGHT})
                 .setPixelFormat(static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888))
                 .setIsSecure(false)
@@ -189,6 +190,7 @@
     StrictMock<renderengine::mock::RenderEngine> mRenderEngine;
     StrictMock<mock::CompositionEngine> mCompositionEngine;
     sp<mock::NativeWindow> mNativeWindow = new StrictMock<mock::NativeWindow>();
+    RandomDisplayIdGenerator<GpuVirtualDisplayId> mGpuDisplayIdGenerator;
 };
 
 struct PartialMockDisplayTestCommon : public DisplayTestCommon {
@@ -245,7 +247,7 @@
                                        getDisplayCreationArgsForNonHWCVirtualDisplay());
     EXPECT_FALSE(display->isSecure());
     EXPECT_TRUE(display->isVirtual());
-    EXPECT_EQ(std::nullopt, display->getId());
+    EXPECT_TRUE(GpuVirtualDisplayId::tryCast(display->getId()));
 }
 
 /*
@@ -332,6 +334,7 @@
     mDisplay->setConfiguration(
             DisplayCreationArgsBuilder()
                     .setUseHwcVirtualDisplays(true)
+                    .setGpuVirtualDisplayIdGenerator(mGpuDisplayIdGenerator)
                     .setPixels(ui::Size(DEFAULT_DISPLAY_WIDTH, DEFAULT_DISPLAY_WIDTH))
                     .setPixelFormat(static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888))
                     .setIsSecure(false)
@@ -340,7 +343,7 @@
                     .setName(getDisplayNameFromCurrentTest())
                     .build());
 
-    EXPECT_EQ(std::nullopt, mDisplay->getId());
+    EXPECT_TRUE(GpuVirtualDisplayId::tryCast(mDisplay->getId()));
     EXPECT_FALSE(mDisplay->isSecure());
     EXPECT_TRUE(mDisplay->isVirtual());
     EXPECT_EQ(DEFAULT_LAYER_STACK, mDisplay->getState().layerStackId);
@@ -352,6 +355,7 @@
     mDisplay->setConfiguration(
             DisplayCreationArgsBuilder()
                     .setUseHwcVirtualDisplays(false)
+                    .setGpuVirtualDisplayIdGenerator(mGpuDisplayIdGenerator)
                     .setPixels(ui::Size(DEFAULT_DISPLAY_WIDTH, DEFAULT_DISPLAY_WIDTH))
                     .setPixelFormat(static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888))
                     .setIsSecure(false)
@@ -360,7 +364,7 @@
                     .setName(getDisplayNameFromCurrentTest())
                     .build());
 
-    EXPECT_EQ(std::nullopt, mDisplay->getId());
+    EXPECT_TRUE(GpuVirtualDisplayId::tryCast(mDisplay->getId()));
     EXPECT_FALSE(mDisplay->isSecure());
     EXPECT_TRUE(mDisplay->isVirtual());
     EXPECT_EQ(DEFAULT_LAYER_STACK, mDisplay->getState().layerStackId);
@@ -375,16 +379,13 @@
 using DisplayDisconnectTest = PartialMockDisplayTestCommon;
 
 TEST_F(DisplayDisconnectTest, disconnectsDisplay) {
-    // The first call to disconnect will disconnect the display with the HWC and
-    // set mHwcId to -1.
-    EXPECT_CALL(mHwComposer, disconnectDisplay(DEFAULT_DISPLAY_ID)).Times(1);
+    // The first call to disconnect will disconnect the display with the HWC.
+    EXPECT_CALL(mHwComposer, disconnectDisplay(HalDisplayId(DEFAULT_DISPLAY_ID))).Times(1);
     mDisplay->disconnect();
-    EXPECT_FALSE(mDisplay->getId());
 
     // Subsequent calls will do nothing,
-    EXPECT_CALL(mHwComposer, disconnectDisplay(DEFAULT_DISPLAY_ID)).Times(0);
+    EXPECT_CALL(mHwComposer, disconnectDisplay(HalDisplayId(DEFAULT_DISPLAY_ID))).Times(0);
     mDisplay->disconnect();
-    EXPECT_FALSE(mDisplay->getId());
 }
 
 /*
@@ -402,7 +403,8 @@
     // Identity matrix sets an identity state value
     const mat4 kIdentity;
 
-    EXPECT_CALL(mHwComposer, setColorTransform(DEFAULT_DISPLAY_ID, kIdentity)).Times(1);
+    EXPECT_CALL(mHwComposer, setColorTransform(HalDisplayId(DEFAULT_DISPLAY_ID), kIdentity))
+            .Times(1);
 
     refreshArgs.colorTransformMatrix = kIdentity;
     mDisplay->setColorTransform(refreshArgs);
@@ -410,7 +412,8 @@
     // Non-identity matrix sets a non-identity state value
     const mat4 kNonIdentity = mat4() * 2;
 
-    EXPECT_CALL(mHwComposer, setColorTransform(DEFAULT_DISPLAY_ID, kNonIdentity)).Times(1);
+    EXPECT_CALL(mHwComposer, setColorTransform(HalDisplayId(DEFAULT_DISPLAY_ID), kNonIdentity))
+            .Times(1);
 
     refreshArgs.colorTransformMatrix = kNonIdentity;
     mDisplay->setColorTransform(refreshArgs);
@@ -527,13 +530,14 @@
     sp<mock::LayerFE> layerFE = new StrictMock<mock::LayerFE>();
     StrictMock<HWC2::mock::Layer> hwcLayer;
 
-    EXPECT_CALL(mHwComposer, createLayer(DEFAULT_DISPLAY_ID)).WillOnce(Return(&hwcLayer));
+    EXPECT_CALL(mHwComposer, createLayer(HalDisplayId(DEFAULT_DISPLAY_ID)))
+            .WillOnce(Return(&hwcLayer));
 
     auto outputLayer = mDisplay->createOutputLayer(layerFE);
 
     EXPECT_EQ(&hwcLayer, outputLayer->getHwcLayer());
 
-    EXPECT_CALL(mHwComposer, destroyLayer(DEFAULT_DISPLAY_ID, &hwcLayer));
+    EXPECT_CALL(mHwComposer, destroyLayer(HalDisplayId(DEFAULT_DISPLAY_ID), &hwcLayer));
     outputLayer.reset();
 }
 
@@ -606,7 +610,7 @@
     auto args = getDisplayCreationArgsForNonHWCVirtualDisplay();
     std::shared_ptr<Display> nonHwcDisplay =
             createPartialMockDisplay<Display>(mCompositionEngine, args);
-    EXPECT_FALSE(nonHwcDisplay->getId());
+    EXPECT_TRUE(GpuVirtualDisplayId::tryCast(nonHwcDisplay->getId()));
 
     nonHwcDisplay->chooseCompositionStrategy();
 
@@ -617,7 +621,8 @@
 
 TEST_F(DisplayChooseCompositionStrategyTest, takesEarlyOutOnHwcError) {
     EXPECT_CALL(*mDisplay, anyLayersRequireClientComposition()).WillOnce(Return(false));
-    EXPECT_CALL(mHwComposer, getDeviceCompositionChanges(DEFAULT_DISPLAY_ID, false, _))
+    EXPECT_CALL(mHwComposer,
+                getDeviceCompositionChanges(HalDisplayId(DEFAULT_DISPLAY_ID), false, _))
             .WillOnce(Return(INVALID_OPERATION));
 
     mDisplay->chooseCompositionStrategy();
@@ -639,7 +644,7 @@
             .InSequence(s)
             .WillOnce(Return(false));
 
-    EXPECT_CALL(mHwComposer, getDeviceCompositionChanges(DEFAULT_DISPLAY_ID, true, _))
+    EXPECT_CALL(mHwComposer, getDeviceCompositionChanges(HalDisplayId(DEFAULT_DISPLAY_ID), true, _))
             .WillOnce(Return(NO_ERROR));
     EXPECT_CALL(*mDisplay, allLayersRequireClientComposition()).WillOnce(Return(false));
 
@@ -669,7 +674,7 @@
             .InSequence(s)
             .WillOnce(Return(false));
 
-    EXPECT_CALL(mHwComposer, getDeviceCompositionChanges(DEFAULT_DISPLAY_ID, true, _))
+    EXPECT_CALL(mHwComposer, getDeviceCompositionChanges(HalDisplayId(DEFAULT_DISPLAY_ID), true, _))
             .WillOnce(DoAll(SetArgPointee<2>(changes), Return(NO_ERROR)));
     EXPECT_CALL(*mDisplay, applyChangedTypesToLayers(changes.changedTypes)).Times(1);
     EXPECT_CALL(*mDisplay, applyDisplayRequests(changes.displayRequests)).Times(1);
@@ -699,7 +704,7 @@
 
 TEST_F(DisplayGetSkipColorTransformTest, checksDisplayCapability) {
     EXPECT_CALL(mHwComposer,
-                hasDisplayCapability(DEFAULT_DISPLAY_ID,
+                hasDisplayCapability(HalDisplayId(DEFAULT_DISPLAY_ID),
                                      hal::DisplayCapability::SKIP_CLIENT_COLOR_TRANSFORM))
             .WillOnce(Return(true));
     EXPECT_TRUE(mDisplay->getSkipColorTransform());
@@ -857,13 +862,16 @@
     sp<Fence> layer1Fence = new Fence();
     sp<Fence> layer2Fence = new Fence();
 
-    EXPECT_CALL(mHwComposer, presentAndGetReleaseFences(DEFAULT_DISPLAY_ID)).Times(1);
-    EXPECT_CALL(mHwComposer, getPresentFence(DEFAULT_DISPLAY_ID)).WillOnce(Return(presentFence));
-    EXPECT_CALL(mHwComposer, getLayerReleaseFence(DEFAULT_DISPLAY_ID, &mLayer1.hwc2Layer))
+    EXPECT_CALL(mHwComposer, presentAndGetReleaseFences(HalDisplayId(DEFAULT_DISPLAY_ID))).Times(1);
+    EXPECT_CALL(mHwComposer, getPresentFence(HalDisplayId(DEFAULT_DISPLAY_ID)))
+            .WillOnce(Return(presentFence));
+    EXPECT_CALL(mHwComposer,
+                getLayerReleaseFence(HalDisplayId(DEFAULT_DISPLAY_ID), &mLayer1.hwc2Layer))
             .WillOnce(Return(layer1Fence));
-    EXPECT_CALL(mHwComposer, getLayerReleaseFence(DEFAULT_DISPLAY_ID, &mLayer2.hwc2Layer))
+    EXPECT_CALL(mHwComposer,
+                getLayerReleaseFence(HalDisplayId(DEFAULT_DISPLAY_ID), &mLayer2.hwc2Layer))
             .WillOnce(Return(layer2Fence));
-    EXPECT_CALL(mHwComposer, clearReleaseFences(DEFAULT_DISPLAY_ID)).Times(1);
+    EXPECT_CALL(mHwComposer, clearReleaseFences(HalDisplayId(DEFAULT_DISPLAY_ID))).Times(1);
 
     auto result = mDisplay->presentAndGetFrameFences();
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
index 1dd5df4..b5cda68 100644
--- a/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
+++ b/services/surfaceflinger/CompositionEngine/tests/MockHWComposer.h
@@ -42,63 +42,68 @@
     MOCK_CONST_METHOD3(getDisplayIdentificationData,
                        bool(hal::HWDisplayId, uint8_t*, DisplayIdentificationData*));
     MOCK_CONST_METHOD1(hasCapability, bool(hal::Capability));
-    MOCK_CONST_METHOD2(hasDisplayCapability, bool(DisplayId, hal::DisplayCapability));
+    MOCK_CONST_METHOD2(hasDisplayCapability, bool(HalDisplayId, hal::DisplayCapability));
 
     MOCK_METHOD3(allocateVirtualDisplay,
                  std::optional<DisplayId>(uint32_t, uint32_t, ui::PixelFormat*));
     MOCK_METHOD2(allocatePhysicalDisplay, void(hal::HWDisplayId, PhysicalDisplayId));
-    MOCK_METHOD1(createLayer, HWC2::Layer*(DisplayId));
-    MOCK_METHOD2(destroyLayer, void(DisplayId, HWC2::Layer*));
+    MOCK_METHOD1(createLayer, HWC2::Layer*(HalDisplayId));
+    MOCK_METHOD2(destroyLayer, void(HalDisplayId, HWC2::Layer*));
     MOCK_METHOD3(getDeviceCompositionChanges,
-                 status_t(DisplayId, bool,
+                 status_t(HalDisplayId, bool,
                           std::optional<android::HWComposer::DeviceRequestedChanges>*));
     MOCK_METHOD5(setClientTarget,
-                 status_t(DisplayId, uint32_t, const sp<Fence>&, const sp<GraphicBuffer>&,
+                 status_t(HalDisplayId, uint32_t, const sp<Fence>&, const sp<GraphicBuffer>&,
                           ui::Dataspace));
-    MOCK_METHOD1(presentAndGetReleaseFences, status_t(DisplayId));
-    MOCK_METHOD2(setPowerMode, status_t(DisplayId, hal::PowerMode));
-    MOCK_METHOD2(setActiveConfig, status_t(DisplayId, size_t));
-    MOCK_METHOD2(setColorTransform, status_t(DisplayId, const mat4&));
-    MOCK_METHOD1(disconnectDisplay, void(DisplayId));
+    MOCK_METHOD1(presentAndGetReleaseFences, status_t(HalDisplayId));
+    MOCK_METHOD2(setPowerMode, status_t(PhysicalDisplayId, hal::PowerMode));
+    MOCK_METHOD2(setActiveConfig, status_t(HalDisplayId, size_t));
+    MOCK_METHOD2(setColorTransform, status_t(HalDisplayId, const mat4&));
+    MOCK_METHOD1(disconnectDisplay, void(HalDisplayId));
     MOCK_CONST_METHOD1(hasDeviceComposition, bool(const std::optional<DisplayId>&));
-    MOCK_CONST_METHOD1(getPresentFence, sp<Fence>(DisplayId));
-    MOCK_CONST_METHOD2(getLayerReleaseFence, sp<Fence>(DisplayId, HWC2::Layer*));
-    MOCK_METHOD3(setOutputBuffer, status_t(DisplayId, const sp<Fence>&, const sp<GraphicBuffer>&));
-    MOCK_METHOD1(clearReleaseFences, void(DisplayId));
-    MOCK_METHOD2(getHdrCapabilities, status_t(DisplayId, HdrCapabilities*));
-    MOCK_CONST_METHOD1(getSupportedPerFrameMetadata, int32_t(DisplayId));
-    MOCK_CONST_METHOD2(getRenderIntents, std::vector<ui::RenderIntent>(DisplayId, ui::ColorMode));
-    MOCK_METHOD2(getDataspaceSaturationMatrix, mat4(DisplayId, ui::Dataspace));
+    MOCK_CONST_METHOD1(getPresentFence, sp<Fence>(HalDisplayId));
+    MOCK_CONST_METHOD2(getLayerReleaseFence, sp<Fence>(HalDisplayId, HWC2::Layer*));
+    MOCK_METHOD3(setOutputBuffer,
+                 status_t(HalVirtualDisplayId, const sp<Fence>&, const sp<GraphicBuffer>&));
+    MOCK_METHOD1(clearReleaseFences, void(HalDisplayId));
+    MOCK_METHOD2(getHdrCapabilities, status_t(HalDisplayId, HdrCapabilities*));
+    MOCK_CONST_METHOD1(getSupportedPerFrameMetadata, int32_t(HalDisplayId));
+    MOCK_CONST_METHOD2(getRenderIntents,
+                       std::vector<ui::RenderIntent>(HalDisplayId, ui::ColorMode));
+    MOCK_METHOD2(getDataspaceSaturationMatrix, mat4(HalDisplayId, ui::Dataspace));
     MOCK_METHOD4(getDisplayedContentSamplingAttributes,
-                 status_t(DisplayId, ui::PixelFormat*, ui::Dataspace*, uint8_t*));
-    MOCK_METHOD4(setDisplayContentSamplingEnabled, status_t(DisplayId, bool, uint8_t, uint64_t));
+                 status_t(HalDisplayId, ui::PixelFormat*, ui::Dataspace*, uint8_t*));
+    MOCK_METHOD4(setDisplayContentSamplingEnabled, status_t(HalDisplayId, bool, uint8_t, uint64_t));
     MOCK_METHOD4(getDisplayedContentSample,
-                 status_t(DisplayId, uint64_t, uint64_t, DisplayedFrameStats*));
-    MOCK_METHOD2(setDisplayBrightness, std::future<status_t>(DisplayId, float));
-    MOCK_METHOD2(getDisplayBrightnessSupport, status_t(DisplayId, bool*));
+                 status_t(HalDisplayId, uint64_t, uint64_t, DisplayedFrameStats*));
+    MOCK_METHOD2(setDisplayBrightness, std::future<status_t>(PhysicalDisplayId, float));
+    MOCK_METHOD2(getDisplayBrightnessSupport, status_t(PhysicalDisplayId, bool*));
 
     MOCK_METHOD2(onHotplug,
                  std::optional<DisplayIdentificationInfo>(hal::HWDisplayId, hal::Connection));
     MOCK_METHOD2(onVsync, bool(hal::HWDisplayId, int64_t));
-    MOCK_METHOD2(setVsyncEnabled, void(DisplayId, hal::Vsync));
-    MOCK_CONST_METHOD1(getRefreshTimestamp, nsecs_t(DisplayId));
-    MOCK_CONST_METHOD1(isConnected, bool(DisplayId));
-    MOCK_CONST_METHOD1(getConfigs,
-                       std::vector<std::shared_ptr<const HWC2::Display::Config>>(DisplayId));
-    MOCK_CONST_METHOD1(getActiveConfig, std::shared_ptr<const HWC2::Display::Config>(DisplayId));
-    MOCK_CONST_METHOD1(getActiveConfigIndex, int(DisplayId));
-    MOCK_CONST_METHOD1(getColorModes, std::vector<ui::ColorMode>(DisplayId));
-    MOCK_METHOD3(setActiveColorMode, status_t(DisplayId, ui::ColorMode, ui::RenderIntent));
+    MOCK_METHOD2(setVsyncEnabled, void(PhysicalDisplayId, hal::Vsync));
+    MOCK_CONST_METHOD1(getRefreshTimestamp, nsecs_t(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(isConnected, bool(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(
+            getConfigs,
+            std::vector<std::shared_ptr<const HWC2::Display::Config>>(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getActiveConfig,
+                       std::shared_ptr<const HWC2::Display::Config>(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getActiveConfigIndex, int(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getColorModes, std::vector<ui::ColorMode>(PhysicalDisplayId));
+    MOCK_METHOD3(setActiveColorMode, status_t(PhysicalDisplayId, ui::ColorMode, ui::RenderIntent));
     MOCK_CONST_METHOD0(isUsingVrComposer, bool());
-    MOCK_CONST_METHOD1(getDisplayConnectionType, DisplayConnectionType(DisplayId));
-    MOCK_CONST_METHOD1(isVsyncPeriodSwitchSupported, bool(DisplayId));
-    MOCK_CONST_METHOD1(getDisplayVsyncPeriod, nsecs_t(DisplayId));
+    MOCK_CONST_METHOD1(getDisplayConnectionType, DisplayConnectionType(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(isVsyncPeriodSwitchSupported, bool(PhysicalDisplayId));
+    MOCK_CONST_METHOD1(getDisplayVsyncPeriod, nsecs_t(PhysicalDisplayId));
     MOCK_METHOD4(setActiveConfigWithConstraints,
-                 status_t(DisplayId, size_t, const hal::VsyncPeriodChangeConstraints&,
+                 status_t(PhysicalDisplayId, size_t, const hal::VsyncPeriodChangeConstraints&,
                           hal::VsyncPeriodChangeTimeline*));
-    MOCK_METHOD2(setAutoLowLatencyMode, status_t(DisplayId, bool));
-    MOCK_METHOD2(getSupportedContentTypes, status_t(DisplayId, std::vector<hal::ContentType>*));
-    MOCK_METHOD2(setContentType, status_t(DisplayId, hal::ContentType));
+    MOCK_METHOD2(setAutoLowLatencyMode, status_t(PhysicalDisplayId, bool));
+    MOCK_METHOD2(getSupportedContentTypes,
+                 status_t(PhysicalDisplayId, std::vector<hal::ContentType>*));
+    MOCK_METHOD2(setContentType, status_t(PhysicalDisplayId, hal::ContentType));
     MOCK_CONST_METHOD0(getSupportedLayerGenericMetadata,
                        const std::unordered_map<std::string, bool>&());
 
diff --git a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
index 8d1eb36..6ce8a6b 100644
--- a/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
+++ b/services/surfaceflinger/CompositionEngine/tests/RenderSurfaceTest.cpp
@@ -33,7 +33,7 @@
 
 constexpr int32_t DEFAULT_DISPLAY_WIDTH = 1920;
 constexpr int32_t DEFAULT_DISPLAY_HEIGHT = 1080;
-constexpr std::optional<DisplayId> DEFAULT_DISPLAY_ID = {PhysicalDisplayId(123u)};
+constexpr DisplayId DEFAULT_DISPLAY_ID = PhysicalDisplayId(123u);
 const std::string DEFAULT_DISPLAY_NAME = "Mock Display";
 
 using testing::_;
@@ -48,7 +48,7 @@
 class RenderSurfaceTest : public testing::Test {
 public:
     RenderSurfaceTest() {
-        EXPECT_CALL(mDisplay, getId()).WillRepeatedly(ReturnRef(DEFAULT_DISPLAY_ID));
+        EXPECT_CALL(mDisplay, getId()).WillRepeatedly(Return(DEFAULT_DISPLAY_ID));
         EXPECT_CALL(mDisplay, getName()).WillRepeatedly(ReturnRef(DEFAULT_DISPLAY_NAME));
         EXPECT_CALL(mCompositionEngine, getRenderEngine).WillRepeatedly(ReturnRef(mRenderEngine));
         EXPECT_CALL(*mNativeWindow, disconnect(NATIVE_WINDOW_API_EGL))