• 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.shadowSettings.length > 0.0f) {
226         const auto outset = layerState.shadowSettings.length;
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     auto pixelFormat = layerFEState->buffer ? std::make_optional(static_cast<ui::PixelFormat>(
315                                                       layerFEState->buffer->getPixelFormat()))
316                                             : std::nullopt;
317 
318     auto hdrRenderType =
319             getHdrRenderType(outputState.dataspace, pixelFormat, layerFEState->desiredHdrSdrRatio);
320 
321     // Determine the output dependent dataspace for this layer. If it is
322     // colorspace agnostic, it just uses the dataspace chosen for the output to
323     // avoid the need for color conversion.
324     // For now, also respect the colorspace agnostic flag if we're drawing to HDR, to avoid drastic
325     // luminance shift. TODO(b/292162273): we should check if that's true though.
326     state.dataspace = layerFEState->isColorspaceAgnostic && hdrRenderType == HdrRenderType::SDR
327             ? outputState.dataspace
328             : layerFEState->dataspace;
329 
330     // Override the dataspace transfer from 170M to sRGB if the device configuration requests this.
331     // We do this here instead of in buffer info so that dumpsys can still report layers that are
332     // using the 170M transfer. Also we only do this if the colorspace is not agnostic for the
333     // layer, in case the color profile uses a 170M transfer function.
334     if (outputState.treat170mAsSrgb && !layerFEState->isColorspaceAgnostic &&
335         (state.dataspace & HAL_DATASPACE_TRANSFER_MASK) == HAL_DATASPACE_TRANSFER_SMPTE_170M) {
336         state.dataspace = static_cast<ui::Dataspace>(
337                 (state.dataspace & HAL_DATASPACE_STANDARD_MASK) |
338                 (state.dataspace & HAL_DATASPACE_RANGE_MASK) | HAL_DATASPACE_TRANSFER_SRGB);
339     }
340 
341     // re-get HdrRenderType after the dataspace gets changed.
342     hdrRenderType =
343             getHdrRenderType(state.dataspace, pixelFormat, layerFEState->desiredHdrSdrRatio);
344 
345     // For hdr content, treat the white point as the display brightness - HDR content should not be
346     // boosted or dimmed.
347     // If the layer explicitly requests to disable dimming, then don't dim either.
348     if (hdrRenderType == HdrRenderType::GENERIC_HDR ||
349         getOutput().getState().displayBrightnessNits == getOutput().getState().sdrWhitePointNits ||
350         getOutput().getState().displayBrightnessNits == 0.f || !layerFEState->dimmingEnabled) {
351         state.dimmingRatio = 1.f;
352         state.whitePointNits = getOutput().getState().displayBrightnessNits;
353     } else {
354         float layerBrightnessNits = getOutput().getState().sdrWhitePointNits;
355         // RANGE_EXTENDED can "self-promote" to HDR, but is still rendered for a particular
356         // range that we may need to re-adjust to the current display conditions
357         if (hdrRenderType == HdrRenderType::DISPLAY_HDR) {
358             layerBrightnessNits *= layerFEState->currentHdrSdrRatio;
359         }
360         state.dimmingRatio =
361                 std::clamp(layerBrightnessNits / getOutput().getState().displayBrightnessNits, 0.f,
362                            1.f);
363         state.whitePointNits = layerBrightnessNits;
364     }
365 
366     // These are evaluated every frame as they can potentially change at any
367     // time.
368     if (layerFEState->forceClientComposition || !profile.isDataspaceSupported(state.dataspace) ||
369         forceClientComposition) {
370         state.forceClientComposition = true;
371     }
372 }
373 
writeStateToHWC(bool includeGeometry,bool skipLayer,uint32_t z,bool zIsOverridden,bool isPeekingThrough)374 void OutputLayer::writeStateToHWC(bool includeGeometry, bool skipLayer, uint32_t z,
375                                   bool zIsOverridden, bool isPeekingThrough) {
376     const auto& state = getState();
377     // Skip doing this if there is no HWC interface
378     if (!state.hwc) {
379         return;
380     }
381 
382     auto& hwcLayer = (*state.hwc).hwcLayer;
383     if (!hwcLayer) {
384         ALOGE("[%s] failed to write composition state to HWC -- no hwcLayer for output %s",
385               getLayerFE().getDebugName(), getOutput().getName().c_str());
386         return;
387     }
388 
389     const auto* outputIndependentState = getLayerFE().getCompositionState();
390     if (!outputIndependentState) {
391         return;
392     }
393 
394     auto requestedCompositionType = outputIndependentState->compositionType;
395 
396     if (requestedCompositionType == Composition::SOLID_COLOR && state.overrideInfo.buffer) {
397         requestedCompositionType = Composition::DEVICE;
398     }
399 
400     // TODO(b/181172795): We now update geometry for all flattened layers. We should update it
401     // only when the geometry actually changes
402     const bool isOverridden =
403             state.overrideInfo.buffer != nullptr || isPeekingThrough || zIsOverridden;
404     const bool prevOverridden = state.hwc->stateOverridden;
405     if (isOverridden || prevOverridden || skipLayer || includeGeometry) {
406         writeOutputDependentGeometryStateToHWC(hwcLayer.get(), requestedCompositionType, z);
407         writeOutputIndependentGeometryStateToHWC(hwcLayer.get(), *outputIndependentState,
408                                                  skipLayer);
409     }
410 
411     writeOutputDependentPerFrameStateToHWC(hwcLayer.get());
412     writeOutputIndependentPerFrameStateToHWC(hwcLayer.get(), *outputIndependentState,
413                                              requestedCompositionType, skipLayer);
414 
415     writeCompositionTypeToHWC(hwcLayer.get(), requestedCompositionType, isPeekingThrough,
416                               skipLayer);
417 
418     if (requestedCompositionType == Composition::SOLID_COLOR) {
419         writeSolidColorStateToHWC(hwcLayer.get(), *outputIndependentState);
420     }
421 
422     editState().hwc->stateOverridden = isOverridden;
423     editState().hwc->layerSkipped = skipLayer;
424 }
425 
writeOutputDependentGeometryStateToHWC(HWC2::Layer * hwcLayer,Composition requestedCompositionType,uint32_t z)426 void OutputLayer::writeOutputDependentGeometryStateToHWC(HWC2::Layer* hwcLayer,
427                                                          Composition requestedCompositionType,
428                                                          uint32_t z) {
429     const auto& outputDependentState = getState();
430 
431     Rect displayFrame = outputDependentState.displayFrame;
432     FloatRect sourceCrop = outputDependentState.sourceCrop;
433 
434     if (outputDependentState.overrideInfo.buffer != nullptr) {
435         displayFrame = outputDependentState.overrideInfo.displayFrame;
436         sourceCrop =
437                 FloatRect(0.f, 0.f,
438                           static_cast<float>(outputDependentState.overrideInfo.buffer->getBuffer()
439                                                      ->getWidth()),
440                           static_cast<float>(outputDependentState.overrideInfo.buffer->getBuffer()
441                                                      ->getHeight()));
442     }
443 
444     ALOGV("Writing display frame [%d, %d, %d, %d]", displayFrame.left, displayFrame.top,
445           displayFrame.right, displayFrame.bottom);
446 
447     if (auto error = hwcLayer->setDisplayFrame(displayFrame); error != hal::Error::NONE) {
448         ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
449               getLayerFE().getDebugName(), displayFrame.left, displayFrame.top, displayFrame.right,
450               displayFrame.bottom, to_string(error).c_str(), static_cast<int32_t>(error));
451     }
452 
453     if (auto error = hwcLayer->setSourceCrop(sourceCrop); error != hal::Error::NONE) {
454         ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
455               "%s (%d)",
456               getLayerFE().getDebugName(), sourceCrop.left, sourceCrop.top, sourceCrop.right,
457               sourceCrop.bottom, to_string(error).c_str(), static_cast<int32_t>(error));
458     }
459 
460     if (auto error = hwcLayer->setZOrder(z); error != hal::Error::NONE) {
461         ALOGE("[%s] Failed to set Z %u: %s (%d)", getLayerFE().getDebugName(), z,
462               to_string(error).c_str(), static_cast<int32_t>(error));
463     }
464 
465     // Solid-color layers and overridden buffers should always use an identity transform.
466     const auto bufferTransform = (requestedCompositionType != Composition::SOLID_COLOR &&
467                                   getState().overrideInfo.buffer == nullptr)
468             ? outputDependentState.bufferTransform
469             : static_cast<hal::Transform>(0);
470     if (auto error = hwcLayer->setTransform(static_cast<hal::Transform>(bufferTransform));
471         error != hal::Error::NONE) {
472         ALOGE("[%s] Failed to set transform %s: %s (%d)", getLayerFE().getDebugName(),
473               toString(outputDependentState.bufferTransform).c_str(), to_string(error).c_str(),
474               static_cast<int32_t>(error));
475     }
476 }
477 
writeOutputIndependentGeometryStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,bool skipLayer)478 void OutputLayer::writeOutputIndependentGeometryStateToHWC(
479         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState,
480         bool skipLayer) {
481     // If there is a peekThroughLayer, then this layer has a hole in it. We need to use
482     // PREMULTIPLIED so it will peek through.
483     const auto& overrideInfo = getState().overrideInfo;
484     const auto blendMode = overrideInfo.buffer || overrideInfo.peekThroughLayer
485             ? hardware::graphics::composer::hal::BlendMode::PREMULTIPLIED
486             : outputIndependentState.blendMode;
487     if (auto error = hwcLayer->setBlendMode(blendMode); error != hal::Error::NONE) {
488         ALOGE("[%s] Failed to set blend mode %s: %s (%d)", getLayerFE().getDebugName(),
489               toString(blendMode).c_str(), to_string(error).c_str(), static_cast<int32_t>(error));
490     }
491 
492     const float alpha = skipLayer
493             ? 0.0f
494             : (getState().overrideInfo.buffer ? 1.0f : outputIndependentState.alpha);
495     ALOGV("Writing alpha %f", alpha);
496 
497     if (auto error = hwcLayer->setPlaneAlpha(alpha); error != hal::Error::NONE) {
498         ALOGE("[%s] Failed to set plane alpha %.3f: %s (%d)", getLayerFE().getDebugName(), alpha,
499               to_string(error).c_str(), static_cast<int32_t>(error));
500     }
501 
502     for (const auto& [name, entry] : outputIndependentState.metadata) {
503         if (auto error = hwcLayer->setLayerGenericMetadata(name, entry.mandatory, entry.value);
504             error != hal::Error::NONE) {
505             ALOGE("[%s] Failed to set generic metadata %s %s (%d)", getLayerFE().getDebugName(),
506                   name.c_str(), to_string(error).c_str(), static_cast<int32_t>(error));
507         }
508     }
509 }
510 
writeOutputDependentPerFrameStateToHWC(HWC2::Layer * hwcLayer)511 void OutputLayer::writeOutputDependentPerFrameStateToHWC(HWC2::Layer* hwcLayer) {
512     const auto& outputDependentState = getState();
513 
514     // TODO(lpique): b/121291683 outputSpaceVisibleRegion is output-dependent geometry
515     // state and should not change every frame.
516     Region visibleRegion = outputDependentState.overrideInfo.buffer
517             ? Region(outputDependentState.overrideInfo.visibleRegion)
518             : outputDependentState.outputSpaceVisibleRegion;
519     if (auto error = hwcLayer->setVisibleRegion(visibleRegion); error != hal::Error::NONE) {
520         ALOGE("[%s] Failed to set visible region: %s (%d)", getLayerFE().getDebugName(),
521               to_string(error).c_str(), static_cast<int32_t>(error));
522         visibleRegion.dump(LOG_TAG);
523     }
524 
525     if (auto error =
526                 hwcLayer->setBlockingRegion(outputDependentState.outputSpaceBlockingRegionHint);
527         error != hal::Error::NONE) {
528         ALOGE("[%s] Failed to set blocking region: %s (%d)", getLayerFE().getDebugName(),
529               to_string(error).c_str(), static_cast<int32_t>(error));
530         outputDependentState.outputSpaceBlockingRegionHint.dump(LOG_TAG);
531     }
532 
533     const auto dataspace = outputDependentState.overrideInfo.buffer
534             ? outputDependentState.overrideInfo.dataspace
535             : outputDependentState.dataspace;
536 
537     if (auto error = hwcLayer->setDataspace(dataspace); error != hal::Error::NONE) {
538         ALOGE("[%s] Failed to set dataspace %d: %s (%d)", getLayerFE().getDebugName(), dataspace,
539               to_string(error).c_str(), static_cast<int32_t>(error));
540     }
541 
542     // Cached layers are not dimmed, which means that composer should attempt to dim.
543     // Note that if the dimming ratio is large, then this may cause the cached layer
544     // to kick back into GPU composition :(
545     // Also note that this assumes that there are no HDR layers that are able to be cached.
546     // Otherwise, this could cause HDR layers to be dimmed twice.
547     const auto dimmingRatio = outputDependentState.overrideInfo.buffer
548             ? (getOutput().getState().displayBrightnessNits != 0.f
549                        ? std::clamp(getOutput().getState().sdrWhitePointNits /
550                                             getOutput().getState().displayBrightnessNits,
551                                     0.f, 1.f)
552                        : 1.f)
553             : outputDependentState.dimmingRatio;
554 
555     if (auto error = hwcLayer->setBrightness(dimmingRatio); error != hal::Error::NONE) {
556         ALOGE("[%s] Failed to set brightness %f: %s (%d)", getLayerFE().getDebugName(),
557               dimmingRatio, to_string(error).c_str(), static_cast<int32_t>(error));
558     }
559 }
560 
writeOutputIndependentPerFrameStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,Composition compositionType,bool skipLayer)561 void OutputLayer::writeOutputIndependentPerFrameStateToHWC(
562         HWC2::Layer* hwcLayer, const LayerFECompositionState& outputIndependentState,
563         Composition compositionType, bool skipLayer) {
564     switch (auto error = hwcLayer->setColorTransform(outputIndependentState.colorTransform)) {
565         case hal::Error::NONE:
566             break;
567         case hal::Error::UNSUPPORTED:
568             editState().forceClientComposition = true;
569             break;
570         default:
571             ALOGE("[%s] Failed to set color transform: %s (%d)", getLayerFE().getDebugName(),
572                   to_string(error).c_str(), static_cast<int32_t>(error));
573     }
574 
575     const Region& surfaceDamage = getState().overrideInfo.buffer
576             ? getState().overrideInfo.damageRegion
577             : (getState().hwc->stateOverridden ? Region::INVALID_REGION
578                                                : outputIndependentState.surfaceDamage);
579 
580     if (auto error = hwcLayer->setSurfaceDamage(surfaceDamage); error != hal::Error::NONE) {
581         ALOGE("[%s] Failed to set surface damage: %s (%d)", getLayerFE().getDebugName(),
582               to_string(error).c_str(), static_cast<int32_t>(error));
583         outputIndependentState.surfaceDamage.dump(LOG_TAG);
584     }
585 
586     // Content-specific per-frame state
587     switch (compositionType) {
588         case Composition::SOLID_COLOR:
589             // For compatibility, should be written AFTER the composition type.
590             break;
591         case Composition::SIDEBAND:
592             writeSidebandStateToHWC(hwcLayer, outputIndependentState);
593             break;
594         case Composition::CURSOR:
595         case Composition::DEVICE:
596         case Composition::DISPLAY_DECORATION:
597         case Composition::REFRESH_RATE_INDICATOR:
598             writeBufferStateToHWC(hwcLayer, outputIndependentState, skipLayer);
599             break;
600         case Composition::INVALID:
601         case Composition::CLIENT:
602             // Ignored
603             break;
604     }
605 }
606 
writeSolidColorStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState)607 void OutputLayer::writeSolidColorStateToHWC(HWC2::Layer* hwcLayer,
608                                             const LayerFECompositionState& outputIndependentState) {
609     aidl::android::hardware::graphics::composer3::Color color = {outputIndependentState.color.r,
610                                                                  outputIndependentState.color.g,
611                                                                  outputIndependentState.color.b,
612                                                                  1.0f};
613 
614     if (auto error = hwcLayer->setColor(color); error != hal::Error::NONE) {
615         ALOGE("[%s] Failed to set color: %s (%d)", getLayerFE().getDebugName(),
616               to_string(error).c_str(), static_cast<int32_t>(error));
617     }
618 }
619 
writeSidebandStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState)620 void OutputLayer::writeSidebandStateToHWC(HWC2::Layer* hwcLayer,
621                                           const LayerFECompositionState& outputIndependentState) {
622     if (auto error = hwcLayer->setSidebandStream(outputIndependentState.sidebandStream->handle());
623         error != hal::Error::NONE) {
624         ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", getLayerFE().getDebugName(),
625               outputIndependentState.sidebandStream->handle(), to_string(error).c_str(),
626               static_cast<int32_t>(error));
627     }
628 }
629 
uncacheBuffers(const std::vector<uint64_t> & bufferIdsToUncache)630 void OutputLayer::uncacheBuffers(const std::vector<uint64_t>& bufferIdsToUncache) {
631     auto& state = editState();
632     // Skip doing this if there is no HWC interface
633     if (!state.hwc) {
634         return;
635     }
636 
637     // Uncache the active buffer last so that it's the first buffer to be purged from the cache
638     // next time a buffer is sent to this layer.
639     bool uncacheActiveBuffer = false;
640 
641     std::vector<uint32_t> slotsToClear;
642     for (uint64_t bufferId : bufferIdsToUncache) {
643         if (bufferId == state.hwc->activeBufferId) {
644             uncacheActiveBuffer = true;
645         } else {
646             uint32_t slot = state.hwc->hwcBufferCache.uncache(bufferId);
647             if (slot != UINT32_MAX) {
648                 slotsToClear.push_back(slot);
649             }
650         }
651     }
652     if (uncacheActiveBuffer) {
653         slotsToClear.push_back(state.hwc->hwcBufferCache.uncache(state.hwc->activeBufferId));
654     }
655 
656     hal::Error error =
657             state.hwc->hwcLayer->setBufferSlotsToClear(slotsToClear, state.hwc->activeBufferSlot);
658     if (error != hal::Error::NONE) {
659         ALOGE("[%s] Failed to clear buffer slots: %s (%d)", getLayerFE().getDebugName(),
660               to_string(error).c_str(), static_cast<int32_t>(error));
661     }
662 }
663 
writeBufferStateToHWC(HWC2::Layer * hwcLayer,const LayerFECompositionState & outputIndependentState,bool skipLayer)664 void OutputLayer::writeBufferStateToHWC(HWC2::Layer* hwcLayer,
665                                         const LayerFECompositionState& outputIndependentState,
666                                         bool skipLayer) {
667     if (skipLayer && outputIndependentState.buffer == nullptr) {
668         return;
669     }
670     auto supportedPerFrameMetadata =
671             getOutput().getDisplayColorProfile()->getSupportedPerFrameMetadata();
672     if (auto error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata,
673                                                    outputIndependentState.hdrMetadata);
674         error != hal::Error::NONE && error != hal::Error::UNSUPPORTED) {
675         ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", getLayerFE().getDebugName(),
676               to_string(error).c_str(), static_cast<int32_t>(error));
677     }
678 
679     HwcSlotAndBuffer hwcSlotAndBuffer;
680     sp<Fence> hwcFence;
681     {
682         // Editing the state only because we update the HWC buffer cache and active buffer.
683         auto& state = editState();
684         // Override buffers use a special cache slot so that they don't evict client buffers.
685         if (state.overrideInfo.buffer != nullptr && !skipLayer) {
686             hwcSlotAndBuffer = state.hwc->hwcBufferCache.getOverrideHwcSlotAndBuffer(
687                     state.overrideInfo.buffer->getBuffer());
688             hwcFence = state.overrideInfo.acquireFence;
689             // Keep track of the active buffer ID so when it's discarded we uncache it last so its
690             // slot will be used first, allowing the memory to be freed as soon as possible.
691             state.hwc->activeBufferId = state.overrideInfo.buffer->getBuffer()->getId();
692         } else {
693             hwcSlotAndBuffer =
694                     state.hwc->hwcBufferCache.getHwcSlotAndBuffer(outputIndependentState.buffer);
695             hwcFence = outputIndependentState.acquireFence;
696             // Keep track of the active buffer ID so when it's discarded we uncache it last so its
697             // slot will be used first, allowing the memory to be freed as soon as possible.
698             state.hwc->activeBufferId = outputIndependentState.buffer->getId();
699         }
700         // Keep track of the active buffer slot, so we can restore it after clearing other buffer
701         // slots.
702         state.hwc->activeBufferSlot = hwcSlotAndBuffer.slot;
703     }
704 
705     if (auto error = hwcLayer->setBuffer(hwcSlotAndBuffer.slot, hwcSlotAndBuffer.buffer, hwcFence);
706         error != hal::Error::NONE) {
707         ALOGE("[%s] Failed to set buffer %p: %s (%d)", getLayerFE().getDebugName(),
708               hwcSlotAndBuffer.buffer->handle, to_string(error).c_str(),
709               static_cast<int32_t>(error));
710     }
711 }
712 
writeCompositionTypeToHWC(HWC2::Layer * hwcLayer,Composition requestedCompositionType,bool isPeekingThrough,bool skipLayer)713 void OutputLayer::writeCompositionTypeToHWC(HWC2::Layer* hwcLayer,
714                                             Composition requestedCompositionType,
715                                             bool isPeekingThrough, bool skipLayer) {
716     auto& outputDependentState = editState();
717 
718     if (isClientCompositionForced(isPeekingThrough)) {
719         // If we are forcing client composition, we need to tell the HWC
720         requestedCompositionType = Composition::CLIENT;
721     }
722 
723     // Set the requested composition type with the HWC whenever it changes
724     // We also resend the composition type when this layer was previously skipped, to ensure that
725     // the composition type is up-to-date.
726     if (outputDependentState.hwc->hwcCompositionType != requestedCompositionType ||
727         (outputDependentState.hwc->layerSkipped && !skipLayer)) {
728         outputDependentState.hwc->hwcCompositionType = requestedCompositionType;
729 
730         if (auto error = hwcLayer->setCompositionType(requestedCompositionType);
731             error != hal::Error::NONE) {
732             ALOGE("[%s] Failed to set composition type %s: %s (%d)", getLayerFE().getDebugName(),
733                   to_string(requestedCompositionType).c_str(), to_string(error).c_str(),
734                   static_cast<int32_t>(error));
735         }
736     }
737 }
738 
writeCursorPositionToHWC() const739 void OutputLayer::writeCursorPositionToHWC() const {
740     // Skip doing this if there is no HWC interface
741     auto hwcLayer = getHwcLayer();
742     if (!hwcLayer) {
743         return;
744     }
745 
746     const auto* layerFEState = getLayerFE().getCompositionState();
747     if (!layerFEState) {
748         return;
749     }
750 
751     const auto& outputState = getOutput().getState();
752 
753     Rect frame = layerFEState->cursorFrame;
754     frame.intersect(outputState.layerStackSpace.getContent(), &frame);
755     Rect position = outputState.transform.transform(frame);
756 
757     if (auto error = hwcLayer->setCursorPosition(position.left, position.top);
758         error != hal::Error::NONE) {
759         ALOGE("[%s] Failed to set cursor position to (%d, %d): %s (%d)",
760               getLayerFE().getDebugName(), position.left, position.top, to_string(error).c_str(),
761               static_cast<int32_t>(error));
762     }
763 }
764 
getHwcLayer() const765 HWC2::Layer* OutputLayer::getHwcLayer() const {
766     const auto& state = getState();
767     return state.hwc ? state.hwc->hwcLayer.get() : nullptr;
768 }
769 
requiresClientComposition() const770 bool OutputLayer::requiresClientComposition() const {
771     const auto& state = getState();
772     return !state.hwc || state.hwc->hwcCompositionType == Composition::CLIENT;
773 }
774 
isHardwareCursor() const775 bool OutputLayer::isHardwareCursor() const {
776     const auto& state = getState();
777     return state.hwc && state.hwc->hwcCompositionType == Composition::CURSOR;
778 }
779 
detectDisallowedCompositionTypeChange(Composition from,Composition to) const780 void OutputLayer::detectDisallowedCompositionTypeChange(Composition from, Composition to) const {
781     bool result = false;
782     switch (from) {
783         case Composition::INVALID:
784         case Composition::CLIENT:
785             result = false;
786             break;
787 
788         case Composition::DEVICE:
789         case Composition::SOLID_COLOR:
790             result = (to == Composition::CLIENT);
791             break;
792 
793         case Composition::CURSOR:
794         case Composition::SIDEBAND:
795         case Composition::DISPLAY_DECORATION:
796         case Composition::REFRESH_RATE_INDICATOR:
797             result = (to == Composition::CLIENT || to == Composition::DEVICE);
798             break;
799     }
800 
801     if (!result) {
802         ALOGE("[%s] Invalid device requested composition type change: %s (%d) --> %s (%d)",
803               getLayerFE().getDebugName(), to_string(from).c_str(), static_cast<int>(from),
804               to_string(to).c_str(), static_cast<int>(to));
805     }
806 }
807 
isClientCompositionForced(bool isPeekingThrough) const808 bool OutputLayer::isClientCompositionForced(bool isPeekingThrough) const {
809     return getState().forceClientComposition ||
810             (!isPeekingThrough && getLayerFE().hasRoundedCorners());
811 }
812 
applyDeviceCompositionTypeChange(Composition compositionType)813 void OutputLayer::applyDeviceCompositionTypeChange(Composition compositionType) {
814     auto& state = editState();
815     LOG_FATAL_IF(!state.hwc);
816     auto& hwcState = *state.hwc;
817 
818     // Only detected disallowed changes if this was not a skip layer, because the
819     // validated composition type may be arbitrary (usually DEVICE, to reflect that there were
820     // fewer GPU layers)
821     if (!hwcState.layerSkipped) {
822         detectDisallowedCompositionTypeChange(hwcState.hwcCompositionType, compositionType);
823     }
824 
825     hwcState.hwcCompositionType = compositionType;
826 }
827 
prepareForDeviceLayerRequests()828 void OutputLayer::prepareForDeviceLayerRequests() {
829     auto& state = editState();
830     state.clearClientTarget = false;
831 }
832 
applyDeviceLayerRequest(hal::LayerRequest request)833 void OutputLayer::applyDeviceLayerRequest(hal::LayerRequest request) {
834     auto& state = editState();
835     switch (request) {
836         case hal::LayerRequest::CLEAR_CLIENT_TARGET:
837             state.clearClientTarget = true;
838             break;
839 
840         default:
841             ALOGE("[%s] Unknown device layer request %s (%d)", getLayerFE().getDebugName(),
842                   toString(request).c_str(), static_cast<int>(request));
843             break;
844     }
845 }
846 
needsFiltering() const847 bool OutputLayer::needsFiltering() const {
848     const auto& state = getState();
849     const auto& sourceCrop = state.sourceCrop;
850     auto displayFrameWidth = static_cast<float>(state.displayFrame.getWidth());
851     auto displayFrameHeight = static_cast<float>(state.displayFrame.getHeight());
852 
853     if (state.bufferTransform & HAL_TRANSFORM_ROT_90) {
854         std::swap(displayFrameWidth, displayFrameHeight);
855     }
856 
857     return sourceCrop.getHeight() != displayFrameHeight ||
858             sourceCrop.getWidth() != displayFrameWidth;
859 }
860 
getOverrideCompositionSettings() const861 std::optional<LayerFE::LayerSettings> OutputLayer::getOverrideCompositionSettings() const {
862     if (getState().overrideInfo.buffer == nullptr) {
863         return {};
864     }
865 
866     // Compute the geometry boundaries in layer stack space: we need to transform from the
867     // framebuffer space of the override buffer to layer space.
868     const ProjectionSpace& layerSpace = getOutput().getState().layerStackSpace;
869     const ui::Transform transform = getState().overrideInfo.displaySpace.getTransform(layerSpace);
870     const Rect boundaries = transform.transform(getState().overrideInfo.displayFrame);
871 
872     LayerFE::LayerSettings settings;
873     settings.geometry = renderengine::Geometry{
874             .boundaries = boundaries.toFloatRect(),
875     };
876     settings.bufferId = getState().overrideInfo.buffer->getBuffer()->getId();
877     settings.source = renderengine::PixelSource{
878             .buffer = renderengine::Buffer{
879                     .buffer = getState().overrideInfo.buffer,
880                     .fence = getState().overrideInfo.acquireFence,
881                     // If the transform from layer space to display space contains a rotation, we
882                     // need to undo the rotation in the texture transform
883                     .textureTransform =
884                             ui::Transform(transform.inverse().getOrientation(), 1, 1).asMatrix4(),
885             }};
886     settings.sourceDataspace = getState().overrideInfo.dataspace;
887     settings.alpha = 1.0f;
888     settings.whitePointNits = getOutput().getState().sdrWhitePointNits;
889 
890     return settings;
891 }
892 
dump(std::string & out) const893 void OutputLayer::dump(std::string& out) const {
894     using android::base::StringAppendF;
895 
896     StringAppendF(&out, "  - Output Layer %p(%s)\n", this, getLayerFE().getDebugName());
897     dumpState(out);
898 }
899 
900 } // namespace impl
901 } // namespace android::compositionengine
902