From 8117c1a78d49c3e02f2ece22b994ace03c200153 Mon Sep 17 00:00:00 2001 From: Lloyd Pique Date: Wed, 24 May 2023 15:12:15 -0700 Subject: SF: Introduce struct surfaceflinger::Config This pulls out all the individual configuration constants read by SurfaceFlinger in its constructor, and moves them to a new surfaceflinger::Config structure which is passed to the constructor. All the initialization is the functionally the same, a few values turned out to not be used, so were removed (mMaxGraphicBufferProducerListSize, mGraphicBufferProducerListSizeLogThreshold). Otherwise all properties read for the new structure consistently use android-base/properties.h to read them. To keep the argument count down, the SurfaceFlinger factory argument to the constructor was moved to be stored in the new Config structure. As a result of the change, SurfaceFlinger now only has one constructor. The tests were using the other constructor (passing SurfaceFlinger::skipInitiailization) to skip over the property reads to help ensure a hermetic configuration of SurfaceFlinger. The tests can now instead create create a minimally configured Config structure, and pass that the structure. The other changes were then to switch over to using the values in the Config structure, both internally to SurfaceFlinger, as well as in other files including Layer.cpp and DisplayDevice.cpp. In some cases, those changes required altering the arguments to the function being called to obtain the values, since originally some of the values where static member data in SurfaceFlinger. There were similar changes required for the tests and the fuzzers, to switch over, including how some tests mutated the configuration values so that they overall coverage was the same. No new tests/fuzzing was added, though it should now be easier to extend coverage. Test: atest libsurfaceflinger_unittest Bug: None Change-Id: I8dc3c2317a92b256e58ec45190e24463032c2f8e --- services/surfaceflinger/RegionSamplingThread.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'services/surfaceflinger/RegionSamplingThread.cpp') diff --git a/services/surfaceflinger/RegionSamplingThread.cpp b/services/surfaceflinger/RegionSamplingThread.cpp index 8f658d5a09..03f3b402c9 100644 --- a/services/surfaceflinger/RegionSamplingThread.cpp +++ b/services/surfaceflinger/RegionSamplingThread.cpp @@ -322,7 +322,7 @@ void RegionSamplingThread::captureSample() { }; std::function>>()> getLayerSnapshots; - if (mFlinger.mLayerLifecycleManagerEnabled) { + if (mFlinger.getConfig().layerLifecycleManagerEnabled) { auto filterFn = [&](const frontend::LayerSnapshot& snapshot, bool& outStopTraversal) -> bool { const Rect bounds = -- cgit v1.2.3-59-g8ed1b From 30db640d22bcfaa25d17c7c7bab8fa179d060a75 Mon Sep 17 00:00:00 2001 From: Lloyd Pique Date: Mon, 26 Jun 2023 18:56:51 +0000 Subject: Revert "SF: Introduce struct surfaceflinger::Config" Revert submission 23423266-SF-Config Reason for revert: UIBench Jank Regression reported in b/288665387 Reverted changes: /q/submissionid:23423266-SF-Config Change-Id: I0942f99fec1f211e607e3ff44da2dfa0e30d34c2 --- services/surfaceflinger/Android.bp | 1 - services/surfaceflinger/DisplayDevice.cpp | 24 +- services/surfaceflinger/DisplayDevice.h | 3 +- .../DisplayHardware/FramebufferSurface.cpp | 6 +- .../DisplayHardware/FramebufferSurface.h | 2 +- .../DisplayHardware/VirtualDisplaySurface.cpp | 4 +- .../DisplayHardware/VirtualDisplaySurface.h | 3 +- services/surfaceflinger/Layer.cpp | 6 +- services/surfaceflinger/LayerRenderArea.cpp | 2 +- services/surfaceflinger/RegionSamplingThread.cpp | 2 +- services/surfaceflinger/SurfaceFlinger.cpp | 325 ++++++++++++++------- services/surfaceflinger/SurfaceFlinger.h | 113 ++++++- services/surfaceflinger/SurfaceFlingerConfig.cpp | 162 ---------- services/surfaceflinger/SurfaceFlingerConfig.h | 145 --------- services/surfaceflinger/SurfaceFlingerFactory.cpp | 11 +- .../surfaceflinger_displayhardware_fuzzer.cpp | 6 +- .../fuzzer/surfaceflinger_fuzzer.cpp | 30 +- .../fuzzer/surfaceflinger_fuzzers_utils.h | 16 +- .../fuzzer/surfaceflinger_service_fuzzer.cpp | 4 +- .../tests/unittests/DisplayTransactionTest.cpp | 2 +- .../unittests/DisplayTransactionTestHelpers.h | 4 +- .../tests/unittests/SchedulerTest.cpp | 4 +- ...urfaceFlinger_GetDisplayNativePrimariesTest.cpp | 4 +- ...ceFlinger_SetupNewDisplayDeviceInternalTest.cpp | 2 +- .../tests/unittests/TestableSurfaceFlinger.h | 17 +- 25 files changed, 405 insertions(+), 493 deletions(-) delete mode 100644 services/surfaceflinger/SurfaceFlingerConfig.cpp delete mode 100644 services/surfaceflinger/SurfaceFlingerConfig.h (limited to 'services/surfaceflinger/RegionSamplingThread.cpp') diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp index bf07f7253f..89c80bc83a 100644 --- a/services/surfaceflinger/Android.bp +++ b/services/surfaceflinger/Android.bp @@ -195,7 +195,6 @@ filegroup { "ScreenCaptureOutput.cpp", "StartPropertySetThread.cpp", "SurfaceFlinger.cpp", - "SurfaceFlingerConfig.cpp", "SurfaceFlingerDefaultFactory.cpp", "Tracing/LayerTracing.cpp", "Tracing/TransactionTracing.cpp", diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp index 2789fa6bf2..f6ca9e2856 100644 --- a/services/surfaceflinger/DisplayDevice.cpp +++ b/services/surfaceflinger/DisplayDevice.cpp @@ -78,19 +78,18 @@ DisplayDevice::DisplayDevice(DisplayDeviceCreationArgs& args) .setDisplayHeight(ANativeWindow_getHeight(args.nativeWindow.get())) .setNativeWindow(std::move(args.nativeWindow)) .setDisplaySurface(std::move(args.displaySurface)) - .setMaxTextureCacheSize(static_cast( - mFlinger->getConfig().maxFrameBufferAcquiredBuffers)) + .setMaxTextureCacheSize( + static_cast(SurfaceFlinger::maxFrameBufferAcquiredBuffers)) .build()); - if (!mFlinger->getConfig().disableClientCompositionCache && - mFlinger->getConfig().maxFrameBufferAcquiredBuffers > 0) { + if (!mFlinger->mDisableClientCompositionCache && + SurfaceFlinger::maxFrameBufferAcquiredBuffers > 0) { mCompositionDisplay->createClientCompositionCache( - static_cast(mFlinger->getConfig().maxFrameBufferAcquiredBuffers)); + static_cast(SurfaceFlinger::maxFrameBufferAcquiredBuffers)); } - mCompositionDisplay->setPredictCompositionStrategy( - mFlinger->getConfig().predictCompositionStrategy); - mCompositionDisplay->setTreat170mAsSrgb(mFlinger->getConfig().treat170mAsSrgb); + mCompositionDisplay->setPredictCompositionStrategy(mFlinger->mPredictCompositionStrategy); + mCompositionDisplay->setTreat170mAsSrgb(mFlinger->mTreat170mAsSrgb); mCompositionDisplay->createDisplayColorProfile( compositionengine::DisplayColorProfileCreationArgsBuilder() .setHasWideColorGamut(args.hasWideColorGamut) @@ -412,22 +411,23 @@ HdrCapabilities DisplayDevice::getHdrCapabilities() const { capabilities.getDesiredMinLuminance()); } -void DisplayDevice::enableRefreshRateOverlay(bool enable, bool setByHwc) { +void DisplayDevice::enableRefreshRateOverlay(bool enable, bool setByHwc, bool showSpinner, + bool showRenderRate, bool showInMiddle) { if (!enable) { mRefreshRateOverlay.reset(); return; } ftl::Flags features; - if (mFlinger->getConfig().refreshRateOverlay.showSpinner) { + if (showSpinner) { features |= RefreshRateOverlay::Features::Spinner; } - if (mFlinger->getConfig().refreshRateOverlay.showRenderRate) { + if (showRenderRate) { features |= RefreshRateOverlay::Features::RenderRate; } - if (mFlinger->getConfig().refreshRateOverlay.showInMiddle) { + if (showInMiddle) { features |= RefreshRateOverlay::Features::ShowInMiddle; } diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h index d2a9fb685a..dc5f8a85af 100644 --- a/services/surfaceflinger/DisplayDevice.h +++ b/services/surfaceflinger/DisplayDevice.h @@ -236,7 +236,8 @@ public: } // Enables an overlay to be displayed with the current refresh rate - void enableRefreshRateOverlay(bool enable, bool setByHwc) REQUIRES(kMainThreadContext); + void enableRefreshRateOverlay(bool enable, bool setByHwc, bool showSpinner, bool showRenderRate, + bool showInMiddle) REQUIRES(kMainThreadContext); void updateRefreshRateOverlayRate(Fps displayFps, Fps renderFps, bool setByHwc = false); bool isRefreshRateOverlayEnabled() const { return mRefreshRateOverlay != nullptr; } bool onKernelTimerChanged(std::optional, bool timerExpired); diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp index 14fff772db..ce602a8ad9 100644 --- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp +++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.cpp @@ -50,8 +50,7 @@ using ui::Dataspace; FramebufferSurface::FramebufferSurface(HWComposer& hwc, PhysicalDisplayId displayId, const sp& consumer, - const ui::Size& size, const ui::Size& maxSize, - int maxAcquiredBufferCount) + const ui::Size& size, const ui::Size& maxSize) : ConsumerBase(consumer), mDisplayId(displayId), mMaxSize(maxSize), @@ -71,7 +70,8 @@ FramebufferSurface::FramebufferSurface(HWComposer& hwc, PhysicalDisplayId displa GRALLOC_USAGE_HW_COMPOSER); const auto limitedSize = limitSize(size); mConsumer->setDefaultBufferSize(limitedSize.width, limitedSize.height); - mConsumer->setMaxAcquiredBufferCount(maxAcquiredBufferCount); + mConsumer->setMaxAcquiredBufferCount( + SurfaceFlinger::maxFrameBufferAcquiredBuffers - 1); for (size_t i = 0; i < sizeof(mHwcBufferIds) / sizeof(mHwcBufferIds[0]); ++i) { mHwcBufferIds[i] = UINT64_MAX; diff --git a/services/surfaceflinger/DisplayHardware/FramebufferSurface.h b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h index 5a1d14fdfe..0b863daf47 100644 --- a/services/surfaceflinger/DisplayHardware/FramebufferSurface.h +++ b/services/surfaceflinger/DisplayHardware/FramebufferSurface.h @@ -42,7 +42,7 @@ class FramebufferSurface : public ConsumerBase, public compositionengine::Displa public: FramebufferSurface(HWComposer& hwc, PhysicalDisplayId displayId, const sp& consumer, const ui::Size& size, - const ui::Size& maxSize, int maxAcquiredBufferCount); + const ui::Size& maxSize); virtual status_t beginFrame(bool mustRecompose); virtual status_t prepareFrame(CompositionType compositionType); diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp index d759c12612..d62075ec65 100644 --- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp +++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.cpp @@ -50,7 +50,7 @@ VirtualDisplaySurface::VirtualDisplaySurface(HWComposer& hwc, VirtualDisplayId d const sp& sink, const sp& bqProducer, const sp& bqConsumer, - const std::string& name, bool useHwcForRgbToYuv) + const std::string& name) : ConsumerBase(bqConsumer), mHwc(hwc), mDisplayId(displayId), @@ -69,7 +69,7 @@ VirtualDisplaySurface::VirtualDisplaySurface(HWComposer& hwc, VirtualDisplayId d mOutputFence(Fence::NO_FENCE), mFbProducerSlot(BufferQueue::INVALID_BUFFER_SLOT), mOutputProducerSlot(BufferQueue::INVALID_BUFFER_SLOT), - mForceHwcCopy(useHwcForRgbToYuv) { + mForceHwcCopy(SurfaceFlinger::useHwcForRgbToYuv) { mSource[SOURCE_SINK] = sink; mSource[SOURCE_SCRATCH] = bqProducer; diff --git a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h index 8a56d5f7b5..be06e2bb10 100644 --- a/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h +++ b/services/surfaceflinger/DisplayHardware/VirtualDisplaySurface.h @@ -77,8 +77,7 @@ class VirtualDisplaySurface : public compositionengine::DisplaySurface, public: VirtualDisplaySurface(HWComposer&, VirtualDisplayId, const sp& sink, const sp& bqProducer, - const sp& bqConsumer, const std::string& name, - bool useHwcForRgbToYuv); + const sp& bqConsumer, const std::string& name); // // DisplaySurface interface diff --git a/services/surfaceflinger/Layer.cpp b/services/surfaceflinger/Layer.cpp index 8e1b8f2c00..5a010e8af6 100644 --- a/services/surfaceflinger/Layer.cpp +++ b/services/surfaceflinger/Layer.cpp @@ -2562,7 +2562,7 @@ bool Layer::hasInputInfo() const { compositionengine::OutputLayer* Layer::findOutputLayerForDisplay( const DisplayDevice* display) const { if (!display) return nullptr; - if (!mFlinger->getConfig().layerLifecycleManagerEnabled) { + if (!mFlinger->mLayerLifecycleManagerEnabled) { return display->getCompositionDisplay()->getOutputLayerForLayer( getCompositionEngineLayerFE()); } @@ -2907,7 +2907,7 @@ void Layer::onSurfaceFrameCreated( void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) { for (const auto& handle : mDrawingState.callbackHandles) { - if (mFlinger->getConfig().layerLifecycleManagerEnabled) { + if (mFlinger->mLayerLifecycleManagerEnabled) { handle->transformHint = mTransformHint; } else { handle->transformHint = mSkipReportingTransformHint @@ -3162,7 +3162,7 @@ bool Layer::setBuffer(std::shared_ptr& buffer, mFlinger->mTimeStats->setPostTime(layerId, mDrawingState.frameNumber, getName().c_str(), mOwnerUid, postTime, getGameMode()); - if (mFlinger->getConfig().legacyFrontEndEnabled) { + if (mFlinger->mLegacyFrontEndEnabled) { recordLayerHistoryBufferUpdate(getLayerProps()); } diff --git a/services/surfaceflinger/LayerRenderArea.cpp b/services/surfaceflinger/LayerRenderArea.cpp index 9c1944b122..51d4ff854f 100644 --- a/services/surfaceflinger/LayerRenderArea.cpp +++ b/services/surfaceflinger/LayerRenderArea.cpp @@ -78,7 +78,7 @@ void LayerRenderArea::render(std::function drawLayers) { mTransform = mLayerTransform.inverse(); } - if (mFlinger.getConfig().layerLifecycleManagerEnabled) { + if (mFlinger.mLayerLifecycleManagerEnabled) { drawLayers(); return; } diff --git a/services/surfaceflinger/RegionSamplingThread.cpp b/services/surfaceflinger/RegionSamplingThread.cpp index 03f3b402c9..8f658d5a09 100644 --- a/services/surfaceflinger/RegionSamplingThread.cpp +++ b/services/surfaceflinger/RegionSamplingThread.cpp @@ -322,7 +322,7 @@ void RegionSamplingThread::captureSample() { }; std::function>>()> getLayerSnapshots; - if (mFlinger.getConfig().layerLifecycleManagerEnabled) { + if (mFlinger.mLayerLifecycleManagerEnabled) { auto filterFn = [&](const frontend::LayerSnapshot& snapshot, bool& outStopTraversal) -> bool { const Rect bounds = diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 60c09049cf..ba13293a8f 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -214,6 +214,16 @@ static constexpr int FOUR_K_HEIGHT = 2160; // TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity. constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV; +float getDensityFromProperty(const char* property, bool required) { + char value[PROPERTY_VALUE_MAX]; + const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f; + if (!density && required) { + ALOGE("%s must be defined as a build property", property); + return FALLBACK_DENSITY; + } + return density; +} + // Currently we only support V0_SRGB and DISPLAY_P3 as composition preference. bool validateCompositionDataspace(Dataspace dataspace) { return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3; @@ -312,6 +322,18 @@ const char* KERNEL_IDLE_TIMER_PROP = "graphics.display.kernel_idle_timer.enabled static const int MAX_TRACING_MEMORY = 1024 * 1024 * 1024; // 1GB // --------------------------------------------------------------------------- +int64_t SurfaceFlinger::dispSyncPresentTimeOffset; +bool SurfaceFlinger::useHwcForRgbToYuv; +bool SurfaceFlinger::hasSyncFramework; +int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers; +int64_t SurfaceFlinger::minAcquiredBuffers = 1; +uint32_t SurfaceFlinger::maxGraphicsWidth; +uint32_t SurfaceFlinger::maxGraphicsHeight; +bool SurfaceFlinger::useContextPriority; +Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB; +ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888; +Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB; +ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888; LatchUnsignaledConfig SurfaceFlinger::enableLatchUnsignaledConfig; std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) { @@ -338,35 +360,136 @@ bool callingThreadHasPermission(const String16& permission) { ui::Transform::RotationFlags SurfaceFlinger::sActiveDisplayRotationFlags = ui::Transform::ROT_0; -SurfaceFlinger::SurfaceFlinger(surfaceflinger::Config& config) - : mConfig(&config), - mDebugFlashDelay(base::GetUintProperty("debug.sf.showupdates"s, 0u)), +SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag) + : mFactory(factory), + mPid(getpid()), mTimeStats(std::make_shared()), - mFrameTracer(mConfig->factory->createFrameTracer()), - mFrameTimeline(mConfig->factory->createFrameTimeline(mTimeStats, mConfig->pid)), - mCompositionEngine(mConfig->factory->createCompositionEngine()), + mFrameTracer(mFactory.createFrameTracer()), + mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)), + mCompositionEngine(mFactory.createCompositionEngine()), + mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)), mTunnelModeEnabledReporter(sp::make()), + mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)), + mInternalDisplayDensity( + getDensityFromProperty("ro.sf.lcd_density", !mEmulatedDisplayDensity)), mPowerAdvisor(std::make_unique(*this)), mWindowInfosListenerInvoker(sp::make()) { + ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str()); +} + +SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) { ATRACE_CALL(); - ALOGI("SurfaceFlinger is starting."); - ALOGI("Using HWComposer service: %s", mConfig->hwcServiceName.c_str()); - ALOGI_IF(mConfig->backpressureGpuComposition, "Enabling backpressure for GPU composition"); - ALOGI_IF(!mConfig->supportsBlur, "Disabling blur effects, they are not supported."); - ALOGI_IF(mConfig->trebleTestingOverride, "Enabling Treble testing override"); + ALOGI("SurfaceFlinger is starting"); + + hasSyncFramework = running_without_sync_framework(true); + + dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0); + + useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false); + + maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2); + minAcquiredBuffers = + SurfaceFlingerProperties::min_acquired_buffers().value_or(minAcquiredBuffers); + + maxGraphicsWidth = std::max(max_graphics_width(0), 0); + maxGraphicsHeight = std::max(max_graphics_height(0), 0); + + mSupportsWideColor = has_wide_color_display(false); + mDefaultCompositionDataspace = + static_cast(default_composition_dataspace(Dataspace::V0_SRGB)); + mWideColorGamutCompositionDataspace = static_cast(wcg_composition_dataspace( + mSupportsWideColor ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB)); + defaultCompositionDataspace = mDefaultCompositionDataspace; + wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace; + defaultCompositionPixelFormat = static_cast( + default_composition_pixel_format(ui::PixelFormat::RGBA_8888)); + wideColorGamutCompositionPixelFormat = + static_cast(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888)); + + mColorSpaceAgnosticDataspace = + static_cast(color_space_agnostic_dataspace(Dataspace::UNKNOWN)); + + mLayerCachingEnabled = [] { + const bool enable = + android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false); + return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable); + }(); + + useContextPriority = use_context_priority(true); + + mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries(); - if (mConfig->trebleTestingOverride) { + // debugging stuff... + char value[PROPERTY_VALUE_MAX]; + + property_get("ro.build.type", value, "user"); + mIsUserBuild = strcmp(value, "user") == 0; + + mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u); + + mBackpressureGpuComposition = base::GetBoolProperty("debug.sf.enable_gl_backpressure"s, true); + ALOGI_IF(mBackpressureGpuComposition, "Enabling backpressure for GPU composition"); + + property_get("ro.surface_flinger.supports_background_blur", value, "0"); + bool supportsBlurs = atoi(value); + mSupportsBlur = supportsBlurs; + ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported."); + + 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 = + std::max(static_cast(0.95 * + static_cast(mMaxGraphicBufferProducerListSize)), + 1); + + property_get("debug.sf.luma_sampling", value, "1"); + mLumaSampling = atoi(value); + + property_get("debug.sf.disable_client_composition_cache", value, "0"); + mDisableClientCompositionCache = atoi(value); + + property_get("debug.sf.predict_hwc_composition_strategy", value, "1"); + mPredictCompositionStrategy = atoi(value); + + property_get("debug.sf.treat_170m_as_sRGB", value, "0"); + mTreat170mAsSrgb = atoi(value); + + mIgnoreHwcPhysicalDisplayOrientation = + base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, false); + + // We should be reading 'persist.sys.sf.color_saturation' here + // but since /data may be encrypted, we need to wait until after vold + // comes online to attempt to read the property. The property is + // instead read after the boot animation + + if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) { // Without the override SurfaceFlinger cannot connect to HIDL // services that are not listed in the manifests. Considered // deriving the setting from the set service name, but it // would be brittle if the name that's not 'default' is used // for production purposes later on. + ALOGI("Enabling Treble testing override"); android::hardware::details::setTrebleTestingOverride(true); } - if (!mConfig->isUserBuild && mConfig->enableTransactionTracing) { + // TODO (b/270966065) Update the HWC based refresh rate overlay to support spinner + mRefreshRateOverlaySpinner = property_get_bool("debug.sf.show_refresh_rate_overlay_spinner", 0); + mRefreshRateOverlayRenderRate = + property_get_bool("debug.sf.show_refresh_rate_overlay_render_rate", 0); + mRefreshRateOverlayShowInMiddle = + property_get_bool("debug.sf.show_refresh_rate_overlay_in_middle", 0); + + if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) { mTransactionTracing.emplace(); } + + mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false); + + mLayerLifecycleManagerEnabled = + base::GetBoolProperty("persist.debug.sf.enable_layer_lifecycle_manager"s, false); + mLegacyFrontEndEnabled = !mLayerLifecycleManagerEnabled || + base::GetBoolProperty("persist.debug.sf.enable_legacy_frontend"s, false); } LatchUnsignaledConfig SurfaceFlinger::getLatchUnsignaledConfig() { @@ -693,18 +816,17 @@ void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) { // Get a RenderEngine for the given display / config (can't fail) // TODO(b/77156734): We need to stop casting and use HAL types when possible. // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display. - auto builder = - renderengine::RenderEngineCreationArgs::Builder() - .setPixelFormat(static_cast(mConfig->defaultCompositionPixelFormat)) - .setImageCacheSize(mConfig->maxFrameBufferAcquiredBuffers) - .setUseColorManagerment(useColorManagement) - .setEnableProtectedContext(enable_protected_contents(false)) - .setPrecacheToneMapperShaderOnly(false) - .setSupportsBackgroundBlur(mConfig->supportsBlur) - .setContextPriority( - mConfig->useContextPriority - ? renderengine::RenderEngine::ContextPriority::REALTIME - : renderengine::RenderEngine::ContextPriority::MEDIUM); + auto builder = renderengine::RenderEngineCreationArgs::Builder() + .setPixelFormat(static_cast(defaultCompositionPixelFormat)) + .setImageCacheSize(maxFrameBufferAcquiredBuffers) + .setUseColorManagerment(useColorManagement) + .setEnableProtectedContext(enable_protected_contents(false)) + .setPrecacheToneMapperShaderOnly(false) + .setSupportsBackgroundBlur(mSupportsBlur) + .setContextPriority( + useContextPriority + ? renderengine::RenderEngine::ContextPriority::REALTIME + : renderengine::RenderEngine::ContextPriority::MEDIUM); if (auto type = chooseRenderEngineTypeViaSysProp()) { builder.setRenderEngineType(type.value()); } @@ -719,7 +841,7 @@ void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) { } mCompositionEngine->setTimeStats(mTimeStats); - mCompositionEngine->setHwComposer(getFactory().createHWComposer(mConfig->hwcServiceName)); + mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName)); mCompositionEngine->getHwComposer().setCallback(*this); ClientCache::getInstance().setRenderEngine(&getRenderEngine()); @@ -909,11 +1031,11 @@ status_t SurfaceFlinger::getStaticDisplayInfo(int64_t displayId, ui::StaticDispl info->connectionType = snapshot.connectionType(); info->deviceProductInfo = snapshot.deviceProductInfo(); - if (mConfig->emulatedDisplayDensity) { - info->density = mConfig->emulatedDisplayDensity; + if (mEmulatedDisplayDensity) { + info->density = mEmulatedDisplayDensity; } else { info->density = info->connectionType == ui::DisplayConnectionType::Internal - ? mConfig->internalDisplayDensity + ? mInternalDisplayDensity : FALLBACK_DENSITY; } info->density /= ACONFIGURATION_DENSITY_MEDIUM; @@ -976,7 +1098,7 @@ void SurfaceFlinger::getDynamicDisplayInfoInternal(ui::DynamicDisplayInfo*& info info->supportedDisplayModes.push_back(outMode); } - info->supportedColorModes = snapshot.filterColorModes(mConfig->supportsWideColor); + info->supportedColorModes = snapshot.filterColorModes(mSupportsWideColor); const PhysicalDisplayId displayId = snapshot.displayId(); @@ -1374,7 +1496,7 @@ status_t SurfaceFlinger::getDisplayNativePrimaries(const sp& displayTok } // TODO(b/229846990): For now, assume that all internal displays have the same primaries. - primaries = mConfig->internalDisplayPrimaries; + primaries = mInternalDisplayPrimaries; return NO_ERROR; } @@ -1398,7 +1520,7 @@ status_t SurfaceFlinger::setActiveColorMode(const sp& displayToken, ui: const auto& [display, snapshotRef] = *displayOpt; const auto& snapshot = snapshotRef.get(); - const auto modes = snapshot.filterColorModes(mConfig->supportsWideColor); + const auto modes = snapshot.filterColorModes(mSupportsWideColor); const bool exists = std::find(modes.begin(), modes.end(), mode) != modes.end(); if (mode < ui::ColorMode::NATIVE || !exists) { @@ -1704,7 +1826,7 @@ status_t SurfaceFlinger::isWideColorDisplay(const sp& displayToken, } *outIsWideColorDisplay = - display->isPrimary() ? mConfig->supportsWideColor : display->hasWideColorGamut(); + display->isPrimary() ? mSupportsWideColor : display->hasWideColorGamut(); return NO_ERROR; } @@ -1725,12 +1847,10 @@ status_t SurfaceFlinger::getCompositionPreference( Dataspace* outDataspace, ui::PixelFormat* outPixelFormat, Dataspace* outWideColorGamutDataspace, ui::PixelFormat* outWideColorGamutPixelFormat) const { - *outDataspace = - mOverrideDefaultCompositionDataspace.value_or(mConfig->defaultCompositionDataspace); - *outPixelFormat = mConfig->defaultCompositionPixelFormat; - *outWideColorGamutDataspace = mOverrideWideColorGamutCompositionDataspace.value_or( - mConfig->wideColorGamutCompositionDataspace); - *outWideColorGamutPixelFormat = mConfig->wideColorGamutCompositionPixelFormat; + *outDataspace = mDefaultCompositionDataspace; + *outPixelFormat = defaultCompositionPixelFormat; + *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace; + *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat; return NO_ERROR; } @@ -2193,7 +2313,7 @@ bool SurfaceFlinger::updateLayerSnapshots(VsyncId vsyncId, nsecs_t frameTimeNs, .displays = mFrontEndDisplayInfos, .displayChanges = mFrontEndDisplayInfosChanged, .globalShadowSettings = mDrawingState.globalShadowSettings, - .supportsBlur = mConfig->supportsBlur, + .supportsBlur = mSupportsBlur, .forceFullDamage = mForceFullDamage, .supportedLayerGenericMetadata = getHwComposer().getSupportedLayerGenericMetadata(), @@ -2213,7 +2333,7 @@ bool SurfaceFlinger::updateLayerSnapshots(VsyncId vsyncId, nsecs_t frameTimeNs, mustComposite |= mLayerLifecycleManager.getGlobalChanges().get() != 0; bool newDataLatched = false; - if (!mConfig->legacyFrontEndEnabled) { + if (!mLegacyFrontEndEnabled) { ATRACE_NAME("DisplayCallbackAndStatsUpdates"); applyTransactions(update.transactions, vsyncId); const nsecs_t latchTime = systemTime(); @@ -2307,7 +2427,7 @@ bool SurfaceFlinger::commit(const scheduler::FrameTarget& pacesetterFrameTarget) } if (pacesetterFrameTarget.isFramePending()) { - if (mConfig->backpressureGpuComposition || pacesetterFrameTarget.didMissHwcFrame()) { + if (mBackpressureGpuComposition || pacesetterFrameTarget.didMissHwcFrame()) { scheduleCommit(FrameHint::kNone); return false; } @@ -2338,7 +2458,7 @@ bool SurfaceFlinger::commit(const scheduler::FrameTarget& pacesetterFrameTarget) mPowerAdvisor->updateTargetWorkDuration(idealVsyncPeriod); } - if (mConfig->refreshRateOverlay.showSpinner) { + if (mRefreshRateOverlaySpinner) { Mutex::Autolock lock(mStateLock); if (const auto display = getDefaultDisplayDeviceLocked()) { display->animateRefreshRateOverlay(); @@ -2354,12 +2474,12 @@ bool SurfaceFlinger::commit(const scheduler::FrameTarget& pacesetterFrameTarget) const bool flushTransactions = clearTransactionFlags(eTransactionFlushNeeded); bool transactionsAreEmpty; - if (mConfig->legacyFrontEndEnabled) { + if (mLegacyFrontEndEnabled) { mustComposite |= updateLayerSnapshotsLegacy(vsyncId, pacesetterFrameTarget.frameBeginTime().ns(), flushTransactions, transactionsAreEmpty); } - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { mustComposite |= updateLayerSnapshots(vsyncId, pacesetterFrameTarget.frameBeginTime().ns(), flushTransactions, transactionsAreEmpty); @@ -2465,7 +2585,7 @@ CompositeResult SurfaceFlinger::composite(scheduler::FrameTargeter& pacesetterFr refreshArgs.outputColorSetting = useColorManagement ? mDisplayColorSetting : compositionengine::OutputColorSetting::kUnmanaged; - refreshArgs.colorSpaceAgnosticDataspace = mConfig->colorSpaceAgnosticDataspace; + refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace; refreshArgs.forceOutputColorMode = mForceColorMode; refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty; @@ -2619,7 +2739,7 @@ bool SurfaceFlinger::isHdrLayer(const frontend::LayerSnapshot& snapshot) const { // Even though the camera layer may be using an HDR transfer function or otherwise be "HDR" // the device may need to avoid boosting the brightness as a result of these layers to // reduce power consumption during camera recording - if (mConfig->ignoreHdrCameraLayers) { + if (mIgnoreHdrCameraLayers) { if (snapshot.externalTexture && (snapshot.externalTexture->getUsage() & GRALLOC_USAGE_HW_CAMERA_WRITE) != 0) { return false; @@ -2650,7 +2770,7 @@ ui::Rotation SurfaceFlinger::getPhysicalDisplayOrientation(DisplayId displayId, if (!id) { return ui::ROTATION_0; } - if (!mConfig->ignoreHwcPhysicalDisplayOrientation && + if (!mIgnoreHwcPhysicalDisplayOrientation && getHwComposer().getComposer()->isSupported( Hwc2::Composer::OptionalFeature::PhysicalDisplayOrientation)) { switch (getHwComposer().getPhysicalDisplayOrientation(*id)) { @@ -2817,7 +2937,7 @@ void SurfaceFlinger::postComposition(scheduler::FrameTargeter& pacesetterFrameTa } }; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { mLayerSnapshotBuilder.forEachVisibleSnapshot( [&, compositionDisplay = compositionDisplay]( std::unique_ptr& snapshot) { @@ -2869,7 +2989,7 @@ void SurfaceFlinger::postComposition(scheduler::FrameTargeter& pacesetterFrameTa const bool isDisplayConnected = defaultDisplay && getHwComposer().isConnected(defaultDisplay->getPhysicalId()); - if (!mConfig->hasSyncFramework) { + if (!hasSyncFramework) { if (isDisplayConnected && defaultDisplay->isPoweredOn()) { mScheduler->enableHardwareVsync(defaultDisplay->getPhysicalId()); } @@ -2910,7 +3030,7 @@ void SurfaceFlinger::postComposition(scheduler::FrameTargeter& pacesetterFrameTa if (!layer->hasTrustedPresentationListener()) { return; } - const frontend::LayerSnapshot* snapshot = mConfig->layerLifecycleManagerEnabled + const frontend::LayerSnapshot* snapshot = mLayerLifecycleManagerEnabled ? mLayerSnapshotBuilder.getSnapshot(layer->sequence) : layer->getLayerSnapshot(); std::optional displayOpt = std::nullopt; @@ -3305,7 +3425,7 @@ void SurfaceFlinger::processDisplayAdded(const wp& displayToken, builder.setPowerAdvisor(mPowerAdvisor.get()); builder.setName(state.displayName); auto compositionDisplay = getCompositionEngine().createDisplay(builder.build()); - compositionDisplay->setLayerCachingEnabled(mConfig->layerCachingEnabled); + compositionDisplay->setLayerCachingEnabled(mLayerCachingEnabled); sp displaySurface; sp producer; @@ -3317,8 +3437,7 @@ void SurfaceFlinger::processDisplayAdded(const wp& displayToken, const auto displayId = VirtualDisplayId::tryCast(compositionDisplay->getId()); LOG_FATAL_IF(!displayId); auto surface = sp::make(getHwComposer(), *displayId, state.surface, - bqProducer, bqConsumer, state.displayName, - mConfig->useHwcForRgbToYuv); + bqProducer, bqConsumer, state.displayName); displaySurface = surface; producer = std::move(surface); } else { @@ -3328,11 +3447,10 @@ void SurfaceFlinger::processDisplayAdded(const wp& displayToken, state.surface.get()); const auto displayId = PhysicalDisplayId::tryCast(compositionDisplay->getId()); LOG_FATAL_IF(!displayId); - displaySurface = sp::make(getHwComposer(), *displayId, bqConsumer, - state.physical->activeMode->getResolution(), - ui::Size(mConfig->maxGraphicsWidth, - mConfig->maxGraphicsHeight), - mConfig->maxFrameBufferAcquiredBuffers); + displaySurface = + sp::make(getHwComposer(), *displayId, bqConsumer, + state.physical->activeMode->getResolution(), + ui::Size(maxGraphicsWidth, maxGraphicsHeight)); producer = bqProducer; } @@ -3513,7 +3631,7 @@ void SurfaceFlinger::commitTransactionsLocked(uint32_t transactionFlags) { // Commit display transactions. const bool displayTransactionNeeded = transactionFlags & eDisplayTransactionNeeded; mFrontEndDisplayInfosChanged = displayTransactionNeeded; - if (displayTransactionNeeded && !mConfig->layerLifecycleManagerEnabled) { + if (displayTransactionNeeded && !mLayerLifecycleManagerEnabled) { processDisplayChangesLocked(); mFrontEndDisplayInfos.clear(); for (const auto& [_, display] : mDisplays) { @@ -3713,7 +3831,7 @@ void SurfaceFlinger::buildWindowInfos(std::vector& outWindowInfos, outWindowInfos.reserve(sNumWindowInfos); sNumWindowInfos = 0; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { mLayerSnapshotBuilder.forEachInputSnapshot( [&outWindowInfos](const frontend::LayerSnapshot& snapshot) { outWindowInfos.push_back(snapshot.inputInfo); @@ -3837,7 +3955,7 @@ void SurfaceFlinger::initScheduler(const sp& display) { if (display->refreshRateSelector().kernelIdleTimerController()) { features |= Feature::kKernelIdleTimer; } - if (mConfig->backpressureGpuComposition) { + if (mBackpressureGpuComposition) { features |= Feature::kBackpressureGpuComposition; } @@ -4383,7 +4501,7 @@ TransactionHandler::TransactionReadiness SurfaceFlinger::transactionReadyBufferC void SurfaceFlinger::addTransactionReadyFilters() { mTransactionHandler.addTransactionReadyFilter( std::bind(&SurfaceFlinger::transactionReadyTimelineCheck, this, std::placeholders::_1)); - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { mTransactionHandler.addTransactionReadyFilter( std::bind(&SurfaceFlinger::transactionReadyBufferCheck, this, std::placeholders::_1)); @@ -4614,7 +4732,7 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin const std::vector& listenerCallbacks, int originPid, int originUid, uint64_t transactionId) { uint32_t transactionFlags = 0; - if (!mConfig->layerLifecycleManagerEnabled) { + if (!mLayerLifecycleManagerEnabled) { for (DisplayState& display : displays) { transactionFlags |= setDisplayStateLocked(display); } @@ -4629,12 +4747,12 @@ bool SurfaceFlinger::applyTransactionState(const FrameTimelineInfo& frameTimelin uint32_t clientStateFlags = 0; for (auto& resolvedState : states) { - if (mConfig->legacyFrontEndEnabled) { + if (mLegacyFrontEndEnabled) { clientStateFlags |= setClientStateLocked(frameTimelineInfo, resolvedState, desiredPresentTime, isAutoTimestamp, postTime, transactionId); - } else /* mConfig->layerLifecycleManagerEnabled */ { + } else /*mLayerLifecycleManagerEnabled*/ { clientStateFlags |= updateLayerCallbacksAndStats(frameTimelineInfo, resolvedState, desiredPresentTime, isAutoTimestamp, postTime, transactionId); @@ -4708,7 +4826,7 @@ bool SurfaceFlinger::applyAndCommitDisplayTransactionStates( } mFrontEndDisplayInfosChanged = mTransactionFlags & eDisplayTransactionNeeded; - if (mFrontEndDisplayInfosChanged && !mConfig->legacyFrontEndEnabled) { + if (mFrontEndDisplayInfosChanged && !mLegacyFrontEndEnabled) { processDisplayChangesLocked(); mFrontEndDisplayInfos.clear(); for (const auto& [_, display] : mDisplays) { @@ -4911,7 +5029,7 @@ uint32_t SurfaceFlinger::setClientStateLocked(const FrameTimelineInfo& frameTime if (layer->setCornerRadius(s.cornerRadius)) flags |= eTraversalNeeded; } - if (what & layer_state_t::eBackgroundBlurRadiusChanged && mConfig->supportsBlur) { + if (what & layer_state_t::eBackgroundBlurRadiusChanged && mSupportsBlur) { if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded; } if (what & layer_state_t::eBlurRegionsChanged) { @@ -5315,7 +5433,7 @@ status_t SurfaceFlinger::mirrorDisplay(DisplayId displayId, const LayerCreationA return result; } - if (mConfig->legacyFrontEndEnabled) { + if (mLegacyFrontEndEnabled) { std::scoped_lock lock(mMirrorDisplayLock); mMirrorDisplays.emplace_back(layerStack, outResult.handle, args.client); } @@ -5422,10 +5540,9 @@ void SurfaceFlinger::initializeDisplays() { const nsecs_t now = systemTime(); state.desiredPresentTime = now; state.postTime = now; - state.originPid = mConfig->pid; + state.originPid = mPid; state.originUid = static_cast(getuid()); - const uint64_t transactionId = - (static_cast(mConfig->pid) << 32) | mUniqueTransactionId++; + const uint64_t transactionId = (static_cast(mPid) << 32) | mUniqueTransactionId++; state.id = transactionId; // reset screen orientation and use primary layer stack @@ -5445,7 +5562,7 @@ void SurfaceFlinger::initializeDisplays() { std::vector transactions; transactions.emplace_back(state); - if (mConfig->legacyFrontEndEnabled) { + if (mLegacyFrontEndEnabled) { applyTransactions(transactions, VsyncId{0}); } else { applyAndCommitDisplayTransactionStates(transactions); @@ -5741,13 +5858,13 @@ void SurfaceFlinger::logFrameStats(TimePoint now) { void SurfaceFlinger::appendSfConfigString(std::string& result) const { result.append(" [sf"); - StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, mConfig->dispSyncPresentTimeOffset); - StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", mConfig->useHwcForRgbToYuv); + StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset); + StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv); StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%zu", getHwComposer().getMaxVirtualDisplayDimension()); - StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !mConfig->hasSyncFramework); + StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework); StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64, - mConfig->maxFrameBufferAcquiredBuffers); + maxFrameBufferAcquiredBuffers); result.append("]"); } @@ -5767,7 +5884,7 @@ void SurfaceFlinger::dumpScheduler(std::string& result) const { StringAppendF(&result, " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n", - mConfig->dispSyncPresentTimeOffset, getVsyncPeriodFromHWC()); + dispSyncPresentTimeOffset, getVsyncPeriodFromHWC()); } void SurfaceFlinger::dumpEvents(std::string& result) const { @@ -5866,7 +5983,7 @@ void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args, } void SurfaceFlinger::dumpWideColorInfo(std::string& result) const { - StringAppendF(&result, "Device supports wide color: %d\n", mConfig->supportsWideColor); + StringAppendF(&result, "Device supports wide color: %d\n", mSupportsWideColor); StringAppendF(&result, "Device uses color management: %d\n", useColorManagement); StringAppendF(&result, "DisplayColorSetting: %s\n", decodeDisplayColorSetting(mDisplayColorSetting).c_str()); @@ -5900,7 +6017,7 @@ LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const { } } - if (mConfig->legacyFrontEndEnabled) { + if (mLegacyFrontEndEnabled) { LayersProto layersProto; for (const sp& layer : mDrawingState.layersSortedByZ) { if (stackIdsToSkip.find(layer->getLayerStack().id) != stackIdsToSkip.end()) { @@ -6557,7 +6674,7 @@ status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* r if (!validateCompositionDataspace(dataspace)) { return BAD_VALUE; } - mOverrideDefaultCompositionDataspace = dataspace; + mDefaultCompositionDataspace = dataspace; } n = data.readInt32(); if (n) { @@ -6565,12 +6682,12 @@ status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* r if (!validateCompositionDataspace(dataspace)) { return BAD_VALUE; } - mOverrideWideColorGamutCompositionDataspace = dataspace; + mWideColorGamutCompositionDataspace = dataspace; } } else { - // Reset data space overrides. - mOverrideDefaultCompositionDataspace.reset(); - mOverrideWideColorGamutCompositionDataspace.reset(); + // restore composition data space. + mDefaultCompositionDataspace = defaultCompositionDataspace; + mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace; } return NO_ERROR; } @@ -6709,10 +6826,10 @@ status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* r } { Mutex::Autolock lock(mStateLock); - mConfig->layerCachingEnabled = n != 0; + mLayerCachingEnabled = n != 0; for (const auto& [_, display] : mDisplays) { if (!inputId || *inputId == display->getPhysicalId()) { - display->enableLayerCaching(mConfig->layerCachingEnabled); + display->enableLayerCaching(mLayerCachingEnabled); } } } @@ -7037,7 +7154,7 @@ status_t SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args, }); GetLayerSnapshotsFunction getLayerSnapshots; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { getLayerSnapshots = getLayerSnapshotsForScreenshots(layerStack, args.uid, std::move(excludeLayerIds)); } else { @@ -7080,7 +7197,7 @@ status_t SurfaceFlinger::captureDisplay(DisplayId displayId, }); GetLayerSnapshotsFunction getLayerSnapshots; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { getLayerSnapshots = getLayerSnapshotsForScreenshots(layerStack, CaptureArgs::UNSET_UID, /*snapshotFilterFn=*/nullptr); } else { @@ -7176,7 +7293,7 @@ status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args, RenderAreaFuture renderAreaFuture = ftl::defer([=]() -> std::unique_ptr { ui::Transform layerTransform; Rect layerBufferSize; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { frontend::LayerSnapshot* snapshot = mLayerSnapshotBuilder.getSnapshot(parent->getSequence()); if (!snapshot) { @@ -7196,7 +7313,7 @@ status_t SurfaceFlinger::captureLayers(const LayerCaptureArgs& args, args.hintForSeamlessTransition); }); GetLayerSnapshotsFunction getLayerSnapshots; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { std::optional parentCrop = std::nullopt; if (args.childrenOnly) { parentCrop = crop.isEmpty() ? FloatRect(0, 0, reqSize.width, reqSize.height) @@ -7449,7 +7566,7 @@ ftl::SharedFuture SurfaceFlinger::renderScreenImpl( layerStack, regionSampling, renderArea = std::move(renderArea), renderIntent]() -> FenceResult { std::unique_ptr compositionEngine = - mConfig->factory->createCompositionEngine(); + mFactory.createCompositionEngine(); compositionEngine->setRenderEngine(mRenderEngine.get()); compositionengine::Output::ColorProfile colorProfile{.dataspace = dataspace, @@ -7519,7 +7636,7 @@ ftl::SharedFuture SurfaceFlinger::renderScreenImpl( } void SurfaceFlinger::traverseLegacyLayers(const LayerVector::Visitor& visitor) const { - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { for (auto& layer : mLegacyLayers) { visitor(layer.second.get()); } @@ -7841,7 +7958,9 @@ void SurfaceFlinger::enableRefreshRateOverlay(bool enable) { } if (const auto device = getDisplayDeviceLocked(id)) { - device->enableRefreshRateOverlay(enable, setByHwc); + device->enableRefreshRateOverlay(enable, setByHwc, mRefreshRateOverlaySpinner, + mRefreshRateOverlayRenderRate, + mRefreshRateOverlayShowInMiddle); } } } @@ -7852,12 +7971,12 @@ int SurfaceFlinger::getGpuContextPriority() { } int SurfaceFlinger::calculateMaxAcquiredBufferCount(Fps refreshRate, - std::chrono::nanoseconds presentLatency) const { + std::chrono::nanoseconds presentLatency) { auto pipelineDepth = presentLatency.count() / refreshRate.getPeriodNsecs(); if (presentLatency.count() % refreshRate.getPeriodNsecs()) { pipelineDepth++; } - return std::max(mConfig->minAcquiredBuffers, static_cast(pipelineDepth - 1)); + return std::max(minAcquiredBuffers, static_cast(pipelineDepth - 1)); } status_t SurfaceFlinger::getMaxAcquiredBufferCount(int* buffers) const { @@ -7939,7 +8058,7 @@ void SurfaceFlinger::handleLayerCreatedLocked(const LayerCreatedState& state, Vs } void SurfaceFlinger::sample() { - if (!mConfig->lumaSampling || !mRegionSamplingThread) { + if (!mLumaSampling || !mRegionSamplingThread) { return; } @@ -8131,7 +8250,7 @@ void SurfaceFlinger::updateLayerMetadataSnapshot() { void SurfaceFlinger::moveSnapshotsFromCompositionArgs( compositionengine::CompositionRefreshArgs& refreshArgs, const std::vector>& layers) { - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { std::vector>& snapshots = mLayerSnapshotBuilder.getSnapshots(); for (auto [_, layerFE] : layers) { @@ -8139,7 +8258,7 @@ void SurfaceFlinger::moveSnapshotsFromCompositionArgs( snapshots[i] = std::move(layerFE->mSnapshot); } } - if (mConfig->legacyFrontEndEnabled && !mConfig->layerLifecycleManagerEnabled) { + if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) { for (auto [layer, layerFE] : layers) { layer->updateLayerSnapshot(std::move(layerFE->mSnapshot)); } @@ -8149,7 +8268,7 @@ void SurfaceFlinger::moveSnapshotsFromCompositionArgs( std::vector> SurfaceFlinger::moveSnapshotsToCompositionArgs( compositionengine::CompositionRefreshArgs& refreshArgs, bool cursorOnly) { std::vector> layers; - if (mConfig->layerLifecycleManagerEnabled) { + if (mLayerLifecycleManagerEnabled) { nsecs_t currentTime = systemTime(); mLayerSnapshotBuilder.forEachVisibleSnapshot( [&](std::unique_ptr& snapshot) { @@ -8175,7 +8294,7 @@ std::vector> SurfaceFlinger::moveSnapshotsToComposit layers.emplace_back(legacyLayer.get(), layerFE.get()); }); } - if (mConfig->legacyFrontEndEnabled && !mConfig->layerLifecycleManagerEnabled) { + if (mLegacyFrontEndEnabled && !mLayerLifecycleManagerEnabled) { auto moveSnapshots = [&layers, &refreshArgs, cursorOnly](Layer* layer) { if (const auto& layerFE = layer->getCompositionEngineLayerFE()) { if (cursorOnly && @@ -8267,7 +8386,7 @@ SurfaceFlinger::getLayerSnapshotsForScreenshots(std::optional la .displays = mFrontEndDisplayInfos, .displayChanges = true, .globalShadowSettings = mDrawingState.globalShadowSettings, - .supportsBlur = mConfig->supportsBlur, + .supportsBlur = mSupportsBlur, .forceFullDamage = mForceFullDamage, .excludeLayerIds = std::move(excludeLayerIds), .supportedLayerGenericMetadata = @@ -8301,7 +8420,7 @@ SurfaceFlinger::getLayerSnapshotsForScreenshots(uint32_t rootLayerId, uint32_t u .displays = mFrontEndDisplayInfos, .displayChanges = true, .globalShadowSettings = mDrawingState.globalShadowSettings, - .supportsBlur = mConfig->supportsBlur, + .supportsBlur = mSupportsBlur, .forceFullDamage = mForceFullDamage, .parentCrop = parentCrop, .excludeLayerIds = std::move(excludeLayerIds), diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index 55e1b758b7..5c57abdb32 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -63,7 +63,6 @@ #include #include -#include "Client.h" #include "Display/PhysicalDisplay.h" #include "DisplayDevice.h" #include "DisplayHardware/HWC2.h" @@ -82,7 +81,6 @@ #include "Scheduler/RefreshRateSelector.h" #include "Scheduler/RefreshRateStats.h" #include "Scheduler/Scheduler.h" -#include "SurfaceFlingerConfig.h" #include "SurfaceFlingerFactory.h" #include "ThreadContext.h" #include "Tracing/LayerTracing.h" @@ -109,6 +107,7 @@ #include #include +#include "Client.h" using namespace android::surfaceflinger; @@ -198,7 +197,10 @@ class SurfaceFlinger : public BnSurfaceComposer, private scheduler::ISchedulerCallback, private compositionengine::ICEPowerCallback { public: - explicit SurfaceFlinger(surfaceflinger::Config&) ANDROID_API; + struct SkipInitializationTag {}; + + SurfaceFlinger(surfaceflinger::Factory&, SkipInitializationTag) ANDROID_API; + explicit SurfaceFlinger(surfaceflinger::Factory&) ANDROID_API; // set main thread scheduling policy static status_t setSchedFifo(bool enabled) ANDROID_API; @@ -208,9 +210,51 @@ public: static char const* getServiceName() ANDROID_API { return "SurfaceFlinger"; } + // If fences from sync Framework are supported. + static bool hasSyncFramework; + + // The offset in nanoseconds to use when VsyncController timestamps present fence + // signaling time. + static int64_t dispSyncPresentTimeOffset; + + // Some hardware can do RGB->YUV conversion more efficiently in hardware + // controlled by HWC than in hardware controlled by the video encoder. + // This instruct VirtualDisplaySurface to use HWC for such conversion on + // GL composition. + static bool useHwcForRgbToYuv; + + // Controls the number of buffers SurfaceFlinger will allocate for use in + // FramebufferSurface + static int64_t maxFrameBufferAcquiredBuffers; + + // Controls the minimum acquired buffers SurfaceFlinger will suggest via + // ISurfaceComposer.getMaxAcquiredBufferCount(). + static int64_t minAcquiredBuffers; + + // Controls the maximum width and height in pixels that the graphics pipeline can support for + // GPU fallback composition. For example, 8k devices with 4k GPUs, or 4k devices with 2k GPUs. + static uint32_t maxGraphicsWidth; + static uint32_t maxGraphicsHeight; + // Indicate if device wants color management on its display. static const constexpr bool useColorManagement = true; + static bool useContextPriority; + + // The data space and pixel format that SurfaceFlinger expects hardware composer + // to composite efficiently. Meaning under most scenarios, hardware composer + // will accept layers with the data space and pixel format. + static ui::Dataspace defaultCompositionDataspace; + static ui::PixelFormat defaultCompositionPixelFormat; + + // The data space and pixel format that SurfaceFlinger expects hardware composer + // to composite efficiently for wide color gamut surfaces. Meaning under most scenarios, + // hardware composer will accept layers with the data space and pixel format. + static ui::Dataspace wideColorGamutCompositionDataspace; + static ui::PixelFormat wideColorGamutCompositionPixelFormat; + + static constexpr SkipInitializationTag SkipInitialization; + static LatchUnsignaledConfig enableLatchUnsignaledConfig; // must be called before clients can connect @@ -231,8 +275,7 @@ public: // Schedule sampling independently from commit or composite. void scheduleSample(); - const surfaceflinger::Config& getConfig() { return *mConfig; } - surfaceflinger::Factory& getFactory() { return *mConfig->factory; } + surfaceflinger::Factory& getFactory() { return mFactory; } // The CompositionEngine encapsulates all composition related interfaces and actions. compositionengine::CompositionEngine& getCompositionEngine() const; @@ -264,6 +307,10 @@ public: return mTransactionCallbackInvoker; } + // If set, disables reusing client composition buffers. This can be set by + // debug.sf.disable_client_composition_cache + bool mDisableClientCompositionCache = false; + // Disables expensive rendering for all displays // This is scheduled on the main thread void disableExpensiveRendering(); @@ -274,6 +321,17 @@ public: // run parallel to the hwc validateDisplay call and re-run if the predition is incorrect. bool mPredictCompositionStrategy = false; + // If true, then any layer with a SMPTE 170M transfer function is decoded using the sRGB + // transfer instead. This is mainly to preserve legacy behavior, where implementations treated + // SMPTE 170M as sRGB prior to color management being implemented, and now implementations rely + // on this behavior to increase contrast for some media sources. + bool mTreat170mAsSrgb = false; + + // Allows to ignore physical orientation provided through hwc API in favour of + // 'ro.surface_flinger.primary_display_orientation'. + // TODO(b/246793311): Clean up a temporary property + bool mIgnoreHwcPhysicalDisplayOrientation = false; + void forceFutureUpdate(int delayInMs); const DisplayDevice* getDisplayFromLayerStack(ui::LayerStack) REQUIRES(mStateLock, kMainThreadContext); @@ -608,6 +666,12 @@ private: // Keeps track of whether the kernel idle timer is currently enabled, so we don't have to // make calls to sys prop each time. bool mKernelIdleTimerEnabled = false; + // Show spinner with refresh rate overlay + bool mRefreshRateOverlaySpinner = false; + // Show render rate with refresh rate overlay + bool mRefreshRateOverlayRenderRate = false; + // Show render rate overlay offseted to the middle of the screen (e.g. for circular displays) + bool mRefreshRateOverlayShowInMiddle = false; void setDesiredActiveMode(display::DisplayModeRequest&&, bool force = false) REQUIRES(mStateLock); @@ -1042,8 +1106,8 @@ private: */ const std::unordered_map& getGenericLayerMetadataKeyMap() const; - int calculateMaxAcquiredBufferCount(Fps refreshRate, - std::chrono::nanoseconds presentLatency) const; + static int calculateMaxAcquiredBufferCount(Fps refreshRate, + std::chrono::nanoseconds presentLatency); int getMaxAcquiredBufferCountForRefreshRate(Fps refreshRate) const; bool isHdrLayer(const frontend::LayerSnapshot& snapshot) const; @@ -1053,7 +1117,8 @@ private: void traverseLegacyLayers(const LayerVector::Visitor& visitor) const; sp mStartPropertySetThread; - surfaceflinger::Config* const mConfig = nullptr; + surfaceflinger::Factory& mFactory; + pid_t mPid; std::future mRenderEnginePrimeCacheFuture; // mStateLock has conventions related to the current thread, because only @@ -1080,6 +1145,12 @@ private: float mGlobalSaturationFactor = 1.0f; mat4 mClientColorMatrix; + size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS; + // If there are more GraphicBufferProducers tracked by SurfaceFlinger than + // this threshold, then begin logging. + size_t mGraphicBufferProducerListSizeLogThreshold = + static_cast(0.95 * static_cast(MAX_LAYERS)); + // protected by mStateLock (but we could use another lock) bool mLayersRemoved = false; bool mLayersAdded = false; @@ -1089,6 +1160,7 @@ private: // constant members (no synchronization needed for access) const nsecs_t mBootTime = systemTime(); + bool mIsUserBuild = true; // Can only accessed from the main thread, these members // don't need synchronization @@ -1100,6 +1172,7 @@ private: // Used to ensure we omit a callback when HDR layer info listener is newly added but the // scene hasn't changed bool mAddingHDRLayerInfoListener = false; + bool mIgnoreHdrCameraLayers = false; // Set during transaction application stage to track if the input info or children // for a layer has changed. @@ -1158,6 +1231,9 @@ private: std::atomic mDebugInTransaction = 0; std::atomic_bool mForceFullDamage = false; + bool mLayerCachingEnabled = false; + bool mBackpressureGpuComposition = false; + LayerTracing mLayerTracing; bool mLayerTracingEnabled = false; @@ -1170,6 +1246,9 @@ private: VsyncId mLastCommittedVsyncId; + // If blurs should be enabled on this device. + bool mSupportsBlur = false; + TransactionCallbackInvoker mTransactionCallbackInvoker; // We maintain a pool of pre-generated texture names to hand out to avoid @@ -1201,9 +1280,13 @@ private: // This property can be used to force SurfaceFlinger to always pick a certain color mode. ui::ColorMode mForceColorMode = ui::ColorMode::NATIVE; - std::optional mOverrideDefaultCompositionDataspace; - std::optional mOverrideWideColorGamutCompositionDataspace; + // Whether to enable wide color gamut (e.g. Display P3) for internal displays that support it. + // If false, wide color modes are filtered out for all internal displays. + bool mSupportsWideColor = false; + ui::Dataspace mDefaultCompositionDataspace; + ui::Dataspace mWideColorGamutCompositionDataspace; + ui::Dataspace mColorSpaceAgnosticDataspace; float mDimmingRatio = -1.f; std::unique_ptr mRenderEngine; @@ -1217,6 +1300,8 @@ private: // any mutex. size_t mMaxRenderTargetSize{1}; + const std::string mHwcServiceName; + /* * Scheduler */ @@ -1233,9 +1318,14 @@ private: // below flags are set by main thread only bool mSetActiveModePending = false; + bool mLumaSampling = true; sp mRegionSamplingThread; sp mFpsReporter; sp mTunnelModeEnabledReporter; + ui::DisplayPrimaries mInternalDisplayPrimaries; + + const float mEmulatedDisplayDensity; + const float mInternalDisplayDensity; // Should only be accessed by the main thread. sp mInputFlinger; @@ -1312,6 +1402,9 @@ private: bool mPowerHintSessionEnabled; + bool mLayerLifecycleManagerEnabled = false; + bool mLegacyFrontEndEnabled = true; + frontend::LayerLifecycleManager mLayerLifecycleManager; frontend::LayerHierarchyBuilder mLayerHierarchyBuilder{{}}; frontend::LayerSnapshotBuilder mLayerSnapshotBuilder; diff --git a/services/surfaceflinger/SurfaceFlingerConfig.cpp b/services/surfaceflinger/SurfaceFlingerConfig.cpp deleted file mode 100644 index 0b25a4462d..0000000000 --- a/services/surfaceflinger/SurfaceFlingerConfig.cpp +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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 - -#include "SurfaceFlingerConfig.h" - -namespace android::surfaceflinger { - -using namespace std::string_literals; - -namespace { - -// TODO(b/141333600): Consolidate with DisplayMode::Builder::getDefaultDensity. -constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV; - -float getDensityFromProperty(const std::string& key, bool required) { - std::string value = base::GetProperty(key, ""s); - const float density = static_cast(std::atof(value.c_str())); - if (density == 0.f && required) { - ALOGE("%s must be defined as a build property", key.c_str()); - return FALLBACK_DENSITY; - } - return density; -} - -} // namespace - -Config::Config() = default; - -Config Config::makeDefault(Factory* factory) { - Config cfg{}; - - // Note: The values set here will affect tests. - // To keep tests hermetic, do not set values here based on runtime values. - - cfg.factory = factory; - cfg.hwcServiceName = "default"s; - cfg.pid = getpid(); // Exception to the hermetic rules. Allow the pid to be cached. - - return cfg; -} - -Config Config::makeProduction(Factory* factory) { - Config cfg = makeDefault(factory); - - cfg.hwcServiceName = base::GetProperty("debug.sf.hwc_service_name"s, "default"s); - - cfg.emulatedDisplayDensity = getDensityFromProperty("qemu.sf.lcd_density"s, false), - cfg.internalDisplayDensity = - getDensityFromProperty("ro.sf.lcd_density"s, cfg.emulatedDisplayDensity == 0.f), - - cfg.hasSyncFramework = sysprop::running_without_sync_framework(cfg.hasSyncFramework); - cfg.dispSyncPresentTimeOffset = - sysprop::present_time_offset_from_vsync_ns(cfg.dispSyncPresentTimeOffset); - cfg.useHwcForRgbToYuv = sysprop::force_hwc_copy_for_virtual_displays(cfg.useHwcForRgbToYuv); - cfg.maxFrameBufferAcquiredBuffers = - sysprop::max_frame_buffer_acquired_buffers(cfg.maxFrameBufferAcquiredBuffers); - cfg.minAcquiredBuffers = sysprop::SurfaceFlingerProperties::min_acquired_buffers().value_or( - cfg.minAcquiredBuffers); - - cfg.maxGraphicsWidth = std::max(static_cast(sysprop::max_graphics_width( - static_cast(cfg.maxGraphicsWidth))), - 0u); - cfg.maxGraphicsHeight = std::max(static_cast(sysprop::max_graphics_height( - static_cast(cfg.maxGraphicsHeight))), - 0u); - - cfg.supportsWideColor = sysprop::has_wide_color_display(cfg.supportsWideColor); - - cfg.defaultCompositionDataspace = static_cast( - sysprop::default_composition_dataspace(cfg.defaultCompositionDataspace)); - cfg.defaultCompositionPixelFormat = static_cast( - sysprop::default_composition_pixel_format(cfg.defaultCompositionPixelFormat)); - - cfg.wideColorGamutCompositionDataspace = - static_cast(sysprop::wcg_composition_dataspace( - cfg.supportsWideColor ? ui::Dataspace::DISPLAY_P3 : ui::Dataspace::V0_SRGB)); - cfg.wideColorGamutCompositionPixelFormat = static_cast( - sysprop::wcg_composition_pixel_format(cfg.wideColorGamutCompositionPixelFormat)); - - cfg.colorSpaceAgnosticDataspace = static_cast( - sysprop::color_space_agnostic_dataspace(cfg.colorSpaceAgnosticDataspace)); - - cfg.internalDisplayPrimaries = sysprop::getDisplayNativePrimaries(); - - cfg.layerCachingEnabled = - base::GetBoolProperty("debug.sf.enable_layer_caching"s, - android::sysprop::SurfaceFlingerProperties::enable_layer_caching() - .value_or(cfg.layerCachingEnabled)); - cfg.useContextPriority = sysprop::use_context_priority(cfg.useContextPriority); - - cfg.isUserBuild = "user"s == base::GetProperty("ro.build.type"s, "user"s); - - cfg.backpressureGpuComposition = base::GetBoolProperty("debug.sf.enable_gl_backpressure"s, - cfg.backpressureGpuComposition); - cfg.supportsBlur = - base::GetBoolProperty("ro.surface_flinger.supports_background_blur"s, cfg.supportsBlur); - - cfg.lumaSampling = base::GetBoolProperty("debug.sf.luma_sampling"s, cfg.lumaSampling); - - cfg.disableClientCompositionCache = - base::GetBoolProperty("debug.sf.disable_client_composition_cache"s, - cfg.disableClientCompositionCache); - - cfg.predictCompositionStrategy = - base::GetBoolProperty("debug.sf.predict_hwc_composition_strategy"s, - cfg.predictCompositionStrategy); - - cfg.treat170mAsSrgb = - base::GetBoolProperty("debug.sf.treat_170m_as_sRGB"s, cfg.treat170mAsSrgb); - - cfg.ignoreHwcPhysicalDisplayOrientation = - base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, - cfg.ignoreHwcPhysicalDisplayOrientation); - - cfg.trebleTestingOverride = - base::GetBoolProperty("debug.sf.treble_testing_override"s, cfg.trebleTestingOverride); - - // TODO (b/270966065) Update the HWC based refresh rate overlay to support spinner - cfg.refreshRateOverlay.showSpinner = - base::GetBoolProperty("debug.sf.show_refresh_rate_overlay_spinner"s, - cfg.refreshRateOverlay.showSpinner); - cfg.refreshRateOverlay.showRenderRate = - base::GetBoolProperty("debug.sf.show_refresh_rate_overlay_render_rate"s, - cfg.refreshRateOverlay.showRenderRate); - cfg.refreshRateOverlay.showInMiddle = - base::GetBoolProperty("debug.sf.show_refresh_rate_overlay_in_middle"s, - cfg.refreshRateOverlay.showInMiddle); - - cfg.ignoreHdrCameraLayers = sysprop::ignore_hdr_camera_layers(cfg.ignoreHdrCameraLayers); - - cfg.enableTransactionTracing = base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, - cfg.enableTransactionTracing); - cfg.layerLifecycleManagerEnabled = - base::GetBoolProperty("persist.debug.sf.enable_layer_lifecycle_manager"s, - cfg.layerLifecycleManagerEnabled); - cfg.legacyFrontEndEnabled = !cfg.layerLifecycleManagerEnabled || - base::GetBoolProperty("persist.debug.sf.enable_legacy_frontend"s, false); - - return cfg; -} - -} // namespace android::surfaceflinger \ No newline at end of file diff --git a/services/surfaceflinger/SurfaceFlingerConfig.h b/services/surfaceflinger/SurfaceFlingerConfig.h deleted file mode 100644 index 7c3348e3bd..0000000000 --- a/services/surfaceflinger/SurfaceFlingerConfig.h +++ /dev/null @@ -1,145 +0,0 @@ -/* - * 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. - */ - -#pragma once - -#include - -#include -#include - -namespace android::surfaceflinger { - -class Factory; - -struct Config final { - Factory* factory = nullptr; - - std::string hwcServiceName; - pid_t pid; - - float emulatedDisplayDensity = 0; - float internalDisplayDensity = 0; - - // If fences from sync Framework are supported. - bool hasSyncFramework = true; - - // The offset in nanoseconds to use when VsyncController timestamps present - // fence signaling time. - int64_t dispSyncPresentTimeOffset = 0; - - // Some hardware can do RGB->YUV conversion more efficiently in hardware - // controlled by HWC than in hardware controlled by the video encoder. This - // instruct VirtualDisplaySurface to use HWC for such conversion on GL - // composition. - bool useHwcForRgbToYuv = false; - - // Controls the number of buffers SurfaceFlinger will allocate for use in - // FramebufferSurface - int64_t maxFrameBufferAcquiredBuffers = 2; - - // Controls the minimum acquired buffers SurfaceFlinger will suggest via - // ISurfaceComposer.getMaxAcquiredBufferCount(). - int64_t minAcquiredBuffers = 1; - - // Controls the maximum width and height in pixels that the graphics - // pipeline can support for GPU fallback composition. For example, 8k - // devices with 4k GPUs, or 4k devices with 2k GPUs. - uint32_t maxGraphicsWidth = 0; - uint32_t maxGraphicsHeight = 0; - - // Whether to enable wide color gamut (e.g. Display P3) for internal - // displays that support it. If false, wide color modes are filtered out - // for all internal displays. - bool mSupportsWideColor = false; - bool supportsWideColor = false; - - // The data space and pixel format that SurfaceFlinger expects hardware - // composer to composite efficiently. Meaning under most scenarios, - // hardware composer will accept layers with the data space and pixel - // format. - ui::Dataspace defaultCompositionDataspace = ui::Dataspace::V0_SRGB; - ui::PixelFormat defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888; - - // The data space and pixel format that SurfaceFlinger expects hardware - // composer to composite efficiently for wide color gamut surfaces. Meaning - // under most scenarios, hardware composer will accept layers with the data - // space and pixel format. - ui::Dataspace wideColorGamutCompositionDataspace = ui::Dataspace::V0_SRGB; - ui::PixelFormat wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888; - - ui::Dataspace colorSpaceAgnosticDataspace = ui::Dataspace::UNKNOWN; - - ui::DisplayPrimaries internalDisplayPrimaries{}; - - bool layerCachingEnabled = false; - bool useContextPriority = true; - bool isUserBuild = true; - bool backpressureGpuComposition = true; - - // If blurs should be enabled on this device. - bool supportsBlur = false; - bool lumaSampling = true; - - // If set, disables reusing client composition buffers. This can be set by - // debug.sf.disable_client_composition_cache - bool disableClientCompositionCache = false; - - // If set, composition engine tries to predict the composition strategy - // provided by HWC based on the previous frame. If the strategy can be - // predicted, gpu composition will run parallel to the hwc validateDisplay - // call and re-run if the predition is incorrect. - bool predictCompositionStrategy = true; - - // If true, then any layer with a SMPTE 170M transfer function is decoded - // using the sRGB transfer instead. This is mainly to preserve legacy - // behavior, where implementations treated SMPTE 170M as sRGB prior to - // color management being implemented, and now implementations rely on this - // behavior to increase contrast for some media sources. - bool treat170mAsSrgb = false; - - // Allows to ignore physical orientation provided through hwc API in favour - // of 'ro.surface_flinger.primary_display_orientation'. - // TODO(b/246793311): Clean up a temporary property - bool ignoreHwcPhysicalDisplayOrientation = false; - - bool trebleTestingOverride = false; - - struct { - // Show spinner with refresh rate overlay - bool showSpinner = false; - - // Show render rate with refresh rate overlay - bool showRenderRate = false; - - // Show render rate overlay offseted to the middle of the screen (e.g. - // for circular displays) - bool showInMiddle = false; - } refreshRateOverlay; - - bool ignoreHdrCameraLayers = false; - bool enableTransactionTracing = true; - bool layerLifecycleManagerEnabled = false; - bool legacyFrontEndEnabled = true; - - static Config makeDefault(Factory* factory); - static Config makeProduction(Factory* factory); - -private: - Config(); -}; - -} // namespace android::surfaceflinger diff --git a/services/surfaceflinger/SurfaceFlingerFactory.cpp b/services/surfaceflinger/SurfaceFlingerFactory.cpp index ac351cb1d7..7bd6cf69f3 100644 --- a/services/surfaceflinger/SurfaceFlingerFactory.cpp +++ b/services/surfaceflinger/SurfaceFlingerFactory.cpp @@ -14,17 +14,22 @@ * 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 "SurfaceFlinger.h" -#include "SurfaceFlingerConfig.h" #include "SurfaceFlingerDefaultFactory.h" namespace android::surfaceflinger { sp createSurfaceFlinger() { static DefaultFactory factory; - static Config config = Config::makeProduction(&factory); - return sp::make(config); + return sp::make(factory); } } // namespace android::surfaceflinger + +// TODO(b/129481165): remove the #pragma below and fix conversion issues +#pragma clang diagnostic pop // ignored "-Wconversion" diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp index d296c47237..9fac14ed4c 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_displayhardware_fuzzer.cpp @@ -481,8 +481,7 @@ void DisplayHardwareFuzzer::invokeFrameBufferSurface() { sp surface = sp::make(mHwc, mPhysicalDisplayId, bqConsumer, - getFuzzedSize() /*size*/, getFuzzedSize() /*maxSize*/, - mFdp.PickValueInArray(kMaxFrameBufferAcquiredBuffers)); + getFuzzedSize() /*size*/, getFuzzedSize() /*maxSize*/); surface->beginFrame(mFdp.ConsumeBool()); surface->prepareFrame(mFdp.PickValueInArray(kCompositionTypes)); @@ -516,8 +515,7 @@ void DisplayHardwareFuzzer::invokeVirtualDisplaySurface() { auto surface = sp::make(mHwc, VirtualDisplayId, sink, bqProducer, bqConsumer, - mFdp.ConsumeRandomLengthString().c_str() /*name*/, - mFdp.ConsumeBool() /* useHwcForRgbToYuv */); + mFdp.ConsumeRandomLengthString().c_str() /*name*/); surface->beginFrame(mFdp.ConsumeBool()); surface->prepareFrame(mFdp.PickValueInArray(kCompositionTypes)); diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp index df342dcd8e..80943b5b63 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzer.cpp @@ -124,20 +124,19 @@ void SurfaceFlingerFuzzer::invokeFlinger() { mFlinger->setSchedFifo(mFdp.ConsumeBool()); mFlinger->setSchedAttr(mFdp.ConsumeBool()); mFlinger->getServiceName(); - - auto& config = mTestableFlinger.mutableConfig(); - config.hasSyncFramework = mFdp.ConsumeBool(); - config.dispSyncPresentTimeOffset = mFdp.ConsumeIntegral(); - config.useHwcForRgbToYuv = mFdp.ConsumeBool(); - config.maxFrameBufferAcquiredBuffers = mFdp.ConsumeIntegral(); - config.maxGraphicsWidth = mFdp.ConsumeIntegral(); - config.maxGraphicsHeight = mFdp.ConsumeIntegral(); - config.supportsWideColor = mFdp.ConsumeBool(); - config.useContextPriority = mFdp.ConsumeBool(); - config.defaultCompositionDataspace = mFdp.PickValueInArray(kDataspaces); - config.defaultCompositionPixelFormat = mFdp.PickValueInArray(kPixelFormats); - config.wideColorGamutCompositionDataspace = mFdp.PickValueInArray(kDataspaces); - config.wideColorGamutCompositionPixelFormat = mFdp.PickValueInArray(kPixelFormats); + mFlinger->hasSyncFramework = mFdp.ConsumeBool(); + mFlinger->dispSyncPresentTimeOffset = mFdp.ConsumeIntegral(); + mFlinger->useHwcForRgbToYuv = mFdp.ConsumeBool(); + mFlinger->maxFrameBufferAcquiredBuffers = mFdp.ConsumeIntegral(); + mFlinger->maxGraphicsWidth = mFdp.ConsumeIntegral(); + mFlinger->maxGraphicsHeight = mFdp.ConsumeIntegral(); + mTestableFlinger.mutableSupportsWideColor() = mFdp.ConsumeBool(); + mFlinger->useContextPriority = mFdp.ConsumeBool(); + + mFlinger->defaultCompositionDataspace = mFdp.PickValueInArray(kDataspaces); + mFlinger->defaultCompositionPixelFormat = mFdp.PickValueInArray(kPixelFormats); + mFlinger->wideColorGamutCompositionDataspace = mFdp.PickValueInArray(kDataspaces); + mFlinger->wideColorGamutCompositionPixelFormat = mFdp.PickValueInArray(kPixelFormats); mFlinger->enableLatchUnsignaledConfig = mFdp.PickValueInArray(kLatchUnsignaledConfig); @@ -156,7 +155,7 @@ void SurfaceFlingerFuzzer::invokeFlinger() { } void SurfaceFlingerFuzzer::setInternalDisplayPrimaries() { - auto& primaries = mTestableFlinger.mutableConfig().internalDisplayPrimaries; + ui::DisplayPrimaries primaries; primaries.red.X = mFdp.ConsumeFloatingPoint(); primaries.red.Y = mFdp.ConsumeFloatingPoint(); primaries.red.Z = mFdp.ConsumeFloatingPoint(); @@ -169,6 +168,7 @@ void SurfaceFlingerFuzzer::setInternalDisplayPrimaries() { primaries.white.X = mFdp.ConsumeFloatingPoint(); primaries.white.Y = mFdp.ConsumeFloatingPoint(); primaries.white.Z = mFdp.ConsumeFloatingPoint(); + mTestableFlinger.setInternalDisplayPrimaries(primaries); } void SurfaceFlingerFuzzer::setTransactionState() { diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h index 97cb5d35e3..0c9a16bee3 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h +++ b/services/surfaceflinger/fuzzer/surfaceflinger_fuzzers_utils.h @@ -46,7 +46,6 @@ #include "Scheduler/VsyncModulator.h" #include "StartPropertySetThread.h" #include "SurfaceFlinger.h" -#include "SurfaceFlingerConfig.h" #include "SurfaceFlingerDefaultFactory.h" #include "ThreadContext.h" #include "TimeStats/TimeStats.h" @@ -151,8 +150,6 @@ static constexpr ui::PixelFormat kPixelFormats[] = {ui::PixelFormat::RGBA_8888, ui::PixelFormat::YCBCR_P010, ui::PixelFormat::HSV_888}; -static constexpr int kMaxFrameBufferAcquiredBuffers[] = {2, 3, 4}; - inline VsyncId getFuzzedVsyncId(FuzzedDataProvider& fdp) { return VsyncId{fdp.ConsumeIntegral()}; } @@ -407,8 +404,6 @@ public: SurfaceFlinger *flinger() { return mFlinger.get(); } scheduler::TestableScheduler *scheduler() { return mScheduler; } - auto& mutableConfig() { return mConfig; } - void initializeDisplays() { FTL_FAKE_GUARD(kMainThreadContext, mFlinger->initializeDisplays()); } @@ -700,6 +695,10 @@ public: mFactory.mCreateNativeWindowSurface = f; } + void setInternalDisplayPrimaries(const ui::DisplayPrimaries &primaries) { + memcpy(&mFlinger->mInternalDisplayPrimaries, &primaries, sizeof(ui::DisplayPrimaries)); + } + static auto &mutableLayerDrawingState(const sp &layer) { return layer->mDrawingState; } auto &mutableStateLock() { return mFlinger->mStateLock; } @@ -765,12 +764,13 @@ public: auto calculateMaxAcquiredBufferCount(Fps refreshRate, std::chrono::nanoseconds presentLatency) const { - return mFlinger->calculateMaxAcquiredBufferCount(refreshRate, presentLatency); + return SurfaceFlinger::calculateMaxAcquiredBufferCount(refreshRate, presentLatency); } /* 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; } @@ -794,8 +794,8 @@ private: void triggerOnFrameRateOverridesChanged() override {} surfaceflinger::test::Factory mFactory; - surfaceflinger::Config mConfig = surfaceflinger::Config::makeDefault(&mFactory); - sp mFlinger = sp::make(mConfig); + sp mFlinger = + sp::make(mFactory, SurfaceFlinger::SkipInitialization); scheduler::TestableScheduler *mScheduler = nullptr; std::shared_ptr mRefreshRateSelector; }; diff --git a/services/surfaceflinger/fuzzer/surfaceflinger_service_fuzzer.cpp b/services/surfaceflinger/fuzzer/surfaceflinger_service_fuzzer.cpp index c16a005f0d..849a896ce2 100644 --- a/services/surfaceflinger/fuzzer/surfaceflinger_service_fuzzer.cpp +++ b/services/surfaceflinger/fuzzer/surfaceflinger_service_fuzzer.cpp @@ -17,15 +17,13 @@ #include #include "SurfaceFlinger.h" -#include "SurfaceFlingerConfig.h" #include "SurfaceFlingerDefaultFactory.h" using namespace android; extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { DefaultFactory factory; - surfaceflinger::Config config = surfaceflinger::Config::makeDefault(&factory); - sp flinger = sp::make(config); + sp flinger = sp::make(factory); flinger->init(); sp composerAIDL = sp::make(flinger); diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp index 7124f879e9..e32cf8863b 100644 --- a/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp +++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTest.cpp @@ -34,7 +34,7 @@ DisplayTransactionTest::DisplayTransactionTest(bool withMockScheduler) { ::testing::UnitTest::GetInstance()->current_test_info(); ALOGD("**** Setting up for %s.%s\n", test_info->test_case_name(), test_info->name()); - mFlinger.mutableConfig().supportsWideColor = false; + mFlinger.mutableSupportsWideColor() = false; mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::kUnmanaged; mFlinger.setCreateBufferQueueFunction([](auto, auto, auto) { diff --git a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h index 5599a7a600..ee12276994 100644 --- a/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h +++ b/services/surfaceflinger/tests/unittests/DisplayTransactionTestHelpers.h @@ -684,7 +684,7 @@ struct WideColorNotSupportedVariant { static constexpr bool WIDE_COLOR_SUPPORTED = false; static void injectConfigChange(DisplayTransactionTest* test) { - test->mFlinger.mutableConfig().supportsWideColor = true; + test->mFlinger.mutableSupportsWideColor() = true; } static void setupComposerCallExpectations(DisplayTransactionTest* test) { @@ -699,7 +699,7 @@ struct WideColorSupportNotConfiguredVariant { static constexpr bool WIDE_COLOR_SUPPORTED = false; static void injectConfigChange(DisplayTransactionTest* test) { - test->mFlinger.mutableConfig().supportsWideColor = false; + test->mFlinger.mutableSupportsWideColor() = false; test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::kUnmanaged; } diff --git a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp index 6c14f6e1c1..fab3c0e887 100644 --- a/services/surfaceflinger/tests/unittests/SchedulerTest.cpp +++ b/services/surfaceflinger/tests/unittests/SchedulerTest.cpp @@ -250,8 +250,10 @@ TEST_F(SchedulerTest, calculateMaxAcquiredBufferCount) { EXPECT_EQ(1, mFlinger.calculateMaxAcquiredBufferCount(60_Hz, 10ms)); - mFlinger.mutableConfig().minAcquiredBuffers = 2; + const auto savedMinAcquiredBuffers = mFlinger.mutableMinAcquiredBuffers(); + mFlinger.mutableMinAcquiredBuffers() = 2; EXPECT_EQ(2, mFlinger.calculateMaxAcquiredBufferCount(60_Hz, 10ms)); + mFlinger.mutableMinAcquiredBuffers() = savedMinAcquiredBuffers; } MATCHER(Is120Hz, "") { diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp index fe383846d1..5951c9893f 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_GetDisplayNativePrimariesTest.cpp @@ -84,7 +84,9 @@ TEST_F(GetDisplayNativePrimaries, internalDisplayWithPrimariesData) { injector.inject(); auto internalDisplayToken = injector.token(); - populateDummyDisplayNativePrimaries(mFlinger.mutableConfig().internalDisplayPrimaries); + ui::DisplayPrimaries expectedPrimaries; + populateDummyDisplayNativePrimaries(expectedPrimaries); + mFlinger.setInternalDisplayPrimaries(expectedPrimaries); ui::DisplayPrimaries primaries; EXPECT_EQ(NO_ERROR, mFlinger.getDisplayNativePrimaries(internalDisplayToken, primaries)); diff --git a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp index 61891c14c7..c0796df6cb 100644 --- a/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp +++ b/services/surfaceflinger/tests/unittests/SurfaceFlinger_SetupNewDisplayDeviceInternalTest.cpp @@ -36,7 +36,7 @@ struct WideColorP3ColorimetricSupportedVariant { static constexpr bool WIDE_COLOR_SUPPORTED = true; static void injectConfigChange(DisplayTransactionTest* test) { - test->mFlinger.mutableConfig().supportsWideColor = true; + test->mFlinger.mutableSupportsWideColor() = true; test->mFlinger.mutableDisplayColorSetting() = DisplayColorSetting::kUnmanaged; } diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index 099abf59b4..156c40a721 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -45,8 +45,6 @@ #include "Scheduler/RefreshRateSelector.h" #include "StartPropertySetThread.h" #include "SurfaceFlinger.h" -#include "SurfaceFlingerConfig.h" -#include "SurfaceFlingerDefaultFactory.h" #include "TestableScheduler.h" #include "mock/DisplayHardware/MockComposer.h" #include "mock/DisplayHardware/MockDisplayMode.h" @@ -170,15 +168,13 @@ public: TestableSurfaceFlinger(sp flinger = nullptr) : mFlinger(flinger) { if (!mFlinger) { - mFlinger = sp::make(mConfig); + mFlinger = sp::make(mFactory, SurfaceFlinger::SkipInitialization); } } SurfaceFlinger* flinger() { return mFlinger.get(); } scheduler::TestableScheduler* scheduler() { return mScheduler; } - auto& mutableConfig() { return mConfig; } - // Extend this as needed for accessing SurfaceFlinger private (and public) // functions. @@ -316,6 +312,10 @@ public: mFactory.mCreateNativeWindowSurface = f; } + void setInternalDisplayPrimaries(const ui::DisplayPrimaries& primaries) { + memcpy(&mFlinger->mInternalDisplayPrimaries, &primaries, sizeof(ui::DisplayPrimaries)); + } + static auto& mutableLayerDrawingState(const sp& layer) { return layer->mDrawingState; } auto& mutableStateLock() { return mFlinger->mStateLock; } @@ -513,7 +513,7 @@ public: auto calculateMaxAcquiredBufferCount(Fps refreshRate, std::chrono::nanoseconds presentLatency) const { - return mFlinger->calculateMaxAcquiredBufferCount(refreshRate, presentLatency); + return SurfaceFlinger::calculateMaxAcquiredBufferCount(refreshRate, presentLatency); } auto setDesiredDisplayModeSpecs(const sp& displayToken, @@ -596,6 +596,8 @@ public: const auto& hwcPhysicalDisplayIdMap() const { return getHwComposer().mPhysicalDisplayIdMap; } const auto& hwcDisplayData() const { return getHwComposer().mDisplayData; } + auto& mutableSupportsWideColor() { return mFlinger->mSupportsWideColor; } + auto& mutableCurrentState() { return mFlinger->mCurrentState; } auto& mutableDisplayColorSetting() { return mFlinger->mDisplayColorSetting; } auto& mutableDisplays() { return mFlinger->mDisplays; } @@ -620,6 +622,8 @@ public: return SurfaceFlinger::sActiveDisplayRotationFlags; } + auto& mutableMinAcquiredBuffers() { return SurfaceFlinger::minAcquiredBuffers; } + auto fromHandle(const sp& handle) { return LayerHandle::getLayer(handle); } ~TestableSurfaceFlinger() { @@ -1004,7 +1008,6 @@ private: static constexpr VsyncId kVsyncId{123}; surfaceflinger::test::Factory mFactory; - surfaceflinger::Config mConfig = surfaceflinger::Config::makeDefault(&mFactory); sp mFlinger; scheduler::mock::SchedulerCallback mSchedulerCallback; scheduler::mock::NoOpSchedulerCallback mNoOpSchedulerCallback; -- cgit v1.2.3-59-g8ed1b From 70a63e5f65891c9d22d1a554ed4bda11b16f48ba Mon Sep 17 00:00:00 2001 From: Melody Hsu Date: Fri, 17 Nov 2023 19:49:12 +0000 Subject: Remove useIdentityTransform from DisplayCaptureArgs. Screenshots do not set useIdentityTransfrom to true with a rotated display. The default value is false in SurfaceFlinger and is not relevant for captureLayers, which is the API that will be used for screenshots going forward. Rotation flags are no longer relevant in DisplayRenderArea and rotation values can be simplified to 0 rotation by default. Bug: 293445881 Test: atest LayerStateTest Test: presubmit Change-Id: Id0cce05458c3daa4078097057f00fd856df1e092 --- libs/gui/LayerState.cpp | 2 -- libs/gui/include/gui/DisplayCaptureArgs.h | 1 - services/surfaceflinger/DisplayRenderArea.cpp | 33 +++-------------------- services/surfaceflinger/DisplayRenderArea.h | 4 +-- services/surfaceflinger/RegionSamplingThread.cpp | 4 +-- services/surfaceflinger/RenderArea.h | 10 +------ services/surfaceflinger/ScreenCaptureOutput.cpp | 26 +++--------------- services/surfaceflinger/SurfaceFlinger.cpp | 4 +-- services/surfaceflinger/tests/LayerState_test.cpp | 2 -- 9 files changed, 12 insertions(+), 74 deletions(-) (limited to 'services/surfaceflinger/RegionSamplingThread.cpp') diff --git a/libs/gui/LayerState.cpp b/libs/gui/LayerState.cpp index fd8fc8d123..7dea38e4cc 100644 --- a/libs/gui/LayerState.cpp +++ b/libs/gui/LayerState.cpp @@ -930,7 +930,6 @@ status_t DisplayCaptureArgs::writeToParcel(Parcel* output) const { SAFE_PARCEL(output->writeStrongBinder, displayToken); SAFE_PARCEL(output->writeUint32, width); SAFE_PARCEL(output->writeUint32, height); - SAFE_PARCEL(output->writeBool, useIdentityTransform); return NO_ERROR; } @@ -940,7 +939,6 @@ status_t DisplayCaptureArgs::readFromParcel(const Parcel* input) { SAFE_PARCEL(input->readStrongBinder, &displayToken); SAFE_PARCEL(input->readUint32, &width); SAFE_PARCEL(input->readUint32, &height); - SAFE_PARCEL(input->readBool, &useIdentityTransform); return NO_ERROR; } diff --git a/libs/gui/include/gui/DisplayCaptureArgs.h b/libs/gui/include/gui/DisplayCaptureArgs.h index 2676e0a338..e29ce41bd5 100644 --- a/libs/gui/include/gui/DisplayCaptureArgs.h +++ b/libs/gui/include/gui/DisplayCaptureArgs.h @@ -76,7 +76,6 @@ struct DisplayCaptureArgs : CaptureArgs { sp displayToken; uint32_t width{0}; uint32_t height{0}; - bool useIdentityTransform{false}; status_t writeToParcel(Parcel* output) const override; status_t readFromParcel(const Parcel* input) override; diff --git a/services/surfaceflinger/DisplayRenderArea.cpp b/services/surfaceflinger/DisplayRenderArea.cpp index e55cd3ea42..55b395b458 100644 --- a/services/surfaceflinger/DisplayRenderArea.cpp +++ b/services/surfaceflinger/DisplayRenderArea.cpp @@ -18,41 +18,26 @@ #include "DisplayDevice.h" namespace android { -namespace { - -RenderArea::RotationFlags applyDeviceOrientation(bool useIdentityTransform, - const DisplayDevice& display) { - if (!useIdentityTransform) { - return RenderArea::RotationFlags::ROT_0; - } - - return ui::Transform::toRotationFlags(display.getOrientation()); -} - -} // namespace std::unique_ptr DisplayRenderArea::create(wp displayWeak, const Rect& sourceCrop, ui::Size reqSize, ui::Dataspace reqDataSpace, - bool useIdentityTransform, bool hintForSeamlessTransition, bool allowSecureLayers) { if (auto display = displayWeak.promote()) { // Using new to access a private constructor. return std::unique_ptr( new DisplayRenderArea(std::move(display), sourceCrop, reqSize, reqDataSpace, - useIdentityTransform, hintForSeamlessTransition, - allowSecureLayers)); + hintForSeamlessTransition, allowSecureLayers)); } return nullptr; } DisplayRenderArea::DisplayRenderArea(sp display, const Rect& sourceCrop, ui::Size reqSize, ui::Dataspace reqDataSpace, - bool useIdentityTransform, bool hintForSeamlessTransition, - bool allowSecureLayers) + bool hintForSeamlessTransition, bool allowSecureLayers) : RenderArea(reqSize, CaptureFill::OPAQUE, reqDataSpace, hintForSeamlessTransition, - allowSecureLayers, applyDeviceOrientation(useIdentityTransform, *display)), + allowSecureLayers), mDisplay(std::move(display)), mSourceCrop(sourceCrop) {} @@ -73,17 +58,7 @@ Rect DisplayRenderArea::getSourceCrop() const { if (mSourceCrop.isEmpty()) { return mDisplay->getLayerStackSpaceRect(); } - - // Correct for the orientation when the screen capture request contained - // useIdentityTransform. This will cause the rotation flag to be non 0 since - // it needs to rotate based on the screen orientation to allow the screenshot - // to be taken in the ROT_0 orientation - const auto flags = getRotationFlags(); - int width = mDisplay->getLayerStackSpaceRect().getWidth(); - int height = mDisplay->getLayerStackSpaceRect().getHeight(); - ui::Transform rotation; - rotation.set(flags, width, height); - return rotation.transform(mSourceCrop); + return mSourceCrop; } } // namespace android diff --git a/services/surfaceflinger/DisplayRenderArea.h b/services/surfaceflinger/DisplayRenderArea.h index 9a4981c881..4555a9ed66 100644 --- a/services/surfaceflinger/DisplayRenderArea.h +++ b/services/surfaceflinger/DisplayRenderArea.h @@ -29,7 +29,6 @@ class DisplayRenderArea : public RenderArea { public: static std::unique_ptr create(wp, const Rect& sourceCrop, ui::Size reqSize, ui::Dataspace, - bool useIdentityTransform, bool hintForSeamlessTransition, bool allowSecureLayers = true); @@ -40,8 +39,7 @@ public: private: DisplayRenderArea(sp, const Rect& sourceCrop, ui::Size reqSize, - ui::Dataspace, bool useIdentityTransform, bool hintForSeamlessTransition, - bool allowSecureLayers = true); + ui::Dataspace, bool hintForSeamlessTransition, bool allowSecureLayers = true); const sp mDisplay; const Rect mSourceCrop; diff --git a/services/surfaceflinger/RegionSamplingThread.cpp b/services/surfaceflinger/RegionSamplingThread.cpp index 8f658d5a09..6db39f143f 100644 --- a/services/surfaceflinger/RegionSamplingThread.cpp +++ b/services/surfaceflinger/RegionSamplingThread.cpp @@ -276,13 +276,11 @@ void RegionSamplingThread::captureSample() { } const Rect sampledBounds = sampleRegion.bounds(); - constexpr bool kUseIdentityTransform = false; constexpr bool kHintForSeamlessTransition = false; SurfaceFlinger::RenderAreaFuture renderAreaFuture = ftl::defer([=] { return DisplayRenderArea::create(displayWeak, sampledBounds, sampledBounds.getSize(), - ui::Dataspace::V0_SRGB, kUseIdentityTransform, - kHintForSeamlessTransition); + ui::Dataspace::V0_SRGB, kHintForSeamlessTransition); }); std::unordered_set, SpHash> listeners; diff --git a/services/surfaceflinger/RenderArea.h b/services/surfaceflinger/RenderArea.h index 71b85bd3b2..5de148e3bd 100644 --- a/services/surfaceflinger/RenderArea.h +++ b/services/surfaceflinger/RenderArea.h @@ -18,20 +18,16 @@ class DisplayDevice; // physical render area. class RenderArea { public: - using RotationFlags = ui::Transform::RotationFlags; - enum class CaptureFill {CLEAR, OPAQUE}; static float getCaptureFillValue(CaptureFill captureFill); RenderArea(ui::Size reqSize, CaptureFill captureFill, ui::Dataspace reqDataSpace, - bool hintForSeamlessTransition, bool allowSecureLayers = false, - RotationFlags rotation = ui::Transform::ROT_0) + bool hintForSeamlessTransition, bool allowSecureLayers = false) : mAllowSecureLayers(allowSecureLayers), mReqSize(reqSize), mReqDataSpace(reqDataSpace), mCaptureFill(captureFill), - mRotationFlags(rotation), mHintForSeamlessTransition(hintForSeamlessTransition) {} static std::function>>()> fromTraverseLayersLambda( @@ -72,9 +68,6 @@ public: // on the display). virtual Rect getSourceCrop() const = 0; - // Returns the rotation of the source crop and the layers. - RotationFlags getRotationFlags() const { return mRotationFlags; } - // Returns the size of the physical render area. int getReqWidth() const { return mReqSize.width; } int getReqHeight() const { return mReqSize.height; } @@ -103,7 +96,6 @@ private: const ui::Size mReqSize; const ui::Dataspace mReqDataSpace; const CaptureFill mCaptureFill; - const RotationFlags mRotationFlags; const bool mHintForSeamlessTransition; }; diff --git a/services/surfaceflinger/ScreenCaptureOutput.cpp b/services/surfaceflinger/ScreenCaptureOutput.cpp index ef9b457fc9..57b0d5e0ea 100644 --- a/services/surfaceflinger/ScreenCaptureOutput.cpp +++ b/services/surfaceflinger/ScreenCaptureOutput.cpp @@ -16,6 +16,7 @@ #include "ScreenCaptureOutput.h" #include "ScreenCaptureRenderSurface.h" +#include "ui/Rotation.h" #include #include @@ -24,24 +25,6 @@ namespace android { -namespace { - -ui::Size getDisplaySize(ui::Rotation orientation, const Rect& sourceCrop) { - if (orientation == ui::Rotation::Rotation90 || orientation == ui::Rotation::Rotation270) { - return {sourceCrop.getHeight(), sourceCrop.getWidth()}; - } - return {sourceCrop.getWidth(), sourceCrop.getHeight()}; -} - -Rect getOrientedDisplaySpaceRect(ui::Rotation orientation, int reqWidth, int reqHeight) { - if (orientation == ui::Rotation::Rotation90 || orientation == ui::Rotation::Rotation270) { - return {reqHeight, reqWidth}; - } - return {reqWidth, reqHeight}; -} - -} // namespace - std::shared_ptr createScreenCaptureOutput(ScreenCaptureOutputArgs args) { std::shared_ptr output = compositionengine::impl::createOutputTemplated< ScreenCaptureOutput, compositionengine::CompositionEngine, const RenderArea&, @@ -62,11 +45,10 @@ std::shared_ptr createScreenCaptureOutput(ScreenCaptureOutp .Build())); const Rect& sourceCrop = args.renderArea.getSourceCrop(); - const ui::Rotation orientation = ui::Transform::toRotation(args.renderArea.getRotationFlags()); - output->setDisplaySize(getDisplaySize(orientation, sourceCrop)); + const ui::Rotation orientation = ui::ROTATION_0; + output->setDisplaySize({sourceCrop.getWidth(), sourceCrop.getHeight()}); output->setProjection(orientation, sourceCrop, - getOrientedDisplaySpaceRect(orientation, args.renderArea.getReqWidth(), - args.renderArea.getReqHeight())); + {args.renderArea.getReqWidth(), args.renderArea.getReqHeight()}); { std::string name = args.regionSampling ? "RegionSampling" : "ScreenCaptureOutput"; diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 644b6ef30e..bd70791c31 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -7559,8 +7559,7 @@ void SurfaceFlinger::captureDisplay(const DisplayCaptureArgs& args, RenderAreaFuture renderAreaFuture = ftl::defer([=] { return DisplayRenderArea::create(displayWeak, args.sourceCrop, reqSize, args.dataspace, - args.useIdentityTransform, args.hintForSeamlessTransition, - args.captureSecureLayers); + args.hintForSeamlessTransition, args.captureSecureLayers); }); GetLayerSnapshotsFunction getLayerSnapshots; @@ -7613,7 +7612,6 @@ void SurfaceFlinger::captureDisplay(DisplayId displayId, const CaptureArgs& args RenderAreaFuture renderAreaFuture = ftl::defer([=] { return DisplayRenderArea::create(displayWeak, Rect(), size, args.dataspace, - false /* useIdentityTransform */, args.hintForSeamlessTransition, false /* captureSecureLayers */); }); diff --git a/services/surfaceflinger/tests/LayerState_test.cpp b/services/surfaceflinger/tests/LayerState_test.cpp index 21813700a2..15a98df275 100644 --- a/services/surfaceflinger/tests/LayerState_test.cpp +++ b/services/surfaceflinger/tests/LayerState_test.cpp @@ -38,7 +38,6 @@ TEST(LayerStateTest, ParcellingDisplayCaptureArgs) { args.displayToken = sp::make(); args.width = 10; args.height = 20; - args.useIdentityTransform = true; args.grayscale = true; Parcel p; @@ -56,7 +55,6 @@ TEST(LayerStateTest, ParcellingDisplayCaptureArgs) { ASSERT_EQ(args.displayToken, args2.displayToken); ASSERT_EQ(args.width, args2.width); ASSERT_EQ(args.height, args2.height); - ASSERT_EQ(args.useIdentityTransform, args2.useIdentityTransform); ASSERT_EQ(args.grayscale, args2.grayscale); } -- cgit v1.2.3-59-g8ed1b From 18fa7c60ccd9697973308fce60482e67dee58d98 Mon Sep 17 00:00:00 2001 From: Chavi Weingarten Date: Tue, 28 Nov 2023 21:16:03 +0000 Subject: Add isProtected flag to Output Allow outputs to decide if they want to render protected content, not just if they support it. The current code checks if the Output is secure when deciding whether to render protected content. By adding a new flag, it will allow displays to decide if they want to render secure, protected, or both. This code doesn't have a way to create displays with only protected and will still rely on the isSecure flag to ensure backwards compatibility. Test: presubmit Fixes: 285553970 Fixes: 300492271 Change-Id: If5e65388825d37f4ddaea5190259a136cfa89264 --- .../compositionengine/DisplayCreationArgs.h | 9 ++++++ .../include/compositionengine/LayerFE.h | 7 ++--- .../impl/OutputCompositionState.h | 3 ++ .../CompositionEngine/src/Display.cpp | 1 + .../CompositionEngine/src/Output.cpp | 22 ++++++++++---- .../CompositionEngine/src/planner/CachedSet.cpp | 2 +- services/surfaceflinger/DisplayDevice.cpp | 1 + services/surfaceflinger/DisplayDevice.h | 2 ++ services/surfaceflinger/LayerFE.cpp | 12 ++++++-- services/surfaceflinger/RegionSamplingThread.cpp | 3 +- services/surfaceflinger/ScreenCaptureOutput.cpp | 1 + services/surfaceflinger/ScreenCaptureOutput.h | 1 + services/surfaceflinger/SurfaceFlinger.cpp | 34 +++++++++++++--------- services/surfaceflinger/SurfaceFlinger.h | 4 +-- services/surfaceflinger/common/FlagManager.cpp | 2 ++ .../common/include/common/FlagManager.h | 1 + .../surfaceflinger/surfaceflinger_flags.aconfig | 8 +++++ .../tests/unittests/TestableSurfaceFlinger.h | 3 +- 18 files changed, 86 insertions(+), 30 deletions(-) (limited to 'services/surfaceflinger/RegionSamplingThread.cpp') diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h index 98c4af487e..6e60839dd9 100644 --- a/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h +++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/DisplayCreationArgs.h @@ -42,6 +42,10 @@ struct DisplayCreationArgs { // True if this display should be considered secure bool isSecure = false; + // True if this display should be considered protected, as in this display should render DRM + // content. + bool isProtected = false; + // Optional pointer to the power advisor interface, if one is needed for // this display. Hwc2::PowerAdvisor* powerAdvisor = nullptr; @@ -73,6 +77,11 @@ public: return *this; } + DisplayCreationArgsBuilder& setIsProtected(bool isProtected) { + mArgs.isProtected = isProtected; + return *this; + } + DisplayCreationArgsBuilder& setPowerAdvisor(Hwc2::PowerAdvisor* powerAdvisor) { mArgs.powerAdvisor = powerAdvisor; return *this; diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h index ccff1eccb6..a1d61323a8 100644 --- a/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h +++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/LayerFE.h @@ -97,7 +97,7 @@ public: const bool isSecure; // If set to true, the target buffer has protected content support. - const bool supportsProtectedContent; + const bool isProtected; // Viewport of the target being rendered to. This is used to determine // the shadow light position. @@ -167,8 +167,7 @@ using LayerFESet = std::unordered_set, LayerFESpHash>; static inline bool operator==(const LayerFE::ClientCompositionTargetSettings& lhs, const LayerFE::ClientCompositionTargetSettings& rhs) { return lhs.clip.hasSameRects(rhs.clip) && lhs.needsFiltering == rhs.needsFiltering && - lhs.isSecure == rhs.isSecure && - lhs.supportsProtectedContent == rhs.supportsProtectedContent && + lhs.isSecure == rhs.isSecure && lhs.isProtected == rhs.isProtected && lhs.viewport == rhs.viewport && lhs.dataspace == rhs.dataspace && lhs.realContentIsVisible == rhs.realContentIsVisible && lhs.clearContent == rhs.clearContent; @@ -189,7 +188,7 @@ static inline void PrintTo(const LayerFE::ClientCompositionTargetSettings& setti PrintTo(settings.clip, os); *os << "\n .needsFiltering = " << settings.needsFiltering; *os << "\n .isSecure = " << settings.isSecure; - *os << "\n .supportsProtectedContent = " << settings.supportsProtectedContent; + *os << "\n .isProtected = " << settings.isProtected; *os << "\n .viewport = "; PrintTo(settings.viewport, os); *os << "\n .dataspace = "; diff --git a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputCompositionState.h b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputCompositionState.h index 692ed24899..6b1c318d1c 100644 --- a/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputCompositionState.h +++ b/services/surfaceflinger/CompositionEngine/include/compositionengine/impl/OutputCompositionState.h @@ -53,6 +53,9 @@ struct OutputCompositionState { // If false, this output is not considered secure bool isSecure{false}; + // If false, this output is not considered protected + bool isProtected{false}; + // If true, the current frame on this output uses client composition bool usesClientComposition{false}; diff --git a/services/surfaceflinger/CompositionEngine/src/Display.cpp b/services/surfaceflinger/CompositionEngine/src/Display.cpp index 0475881bae..690d35f068 100644 --- a/services/surfaceflinger/CompositionEngine/src/Display.cpp +++ b/services/surfaceflinger/CompositionEngine/src/Display.cpp @@ -57,6 +57,7 @@ void Display::setConfiguration(const compositionengine::DisplayCreationArgs& arg mId = args.id; mPowerAdvisor = args.powerAdvisor; editState().isSecure = args.isSecure; + editState().isProtected = args.isProtected; editState().displaySpace.setBounds(args.pixels); setName(args.name); } diff --git a/services/surfaceflinger/CompositionEngine/src/Output.cpp b/services/surfaceflinger/CompositionEngine/src/Output.cpp index e4d757810a..c399224491 100644 --- a/services/surfaceflinger/CompositionEngine/src/Output.cpp +++ b/services/surfaceflinger/CompositionEngine/src/Output.cpp @@ -1232,10 +1232,18 @@ void Output::updateProtectedContentState() { auto& renderEngine = getCompositionEngine().getRenderEngine(); const bool supportsProtectedContent = renderEngine.supportsProtectedContent(); - // If we the display is secure, protected content support is enabled, and at - // least one layer has protected content, we need to use a secure back - // buffer. - if (outputState.isSecure && supportsProtectedContent) { + bool isProtected; + if (FlagManager::getInstance().display_protected()) { + isProtected = outputState.isProtected; + } else { + isProtected = outputState.isSecure; + } + + // We need to set the render surface as protected (DRM) if all the following conditions are met: + // 1. The display is protected (in legacy, check if the display is secure) + // 2. Protected content is supported + // 3. At least one layer has protected content. + if (isProtected && supportsProtectedContent) { auto layers = getOutputLayersOrderedByZ(); bool needsProtected = std::any_of(layers.begin(), layers.end(), [](auto* layer) { return layer->getLayerFE().getCompositionState()->hasProtectedContent; @@ -1475,12 +1483,16 @@ std::vector Output::generateClientCompositionRequests( BlurRegionsOnly : LayerFE::ClientCompositionTargetSettings::BlurSetting:: Enabled); + bool isProtected = supportsProtectedContent; + if (FlagManager::getInstance().display_protected()) { + isProtected = outputState.isProtected && supportsProtectedContent; + } compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{.clip = clip, .needsFiltering = layer->needsFiltering() || outputState.needsFiltering, .isSecure = outputState.isSecure, - .supportsProtectedContent = supportsProtectedContent, + .isProtected = isProtected, .viewport = outputState.layerStackSpace.getContent(), .dataspace = outputDataspace, .realContentIsVisible = realContentIsVisible, diff --git a/services/surfaceflinger/CompositionEngine/src/planner/CachedSet.cpp b/services/surfaceflinger/CompositionEngine/src/planner/CachedSet.cpp index 579c6ba772..869dda61bb 100644 --- a/services/surfaceflinger/CompositionEngine/src/planner/CachedSet.cpp +++ b/services/surfaceflinger/CompositionEngine/src/planner/CachedSet.cpp @@ -184,7 +184,7 @@ void CachedSet::render(renderengine::RenderEngine& renderEngine, TexturePool& te targetSettings{.clip = Region(viewport), .needsFiltering = false, .isSecure = outputState.isSecure, - .supportsProtectedContent = false, + .isProtected = false, .viewport = viewport, .dataspace = outputDataspace, .realContentIsVisible = true, diff --git a/services/surfaceflinger/DisplayDevice.cpp b/services/surfaceflinger/DisplayDevice.cpp index 249c40b473..950b05e1da 100644 --- a/services/surfaceflinger/DisplayDevice.cpp +++ b/services/surfaceflinger/DisplayDevice.cpp @@ -72,6 +72,7 @@ DisplayDevice::DisplayDevice(DisplayDeviceCreationArgs& args) mRefreshRateSelector(std::move(args.refreshRateSelector)), mHasDesiredModeTrace(concatId("HasDesiredMode"), false) { mCompositionDisplay->editState().isSecure = args.isSecure; + mCompositionDisplay->editState().isProtected = args.isProtected; mCompositionDisplay->createRenderSurface( compositionengine::RenderSurfaceCreationArgsBuilder() .setDisplayWidth(ANativeWindow_getWidth(args.nativeWindow.get())) diff --git a/services/surfaceflinger/DisplayDevice.h b/services/surfaceflinger/DisplayDevice.h index 51c7be0490..ac390cb8ff 100644 --- a/services/surfaceflinger/DisplayDevice.h +++ b/services/surfaceflinger/DisplayDevice.h @@ -332,6 +332,7 @@ struct DisplayDeviceState { uint32_t height = 0; std::string displayName; bool isSecure = false; + bool isProtected = false; // Refer to DisplayDevice::mRequestedRefreshRate, for virtual display only Fps requestedRefreshRate; @@ -353,6 +354,7 @@ struct DisplayDeviceCreationArgs { int32_t sequenceId{0}; bool isSecure{false}; + bool isProtected{false}; sp nativeWindow; sp displaySurface; ui::Rotation physicalOrientation{ui::ROTATION_0}; diff --git a/services/surfaceflinger/LayerFE.cpp b/services/surfaceflinger/LayerFE.cpp index f25619a6c0..2dbcb841ac 100644 --- a/services/surfaceflinger/LayerFE.cpp +++ b/services/surfaceflinger/LayerFE.cpp @@ -208,9 +208,15 @@ void LayerFE::prepareBufferStateClientComposition( // activeBuffer, then we need to return LayerSettings. return; } - const bool blackOutLayer = - (mSnapshot->hasProtectedContent && !targetSettings.supportsProtectedContent) || - ((mSnapshot->isSecure || mSnapshot->hasProtectedContent) && !targetSettings.isSecure); + bool blackOutLayer; + if (FlagManager::getInstance().display_protected()) { + blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) || + (mSnapshot->isSecure && !targetSettings.isSecure); + } else { + blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) || + ((mSnapshot->isSecure || mSnapshot->hasProtectedContent) && + !targetSettings.isSecure); + } const bool bufferCanBeUsedAsHwTexture = mSnapshot->externalTexture->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE; if (blackOutLayer || !bufferCanBeUsedAsHwTexture) { diff --git a/services/surfaceflinger/RegionSamplingThread.cpp b/services/surfaceflinger/RegionSamplingThread.cpp index 6db39f143f..c888ccc8ae 100644 --- a/services/surfaceflinger/RegionSamplingThread.cpp +++ b/services/surfaceflinger/RegionSamplingThread.cpp @@ -374,10 +374,11 @@ void RegionSamplingThread::captureSample() { constexpr bool kRegionSampling = true; constexpr bool kGrayscale = false; + constexpr bool kIsProtected = false; if (const auto fenceResult = mFlinger.captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, buffer, - kRegionSampling, kGrayscale, nullptr) + kRegionSampling, kGrayscale, kIsProtected, nullptr) .get(); fenceResult.ok()) { fenceResult.value()->waitForever(LOG_TAG); diff --git a/services/surfaceflinger/ScreenCaptureOutput.cpp b/services/surfaceflinger/ScreenCaptureOutput.cpp index 57b0d5e0ea..a4a5ce2b46 100644 --- a/services/surfaceflinger/ScreenCaptureOutput.cpp +++ b/services/surfaceflinger/ScreenCaptureOutput.cpp @@ -32,6 +32,7 @@ std::shared_ptr createScreenCaptureOutput(ScreenCaptureOutp bool>(args.compositionEngine, args.renderArea, args.colorProfile, args.regionSampling, args.dimInGammaSpaceForEnhancedScreenshots); output->editState().isSecure = args.renderArea.isSecure(); + output->editState().isProtected = args.isProtected; output->setCompositionEnabled(true); output->setLayerFilter({args.layerStack}); output->setRenderSurface(std::make_unique(std::move(args.buffer))); diff --git a/services/surfaceflinger/ScreenCaptureOutput.h b/services/surfaceflinger/ScreenCaptureOutput.h index fc095def99..1c16308e15 100644 --- a/services/surfaceflinger/ScreenCaptureOutput.h +++ b/services/surfaceflinger/ScreenCaptureOutput.h @@ -38,6 +38,7 @@ struct ScreenCaptureOutputArgs { bool regionSampling; bool treat170mAsSrgb; bool dimInGammaSpaceForEnhancedScreenshots; + bool isProtected = false; }; // ScreenCaptureOutput is used to compose a set of layers into a preallocated buffer. diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp index 1dcc19e40d..c4de02fce9 100644 --- a/services/surfaceflinger/SurfaceFlinger.cpp +++ b/services/surfaceflinger/SurfaceFlinger.cpp @@ -565,6 +565,9 @@ sp SurfaceFlinger::createDisplay(const String8& displayName, bool secur // Display ID is assigned when virtual display is allocated by HWC. DisplayDeviceState state; state.isSecure = secure; + // Set display as protected when marked as secure to ensure no behavior change + // TODO (b/314820005): separate as a different arg when creating the display. + state.isProtected = secure; state.displayName = displayName; state.requestedRefreshRate = Fps::fromValue(requestedRefreshRate); mCurrentState.displays.add(token, state); @@ -3381,6 +3384,7 @@ const char* SurfaceFlinger::processHotplug(PhysicalDisplayId displayId, .hwcDisplayId = hwcDisplayId, .activeMode = std::move(activeMode)}; state.isSecure = true; // All physical displays are currently considered secure. + state.isProtected = true; state.displayName = std::move(info.name); mCurrentState.displays.add(token, state); @@ -3412,6 +3416,7 @@ sp SurfaceFlinger::setupNewDisplayDeviceInternal( displayToken, compositionDisplay); creationArgs.sequenceId = state.sequenceId; creationArgs.isSecure = state.isSecure; + creationArgs.isProtected = state.isProtected; creationArgs.displaySurface = displaySurface; creationArgs.hasWideColorGamut = false; creationArgs.supportedPerFrameMetadata = 0; @@ -3543,6 +3548,7 @@ void SurfaceFlinger::processDisplayAdded(const wp& displayToken, builder.setPixels(resolution); builder.setIsSecure(state.isSecure); + builder.setIsProtected(state.isProtected); builder.setPowerAdvisor(mPowerAdvisor.get()); builder.setName(state.displayName); auto compositionDisplay = getCompositionEngine().createDisplay(builder.build()); @@ -7856,12 +7862,11 @@ void SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture, }) .get(); } - + const bool isProtected = hasProtectedLayer && allowProtected && supportsProtected; const uint32_t usage = GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE | - (hasProtectedLayer && allowProtected && supportsProtected - ? GRALLOC_USAGE_PROTECTED - : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN); + (isProtected ? GRALLOC_USAGE_PROTECTED + : GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN); sp buffer = getFactory().createGraphicBuffer(bufferSize.getWidth(), bufferSize.getHeight(), static_cast(reqPixelFormat), @@ -7881,14 +7886,15 @@ void SurfaceFlinger::captureScreenCommon(RenderAreaFuture renderAreaFuture, renderengine::impl::ExternalTexture::Usage:: WRITEABLE); auto fence = captureScreenCommon(std::move(renderAreaFuture), getLayerSnapshots, texture, - false /* regionSampling */, grayscale, captureListener); + false /* regionSampling */, grayscale, isProtected, + captureListener); fence.get(); } ftl::SharedFuture SurfaceFlinger::captureScreenCommon( RenderAreaFuture renderAreaFuture, GetLayerSnapshotsFunction getLayerSnapshots, const std::shared_ptr& buffer, bool regionSampling, - bool grayscale, const sp& captureListener) { + bool grayscale, bool isProtected, const sp& captureListener) { ATRACE_CALL(); auto future = mScheduler->schedule( @@ -7907,8 +7913,9 @@ ftl::SharedFuture SurfaceFlinger::captureScreenCommon( ftl::SharedFuture renderFuture; renderArea->render([&]() FTL_FAKE_GUARD(kMainThreadContext) { - renderFuture = renderScreenImpl(renderArea, getLayerSnapshots, buffer, - regionSampling, grayscale, captureResults); + renderFuture = + renderScreenImpl(renderArea, getLayerSnapshots, buffer, regionSampling, + grayscale, isProtected, captureResults); }); if (captureListener) { @@ -7936,7 +7943,7 @@ ftl::SharedFuture SurfaceFlinger::captureScreenCommon( ftl::SharedFuture SurfaceFlinger::renderScreenImpl( std::shared_ptr renderArea, GetLayerSnapshotsFunction getLayerSnapshots, const std::shared_ptr& buffer, bool regionSampling, - bool grayscale, ScreenCaptureResults& captureResults) { + bool grayscale, bool isProtected, ScreenCaptureResults& captureResults) { ATRACE_CALL(); auto layers = getLayerSnapshots(); @@ -8031,9 +8038,9 @@ ftl::SharedFuture SurfaceFlinger::renderScreenImpl( }; auto present = [this, buffer = capturedBuffer, dataspace = captureResults.capturedDataspace, - sdrWhitePointNits, displayBrightnessNits, grayscale, layerFEs = copyLayerFEs(), - layerStack, regionSampling, renderArea = std::move(renderArea), - renderIntent]() -> FenceResult { + sdrWhitePointNits, displayBrightnessNits, grayscale, isProtected, + layerFEs = copyLayerFEs(), layerStack, regionSampling, + renderArea = std::move(renderArea), renderIntent]() -> FenceResult { std::unique_ptr compositionEngine = mFactory.createCompositionEngine(); compositionEngine->setRenderEngine(mRenderEngine.get()); @@ -8067,7 +8074,8 @@ ftl::SharedFuture SurfaceFlinger::renderScreenImpl( .regionSampling = regionSampling, .treat170mAsSrgb = mTreat170mAsSrgb, .dimInGammaSpaceForEnhancedScreenshots = - dimInGammaSpaceForEnhancedScreenshots}); + dimInGammaSpaceForEnhancedScreenshots, + .isProtected = isProtected}); const float colorSaturation = grayscale ? 0 : 1; compositionengine::CompositionRefreshArgs refreshArgs{ diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h index c4af271742..6909055801 100644 --- a/services/surfaceflinger/SurfaceFlinger.h +++ b/services/surfaceflinger/SurfaceFlinger.h @@ -855,11 +855,11 @@ private: ftl::SharedFuture captureScreenCommon( RenderAreaFuture, GetLayerSnapshotsFunction, const std::shared_ptr&, bool regionSampling, - bool grayscale, const sp&); + bool grayscale, bool isProtected, const sp&); ftl::SharedFuture renderScreenImpl( std::shared_ptr, GetLayerSnapshotsFunction, const std::shared_ptr&, bool regionSampling, - bool grayscale, ScreenCaptureResults&) EXCLUDES(mStateLock) + bool grayscale, bool isProtected, ScreenCaptureResults&) EXCLUDES(mStateLock) REQUIRES(kMainThreadContext); // If the uid provided is not UNSET_UID, the traverse will skip any layers that don't have a diff --git a/services/surfaceflinger/common/FlagManager.cpp b/services/surfaceflinger/common/FlagManager.cpp index 07a606c9ed..2d7482862a 100644 --- a/services/surfaceflinger/common/FlagManager.cpp +++ b/services/surfaceflinger/common/FlagManager.cpp @@ -124,6 +124,7 @@ void FlagManager::dump(std::string& result) const { DUMP_READ_ONLY_FLAG(use_known_refresh_rate_for_fps_consistency); DUMP_READ_ONLY_FLAG(cache_if_source_crop_layer_only_moved); DUMP_READ_ONLY_FLAG(enable_fro_dependent_features); + DUMP_READ_ONLY_FLAG(display_protected); #undef DUMP_READ_ONLY_FLAG #undef DUMP_SERVER_FLAG @@ -197,6 +198,7 @@ FLAG_MANAGER_READ_ONLY_FLAG(use_known_refresh_rate_for_fps_consistency, "") FLAG_MANAGER_READ_ONLY_FLAG(cache_if_source_crop_layer_only_moved, "debug.sf.cache_source_crop_only_moved") FLAG_MANAGER_READ_ONLY_FLAG(enable_fro_dependent_features, "") +FLAG_MANAGER_READ_ONLY_FLAG(display_protected, "") /// Trunk stable server flags /// FLAG_MANAGER_SERVER_FLAG(late_boot_misc2, "") diff --git a/services/surfaceflinger/common/include/common/FlagManager.h b/services/surfaceflinger/common/include/common/FlagManager.h index 38cb43a269..e0f620465c 100644 --- a/services/surfaceflinger/common/include/common/FlagManager.h +++ b/services/surfaceflinger/common/include/common/FlagManager.h @@ -63,6 +63,7 @@ public: bool use_known_refresh_rate_for_fps_consistency() const; bool cache_if_source_crop_layer_only_moved() const; bool enable_fro_dependent_features() const; + bool display_protected() const; protected: // overridden for unit tests diff --git a/services/surfaceflinger/surfaceflinger_flags.aconfig b/services/surfaceflinger/surfaceflinger_flags.aconfig index fcb52c72f4..620ac26cfd 100644 --- a/services/surfaceflinger/surfaceflinger_flags.aconfig +++ b/services/surfaceflinger/surfaceflinger_flags.aconfig @@ -107,3 +107,11 @@ flag { bug: "314217419" is_fixed_read_only: true } + +flag { + name: "display_protected" + namespace: "core_graphics" + description: "Introduce protected displays to specify whether they should render protected content" + bug: "301647974" + is_fixed_read_only: true +} diff --git a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h index ebb05d4da7..8ba6bf87e2 100644 --- a/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h +++ b/services/surfaceflinger/tests/unittests/TestableSurfaceFlinger.h @@ -498,7 +498,8 @@ public: return FTL_FAKE_GUARD(kMainThreadContext, mFlinger->renderScreenImpl(std::move(renderArea), traverseLayers, buffer, regionSampling, - false /* grayscale */, captureResults)); + false /* grayscale */, + false /* isProtected */, captureResults)); } auto traverseLayersInLayerStack(ui::LayerStack layerStack, int32_t uid, -- cgit v1.2.3-59-g8ed1b