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