blob: 620edca4fb282ae8fbcc235256621843dafef9f0 [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
22#include <gui/GLConsumer.h>
23#include <gui/TraceUtils.h>
24#include <math/vec3.h>
25#include <system/window.h>
26#include <utils/Log.h>
27
Vishnu Naire14c6b32022-08-06 04:20:15 +000028#include "LayerFE.h"
Leon Scroggins III85d4b222023-05-09 13:58:18 -040029#include "SurfaceFlinger.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
83const compositionengine::LayerFECompositionState* LayerFE::getCompositionState() const {
84 return mSnapshot.get();
85}
86
Melody Hsuc949cde2024-03-12 01:43:34 +000087bool LayerFE::onPreComposition(bool) {
Vishnu Naire14c6b32022-08-06 04:20:15 +000088 return mSnapshot->hasReadyFrame;
89}
90
91std::optional<compositionengine::LayerFE::LayerSettings> LayerFE::prepareClientComposition(
92 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
93 std::optional<compositionengine::LayerFE::LayerSettings> layerSettings =
94 prepareClientCompositionInternal(targetSettings);
95 // Nothing to render.
96 if (!layerSettings) {
97 return {};
98 }
99
100 // HWC requests to clear this layer.
101 if (targetSettings.clearContent) {
102 prepareClearClientComposition(*layerSettings, false /* blackout */);
103 return layerSettings;
104 }
105
106 // set the shadow for the layer if needed
107 prepareShadowClientComposition(*layerSettings, targetSettings.viewport);
108
109 return layerSettings;
110}
111
112std::optional<compositionengine::LayerFE::LayerSettings> LayerFE::prepareClientCompositionInternal(
113 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
114 ATRACE_CALL();
115 compositionengine::LayerFE::LayerSettings layerSettings;
116 layerSettings.geometry.boundaries =
117 reduce(mSnapshot->geomLayerBounds, mSnapshot->transparentRegionHint);
118 layerSettings.geometry.positionTransform = mSnapshot->geomLayerTransform.asMatrix4();
119
120 // skip drawing content if the targetSettings indicate the content will be occluded
121 const bool drawContent = targetSettings.realContentIsVisible || targetSettings.clearContent;
122 layerSettings.skipContentDraw = !drawContent;
123
124 if (!mSnapshot->colorTransformIsIdentity) {
125 layerSettings.colorTransform = mSnapshot->colorTransform;
126 }
127
128 const auto& roundedCornerState = mSnapshot->roundedCorner;
129 layerSettings.geometry.roundedCornersRadius = roundedCornerState.radius;
130 layerSettings.geometry.roundedCornersCrop = roundedCornerState.cropRect;
131
132 layerSettings.alpha = mSnapshot->alpha;
133 layerSettings.sourceDataspace = mSnapshot->dataspace;
134
135 // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
136 // We do this here instead of in buffer info so that dumpsys can still report layers that are
137 // using the 170M transfer.
138 if (targetSettings.treat170mAsSrgb &&
139 (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) ==
140 HAL_DATASPACE_TRANSFER_SMPTE_170M) {
141 layerSettings.sourceDataspace = static_cast<ui::Dataspace>(
142 (layerSettings.sourceDataspace & HAL_DATASPACE_STANDARD_MASK) |
143 (layerSettings.sourceDataspace & HAL_DATASPACE_RANGE_MASK) |
144 HAL_DATASPACE_TRANSFER_SRGB);
145 }
146
147 layerSettings.whitePointNits = targetSettings.whitePointNits;
148 switch (targetSettings.blurSetting) {
149 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Enabled:
150 layerSettings.backgroundBlurRadius = mSnapshot->backgroundBlurRadius;
151 layerSettings.blurRegions = mSnapshot->blurRegions;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000152 layerSettings.blurRegionTransform = mSnapshot->localTransformInverse.asMatrix4();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000153 break;
154 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BackgroundBlurOnly:
155 layerSettings.backgroundBlurRadius = mSnapshot->backgroundBlurRadius;
156 break;
157 case LayerFE::ClientCompositionTargetSettings::BlurSetting::BlurRegionsOnly:
158 layerSettings.blurRegions = mSnapshot->blurRegions;
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000159 layerSettings.blurRegionTransform = mSnapshot->localTransformInverse.asMatrix4();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000160 break;
161 case LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled:
162 default:
163 break;
164 }
165 layerSettings.stretchEffect = mSnapshot->stretchEffect;
166 // Record the name of the layer for debugging further down the stack.
167 layerSettings.name = mSnapshot->name;
168
169 if (hasEffect() && !hasBufferOrSidebandStream()) {
170 prepareEffectsClientComposition(layerSettings, targetSettings);
171 return layerSettings;
172 }
173
174 prepareBufferStateClientComposition(layerSettings, targetSettings);
175 return layerSettings;
176}
177
178void LayerFE::prepareClearClientComposition(LayerFE::LayerSettings& layerSettings,
179 bool blackout) const {
180 layerSettings.source.buffer.buffer = nullptr;
181 layerSettings.source.solidColor = half3(0.0f, 0.0f, 0.0f);
182 layerSettings.disableBlending = true;
183 layerSettings.bufferId = 0;
184 layerSettings.frameNumber = 0;
185
186 // If layer is blacked out, force alpha to 1 so that we draw a black color layer.
187 layerSettings.alpha = blackout ? 1.0f : 0.0f;
188 layerSettings.name = mSnapshot->name;
189}
190
191void LayerFE::prepareEffectsClientComposition(
192 compositionengine::LayerFE::LayerSettings& layerSettings,
193 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
194 // If fill bounds are occluded or the fill color is invalid skip the fill settings.
195 if (targetSettings.realContentIsVisible && fillsColor()) {
196 // Set color for color fill settings.
197 layerSettings.source.solidColor = mSnapshot->color.rgb;
198 } else if (hasBlur() || drawShadows()) {
199 layerSettings.skipContentDraw = true;
200 }
201}
202
203void LayerFE::prepareBufferStateClientComposition(
204 compositionengine::LayerFE::LayerSettings& layerSettings,
205 compositionengine::LayerFE::ClientCompositionTargetSettings& targetSettings) const {
206 ATRACE_CALL();
207 if (CC_UNLIKELY(!mSnapshot->externalTexture)) {
208 // If there is no buffer for the layer or we have sidebandstream where there is no
209 // activeBuffer, then we need to return LayerSettings.
210 return;
211 }
Chavi Weingarten18fa7c62023-11-28 21:16:03 +0000212 bool blackOutLayer;
213 if (FlagManager::getInstance().display_protected()) {
214 blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) ||
215 (mSnapshot->isSecure && !targetSettings.isSecure);
216 } else {
217 blackOutLayer = (mSnapshot->hasProtectedContent && !targetSettings.isProtected) ||
218 ((mSnapshot->isSecure || mSnapshot->hasProtectedContent) &&
219 !targetSettings.isSecure);
220 }
Vishnu Naire14c6b32022-08-06 04:20:15 +0000221 const bool bufferCanBeUsedAsHwTexture =
222 mSnapshot->externalTexture->getUsage() & GraphicBuffer::USAGE_HW_TEXTURE;
223 if (blackOutLayer || !bufferCanBeUsedAsHwTexture) {
224 ALOGE_IF(!bufferCanBeUsedAsHwTexture, "%s is blacked out as buffer is not gpu readable",
225 mSnapshot->name.c_str());
226 prepareClearClientComposition(layerSettings, true /* blackout */);
227 return;
228 }
229
230 layerSettings.source.buffer.buffer = mSnapshot->externalTexture;
231 layerSettings.source.buffer.isOpaque = mSnapshot->contentOpaque;
232 layerSettings.source.buffer.fence = mSnapshot->acquireFence;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000233 layerSettings.source.buffer.usePremultipliedAlpha = mSnapshot->premultipliedAlpha;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000234 bool hasSmpte2086 = mSnapshot->hdrMetadata.validTypes & HdrMetadata::SMPTE2086;
235 bool hasCta861_3 = mSnapshot->hdrMetadata.validTypes & HdrMetadata::CTA861_3;
236 float maxLuminance = 0.f;
237 if (hasSmpte2086 && hasCta861_3) {
238 maxLuminance = std::min(mSnapshot->hdrMetadata.smpte2086.maxLuminance,
239 mSnapshot->hdrMetadata.cta8613.maxContentLightLevel);
240 } else if (hasSmpte2086) {
241 maxLuminance = mSnapshot->hdrMetadata.smpte2086.maxLuminance;
242 } else if (hasCta861_3) {
243 maxLuminance = mSnapshot->hdrMetadata.cta8613.maxContentLightLevel;
244 } else {
245 switch (layerSettings.sourceDataspace & HAL_DATASPACE_TRANSFER_MASK) {
246 case HAL_DATASPACE_TRANSFER_ST2084:
247 case HAL_DATASPACE_TRANSFER_HLG:
248 // Behavior-match previous releases for HDR content
249 maxLuminance = defaultMaxLuminance;
250 break;
251 }
252 }
253 layerSettings.source.buffer.maxLuminanceNits = maxLuminance;
254 layerSettings.frameNumber = mSnapshot->frameNumber;
255 layerSettings.bufferId = mSnapshot->externalTexture->getId();
256
Sally Qi380ac3e2023-10-10 20:27:02 +0000257 const bool useFiltering = targetSettings.needsFiltering ||
258 mSnapshot->geomLayerTransform.needsBilinearFiltering();
259
Vishnu Naire14c6b32022-08-06 04:20:15 +0000260 // Query the texture matrix given our current filtering mode.
261 float textureMatrix[16];
262 getDrawingTransformMatrix(layerSettings.source.buffer.buffer, mSnapshot->geomContentCrop,
Sally Qi380ac3e2023-10-10 20:27:02 +0000263 mSnapshot->geomBufferTransform, useFiltering,
Patrick Williams278a88f2023-01-27 16:52:40 -0600264 textureMatrix);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000265
266 if (mSnapshot->geomBufferUsesDisplayInverseTransform) {
267 /*
268 * the code below applies the primary display's inverse transform to
269 * the texture transform
270 */
Leon Scroggins III85d4b222023-05-09 13:58:18 -0400271 uint32_t transform = SurfaceFlinger::getActiveDisplayRotationFlags();
Vishnu Naire14c6b32022-08-06 04:20:15 +0000272 mat4 tr = inverseOrientation(transform);
273
274 /**
275 * TODO(b/36727915): This is basically a hack.
276 *
277 * Ensure that regardless of the parent transformation,
278 * this buffer is always transformed from native display
279 * orientation to display orientation. For example, in the case
280 * of a camera where the buffer remains in native orientation,
281 * we want the pixels to always be upright.
282 */
Vishnu Nair8fc721b2022-12-22 20:06:32 +0000283 const auto parentTransform = mSnapshot->parentTransform;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000284 tr = tr * inverseOrientation(parentTransform.getOrientation());
285
286 // and finally apply it to the original texture matrix
287 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
288 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
289 }
290
291 const Rect win{layerSettings.geometry.boundaries};
292 float bufferWidth = static_cast<float>(mSnapshot->bufferSize.getWidth());
293 float bufferHeight = static_cast<float>(mSnapshot->bufferSize.getHeight());
294
295 // Layers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
296 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
297 // ignore them.
298 if (!mSnapshot->bufferSize.isValid()) {
299 bufferWidth = float(win.right) - float(win.left);
300 bufferHeight = float(win.bottom) - float(win.top);
301 }
302
303 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
304 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
305 const float translateY = float(win.top) / bufferHeight;
306 const float translateX = float(win.left) / bufferWidth;
307
308 // Flip y-coordinates because GLConsumer expects OpenGL convention.
309 mat4 tr = mat4::translate(vec4(.5f, .5f, 0.f, 1.f)) * mat4::scale(vec4(1.f, -1.f, 1.f, 1.f)) *
310 mat4::translate(vec4(-.5f, -.5f, 0.f, 1.f)) *
311 mat4::translate(vec4(translateX, translateY, 0.f, 1.f)) *
312 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0f, 1.0f));
313
Sally Qi380ac3e2023-10-10 20:27:02 +0000314 layerSettings.source.buffer.useTextureFiltering = useFiltering;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000315 layerSettings.source.buffer.textureTransform =
316 mat4(static_cast<const float*>(textureMatrix)) * tr;
317
318 return;
319}
320
321void LayerFE::prepareShadowClientComposition(LayerFE::LayerSettings& caster,
322 const Rect& layerStackRect) const {
Vishnu Naird9e4f462023-10-06 04:05:45 +0000323 ShadowSettings state = mSnapshot->shadowSettings;
Vishnu Naire14c6b32022-08-06 04:20:15 +0000324 if (state.length <= 0.f || (state.ambientColor.a <= 0.f && state.spotColor.a <= 0.f)) {
325 return;
326 }
327
328 // Shift the spot light x-position to the middle of the display and then
329 // offset it by casting layer's screen pos.
330 state.lightPos.x =
331 (static_cast<float>(layerStackRect.width()) / 2.f) - mSnapshot->transformedBounds.left;
332 state.lightPos.y -= mSnapshot->transformedBounds.top;
333 caster.shadow = state;
334}
335
Vishnu Nair7ee4f462023-04-19 09:54:09 -0700336void LayerFE::onLayerDisplayed(ftl::SharedFuture<FenceResult> futureFenceResult,
337 ui::LayerStack layerStack) {
338 mCompositionResult.releaseFences.emplace_back(std::move(futureFenceResult), layerStack);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000339}
340
341CompositionResult&& LayerFE::stealCompositionResult() {
342 return std::move(mCompositionResult);
343}
344
345const char* LayerFE::getDebugName() const {
346 return mName.c_str();
347}
348
349const LayerMetadata* LayerFE::getMetadata() const {
350 return &mSnapshot->layerMetadata;
351}
352
353const LayerMetadata* LayerFE::getRelativeMetadata() const {
354 return &mSnapshot->relativeLayerMetadata;
355}
356
357int32_t LayerFE::getSequence() const {
Vishnu Nair269f69d2023-09-08 11:45:26 -0700358 return static_cast<int32_t>(mSnapshot->uniqueSequence);
Vishnu Naire14c6b32022-08-06 04:20:15 +0000359}
360
361bool LayerFE::hasRoundedCorners() const {
362 return mSnapshot->roundedCorner.hasRoundedCorners();
363}
364
365void LayerFE::setWasClientComposed(const sp<Fence>& fence) {
366 mCompositionResult.lastClientCompositionFence = fence;
367}
368
369bool LayerFE::hasBufferOrSidebandStream() const {
370 return mSnapshot->externalTexture || mSnapshot->sidebandStream;
371}
372
373bool LayerFE::fillsColor() const {
374 return mSnapshot->color.r >= 0.0_hf && mSnapshot->color.g >= 0.0_hf &&
375 mSnapshot->color.b >= 0.0_hf;
376}
377
378bool LayerFE::hasBlur() const {
379 return mSnapshot->backgroundBlurRadius > 0 || mSnapshot->blurRegions.size() > 0;
380}
381
382bool LayerFE::drawShadows() const {
383 return mSnapshot->shadowSettings.length > 0.f &&
384 (mSnapshot->shadowSettings.ambientColor.a > 0 ||
385 mSnapshot->shadowSettings.spotColor.a > 0);
386};
387
388const sp<GraphicBuffer> LayerFE::getBuffer() const {
389 return mSnapshot->externalTexture ? mSnapshot->externalTexture->getBuffer() : nullptr;
390}
391
Melody Hsu793f8362024-01-08 20:00:35 +0000392void LayerFE::setReleaseFence(const FenceResult& releaseFence) {
393 // Promises should not be fulfilled more than once. This case can occur if virtual
394 // displays with the same layerstack ID are being created and destroyed in quick
395 // succession, such as in tests. This would result in a race condition in which
396 // multiple displays have the same layerstack ID within the same vsync interval.
397 if (mReleaseFencePromiseStatus == ReleaseFencePromiseStatus::FULFILLED) {
398 return;
399 }
400 mReleaseFence.set_value(releaseFence);
401 mReleaseFencePromiseStatus = ReleaseFencePromiseStatus::FULFILLED;
402}
403
404// LayerFEs are reused and a new fence needs to be created whevever a buffer is latched.
405ftl::Future<FenceResult> LayerFE::createReleaseFenceFuture() {
406 if (mReleaseFencePromiseStatus == ReleaseFencePromiseStatus::INITIALIZED) {
407 LOG_ALWAYS_FATAL("Attempting to create a new promise while one is still unfulfilled.");
408 }
409 mReleaseFence = std::promise<FenceResult>();
410 mReleaseFencePromiseStatus = ReleaseFencePromiseStatus::INITIALIZED;
411 return mReleaseFence.get_future();
412}
413
414LayerFE::ReleaseFencePromiseStatus LayerFE::getReleaseFencePromiseStatus() {
415 return mReleaseFencePromiseStatus;
416}
Vishnu Naire14c6b32022-08-06 04:20:15 +0000417} // namespace android