blob: 24586148188e9019873aaf63dde7cd1f70ba0e8e [file] [log] [blame]
Vishnu Naire14c6b32022-08-06 04:20:15 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17// #define LOG_NDEBUG 0
18#undef LOG_TAG
Vishnu Nairc6384702023-07-31 12:22:20 -070019#define LOG_TAG "SurfaceFlinger"
Vishnu Naire14c6b32022-08-06 04:20:15 +000020#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Vishnu Nairbe0ad902024-06-27 23:38:43 +000022#include <common/trace.h>
Vishnu Naire14c6b32022-08-06 04:20:15 +000023#include <gui/GLConsumer.h>
Vishnu Naire14c6b32022-08-06 04:20:15 +000024#include <math/vec3.h>
25#include <system/window.h>
Vishnu Naire14c6b32022-08-06 04:20:15 +000026
Vishnu Naire14c6b32022-08-06 04:20:15 +000027#include "LayerFE.h"
Leon Scroggins III85d4b222023-05-09 13:58:18 -040028#include "SurfaceFlinger.h"
Melody Hsu5aeb8162024-03-25 22:09:10 +000029#include "common/FlagManager.h"
Melody Hsu793f8362024-01-08 20:00:35 +000030#include "ui/FenceResult.h"
31#include "ui/LayerStack.h"
Vishnu Naire14c6b32022-08-06 04:20:15 +000032
33namespace android {
34
35namespace {
36constexpr float defaultMaxLuminance = 1000.0;
37
38constexpr mat4 inverseOrientation(uint32_t transform) {
39 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
40 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
41 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
42 mat4 tr;
43
44 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
45 tr = tr * rot90;
46 }
47 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
48 tr = tr * flipH;
49 }
50 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
51 tr = tr * flipV;
52 }
53 return inverse(tr);
54}
55
56FloatRect reduce(const FloatRect& win, const Region& exclude) {
57 if (CC_LIKELY(exclude.isEmpty())) {
58 return win;
59 }
60 // Convert through Rect (by rounding) for lack of FloatRegion
61 return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
62}
63
64// Computes the transform matrix using the setFilteringEnabled to determine whether the
65// transform matrix should be computed for use with bilinear filtering.
66void getDrawingTransformMatrix(const std::shared_ptr<renderengine::ExternalTexture>& buffer,
67 Rect bufferCrop, uint32_t bufferTransform, bool filteringEnabled,
68 float outMatrix[16]) {
69 if (!buffer) {
70 ALOGE("Buffer should not be null!");
71 return;
72 }
73 GLConsumer::computeTransformMatrix(outMatrix, static_cast<float>(buffer->getWidth()),
74 static_cast<float>(buffer->getHeight()),
75 buffer->getPixelFormat(), bufferCrop, bufferTransform,
76 filteringEnabled);
77}
78
79} // namespace
80
81LayerFE::LayerFE(const std::string& name) : mName(name) {}
82
Melody Hsu5aeb8162024-03-25 22:09:10 +000083LayerFE::~LayerFE() {
84 // Ensures that no promise is left unfulfilled before the LayerFE is destroyed.
85 // An unfulfilled promise could occur when a screenshot is attempted, but the
86 // render area is invalid and there is no memory for the capture result.
87 if (FlagManager::getInstance().ce_fence_promise() &&
88 mReleaseFencePromiseStatus == ReleaseFencePromiseStatus::INITIALIZED) {
89 setReleaseFence(Fence::NO_FENCE);
90 }
91}
92
Vishnu Naire14c6b32022-08-06 04:20:15 +000093const compositionengine::LayerFECompositionState* LayerFE::getCompositionState() const {
94 return mSnapshot.get();
95}
96
Melody Hsuc949cde2024-03-12 01:43:34 +000097bool LayerFE::onPreComposition(bool) {
Vishnu Naire14c6b32022-08-06 04:20:15 +000098 return mSnapshot->hasReadyFrame;
99}
100
101std::optional<compositionengine::LayerFE::LayerSettings> LayerFE::prepareClientComposition(
102 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
103 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
104 prepareClientCompositionInternal(targetSettings);
105 // Nothing to render.
106 if (!layerSettings) {
107 return {};
108 }
109
110 // HWC requests to clear this layer.
111 if (targetSettings.clearContent) {
112 prepareClearClientComposition(*layerSettings, false /* blackout */);
113 return layerSettings;
114 }
115
116 // set the shadow for the layer if needed
117 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
118
119 return layerSettings;
120}
121
122std::optional<compositionengine::LayerFE::LayerSettings> LayerFE::prepareClientCompositionInternal(
123 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000124 SFTRACE_CALL();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000125 compositionengine::LayerFE::LayerSettings layerSettings;
126 layerSettings.geometry.boundaries =
127 reduce(mSnapshot->geomLayerBounds, mSnapshot->transparentRegionHint);
128 layerSettings.geometry.positionTransform = mSnapshot->geomLayerTransform.asMatrix4();
129
130 // skip drawing content if the targetSettings indicate the content will be occluded
131 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
132 layerSettings.skipContentDraw = !drawContent;
133
134 if (!mSnapshot->colorTransformIsIdentity) {
135 layerSettings.colorTransform = mSnapshot->colorTransform;
136 }
137
138 const auto& roundedCornerState = mSnapshot->roundedCorner;
139 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
140 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
141
142 layerSettings.alpha = mSnapshot->alpha;
143 layerSettings.sourceDataspace = mSnapshot->dataspace;
144
145 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
146 // We do this here instead of in buffer info so that dumpsys can still report layers that are
147 // using the 170M transfer.
148 if (targetSettings.treat170mAsSrgb &&
149 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
150 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
151 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
152 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
153 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
154 HAL_DATASPACE_TRANSFER_SRGB);
155 }
156
157 layerSettings.whitePointNits = targetSettings.whitePointNits;
158 switch (targetSettings.blurSetting) {
159 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
160 layerSettings.backgroundBlurRadius = mSnapshot->backgroundBlurRadius;
161 layerSettings.blurRegions = mSnapshot->blurRegions;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000162 layerSettings.blurRegionTransform = mSnapshot->localTransformInverse.asMatrix4();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000163 break;
164 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
165 layerSettings.backgroundBlurRadius = mSnapshot->backgroundBlurRadius;
166 break;
167 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
168 layerSettings.blurRegions = mSnapshot->blurRegions;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000169 layerSettings.blurRegionTransform = mSnapshot->localTransformInverse.asMatrix4();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000170 break;
171 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
172 default:
173 break;
174 }
175 layerSettings.stretchEffect = mSnapshot->stretchEffect;
Marzia Favarodcc9d9b2024-01-10 10:17:00 +0000176 layerSettings.edgeExtensionEffect = mSnapshot->edgeExtensionEffect;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000177 // Record the name of the layer for debugging further down the stack.
178 layerSettings.name = mSnapshot->name;
Sally Qi0abc4a52024-09-26 16:13:06 -0700179 layerSettings.luts = mSnapshot->luts;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000180
181 if (hasEffect() && !hasBufferOrSidebandStream()) {
182 prepareEffectsClientComposition(layerSettings, targetSettings);
183 return layerSettings;
184 }
185
186 prepareBufferStateClientComposition(layerSettings, targetSettings);
187 return layerSettings;
188}
189
190void LayerFE::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
191 bool blackout) const {
192 layerSettings.source.buffer.buffer = nullptr;
193 layerSettings.source.solidColor = half3(0.0f, 0.0f, 0.0f);
194 layerSettings.disableBlending = true;
195 layerSettings.bufferId = 0;
196 layerSettings.frameNumber = 0;
197
198 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
199 layerSettings.alpha = blackout ? 1.0f : 0.0f;
200 layerSettings.name = mSnapshot->name;
201}
202
203void LayerFE::prepareEffectsClientComposition(
204 compositionengine::LayerFE::LayerSettings& layerSettings,
205 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
206 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
207 if (targetSettings.realContentIsVisible && fillsColor()) {
208 // Set color for color fill settings.
209 layerSettings.source.solidColor = mSnapshot->color.rgb;
210 } else if (hasBlur() || drawShadows()) {
211 layerSettings.skipContentDraw = true;
212 }
213}
214
215void LayerFE::prepareBufferStateClientComposition(
216 compositionengine::LayerFE::LayerSettings& layerSettings,
217 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000218 SFTRACE_CALL();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000219 if (CC_UNLIKELY(!mSnapshot->externalTexture)) {
220 // If there is no buffer for the layer or we have sidebandstream where there is no
221 // activeBuffer, then we need to return LayerSettings.
222 return;
223 }
Chavi Weingarten18fa7c62023-11-28 21:16:03 +0000224 bool blackOutLayer;
225 if (FlagManager::getInstance().display_protected()) {
226 blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) ||
227 (mSnapshot->isSecure && !targetSettings.isSecure);
228 } else {
229 blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) ||
230 ((mSnapshot->isSecure || mSnapshot->hasProtectedContent) &&
231 !targetSettings.isSecure);
232 }
Vishnu Naire14c6b32022-08-06 04:20:15 +0000233 const bool bufferCanBeUsedAsHwTexture =
234 mSnapshot->externalTexture->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
235 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
236 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
237 mSnapshot->name.c_str());
238 prepareClearClientComposition(layerSettings, true /* blackout */);
239 return;
240 }
241
242 layerSettings.source.buffer.buffer = mSnapshot->externalTexture;
243 layerSettings.source.buffer.isOpaque = mSnapshot->contentOpaque;
244 layerSettings.source.buffer.fence = mSnapshot->acquireFence;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000245 layerSettings.source.buffer.usePremultipliedAlpha = mSnapshot->premultipliedAlpha;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000246 bool hasSmpte2086 = mSnapshot->hdrMetadata.validTypes & HdrMetadata::SMPTE2086;
247 bool hasCta861_3 = mSnapshot->hdrMetadata.validTypes & HdrMetadata::CTA861_3;
248 float maxLuminance = 0.f;
249 if (hasSmpte2086 && hasCta861_3) {
250 maxLuminance = std::min(mSnapshot->hdrMetadata.smpte2086.maxLuminance,
251 mSnapshot->hdrMetadata.cta8613.maxContentLightLevel);
252 } else if (hasSmpte2086) {
253 maxLuminance = mSnapshot->hdrMetadata.smpte2086.maxLuminance;
254 } else if (hasCta861_3) {
255 maxLuminance = mSnapshot->hdrMetadata.cta8613.maxContentLightLevel;
256 } else {
257 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
258 case HAL_DATASPACE_TRANSFER_ST2084:
259 case HAL_DATASPACE_TRANSFER_HLG:
260 // Behavior-match previous releases for HDR content
261 maxLuminance = defaultMaxLuminance;
262 break;
263 }
264 }
265 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
266 layerSettings.frameNumber = mSnapshot->frameNumber;
267 layerSettings.bufferId = mSnapshot->externalTexture->getId();
268
Sally Qi380ac3e2023-10-10 20:27:02 +0000269 const bool useFiltering = targetSettings.needsFiltering ||
270 mSnapshot->geomLayerTransform.needsBilinearFiltering();
271
Vishnu Naire14c6b32022-08-06 04:20:15 +0000272 // Query the texture matrix given our current filtering mode.
273 float textureMatrix[16];
274 getDrawingTransformMatrix(layerSettings.source.buffer.buffer, mSnapshot->geomContentCrop,
Sally Qi380ac3e2023-10-10 20:27:02 +0000275 mSnapshot->geomBufferTransform, useFiltering,
Patrick Williams278a88f2023-01-27 16:52:40 -0600276 textureMatrix);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000277
278 if (mSnapshot->geomBufferUsesDisplayInverseTransform) {
279 /*
280 * the code below applies the primary display's inverse transform to
281 * the texture transform
282 */
Leon Scroggins III85d4b222023-05-09 13:58:18 -0400283 uint32_t transform = SurfaceFlinger::getActiveDisplayRotationFlags();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000284 mat4 tr = inverseOrientation(transform);
285
286 /**
287 * TODO(b/36727915): This is basically a hack.
288 *
289 * Ensure that regardless of the parent transformation,
290 * this buffer is always transformed from native display
291 * orientation to display orientation. For example, in the case
292 * of a camera where the buffer remains in native orientation,
293 * we want the pixels to always be upright.
294 */
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000295 const auto parentTransform = mSnapshot->parentTransform;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000296 tr = tr * inverseOrientation(parentTransform.getOrientation());
297
298 // and finally apply it to the original texture matrix
299 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
300 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
301 }
302
303 const Rect win{layerSettings.geometry.boundaries};
304 float bufferWidth = static_cast<float>(mSnapshot->bufferSize.getWidth());
305 float bufferHeight = static_cast<float>(mSnapshot->bufferSize.getHeight());
306
307 // Layers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
308 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
309 // ignore them.
310 if (!mSnapshot->bufferSize.isValid()) {
311 bufferWidth = float(win.right) - float(win.left);
312 bufferHeight = float(win.bottom) - float(win.top);
313 }
314
315 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
316 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
317 const float translateY = float(win.top) / bufferHeight;
318 const float translateX = float(win.left) / bufferWidth;
319
320 // Flip y-coordinates because GLConsumer expects OpenGL convention.
321 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
322 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
323 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
324 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
325
Sally Qi380ac3e2023-10-10 20:27:02 +0000326 layerSettings.source.buffer.useTextureFiltering = useFiltering;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000327 layerSettings.source.buffer.textureTransform =
328 mat4(static_cast<const float*>(textureMatrix)) * tr;
329
330 return;
331}
332
333void LayerFE::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
334 const Rect& layerStackRect) const {
Vishnu Naird9e4f462023-10-06 04:05:45 +0000335 ShadowSettings state = mSnapshot->shadowSettings;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000336 if (state.length <= 0.f || (state.ambientColor.a <= 0.f && state.spotColor.a <= 0.f)) {
337 return;
338 }
339
340 // Shift the spot light x-position to the middle of the display and then
341 // offset it by casting layer's screen pos.
342 state.lightPos.x =
343 (static_cast<float>(layerStackRect.width()) / 2.f) - mSnapshot->transformedBounds.left;
344 state.lightPos.y -= mSnapshot->transformedBounds.top;
345 caster.shadow = state;
346}
347
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700348void LayerFE::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
349 ui::LayerStack layerStack) {
350 mCompositionResult.releaseFences.emplace_back(std::move(futureFenceResult), layerStack);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000351}
352
353CompositionResult&& LayerFE::stealCompositionResult() {
354 return std::move(mCompositionResult);
355}
356
357const char* LayerFE::getDebugName() const {
358 return mName.c_str();
359}
360
361const LayerMetadata* LayerFE::getMetadata() const {
362 return &mSnapshot->layerMetadata;
363}
364
365const LayerMetadata* LayerFE::getRelativeMetadata() const {
366 return &mSnapshot->relativeLayerMetadata;
367}
368
369int32_t LayerFE::getSequence() const {
Vishnu Nair269f69d2023-09-08 11:45:26 -0700370 return static_cast<int32_t>(mSnapshot->uniqueSequence);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000371}
372
373bool LayerFE::hasRoundedCorners() const {
374 return mSnapshot->roundedCorner.hasRoundedCorners();
375}
376
377void LayerFE::setWasClientComposed(const sp<Fence>& fence) {
378 mCompositionResult.lastClientCompositionFence = fence;
379}
380
381bool LayerFE::hasBufferOrSidebandStream() const {
382 return mSnapshot->externalTexture || mSnapshot->sidebandStream;
383}
384
385bool LayerFE::fillsColor() const {
386 return mSnapshot->color.r >= 0.0_hf && mSnapshot->color.g >= 0.0_hf &&
387 mSnapshot->color.b >= 0.0_hf;
388}
389
390bool LayerFE::hasBlur() const {
391 return mSnapshot->backgroundBlurRadius > 0 || mSnapshot->blurRegions.size() > 0;
392}
393
394bool LayerFE::drawShadows() const {
395 return mSnapshot->shadowSettings.length > 0.f &&
396 (mSnapshot->shadowSettings.ambientColor.a > 0 ||
397 mSnapshot->shadowSettings.spotColor.a > 0);
398};
399
400const sp<GraphicBuffer> LayerFE::getBuffer() const {
401 return mSnapshot->externalTexture ? mSnapshot->externalTexture->getBuffer() : nullptr;
402}
403
Melody Hsu793f8362024-01-08 20:00:35 +0000404void LayerFE::setReleaseFence(const FenceResult& releaseFence) {
405 // Promises should not be fulfilled more than once. This case can occur if virtual
406 // displays with the same layerstack ID are being created and destroyed in quick
407 // succession, such as in tests. This would result in a race condition in which
408 // multiple displays have the same layerstack ID within the same vsync interval.
409 if (mReleaseFencePromiseStatus == ReleaseFencePromiseStatus::FULFILLED) {
410 return;
411 }
412 mReleaseFence.set_value(releaseFence);
413 mReleaseFencePromiseStatus = ReleaseFencePromiseStatus::FULFILLED;
414}
415
416// LayerFEs are reused and a new fence needs to be created whevever a buffer is latched.
417ftl::Future<FenceResult> LayerFE::createReleaseFenceFuture() {
418 if (mReleaseFencePromiseStatus == ReleaseFencePromiseStatus::INITIALIZED) {
419 LOG_ALWAYS_FATAL("Attempting to create a new promise while one is still unfulfilled.");
420 }
421 mReleaseFence = std::promise<FenceResult>();
422 mReleaseFencePromiseStatus = ReleaseFencePromiseStatus::INITIALIZED;
423 return mReleaseFence.get_future();
424}
425
426LayerFE::ReleaseFencePromiseStatus LayerFE::getReleaseFencePromiseStatus() {
427 return mReleaseFencePromiseStatus;
428}
Vishnu Naire14c6b32022-08-06 04:20:15 +0000429} // namespace android