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