• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2019 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 #include <DisplayHardware/Hal.h>
17 #include <android-base/stringprintf.h>
18 #include <compositionengine/DisplayColorProfile.h>
19 #include <compositionengine/LayerFECompositionState.h>
20 #include <compositionengine/Output.h>
21 #include <compositionengine/impl/HwcBufferCache.h>
22 #include <compositionengine/impl/OutputCompositionState.h>
23 #include <compositionengine/impl/OutputLayer.h>
24 #include <compositionengine/impl/OutputLayerCompositionState.h>
25 #include <cstdint>
26 #include "system/graphics-base-v1.0.h"
27 
28 #include <ui/HdrRenderTypeUtils.h>
29 
30 // TODO(b/129481165): remove the #pragma below and fix conversion issues
31 #pragma clang diagnostic push
32 #pragma clang diagnostic ignored "-Wconversion"
33 
34 #include "DisplayHardware/HWComposer.h"
35 
36 // TODO(b/129481165): remove the #pragma below and fix conversion issues
37 #pragma clang diagnostic pop // ignored "-Wconversion"
38 
39 using aidl::android::hardware::graphics::composer3::Composition;
40 
41 namespace android::compositionengine {
42 
43 OutputLayer::~OutputLayer() = default;
44 
45 namespace impl {
46 
47 namespace {
48 
reduce(const FloatRect & win,const Region & exclude)49 FloatRect reduce(const FloatRect& win, const Region& exclude) {
50     if (CC_LIKELY(exclude.isEmpty())) {
51         return win;
52     }
53     // Convert through Rect (by rounding) for lack of FloatRegion
54     return Region(Rect{win}).subtract(exclude).getBounds().toFloatRect();
55 }
56 
57 } // namespace
58 
createOutputLayer(const compositionengine::Output & output,const sp<compositionengine::LayerFE> & layerFE)59 std::unique_ptr<OutputLayer> createOutputLayer(const compositionengine::Output& output,
60                                                const sp<compositionengine::LayerFE>& layerFE) {
61     return createOutputLayerTemplated<OutputLayer>(output, layerFE);
62 }
63 
64 OutputLayer::~OutputLayer() = default;
65 
setHwcLayer(std::shared_ptr<HWC2::Layer> hwcLayer)66 void OutputLayer::setHwcLayer(std::shared_ptr<HWC2::Layer> hwcLayer) {
67     auto& state = editState();
68     if (hwcLayer) {
69         state.hwc.emplace(std::move(hwcLayer));
70     } else {
71         state.hwc.reset();
72     }
73 }
74 
calculateInitialCrop() const75 Rect OutputLayer::calculateInitialCrop() const {
76     const auto& layerState = *getLayerFE().getCompositionState();
77 
78     // apply the projection's clipping to the window crop in
79     // layerstack space, and convert-back to layer space.
80     // if there are no window scaling involved, this operation will map to full
81     // pixels in the buffer.
82 
83     FloatRect activeCropFloat =
84             reduce(layerState.geomLayerBounds, layerState.transparentRegionHint);
85 
86     const Rect& viewport = getOutput().getState().layerStackSpace.getContent();
87     const ui::Transform& layerTransform = layerState.geomLayerTransform;
88     const ui::Transform& inverseLayerTransform = layerState.geomInverseLayerTransform;
89     // Transform to screen space.
90     activeCropFloat = layerTransform.transform(activeCropFloat);
91     activeCropFloat = activeCropFloat.intersect(viewport.toFloatRect());
92     // Back to layer space to work with the content crop.
93     activeCropFloat = inverseLayerTransform.transform(activeCropFloat);
94 
95     // This needs to be here as transform.transform(Rect) computes the
96     // transformed rect and then takes the bounding box of the result before
97     // returning. This means
98     // transform.inverse().transform(transform.transform(Rect)) != Rect
99     // in which case we need to make sure the final rect is clipped to the
100     // display bounds.
101     Rect activeCrop{activeCropFloat};
102     if (!activeCrop.intersect(layerState.geomBufferSize, &activeCrop)) {
103         activeCrop.clear();
104     }
105     return activeCrop;
106 }
107 
calculateOutputSourceCrop(uint32_t internalDisplayRotationFlags) const108 FloatRect OutputLayer::calculateOutputSourceCrop(uint32_t internalDisplayRotationFlags) const {
109     const auto& layerState = *getLayerFE().getCompositionState();
110 
111     if (!layerState.geomUsesSourceCrop) {
112         return {};
113     }
114 
115     // the content crop is the area of the content that gets scaled to the
116     // layer's size. This is in buffer space.
117     FloatRect crop = layerState.geomContentCrop.toFloatRect();
118 
119     // In addition there is a WM-specified crop we pull from our drawing state.
120     Rect activeCrop = calculateInitialCrop();
121     const Rect& bufferSize = layerState.geomBufferSize;
122 
123     int winWidth = bufferSize.getWidth();
124     int winHeight = bufferSize.getHeight();
125 
126     // The bufferSize for buffer state layers can be unbounded ([0, 0, -1, -1])
127     // if display frame hasn't been set and the parent is an unbounded layer.
128     if (winWidth < 0 && winHeight < 0) {
129         return crop;
130     }
131 
132     // Transform the window crop to match the buffer coordinate system,
133     // which means using the inverse of the current transform set on the
134     // SurfaceFlingerConsumer.
135     uint32_t invTransform = layerState.geomBufferTransform;
136     if (layerState.geomBufferUsesDisplayInverseTransform) {
137         /*
138          * the code below applies the primary display's inverse transform to the
139          * buffer
140          */
141         uint32_t invTransformOrient = internalDisplayRotationFlags;
142         // calculate the inverse transform
143         if (invTransformOrient & HAL_TRANSFORM_ROT_90) {
144             invTransformOrient ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H;
145         }
146         // and apply to the current transform
147         invTransform =
148                 (ui::Transform(invTransformOrient) * ui::Transform(invTransform)).getOrientation();
149     }
150 
151     if (invTransform & HAL_TRANSFORM_ROT_90) {
152         // If the activeCrop has been rotate the ends are rotated but not
153         // the space itself so when transforming ends back we can't rely on
154         // a modification of the axes of rotation. To account for this we
155         // need to reorient the inverse rotation in terms of the current
156         // axes of rotation.
157         bool isHFlipped = (invTransform & HAL_TRANSFORM_FLIP_H) != 0;
158         bool isVFlipped = (invTransform & HAL_TRANSFORM_FLIP_V) != 0;
159         if (isHFlipped == isVFlipped) {
160             invTransform ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H;
161         }
162         std::swap(winWidth, winHeight);
163     }
164     const Rect winCrop =
165             activeCrop.transform(invTransform, bufferSize.getWidth(), bufferSize.getHeight());
166 
167     // below, crop is intersected with winCrop expressed in crop's coordinate space
168     const float xScale = crop.getWidth() / float(winWidth);
169     const float yScale = crop.getHeight() / float(winHeight);
170 
171     const float insetLeft = winCrop.left * xScale;
172     const float insetTop = winCrop.top * yScale;
173     const float insetRight = (winWidth - winCrop.right) * xScale;
174     const float insetBottom = (winHeight - winCrop.bottom) * yScale;
175 
176     crop.left += insetLeft;
177     crop.top += insetTop;
178     crop.right -= insetRight;
179     crop.bottom -= insetBottom;
180 
181     return crop;
182 }
183 
calculateOutputDisplayFrame() const184 Rect OutputLayer::calculateOutputDisplayFrame() const {
185     const auto& layerState = *getLayerFE().getCompositionState();
186     const auto& outputState = getOutput().getState();
187 
188     // apply the layer's transform, followed by the display's global transform
189     // here we're guaranteed that the layer's transform preserves rects
190     Region activeTransparentRegion = layerState.transparentRegionHint;
191     const ui::Transform& layerTransform = layerState.geomLayerTransform;
192     const ui::Transform& inverseLayerTransform = layerState.geomInverseLayerTransform;
193     const Rect& bufferSize = layerState.geomBufferSize;
194     Rect activeCrop = layerState.geomCrop;
195     if (!activeCrop.isEmpty() && bufferSize.isValid()) {
196         activeCrop = layerTransform.transform(activeCrop);
197         if (!activeCrop.intersect(outputState.layerStackSpace.getContent(), &activeCrop)) {
198             activeCrop.clear();
199         }
200         activeCrop = inverseLayerTransform.transform(activeCrop, true);
201         // This needs to be here as transform.transform(Rect) computes the
202         // transformed rect and then takes the bounding box of the result before
203         // returning. This means
204         // transform.inverse().transform(transform.transform(Rect)) != Rect
205         // in which case we need to make sure the final rect is clipped to the
206         // display bounds.
207         if (!activeCrop.intersect(bufferSize, &activeCrop)) {
208             activeCrop.clear();
209         }
210         // mark regions outside the crop as transparent
211         activeTransparentRegion.orSelf(Rect(0, 0, bufferSize.getWidth(), activeCrop.top));
212         activeTransparentRegion.orSelf(
213                 Rect(0, activeCrop.bottom, bufferSize.getWidth(), bufferSize.getHeight()));
214         activeTransparentRegion.orSelf(Rect(0, activeCrop.top, activeCrop.left, activeCrop.bottom));
215         activeTransparentRegion.orSelf(
216                 Rect(activeCrop.right, activeCrop.top, bufferSize.getWidth(), activeCrop.bottom));
217     }
218 
219     // reduce uses a FloatRect to provide more accuracy during the
220     // transformation. We then round upon constructing 'frame'.
221     FloatRect geomLayerBounds = layerState.geomLayerBounds;
222 
223     // Some HWCs may clip client composited input to its displayFrame. Make sure
224     // that this does not cut off the shadow.
225     if (layerState.forceClientComposition && layerState.shadowRadius > 0.0f) {
226         const auto outset = layerState.shadowRadius;
227         geomLayerBounds.left -= outset;
228         geomLayerBounds.top -= outset;
229         geomLayerBounds.right += outset;
230         geomLayerBounds.bottom += outset;
231     }
232     Rect frame{layerTransform.transform(reduce(geomLayerBounds, activeTransparentRegion))};
233     if (!frame.intersect(outputState.layerStackSpace.getContent(), &frame)) {
234         frame.clear();
235     }
236     const ui::Transform displayTransform{outputState.transform};
237 
238     return displayTransform.transform(frame);
239 }
240 
calculateOutputRelativeBufferTransform(uint32_t internalDisplayRotationFlags) const241 uint32_t OutputLayer::calculateOutputRelativeBufferTransform(
242         uint32_t internalDisplayRotationFlags) const {
243     const auto& layerState = *getLayerFE().getCompositionState();
244     const auto& outputState = getOutput().getState();
245 
246     /*
247      * Transformations are applied in this order:
248      * 1) buffer orientation/flip/mirror
249      * 2) state transformation (window manager)
250      * 3) layer orientation (screen orientation)
251      * (NOTE: the matrices are multiplied in reverse order)
252      */
253     const ui::Transform& layerTransform = layerState.geomLayerTransform;
254     const ui::Transform displayTransform{outputState.transform};
255     const ui::Transform bufferTransform{layerState.geomBufferTransform};
256     ui::Transform transform(displayTransform * layerTransform * bufferTransform);
257 
258     if (layerState.geomBufferUsesDisplayInverseTransform) {
259         /*
260          * We must apply the internal display's inverse transform to the buffer
261          * transform, and not the one for the output this layer is on.
262          */
263         uint32_t invTransform = internalDisplayRotationFlags;
264 
265         // calculate the inverse transform
266         if (invTransform & HAL_TRANSFORM_ROT_90) {
267             invTransform ^= HAL_TRANSFORM_FLIP_V | HAL_TRANSFORM_FLIP_H;
268         }
269 
270         /*
271          * Here we cancel out the orientation component of the WM transform.
272          * The scaling and translate components are already included in our bounds
273          * computation so it's enough to just omit it in the composition.
274          * See comment in BufferLayer::prepareClientLayer with ref to b/36727915 for why.
275          */
276         transform = ui::Transform(invTransform) * displayTransform * bufferTransform;
277     }
278 
279     // this gives us only the "orientation" component of the transform
280     return transform.getOrientation();
281 }
282 
updateCompositionState(bool includeGeometry,bool forceClientComposition,ui::Transform::RotationFlags internalDisplayRotationFlags)283 void OutputLayer::updateCompositionState(
284         bool includeGeometry, bool forceClientComposition,
285         ui::Transform::RotationFlags internalDisplayRotationFlags) {
286     const auto* layerFEState = getLayerFE().getCompositionState();
287     if (!layerFEState) {
288         return;
289     }
290 
291     const auto& outputState = getOutput().getState();
292     const auto& profile = *getOutput().getDisplayColorProfile();
293     auto& state = editState();
294 
295     if (includeGeometry) {
296         // Clear the forceClientComposition flag before it is set for any
297         // reason. Note that since it can be set by some checks below when
298         // updating the geometry state, we only clear it when updating the
299         // geometry since those conditions for forcing client composition won't
300         // go away otherwise.
301         state.forceClientComposition = false;
302 
303         state.displayFrame = calculateOutputDisplayFrame();
304         state.sourceCrop = calculateOutputSourceCrop(internalDisplayRotationFlags);
305         state.bufferTransform = static_cast<Hwc2::Transform>(
306                 calculateOutputRelativeBufferTransform(internalDisplayRotationFlags));
307 
308         if ((layerFEState->isSecure && !outputState.isSecure) ||
309             (state.bufferTransform & ui::Transform::ROT_INVALID)) {
310             state.forceClientComposition = true;
311         }
312     }
313 
314     // Determine the output dependent dataspace for this layer. If it is
315     // colorspace agnostic, it just uses the dataspace chosen for the output to
316     // avoid the need for color conversion.
317     state.dataspace = layerFEState->isColorspaceAgnostic &&
318                     outputState.targetDataspace != ui::Dataspace::UNKNOWN
319             ? outputState.targetDataspace
320             : layerFEState->dataspace;
321 
322     // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
323     // We do this here instead of in buffer info so that dumpsys can still report layers that are
324     // using the 170M transfer. Also we only do this if the colorspace is not agnostic for the
325     // layer, in case the color profile uses a 170M transfer function.
326     if (outputState.treat170mAsSrgb && !layerFEState->isColorspaceAgnostic &&
327         (state.dataspace & HAL_DATASPACE_TRANSFER_MASK) == HAL_DATASPACE_TRANSFER_SMPTE_170M) {
328         state.dataspace = static_cast<ui::Dataspace>(
329                 (state.dataspace & HAL_DATASPACE_STANDARD_MASK) |
330                 (state.dataspace & HAL_DATASPACE_RANGE_MASK) | HAL_DATASPACE_TRANSFER_SRGB);
331     }
332 
333     auto pixelFormat = layerFEState->buffer ? std::make_optional(static_cast<ui::PixelFormat>(
334                                                       layerFEState->buffer->getPixelFormat()))
335                                             : std::nullopt;
336 
337     // get HdrRenderType after the dataspace gets changed.
338     auto hdrRenderType =
339             getHdrRenderType(state.dataspace, pixelFormat, layerFEState->desiredHdrSdrRatio);
340 
341     // For hdr content, treat the white point as the display brightness - HDR content should not be
342     // boosted or dimmed.
343     // If the layer explicitly requests to disable dimming, then don't dim either.
344     if (hdrRenderType == HdrRenderType::GENERIC_HDR ||
345         getOutput().getState().displayBrightnessNits == getOutput().getState().sdrWhitePointNits ||
346         getOutput().getState().displayBrightnessNits == 0.f || !layerFEState->dimmingEnabled) {
347         state.dimmingRatio = 1.f;
348         state.whitePointNits = getOutput().getState().displayBrightnessNits;
349     } else {
350         float layerBrightnessNits = getOutput().getState().sdrWhitePointNits;
351         // RANGE_EXTENDED can "self-promote" to HDR, but is still rendered for a particular
352         // range that we may need to re-adjust to the current display conditions
353         if (hdrRenderType == HdrRenderType::DISPLAY_HDR) {
354             layerBrightnessNits *= layerFEState->currentHdrSdrRatio;
355         }
356         state.dimmingRatio =
357                 std::clamp(layerBrightnessNits / getOutput().getState().displayBrightnessNits, 0.f,
358                            1.f);
359         state.whitePointNits = layerBrightnessNits;
360     }
361 
362     // These are evaluated every frame as they can potentially change at any
363     // time.
364     if (layerFEState->forceClientComposition || !profile.isDataspaceSupported(state.dataspace) ||
365         forceClientComposition) {
366         state.forceClientComposition = true;
367     }
368 }
369 
writeStateToHWC(bool includeGeometry,bool skipLayer,uint32_t z,bool zIsOverridden,bool isPeekingThrough)370 void OutputLayer::writeStateToHWC(bool includeGeometry, bool skipLayer, uint32_t z,
371                                   bool zIsOverridden, bool isPeekingThrough) {
372     const auto& state = getState();
373     // Skip doing this if there is no HWC interface
374     if (!state.hwc) {
375         return;
376     }
377 
378     auto& hwcLayer = (*state.hwc).hwcLayer;
379     if (!hwcLayer) {
380         ALOGE("[%s] failed to write composition state to HWC -- no hwcLayer for output %s",
381               getLayerFE().getDebugName(), getOutput().getName().c_str());
382         return;
383     }
384 
385     const auto* outputIndependentState = getLayerFE().getCompositionState();
386     if (!outputIndependentState) {
387         return;
388     }
389 
390     auto requestedCompositionType = outputIndependentState->compositionType;
391 
392     if (requestedCompositionType == Composition::SOLID_COLOR && state.overrideInfo.buffer) {
393         // this should never happen, as SOLID_COLOR is skipped from caching, b/230073351
394         requestedCompositionType = Composition::DEVICE;
395     }
396 
397     // TODO(b/181172795): We now update geometry for all flattened layers. We should update it
398     // only when the geometry actually changes
399     const bool isOverridden =
400             state.overrideInfo.buffer != nullptr || isPeekingThrough || zIsOverridden;
401     const bool prevOverridden = state.hwc->stateOverridden;
402     if (isOverridden || prevOverridden || skipLayer || includeGeometry) {
403         writeOutputDependentGeometryStateToHWC(hwcLayer.get(), requestedCompositionType, z);
404         writeOutputIndependentGeometryStateToHWC(hwcLayer.get(), *outputIndependentState,
405                                                  skipLayer);
406     }
407 
408     writeOutputDependentPerFrameStateToHWC(hwcLayer.get());
409     writeOutputIndependentPerFrameStateToHWC(hwcLayer.get(), *outputIndependentState,
410                                              requestedCompositionType, skipLayer);
411 
412     writeCompositionTypeToHWC(hwcLayer.get(), requestedCompositionType, isPeekingThrough,
413                               skipLayer);
414 
415     if (requestedCompositionType == Composition::SOLID_COLOR) {
416         writeSolidColorStateToHWC(hwcLayer.get(), *outputIndependentState);
417     }
418 
419     editState().hwc->stateOverridden = isOverridden;
420     editState().hwc->layerSkipped = skipLayer;
421 }
422 
writeOutputDependentGeometryStateToHWC(HWC2::Layer * hwcLayer,Composition requestedCompositionType,uint32_t z)423 void OutputLayer::writeOutputDependentGeometryStateToHWC(HWC2::Layer* hwcLayer,
424                                                          Composition requestedCompositionType,
425                                                          uint32_t z) {
426     const auto& outputDependentState = getState();
427 
428     Rect displayFrame = outputDependentState.displayFrame;
429     FloatRect sourceCrop = outputDependentState.sourceCrop;
430 
431     if (outputDependentState.overrideInfo.buffer != nullptr) {
432         displayFrame = outputDependentState.overrideInfo.displayFrame;
433         sourceCrop =
434                 FloatRect(0.f, 0.f,
435                           static_cast<float>(outputDependentState.overrideInfo.buffer->getBuffer()
436                                                      ->getWidth()),
437                           static_cast<float>(outputDependentState.overrideInfo.buffer->getBuffer()
438                                                      ->getHeight()));
439     }
440 
441     ALOGV("Writing display frame [%d, %d, %d, %d]", displayFrame.left, displayFrame.top,
442           displayFrame.right, displayFrame.bottom);
443 
444     if (auto error = hwcLayer->setDisplayFrame(displayFrame); error != hal::Error::NONE) {
445         ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
446               getLayerFE().getDebugName(), displayFrame.left, displayFrame.top, displayFrame.right,
447               displayFrame.bottom, to_string(error).c_str(), static_cast<int32_t>(error));
448     }
449 
450     if (auto error = hwcLayer->setSourceCrop(sourceCrop); error != hal::Error::NONE) {
451         ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
452               "%s (%d)",
453               getLayerFE().getDebugName(), sourceCrop.left, sourceCrop.top, sourceCrop.right,
454               sourceCrop.bottom, to_string(error).c_str(), static_cast<int32_t>(error));
455     }
456 
457     if (auto error = hwcLayer->setZOrder(z); error != hal::Error::NONE) {
458         ALOGE("[%s] Failed to set Z %u: %s (%d)", getLayerFE().getDebugName(), z,
459               to_string(error).c_str(), static_cast<int32_t>(error));
460     }
461 
462     // Solid-color layers and overridden buffers should always use an identity transform.
463     const auto bufferTransform = (requestedCompositionType != Composition::SOLID_COLOR &&
464                                   getState().overrideInfo.buffer == nullptr)
465             ? outputDependentState.bufferTransform
466             : static_cast<hal::Transform>(0);
467     if (auto error = hwcLayer->setTransform(static_cast<hal::Transform>(bufferTransform));
468         error != hal::Error::NONE) {
469         ALOGE("[%s] Failed to set transform %s: %s (%d)", getLayerFE().getDebugName(),
470               toString(outputDependentState.bufferTransform).c_str(), to_string(error).c_str(),
471               static_cast<int32_t>(error));
472     }
473 }
474 
writeOutputIndependentGeometryStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,bool skipLayer)475 void OutputLayer::writeOutputIndependentGeometryStateToHWC(
476         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState,
477         bool skipLayer) {
478     // If there is a peekThroughLayer, then this layer has a hole in it. We need to use
479     // PREMULTIPLIED so it will peek through.
480     const auto& overrideInfo = getState().overrideInfo;
481     const auto blendMode = overrideInfo.buffer || overrideInfo.peekThroughLayer
482             ? hardware::graphics::composer::hal::BlendMode::PREMULTIPLIED
483             : outputIndependentState.blendMode;
484     if (auto error = hwcLayer->setBlendMode(blendMode); error != hal::Error::NONE) {
485         ALOGE("[%s] Failed to set blend mode %s: %s (%d)", getLayerFE().getDebugName(),
486               toString(blendMode).c_str(), to_string(error).c_str(), static_cast<int32_t>(error));
487     }
488 
489     const float alpha = skipLayer
490             ? 0.0f
491             : (getState().overrideInfo.buffer ? 1.0f : outputIndependentState.alpha);
492     ALOGV("Writing alpha %f", alpha);
493 
494     if (auto error = hwcLayer->setPlaneAlpha(alpha); error != hal::Error::NONE) {
495         ALOGE("[%s] Failed to set plane alpha %.3f: %s (%d)", getLayerFE().getDebugName(), alpha,
496               to_string(error).c_str(), static_cast<int32_t>(error));
497     }
498 
499     for (const auto& [name, entry] : outputIndependentState.metadata) {
500         if (auto error = hwcLayer->setLayerGenericMetadata(name, entry.mandatory, entry.value);
501             error != hal::Error::NONE) {
502             ALOGE("[%s] Failed to set generic metadata %s %s (%d)", getLayerFE().getDebugName(),
503                   name.c_str(), to_string(error).c_str(), static_cast<int32_t>(error));
504         }
505     }
506 }
507 
writeOutputDependentPerFrameStateToHWC(HWC2::Layer * hwcLayer)508 void OutputLayer::writeOutputDependentPerFrameStateToHWC(HWC2::Layer* hwcLayer) {
509     const auto& outputDependentState = getState();
510 
511     // TODO(lpique): b/121291683 outputSpaceVisibleRegion is output-dependent geometry
512     // state and should not change every frame.
513     Region visibleRegion = outputDependentState.overrideInfo.buffer
514             ? Region(outputDependentState.overrideInfo.visibleRegion)
515             : outputDependentState.outputSpaceVisibleRegion;
516     if (auto error = hwcLayer->setVisibleRegion(visibleRegion); error != hal::Error::NONE) {
517         ALOGE("[%s] Failed to set visible region: %s (%d)", getLayerFE().getDebugName(),
518               to_string(error).c_str(), static_cast<int32_t>(error));
519         visibleRegion.dump(LOG_TAG);
520     }
521 
522     if (auto error =
523                 hwcLayer->setBlockingRegion(outputDependentState.outputSpaceBlockingRegionHint);
524         error != hal::Error::NONE) {
525         ALOGE("[%s] Failed to set blocking region: %s (%d)", getLayerFE().getDebugName(),
526               to_string(error).c_str(), static_cast<int32_t>(error));
527         outputDependentState.outputSpaceBlockingRegionHint.dump(LOG_TAG);
528     }
529 
530     const auto dataspace = outputDependentState.overrideInfo.buffer
531             ? outputDependentState.overrideInfo.dataspace
532             : outputDependentState.dataspace;
533 
534     if (auto error = hwcLayer->setDataspace(dataspace); error != hal::Error::NONE) {
535         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", getLayerFE().getDebugName(), dataspace,
536               to_string(error).c_str(), static_cast<int32_t>(error));
537     }
538 
539     // Cached layers are not dimmed, which means that composer should attempt to dim.
540     // Note that if the dimming ratio is large, then this may cause the cached layer
541     // to kick back into GPU composition :(
542     // Also note that this assumes that there are no HDR layers that are able to be cached.
543     // Otherwise, this could cause HDR layers to be dimmed twice.
544     const auto dimmingRatio = outputDependentState.overrideInfo.buffer
545             ? (getOutput().getState().displayBrightnessNits != 0.f
546                        ? std::clamp(getOutput().getState().sdrWhitePointNits /
547                                             getOutput().getState().displayBrightnessNits,
548                                     0.f, 1.f)
549                        : 1.f)
550             : outputDependentState.dimmingRatio;
551 
552     if (auto error = hwcLayer->setBrightness(dimmingRatio); error != hal::Error::NONE) {
553         ALOGE("[%s] Failed to set brightness %f: %s (%d)", getLayerFE().getDebugName(),
554               dimmingRatio, to_string(error).c_str(), static_cast<int32_t>(error));
555     }
556 }
557 
writeOutputIndependentPerFrameStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,Composition compositionType,bool skipLayer)558 void OutputLayer::writeOutputIndependentPerFrameStateToHWC(
559         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState,
560         Composition compositionType, bool skipLayer) {
561     switch (auto error = hwcLayer->setColorTransform(outputIndependentState.colorTransform)) {
562         case hal::Error::NONE:
563             break;
564         case hal::Error::UNSUPPORTED:
565             editState().forceClientComposition = true;
566             break;
567         default:
568             ALOGE("[%s] Failed to set color transform: %s (%d)", getLayerFE().getDebugName(),
569                   to_string(error).c_str(), static_cast<int32_t>(error));
570     }
571 
572     const Region& surfaceDamage = getState().overrideInfo.buffer
573             ? getState().overrideInfo.damageRegion
574             : (getState().hwc->stateOverridden ? Region::INVALID_REGION
575                                                : outputIndependentState.surfaceDamage);
576 
577     if (auto error = hwcLayer->setSurfaceDamage(surfaceDamage); error != hal::Error::NONE) {
578         ALOGE("[%s] Failed to set surface damage: %s (%d)", getLayerFE().getDebugName(),
579               to_string(error).c_str(), static_cast<int32_t>(error));
580         outputIndependentState.surfaceDamage.dump(LOG_TAG);
581     }
582 
583     // Content-specific per-frame state
584     switch (compositionType) {
585         case Composition::SOLID_COLOR:
586             // For compatibility, should be written AFTER the composition type.
587             break;
588         case Composition::SIDEBAND:
589             writeSidebandStateToHWC(hwcLayer, outputIndependentState);
590             break;
591         case Composition::CURSOR:
592         case Composition::DEVICE:
593         case Composition::DISPLAY_DECORATION:
594         case Composition::REFRESH_RATE_INDICATOR:
595             writeBufferStateToHWC(hwcLayer, outputIndependentState, skipLayer);
596             break;
597         case Composition::INVALID:
598         case Composition::CLIENT:
599             // Ignored
600             break;
601     }
602 }
603 
writeSolidColorStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState)604 void OutputLayer::writeSolidColorStateToHWC(HWC2::Layer* hwcLayer,
605                                             const LayerFECompositionState& outputIndependentState) {
606     aidl::android::hardware::graphics::composer3::Color color = {outputIndependentState.color.r,
607                                                                  outputIndependentState.color.g,
608                                                                  outputIndependentState.color.b,
609                                                                  1.0f};
610 
611     if (auto error = hwcLayer->setColor(color); error != hal::Error::NONE) {
612         ALOGE("[%s] Failed to set color: %s (%d)", getLayerFE().getDebugName(),
613               to_string(error).c_str(), static_cast<int32_t>(error));
614     }
615 }
616 
writeSidebandStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState)617 void OutputLayer::writeSidebandStateToHWC(HWC2::Layer* hwcLayer,
618                                           const LayerFECompositionState& outputIndependentState) {
619     if (auto error = hwcLayer->setSidebandStream(outputIndependentState.sidebandStream->handle());
620         error != hal::Error::NONE) {
621         ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", getLayerFE().getDebugName(),
622               outputIndependentState.sidebandStream->handle(), to_string(error).c_str(),
623               static_cast<int32_t>(error));
624     }
625 }
626 
uncacheBuffers(const std::vector<uint64_t> & bufferIdsToUncache)627 void OutputLayer::uncacheBuffers(const std::vector<uint64_t>& bufferIdsToUncache) {
628     auto& state = editState();
629     // Skip doing this if there is no HWC interface
630     if (!state.hwc) {
631         return;
632     }
633 
634     // Uncache the active buffer last so that it's the first buffer to be purged from the cache
635     // next time a buffer is sent to this layer.
636     bool uncacheActiveBuffer = false;
637 
638     std::vector<uint32_t> slotsToClear;
639     for (uint64_t bufferId : bufferIdsToUncache) {
640         if (bufferId == state.hwc->activeBufferId) {
641             uncacheActiveBuffer = true;
642         } else {
643             uint32_t slot = state.hwc->hwcBufferCache.uncache(bufferId);
644             if (slot != UINT32_MAX) {
645                 slotsToClear.push_back(slot);
646             }
647         }
648     }
649     if (uncacheActiveBuffer) {
650         slotsToClear.push_back(state.hwc->hwcBufferCache.uncache(state.hwc->activeBufferId));
651     }
652 
653     hal::Error error =
654             state.hwc->hwcLayer->setBufferSlotsToClear(slotsToClear, state.hwc->activeBufferSlot);
655     if (error != hal::Error::NONE) {
656         ALOGE("[%s] Failed to clear buffer slots: %s (%d)", getLayerFE().getDebugName(),
657               to_string(error).c_str(), static_cast<int32_t>(error));
658     }
659 }
660 
writeBufferStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,bool skipLayer)661 void OutputLayer::writeBufferStateToHWC(HWC2::Layer* hwcLayer,
662                                         const LayerFECompositionState& outputIndependentState,
663                                         bool skipLayer) {
664     auto supportedPerFrameMetadata =
665             getOutput().getDisplayColorProfile()->getSupportedPerFrameMetadata();
666     if (auto error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata,
667                                                    outputIndependentState.hdrMetadata);
668         error != hal::Error::NONE && error != hal::Error::UNSUPPORTED) {
669         ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", getLayerFE().getDebugName(),
670               to_string(error).c_str(), static_cast<int32_t>(error));
671     }
672 
673     HwcSlotAndBuffer hwcSlotAndBuffer;
674     sp<Fence> hwcFence;
675     {
676         // Editing the state only because we update the HWC buffer cache and active buffer.
677         auto& state = editState();
678         // Override buffers use a special cache slot so that they don't evict client buffers.
679         if (state.overrideInfo.buffer != nullptr && !skipLayer) {
680             hwcSlotAndBuffer = state.hwc->hwcBufferCache.getOverrideHwcSlotAndBuffer(
681                     state.overrideInfo.buffer->getBuffer());
682             hwcFence = state.overrideInfo.acquireFence;
683             // Keep track of the active buffer ID so when it's discarded we uncache it last so its
684             // slot will be used first, allowing the memory to be freed as soon as possible.
685             state.hwc->activeBufferId = state.overrideInfo.buffer->getBuffer()->getId();
686         } else {
687             hwcSlotAndBuffer =
688                     state.hwc->hwcBufferCache.getHwcSlotAndBuffer(outputIndependentState.buffer);
689             hwcFence = outputIndependentState.acquireFence;
690             // Keep track of the active buffer ID so when it's discarded we uncache it last so its
691             // slot will be used first, allowing the memory to be freed as soon as possible.
692             state.hwc->activeBufferId = outputIndependentState.buffer->getId();
693         }
694         // Keep track of the active buffer slot, so we can restore it after clearing other buffer
695         // slots.
696         state.hwc->activeBufferSlot = hwcSlotAndBuffer.slot;
697     }
698 
699     if (auto error = hwcLayer->setBuffer(hwcSlotAndBuffer.slot, hwcSlotAndBuffer.buffer, hwcFence);
700         error != hal::Error::NONE) {
701         ALOGE("[%s] Failed to set buffer %p: %s (%d)", getLayerFE().getDebugName(),
702               hwcSlotAndBuffer.buffer->handle, to_string(error).c_str(),
703               static_cast<int32_t>(error));
704     }
705 }
706 
writeCompositionTypeToHWC(HWC2::Layer * hwcLayer,Composition requestedCompositionType,bool isPeekingThrough,bool skipLayer)707 void OutputLayer::writeCompositionTypeToHWC(HWC2::Layer* hwcLayer,
708                                             Composition requestedCompositionType,
709                                             bool isPeekingThrough, bool skipLayer) {
710     auto& outputDependentState = editState();
711 
712     if (isClientCompositionForced(isPeekingThrough)) {
713         // If we are forcing client composition, we need to tell the HWC
714         requestedCompositionType = Composition::CLIENT;
715     }
716 
717     // Set the requested composition type with the HWC whenever it changes
718     // We also resend the composition type when this layer was previously skipped, to ensure that
719     // the composition type is up-to-date.
720     if (outputDependentState.hwc->hwcCompositionType != requestedCompositionType ||
721         (outputDependentState.hwc->layerSkipped && !skipLayer)) {
722         outputDependentState.hwc->hwcCompositionType = requestedCompositionType;
723 
724         if (auto error = hwcLayer->setCompositionType(requestedCompositionType);
725             error != hal::Error::NONE) {
726             ALOGE("[%s] Failed to set composition type %s: %s (%d)", getLayerFE().getDebugName(),
727                   to_string(requestedCompositionType).c_str(), to_string(error).c_str(),
728                   static_cast<int32_t>(error));
729         }
730     }
731 }
732 
writeCursorPositionToHWC() const733 void OutputLayer::writeCursorPositionToHWC() const {
734     // Skip doing this if there is no HWC interface
735     auto hwcLayer = getHwcLayer();
736     if (!hwcLayer) {
737         return;
738     }
739 
740     const auto* layerFEState = getLayerFE().getCompositionState();
741     if (!layerFEState) {
742         return;
743     }
744 
745     const auto& outputState = getOutput().getState();
746 
747     Rect frame = layerFEState->cursorFrame;
748     frame.intersect(outputState.layerStackSpace.getContent(), &frame);
749     Rect position = outputState.transform.transform(frame);
750 
751     if (auto error = hwcLayer->setCursorPosition(position.left, position.top);
752         error != hal::Error::NONE) {
753         ALOGE("[%s] Failed to set cursor position to (%d, %d): %s (%d)",
754               getLayerFE().getDebugName(), position.left, position.top, to_string(error).c_str(),
755               static_cast<int32_t>(error));
756     }
757 }
758 
getHwcLayer() const759 HWC2::Layer* OutputLayer::getHwcLayer() const {
760     const auto& state = getState();
761     return state.hwc ? state.hwc->hwcLayer.get() : nullptr;
762 }
763 
requiresClientComposition() const764 bool OutputLayer::requiresClientComposition() const {
765     const auto& state = getState();
766     return !state.hwc || state.hwc->hwcCompositionType == Composition::CLIENT;
767 }
768 
isHardwareCursor() const769 bool OutputLayer::isHardwareCursor() const {
770     const auto& state = getState();
771     return state.hwc && state.hwc->hwcCompositionType == Composition::CURSOR;
772 }
773 
detectDisallowedCompositionTypeChange(Composition from,Composition to) const774 void OutputLayer::detectDisallowedCompositionTypeChange(Composition from, Composition to) const {
775     bool result = false;
776     switch (from) {
777         case Composition::INVALID:
778         case Composition::CLIENT:
779             result = false;
780             break;
781 
782         case Composition::DEVICE:
783         case Composition::SOLID_COLOR:
784             result = (to == Composition::CLIENT);
785             break;
786 
787         case Composition::CURSOR:
788         case Composition::SIDEBAND:
789         case Composition::DISPLAY_DECORATION:
790         case Composition::REFRESH_RATE_INDICATOR:
791             result = (to == Composition::CLIENT || to == Composition::DEVICE);
792             break;
793     }
794 
795     if (!result) {
796         ALOGE("[%s] Invalid device requested composition type change: %s (%d) --> %s (%d)",
797               getLayerFE().getDebugName(), to_string(from).c_str(), static_cast<int>(from),
798               to_string(to).c_str(), static_cast<int>(to));
799     }
800 }
801 
isClientCompositionForced(bool isPeekingThrough) const802 bool OutputLayer::isClientCompositionForced(bool isPeekingThrough) const {
803     return getState().forceClientComposition ||
804             (!isPeekingThrough && getLayerFE().hasRoundedCorners());
805 }
806 
applyDeviceCompositionTypeChange(Composition compositionType)807 void OutputLayer::applyDeviceCompositionTypeChange(Composition compositionType) {
808     auto& state = editState();
809     LOG_FATAL_IF(!state.hwc);
810     auto& hwcState = *state.hwc;
811 
812     // Only detected disallowed changes if this was not a skip layer, because the
813     // validated composition type may be arbitrary (usually DEVICE, to reflect that there were
814     // fewer GPU layers)
815     if (!hwcState.layerSkipped) {
816         detectDisallowedCompositionTypeChange(hwcState.hwcCompositionType, compositionType);
817     }
818 
819     hwcState.hwcCompositionType = compositionType;
820 }
821 
prepareForDeviceLayerRequests()822 void OutputLayer::prepareForDeviceLayerRequests() {
823     auto& state = editState();
824     state.clearClientTarget = false;
825 }
826 
applyDeviceLayerRequest(hal::LayerRequest request)827 void OutputLayer::applyDeviceLayerRequest(hal::LayerRequest request) {
828     auto& state = editState();
829     switch (request) {
830         case hal::LayerRequest::CLEAR_CLIENT_TARGET:
831             state.clearClientTarget = true;
832             break;
833 
834         default:
835             ALOGE("[%s] Unknown device layer request %s (%d)", getLayerFE().getDebugName(),
836                   toString(request).c_str(), static_cast<int>(request));
837             break;
838     }
839 }
840 
needsFiltering() const841 bool OutputLayer::needsFiltering() const {
842     const auto& state = getState();
843     const auto& displayFrame = state.displayFrame;
844     const auto& sourceCrop = state.sourceCrop;
845     return sourceCrop.getHeight() != displayFrame.getHeight() ||
846             sourceCrop.getWidth() != displayFrame.getWidth();
847 }
848 
getOverrideCompositionSettings() const849 std::optional<LayerFE::LayerSettings> OutputLayer::getOverrideCompositionSettings() const {
850     if (getState().overrideInfo.buffer == nullptr) {
851         return {};
852     }
853 
854     // Compute the geometry boundaries in layer stack space: we need to transform from the
855     // framebuffer space of the override buffer to layer space.
856     const ProjectionSpace& layerSpace = getOutput().getState().layerStackSpace;
857     const ui::Transform transform = getState().overrideInfo.displaySpace.getTransform(layerSpace);
858     const Rect boundaries = transform.transform(getState().overrideInfo.displayFrame);
859 
860     LayerFE::LayerSettings settings;
861     settings.geometry = renderengine::Geometry{
862             .boundaries = boundaries.toFloatRect(),
863     };
864     settings.bufferId = getState().overrideInfo.buffer->getBuffer()->getId();
865     settings.source = renderengine::PixelSource{
866             .buffer = renderengine::Buffer{
867                     .buffer = getState().overrideInfo.buffer,
868                     .fence = getState().overrideInfo.acquireFence,
869                     // If the transform from layer space to display space contains a rotation, we
870                     // need to undo the rotation in the texture transform
871                     .textureTransform =
872                             ui::Transform(transform.inverse().getOrientation(), 1, 1).asMatrix4(),
873             }};
874     settings.sourceDataspace = getState().overrideInfo.dataspace;
875     settings.alpha = 1.0f;
876     settings.whitePointNits = getOutput().getState().sdrWhitePointNits;
877 
878     return settings;
879 }
880 
dump(std::string & out) const881 void OutputLayer::dump(std::string& out) const {
882     using android::base::StringAppendF;
883 
884     StringAppendF(&out, "  - Output Layer %p(%s)\n", this, getLayerFE().getDebugName());
885     dumpState(out);
886 }
887 
888 } // namespace impl
889 } // namespace android::compositionengine
890