blob: 8d560d732caf81ae75ec1c454d1eea621221f52d [file] [log] [blame]
Lloyd Pique32cbe282018-10-19 13:09:22 -07001/*
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
Alec Mouria90a5702021-04-16 16:36:21 +000017#include <SurfaceFlingerProperties.sysprop.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070018#include <android-base/stringprintf.h>
19#include <compositionengine/CompositionEngine.h>
Lloyd Piquef8cf14d2019-02-28 16:03:12 -080020#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070021#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080022#include <compositionengine/LayerFE.h>
Lloyd Pique9755fb72019-03-26 14:44:40 -070023#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070024#include <compositionengine/RenderSurface.h>
Vishnu Nair7234fa52022-02-24 14:07:11 -080025#include <compositionengine/impl/HwcAsyncWorker.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070026#include <compositionengine/impl/Output.h>
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070027#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080028#include <compositionengine/impl/OutputLayer.h>
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070029#include <compositionengine/impl/OutputLayerCompositionState.h>
Dan Stoza269dc4d2021-01-15 15:07:43 -080030#include <compositionengine/impl/planner/Planner.h>
Sally Qi59a9f502021-10-12 18:53:23 +000031#include <ftl/future.h>
Dan Stoza269dc4d2021-01-15 15:07:43 -080032
Alec Mouria90a5702021-04-16 16:36:21 +000033#include <thread>
34
35#include "renderengine/ExternalTexture.h"
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080036
37// TODO(b/129481165): remove the #pragma below and fix conversion issues
38#pragma clang diagnostic push
39#pragma clang diagnostic ignored "-Wconversion"
40
Lloyd Pique688abd42019-02-15 15:42:24 -080041#include <renderengine/DisplaySettings.h>
42#include <renderengine/RenderEngine.h>
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080043
44// TODO(b/129481165): remove the #pragma below and fix conversion issues
45#pragma clang diagnostic pop // ignored "-Wconversion"
46
Dan Stoza269dc4d2021-01-15 15:07:43 -080047#include <android-base/properties.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070048#include <ui/DebugUtils.h>
Lloyd Pique688abd42019-02-15 15:42:24 -080049#include <ui/HdrCapabilities.h>
Lloyd Pique66d68602019-02-13 14:23:31 -080050#include <utils/Trace.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070051
Lloyd Pique688abd42019-02-15 15:42:24 -080052#include "TracedOrdinal.h"
53
Leon Scroggins III9a0afda2022-01-11 16:53:09 -050054using aidl::android::hardware::graphics::composer3::Composition;
55
Lloyd Piquefeb73d72018-12-04 17:23:44 -080056namespace android::compositionengine {
57
58Output::~Output() = default;
59
60namespace impl {
Lloyd Pique32cbe282018-10-19 13:09:22 -070061
Lloyd Piquec29e4c62019-03-07 21:48:19 -080062namespace {
63
64template <typename T>
65class Reversed {
66public:
67 explicit Reversed(const T& container) : mContainer(container) {}
68 auto begin() { return mContainer.rbegin(); }
69 auto end() { return mContainer.rend(); }
70
71private:
72 const T& mContainer;
73};
74
75// Helper for enumerating over a container in reverse order
76template <typename T>
77Reversed<T> reversed(const T& c) {
78 return Reversed<T>(c);
79}
80
Marin Shalamanovb15d2272020-09-17 21:41:52 +020081struct ScaleVector {
82 float x;
83 float y;
84};
85
86// Returns a ScaleVector (x, y) such that from.scale(x, y) = to',
87// where to' will have the same size as "to". In the case where "from" and "to"
88// start at the origin to'=to.
89ScaleVector getScale(const Rect& from, const Rect& to) {
90 return {.x = static_cast<float>(to.width()) / from.width(),
91 .y = static_cast<float>(to.height()) / from.height()};
92}
93
Lloyd Piquec29e4c62019-03-07 21:48:19 -080094} // namespace
95
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070096std::shared_ptr<Output> createOutput(
97 const compositionengine::CompositionEngine& compositionEngine) {
98 return createOutputTemplated<Output>(compositionEngine);
99}
Lloyd Pique32cbe282018-10-19 13:09:22 -0700100
101Output::~Output() = default;
102
Lloyd Pique32cbe282018-10-19 13:09:22 -0700103bool Output::isValid() const {
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700104 return mDisplayColorProfile && mDisplayColorProfile->isValid() && mRenderSurface &&
105 mRenderSurface->isValid();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700106}
107
Lloyd Pique6c564cf2019-05-17 17:31:36 -0700108std::optional<DisplayId> Output::getDisplayId() const {
109 return {};
110}
111
Lloyd Pique32cbe282018-10-19 13:09:22 -0700112const std::string& Output::getName() const {
113 return mName;
114}
115
116void Output::setName(const std::string& name) {
117 mName = name;
118}
119
120void Output::setCompositionEnabled(bool enabled) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700121 auto& outputState = editState();
122 if (outputState.isEnabled == enabled) {
Lloyd Pique32cbe282018-10-19 13:09:22 -0700123 return;
124 }
125
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700126 outputState.isEnabled = enabled;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700127 dirtyEntireOutput();
128}
129
Alec Mouri023c1882021-05-08 16:36:33 -0700130void Output::setLayerCachingEnabled(bool enabled) {
131 if (enabled == (mPlanner != nullptr)) {
132 return;
133 }
134
135 if (enabled) {
Alec Mouridf6201b2021-06-01 16:20:42 -0700136 mPlanner = std::make_unique<planner::Planner>(getCompositionEngine().getRenderEngine());
Alec Mouri023c1882021-05-08 16:36:33 -0700137 if (mRenderSurface) {
138 mPlanner->setDisplaySize(mRenderSurface->getSize());
139 }
140 } else {
141 mPlanner.reset();
142 }
Alec Mouric773472b2021-05-19 14:29:05 -0700143
144 for (auto* outputLayer : getOutputLayersOrderedByZ()) {
145 if (!outputLayer) {
146 continue;
147 }
148
149 outputLayer->editState().overrideInfo = {};
150 }
Alec Mouri023c1882021-05-08 16:36:33 -0700151}
152
Ady Abrahamdb036a82021-07-16 14:18:34 -0700153void Output::setLayerCachingTexturePoolEnabled(bool enabled) {
154 if (mPlanner) {
155 mPlanner->setTexturePoolEnabled(enabled);
156 }
157}
158
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200159void Output::setProjection(ui::Rotation orientation, const Rect& layerStackSpaceRect,
160 const Rect& orientedDisplaySpaceRect) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700161 auto& outputState = editState();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200162
Angel Aguayob084e0c2021-08-04 23:27:28 +0000163 outputState.displaySpace.setOrientation(orientation);
164 LOG_FATAL_IF(outputState.displaySpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200165 "The display bounds are unknown.");
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200166
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200167 // Compute orientedDisplaySpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000168 ui::Size orientedSize = outputState.displaySpace.getBounds();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200169 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200170 std::swap(orientedSize.width, orientedSize.height);
171 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000172 outputState.orientedDisplaySpace.setBounds(orientedSize);
173 outputState.orientedDisplaySpace.setContent(orientedDisplaySpaceRect);
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200174
175 // Compute displaySpace.content
176 const uint32_t transformOrientationFlags = ui::Transform::toRotationFlags(orientation);
177 ui::Transform rotation;
178 if (transformOrientationFlags != ui::Transform::ROT_INVALID) {
Angel Aguayob084e0c2021-08-04 23:27:28 +0000179 const auto displaySize = outputState.displaySpace.getBoundsAsRect();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200180 rotation.set(transformOrientationFlags, displaySize.width(), displaySize.height());
181 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000182 outputState.displaySpace.setContent(rotation.transform(orientedDisplaySpaceRect));
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200183
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200184 // Compute framebufferSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000185 outputState.framebufferSpace.setOrientation(orientation);
186 LOG_FATAL_IF(outputState.framebufferSpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200187 "The framebuffer bounds are unknown.");
Angel Aguayob084e0c2021-08-04 23:27:28 +0000188 const auto scale = getScale(outputState.displaySpace.getBoundsAsRect(),
189 outputState.framebufferSpace.getBoundsAsRect());
190 outputState.framebufferSpace.setContent(
191 outputState.displaySpace.getContent().scale(scale.x, scale.y));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200192
193 // Compute layerStackSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000194 outputState.layerStackSpace.setContent(layerStackSpaceRect);
195 outputState.layerStackSpace.setBounds(
196 ui::Size(layerStackSpaceRect.getWidth(), layerStackSpaceRect.getHeight()));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200197
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200198 outputState.transform = outputState.layerStackSpace.getTransform(outputState.displaySpace);
199 outputState.needsFiltering = outputState.transform.needsBilinearFiltering();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700200 dirtyEntireOutput();
201}
202
Alec Mouricdf16792021-12-10 13:16:06 -0800203void Output::setNextBrightness(float brightness) {
204 editState().displayBrightness = brightness;
205}
206
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200207void Output::setDisplaySize(const ui::Size& size) {
Lloyd Pique31cb2942018-10-19 17:23:03 -0700208 mRenderSurface->setDisplaySize(size);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200209
210 auto& state = editState();
211
212 // Update framebuffer space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000213 const ui::Size newBounds(size);
214 state.framebufferSpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200215
216 // Update display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000217 state.displaySpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200218 state.transform = state.layerStackSpace.getTransform(state.displaySpace);
219
220 // Update oriented display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000221 const auto orientation = state.displaySpace.getOrientation();
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200222 ui::Size orientedSize = size;
223 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
224 std::swap(orientedSize.width, orientedSize.height);
225 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000226 const ui::Size newOrientedBounds(orientedSize);
227 state.orientedDisplaySpace.setBounds(newOrientedBounds);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700228
Dan Stoza6166c312021-01-15 16:34:05 -0800229 if (mPlanner) {
230 mPlanner->setDisplaySize(size);
231 }
232
Lloyd Pique32cbe282018-10-19 13:09:22 -0700233 dirtyEntireOutput();
234}
235
Garfield Tan54edd912020-10-21 16:31:41 -0700236ui::Transform::RotationFlags Output::getTransformHint() const {
237 return static_cast<ui::Transform::RotationFlags>(getState().transform.getOrientation());
238}
239
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700240void Output::setLayerFilter(ui::LayerFilter filter) {
241 editState().layerFilter = filter;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700242 dirtyEntireOutput();
243}
244
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800245void Output::setColorTransform(const compositionengine::CompositionRefreshArgs& args) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700246 auto& colorTransformMatrix = editState().colorTransformMatrix;
247 if (!args.colorTransformMatrix || colorTransformMatrix == args.colorTransformMatrix) {
Lloyd Pique77f79a22019-04-29 15:55:40 -0700248 return;
249 }
250
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700251 colorTransformMatrix = *args.colorTransformMatrix;
Lloyd Piqueef958122019-02-05 18:00:12 -0800252
253 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700254}
255
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800256void Output::setColorProfile(const ColorProfile& colorProfile) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700257 ui::Dataspace targetDataspace =
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800258 getDisplayColorProfile()->getTargetDataspace(colorProfile.mode, colorProfile.dataspace,
259 colorProfile.colorSpaceAgnosticDataspace);
Lloyd Piquef5275482019-01-29 18:42:42 -0800260
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700261 auto& outputState = editState();
262 if (outputState.colorMode == colorProfile.mode &&
263 outputState.dataspace == colorProfile.dataspace &&
264 outputState.renderIntent == colorProfile.renderIntent &&
265 outputState.targetDataspace == targetDataspace) {
Lloyd Piqueef958122019-02-05 18:00:12 -0800266 return;
267 }
268
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700269 outputState.colorMode = colorProfile.mode;
270 outputState.dataspace = colorProfile.dataspace;
271 outputState.renderIntent = colorProfile.renderIntent;
272 outputState.targetDataspace = targetDataspace;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700273
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800274 mRenderSurface->setBufferDataspace(colorProfile.dataspace);
Lloyd Pique31cb2942018-10-19 17:23:03 -0700275
Lloyd Pique32cbe282018-10-19 13:09:22 -0700276 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d)",
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800277 decodeColorMode(colorProfile.mode).c_str(), colorProfile.mode,
278 decodeRenderIntent(colorProfile.renderIntent).c_str(), colorProfile.renderIntent);
Lloyd Piqueef958122019-02-05 18:00:12 -0800279
280 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700281}
282
John Reckac09e452021-04-07 16:35:37 -0400283void Output::setDisplayBrightness(float sdrWhitePointNits, float displayBrightnessNits) {
284 auto& outputState = editState();
285 if (outputState.sdrWhitePointNits == sdrWhitePointNits &&
286 outputState.displayBrightnessNits == displayBrightnessNits) {
287 // Nothing changed
288 return;
289 }
290 outputState.sdrWhitePointNits = sdrWhitePointNits;
291 outputState.displayBrightnessNits = displayBrightnessNits;
292 dirtyEntireOutput();
293}
294
Lloyd Pique32cbe282018-10-19 13:09:22 -0700295void Output::dump(std::string& out) const {
296 using android::base::StringAppendF;
297
298 StringAppendF(&out, " Composition Output State: [\"%s\"]", mName.c_str());
299
300 out.append("\n ");
301
302 dumpBase(out);
303}
304
305void Output::dumpBase(std::string& out) const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700306 dumpState(out);
Lloyd Pique31cb2942018-10-19 17:23:03 -0700307
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700308 if (mDisplayColorProfile) {
309 mDisplayColorProfile->dump(out);
310 } else {
311 out.append(" No display color profile!\n");
312 }
313
Lloyd Pique31cb2942018-10-19 17:23:03 -0700314 if (mRenderSurface) {
315 mRenderSurface->dump(out);
316 } else {
317 out.append(" No render surface!\n");
318 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800319
Lloyd Pique01c77c12019-04-17 12:48:32 -0700320 android::base::StringAppendF(&out, "\n %zu Layers\n", getOutputLayerCount());
321 for (const auto* outputLayer : getOutputLayersOrderedByZ()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800322 if (!outputLayer) {
323 continue;
324 }
325 outputLayer->dump(out);
326 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700327}
328
Dan Stoza269dc4d2021-01-15 15:07:43 -0800329void Output::dumpPlannerInfo(const Vector<String16>& args, std::string& out) const {
330 if (!mPlanner) {
331 base::StringAppendF(&out, "Planner is disabled\n");
332 return;
333 }
334 base::StringAppendF(&out, "Planner info for display [%s]\n", mName.c_str());
335 mPlanner->dump(args, out);
336}
337
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700338compositionengine::DisplayColorProfile* Output::getDisplayColorProfile() const {
339 return mDisplayColorProfile.get();
340}
341
342void Output::setDisplayColorProfile(std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
343 mDisplayColorProfile = std::move(mode);
344}
345
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800346const Output::ReleasedLayers& Output::getReleasedLayersForTest() const {
347 return mReleasedLayers;
348}
349
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700350void Output::setDisplayColorProfileForTest(
351 std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
352 mDisplayColorProfile = std::move(mode);
353}
354
Lloyd Pique31cb2942018-10-19 17:23:03 -0700355compositionengine::RenderSurface* Output::getRenderSurface() const {
356 return mRenderSurface.get();
357}
358
359void Output::setRenderSurface(std::unique_ptr<compositionengine::RenderSurface> surface) {
360 mRenderSurface = std::move(surface);
Dan Stoza6166c312021-01-15 16:34:05 -0800361 const auto size = mRenderSurface->getSize();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000362 editState().framebufferSpace.setBounds(size);
Dan Stoza6166c312021-01-15 16:34:05 -0800363 if (mPlanner) {
364 mPlanner->setDisplaySize(size);
365 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700366 dirtyEntireOutput();
367}
368
Vishnu Nair9b079a22020-01-21 14:36:08 -0800369void Output::cacheClientCompositionRequests(uint32_t cacheSize) {
370 if (cacheSize == 0) {
371 mClientCompositionRequestCache.reset();
372 } else {
373 mClientCompositionRequestCache = std::make_unique<ClientCompositionRequestCache>(cacheSize);
374 }
375};
376
Lloyd Pique31cb2942018-10-19 17:23:03 -0700377void Output::setRenderSurfaceForTest(std::unique_ptr<compositionengine::RenderSurface> surface) {
378 mRenderSurface = std::move(surface);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700379}
380
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700381Region Output::getDirtyRegion() const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700382 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000383 return outputState.dirtyRegion.intersect(outputState.layerStackSpace.getContent());
Lloyd Pique32cbe282018-10-19 13:09:22 -0700384}
385
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700386bool Output::includesLayer(ui::LayerFilter filter) const {
387 return getState().layerFilter.includes(filter);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700388}
389
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700390bool Output::includesLayer(const sp<LayerFE>& layerFE) const {
Lloyd Piquede196652020-01-22 17:29:58 -0800391 const auto* layerFEState = layerFE->getCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700392 return layerFEState && includesLayer(layerFEState->outputFilter);
Lloyd Pique66c20c42019-03-07 21:44:02 -0800393}
394
Lloyd Piquedf336d92019-03-07 21:38:42 -0800395std::unique_ptr<compositionengine::OutputLayer> Output::createOutputLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800396 const sp<LayerFE>& layerFE) const {
397 return impl::createOutputLayer(*this, layerFE);
Lloyd Piquecc01a452018-12-04 17:24:00 -0800398}
399
Lloyd Piquede196652020-01-22 17:29:58 -0800400compositionengine::OutputLayer* Output::getOutputLayerForLayer(const sp<LayerFE>& layerFE) const {
401 auto index = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700402 return index ? getOutputLayerOrderedByZByIndex(*index) : nullptr;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800403}
404
Lloyd Pique01c77c12019-04-17 12:48:32 -0700405std::optional<size_t> Output::findCurrentOutputLayerForLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800406 const sp<compositionengine::LayerFE>& layer) const {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700407 for (size_t i = 0; i < getOutputLayerCount(); i++) {
408 auto outputLayer = getOutputLayerOrderedByZByIndex(i);
Lloyd Piquede196652020-01-22 17:29:58 -0800409 if (outputLayer && &outputLayer->getLayerFE() == layer.get()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700410 return i;
411 }
412 }
413 return std::nullopt;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800414}
415
Lloyd Piquec7ef21b2019-01-29 18:43:00 -0800416void Output::setReleasedLayers(Output::ReleasedLayers&& layers) {
417 mReleasedLayers = std::move(layers);
418}
419
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800420void Output::prepare(const compositionengine::CompositionRefreshArgs& refreshArgs,
421 LayerFESet& geomSnapshots) {
422 ATRACE_CALL();
423 ALOGV(__FUNCTION__);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800424
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800425 rebuildLayerStacks(refreshArgs, geomSnapshots);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800426}
427
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800428void Output::present(const compositionengine::CompositionRefreshArgs& refreshArgs) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800429 ATRACE_CALL();
430 ALOGV(__FUNCTION__);
431
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800432 updateColorProfile(refreshArgs);
Dan Stoza269dc4d2021-01-15 15:07:43 -0800433 updateCompositionState(refreshArgs);
434 planComposition();
435 writeCompositionState(refreshArgs);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800436 setColorTransform(refreshArgs);
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800437 beginFrame();
Vishnu Nair7234fa52022-02-24 14:07:11 -0800438
439 GpuCompositionResult result;
440 const bool predictCompositionStrategy = canPredictCompositionStrategy(refreshArgs);
441 if (predictCompositionStrategy) {
442 result = prepareFrameAsync(refreshArgs);
443 } else {
444 prepareFrame();
445 }
446
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800447 devOptRepaintFlash(refreshArgs);
Vishnu Nair7234fa52022-02-24 14:07:11 -0800448 finishFrame(refreshArgs, std::move(result));
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800449 postFramebuffer();
Alec Mouriaa831582021-06-07 16:23:01 -0700450 renderCachedSets(refreshArgs);
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800451}
452
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800453void Output::rebuildLayerStacks(const compositionengine::CompositionRefreshArgs& refreshArgs,
454 LayerFESet& layerFESet) {
455 ATRACE_CALL();
456 ALOGV(__FUNCTION__);
457
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700458 auto& outputState = editState();
459
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800460 // Do nothing if this output is not enabled or there is no need to perform this update
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700461 if (!outputState.isEnabled || CC_LIKELY(!refreshArgs.updatingOutputGeometryThisFrame)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800462 return;
463 }
464
465 // Process the layers to determine visibility and coverage
466 compositionengine::Output::CoverageState coverage{layerFESet};
467 collectVisibleLayers(refreshArgs, coverage);
468
469 // Compute the resulting coverage for this output, and store it for later
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700470 const ui::Transform& tr = outputState.transform;
Angel Aguayob084e0c2021-08-04 23:27:28 +0000471 Region undefinedRegion{outputState.displaySpace.getBoundsAsRect()};
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800472 undefinedRegion.subtractSelf(tr.transform(coverage.aboveOpaqueLayers));
473
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700474 outputState.undefinedRegion = undefinedRegion;
475 outputState.dirtyRegion.orSelf(coverage.dirtyRegion);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800476}
477
478void Output::collectVisibleLayers(const compositionengine::CompositionRefreshArgs& refreshArgs,
479 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800480 // Evaluate the layers from front to back to determine what is visible. This
481 // also incrementally calculates the coverage information for each layer as
482 // well as the entire output.
Lloyd Piquede196652020-01-22 17:29:58 -0800483 for (auto layer : reversed(refreshArgs.layers)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700484 // Incrementally process the coverage for each layer
485 ensureOutputLayerIfVisible(layer, coverage);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800486
487 // TODO(b/121291683): Stop early if the output is completely covered and
488 // no more layers could even be visible underneath the ones on top.
489 }
490
Lloyd Pique01c77c12019-04-17 12:48:32 -0700491 setReleasedLayers(refreshArgs);
492
493 finalizePendingOutputLayers();
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800494}
495
Lloyd Piquede196652020-01-22 17:29:58 -0800496void Output::ensureOutputLayerIfVisible(sp<compositionengine::LayerFE>& layerFE,
Lloyd Pique01c77c12019-04-17 12:48:32 -0700497 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800498 // Ensure we have a snapshot of the basic geometry layer state. Limit the
499 // snapshots to once per frame for each candidate layer, as layers may
500 // appear on multiple outputs.
501 if (!coverage.latchedLayers.count(layerFE)) {
502 coverage.latchedLayers.insert(layerFE);
Lloyd Piquede196652020-01-22 17:29:58 -0800503 layerFE->prepareCompositionState(compositionengine::LayerFE::StateSubset::BasicGeometry);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800504 }
505
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700506 // Only consider the layers on this output
507 if (!includesLayer(layerFE)) {
Lloyd Piquede196652020-01-22 17:29:58 -0800508 return;
509 }
510
511 // Obtain a read-only pointer to the front-end layer state
512 const auto* layerFEState = layerFE->getCompositionState();
513 if (CC_UNLIKELY(!layerFEState)) {
514 return;
515 }
516
517 // handle hidden surfaces by setting the visible region to empty
518 if (CC_UNLIKELY(!layerFEState->isVisible)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700519 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800520 }
521
522 /*
523 * opaqueRegion: area of a surface that is fully opaque.
524 */
525 Region opaqueRegion;
526
527 /*
528 * visibleRegion: area of a surface that is visible on screen and not fully
529 * transparent. This is essentially the layer's footprint minus the opaque
530 * regions above it. Areas covered by a translucent surface are considered
531 * visible.
532 */
533 Region visibleRegion;
534
535 /*
536 * coveredRegion: area of a surface that is covered by all visible regions
537 * above it (which includes the translucent areas).
538 */
539 Region coveredRegion;
540
541 /*
542 * transparentRegion: area of a surface that is hinted to be completely
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500543 * transparent.
544 * This is used to tell when the layer has no visible non-transparent
545 * regions and can be removed from the layer list. It does not affect the
546 * visibleRegion of this layer or any layers beneath it. The hint may not
547 * be correct if apps don't respect the SurfaceView restrictions (which,
548 * sadly, some don't).
549 *
550 * In addition, it is used on DISPLAY_DECORATION layers to specify the
551 * blockingRegion, allowing the DPU to skip it to save power. Once we have
552 * hardware that supports a blockingRegion on frames with AFBC, it may be
553 * useful to use this for other layers, too, so long as we can prevent
554 * regressions on b/7179570.
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800555 */
556 Region transparentRegion;
557
Vishnu Naira483b4a2019-12-12 15:07:52 -0800558 /*
559 * shadowRegion: Region cast by the layer's shadow.
560 */
561 Region shadowRegion;
562
Lloyd Piquede196652020-01-22 17:29:58 -0800563 const ui::Transform& tr = layerFEState->geomLayerTransform;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800564
565 // Get the visible region
566 // TODO(b/121291683): Is it worth creating helper methods on LayerFEState
567 // for computations like this?
Lloyd Piquede196652020-01-22 17:29:58 -0800568 const Rect visibleRect(tr.transform(layerFEState->geomLayerBounds));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800569 visibleRegion.set(visibleRect);
570
Lloyd Piquede196652020-01-22 17:29:58 -0800571 if (layerFEState->shadowRadius > 0.0f) {
Vishnu Naira483b4a2019-12-12 15:07:52 -0800572 // if the layer casts a shadow, offset the layers visible region and
573 // calculate the shadow region.
Lloyd Piquede196652020-01-22 17:29:58 -0800574 const auto inset = static_cast<int32_t>(ceilf(layerFEState->shadowRadius) * -1.0f);
Vishnu Naira483b4a2019-12-12 15:07:52 -0800575 Rect visibleRectWithShadows(visibleRect);
576 visibleRectWithShadows.inset(inset, inset, inset, inset);
577 visibleRegion.set(visibleRectWithShadows);
578 shadowRegion = visibleRegion.subtract(visibleRect);
579 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800580
581 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700582 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800583 }
584
585 // Remove the transparent area from the visible region
Lloyd Piquede196652020-01-22 17:29:58 -0800586 if (!layerFEState->isOpaque) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800587 if (tr.preserveRects()) {
588 // transform the transparent region
Lloyd Piquede196652020-01-22 17:29:58 -0800589 transparentRegion = tr.transform(layerFEState->transparentRegionHint);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800590 } else {
591 // transformation too complex, can't do the
592 // transparent region optimization.
593 transparentRegion.clear();
594 }
595 }
596
597 // compute the opaque region
Lloyd Pique0a456232020-01-16 17:51:13 -0800598 const auto layerOrientation = tr.getOrientation();
Lloyd Piquede196652020-01-22 17:29:58 -0800599 if (layerFEState->isOpaque && ((layerOrientation & ui::Transform::ROT_INVALID) == 0)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800600 // If we one of the simple category of transforms (0/90/180/270 rotation
601 // + any flip), then the opaque region is the layer's footprint.
602 // Otherwise we don't try and compute the opaque region since there may
603 // be errors at the edges, and we treat the entire layer as
604 // translucent.
Vishnu Naira483b4a2019-12-12 15:07:52 -0800605 opaqueRegion.set(visibleRect);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800606 }
607
608 // Clip the covered region to the visible region
609 coveredRegion = coverage.aboveCoveredLayers.intersect(visibleRegion);
610
611 // Update accumAboveCoveredLayers for next (lower) layer
612 coverage.aboveCoveredLayers.orSelf(visibleRegion);
613
614 // subtract the opaque region covered by the layers above us
615 visibleRegion.subtractSelf(coverage.aboveOpaqueLayers);
616
617 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700618 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800619 }
620
621 // Get coverage information for the layer as previously displayed,
622 // also taking over ownership from mOutputLayersorderedByZ.
Lloyd Piquede196652020-01-22 17:29:58 -0800623 auto prevOutputLayerIndex = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700624 auto prevOutputLayer =
625 prevOutputLayerIndex ? getOutputLayerOrderedByZByIndex(*prevOutputLayerIndex) : nullptr;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800626
627 // Get coverage information for the layer as previously displayed
628 // TODO(b/121291683): Define kEmptyRegion as a constant in Region.h
629 const Region kEmptyRegion;
630 const Region& oldVisibleRegion =
631 prevOutputLayer ? prevOutputLayer->getState().visibleRegion : kEmptyRegion;
632 const Region& oldCoveredRegion =
633 prevOutputLayer ? prevOutputLayer->getState().coveredRegion : kEmptyRegion;
634
635 // compute this layer's dirty region
636 Region dirty;
Lloyd Piquede196652020-01-22 17:29:58 -0800637 if (layerFEState->contentDirty) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800638 // we need to invalidate the whole region
639 dirty = visibleRegion;
640 // as well, as the old visible region
641 dirty.orSelf(oldVisibleRegion);
642 } else {
643 /* compute the exposed region:
644 * the exposed region consists of two components:
645 * 1) what's VISIBLE now and was COVERED before
646 * 2) what's EXPOSED now less what was EXPOSED before
647 *
648 * note that (1) is conservative, we start with the whole visible region
649 * but only keep what used to be covered by something -- which mean it
650 * may have been exposed.
651 *
652 * (2) handles areas that were not covered by anything but got exposed
653 * because of a resize.
654 *
655 */
656 const Region newExposed = visibleRegion - coveredRegion;
657 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
658 dirty = (visibleRegion & oldCoveredRegion) | (newExposed - oldExposed);
659 }
660 dirty.subtractSelf(coverage.aboveOpaqueLayers);
661
662 // accumulate to the screen dirty region
663 coverage.dirtyRegion.orSelf(dirty);
664
665 // Update accumAboveOpaqueLayers for next (lower) layer
666 coverage.aboveOpaqueLayers.orSelf(opaqueRegion);
667
668 // Compute the visible non-transparent region
669 Region visibleNonTransparentRegion = visibleRegion.subtract(transparentRegion);
670
Vishnu Naira483b4a2019-12-12 15:07:52 -0800671 // Perform the final check to see if this layer is visible on this output
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800672 // TODO(b/121291683): Why does this not use visibleRegion? (see outputSpaceVisibleRegion below)
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700673 const auto& outputState = getState();
674 Region drawRegion(outputState.transform.transform(visibleNonTransparentRegion));
Angel Aguayob084e0c2021-08-04 23:27:28 +0000675 drawRegion.andSelf(outputState.displaySpace.getBoundsAsRect());
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800676 if (drawRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700677 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800678 }
679
Vishnu Naira483b4a2019-12-12 15:07:52 -0800680 Region visibleNonShadowRegion = visibleRegion.subtract(shadowRegion);
681
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800682 // The layer is visible. Either reuse the existing outputLayer if we have
683 // one, or create a new one if we do not.
Lloyd Piquede196652020-01-22 17:29:58 -0800684 auto result = ensureOutputLayer(prevOutputLayerIndex, layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800685
686 // Store the layer coverage information into the layer state as some of it
687 // is useful later.
688 auto& outputLayerState = result->editState();
689 outputLayerState.visibleRegion = visibleRegion;
690 outputLayerState.visibleNonTransparentRegion = visibleNonTransparentRegion;
691 outputLayerState.coveredRegion = coveredRegion;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200692 outputLayerState.outputSpaceVisibleRegion = outputState.transform.transform(
Angel Aguayob084e0c2021-08-04 23:27:28 +0000693 visibleNonShadowRegion.intersect(outputState.layerStackSpace.getContent()));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800694 outputLayerState.shadowRegion = shadowRegion;
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500695 outputLayerState.outputSpaceBlockingRegionHint =
696 layerFEState->compositionType == Composition::DISPLAY_DECORATION ? transparentRegion
697 : Region();
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800698}
699
700void Output::setReleasedLayers(const compositionengine::CompositionRefreshArgs&) {
701 // The base class does nothing with this call.
702}
703
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800704void Output::updateLayerStateFromFE(const CompositionRefreshArgs& args) const {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700705 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800706 layer->getLayerFE().prepareCompositionState(
707 args.updatingGeometryThisFrame ? LayerFE::StateSubset::GeometryAndContent
708 : LayerFE::StateSubset::Content);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800709 }
710}
711
Dan Stoza269dc4d2021-01-15 15:07:43 -0800712void Output::updateCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800713 ATRACE_CALL();
714 ALOGV(__FUNCTION__);
715
Alec Mourif9a2a2c2019-11-12 12:46:02 -0800716 if (!getState().isEnabled) {
717 return;
718 }
719
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800720 mLayerRequestingBackgroundBlur = findLayerRequestingBackgroundComposition();
721 bool forceClientComposition = mLayerRequestingBackgroundBlur != nullptr;
722
Lloyd Pique01c77c12019-04-17 12:48:32 -0700723 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique7a234912019-10-03 11:54:27 -0700724 layer->updateCompositionState(refreshArgs.updatingGeometryThisFrame,
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800725 refreshArgs.devOptForceClientComposition ||
Snild Dolkow9e217d62020-04-22 15:53:42 +0200726 forceClientComposition,
727 refreshArgs.internalDisplayRotationFlags);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800728
729 if (mLayerRequestingBackgroundBlur == layer) {
730 forceClientComposition = false;
731 }
Dan Stoza269dc4d2021-01-15 15:07:43 -0800732 }
733}
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800734
Dan Stoza269dc4d2021-01-15 15:07:43 -0800735void Output::planComposition() {
736 if (!mPlanner || !getState().isEnabled) {
737 return;
738 }
739
740 ATRACE_CALL();
741 ALOGV(__FUNCTION__);
742
743 mPlanner->plan(getOutputLayersOrderedByZ());
744}
745
746void Output::writeCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
747 ATRACE_CALL();
748 ALOGV(__FUNCTION__);
749
750 if (!getState().isEnabled) {
751 return;
752 }
753
Ady Abraham3645e642021-04-20 18:39:00 -0700754 editState().earliestPresentTime = refreshArgs.earliestPresentTime;
Ady Abrahamec7aa8a2021-06-28 12:37:09 -0700755 editState().previousPresentFence = refreshArgs.previousPresentFence;
Ady Abraham43065bd2021-12-10 17:22:15 -0800756 editState().expectedPresentTime = refreshArgs.expectedPresentTime;
Ady Abraham3645e642021-04-20 18:39:00 -0700757
Leon Scroggins III2e74a4c2021-04-09 13:41:14 -0400758 compositionengine::OutputLayer* peekThroughLayer = nullptr;
Dan Stoza6166c312021-01-15 16:34:05 -0800759 sp<GraphicBuffer> previousOverride = nullptr;
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400760 bool includeGeometry = refreshArgs.updatingGeometryThisFrame;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400761 uint32_t z = 0;
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400762 bool overrideZ = false;
Dan Stoza269dc4d2021-01-15 15:07:43 -0800763 for (auto* layer : getOutputLayersOrderedByZ()) {
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400764 if (layer == peekThroughLayer) {
765 // No longer needed, although it should not show up again, so
766 // resetting it is not truly needed either.
767 peekThroughLayer = nullptr;
768
769 // peekThroughLayer was already drawn ahead of its z order.
770 continue;
771 }
Dan Stoza6166c312021-01-15 16:34:05 -0800772 bool skipLayer = false;
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400773 const auto& overrideInfo = layer->getState().overrideInfo;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400774 if (overrideInfo.buffer != nullptr) {
775 if (previousOverride && overrideInfo.buffer->getBuffer() == previousOverride) {
Dan Stoza6166c312021-01-15 16:34:05 -0800776 ALOGV("Skipping redundant buffer");
777 skipLayer = true;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400778 } else {
779 // First layer with the override buffer.
780 if (overrideInfo.peekThroughLayer) {
781 peekThroughLayer = overrideInfo.peekThroughLayer;
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400782
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400783 // Draw peekThroughLayer first.
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400784 overrideZ = true;
785 includeGeometry = true;
786 constexpr bool isPeekingThrough = true;
787 peekThroughLayer->writeStateToHWC(includeGeometry, false, z++, overrideZ,
788 isPeekingThrough);
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400789 }
790
791 previousOverride = overrideInfo.buffer->getBuffer();
Dan Stoza6166c312021-01-15 16:34:05 -0800792 }
Dan Stoza6166c312021-01-15 16:34:05 -0800793 }
794
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400795 constexpr bool isPeekingThrough = false;
796 layer->writeStateToHWC(includeGeometry, skipLayer, z++, overrideZ, isPeekingThrough);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800797 }
798}
799
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800800compositionengine::OutputLayer* Output::findLayerRequestingBackgroundComposition() const {
801 compositionengine::OutputLayer* layerRequestingBgComposition = nullptr;
802 for (auto* layer : getOutputLayersOrderedByZ()) {
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100803 auto* compState = layer->getLayerFE().getCompositionState();
804
805 // If any layer has a sideband stream, we will disable blurs. In that case, we don't
806 // want to force client composition because of the blur.
807 if (compState->sidebandStream != nullptr) {
808 return nullptr;
809 }
Lucas Dupin084a6d42021-08-26 22:10:29 +0000810 if (compState->isOpaque) {
811 continue;
812 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100813 if (compState->backgroundBlurRadius > 0 || compState->blurRegions.size() > 0) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800814 layerRequestingBgComposition = layer;
815 }
816 }
817 return layerRequestingBgComposition;
818}
819
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800820void Output::updateColorProfile(const compositionengine::CompositionRefreshArgs& refreshArgs) {
821 setColorProfile(pickColorProfile(refreshArgs));
822}
823
824// Returns a data space that fits all visible layers. The returned data space
825// can only be one of
826// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
827// - Dataspace::DISPLAY_P3
828// - Dataspace::DISPLAY_BT2020
829// The returned HDR data space is one of
830// - Dataspace::UNKNOWN
831// - Dataspace::BT2020_HLG
832// - Dataspace::BT2020_PQ
833ui::Dataspace Output::getBestDataspace(ui::Dataspace* outHdrDataSpace,
834 bool* outIsHdrClientComposition) const {
835 ui::Dataspace bestDataSpace = ui::Dataspace::V0_SRGB;
836 *outHdrDataSpace = ui::Dataspace::UNKNOWN;
837
Lloyd Pique01c77c12019-04-17 12:48:32 -0700838 for (const auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800839 switch (layer->getLayerFE().getCompositionState()->dataspace) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800840 case ui::Dataspace::V0_SCRGB:
841 case ui::Dataspace::V0_SCRGB_LINEAR:
842 case ui::Dataspace::BT2020:
843 case ui::Dataspace::BT2020_ITU:
844 case ui::Dataspace::BT2020_LINEAR:
845 case ui::Dataspace::DISPLAY_BT2020:
846 bestDataSpace = ui::Dataspace::DISPLAY_BT2020;
847 break;
848 case ui::Dataspace::DISPLAY_P3:
849 bestDataSpace = ui::Dataspace::DISPLAY_P3;
850 break;
851 case ui::Dataspace::BT2020_PQ:
852 case ui::Dataspace::BT2020_ITU_PQ:
853 bestDataSpace = ui::Dataspace::DISPLAY_P3;
854 *outHdrDataSpace = ui::Dataspace::BT2020_PQ;
Lloyd Piquede196652020-01-22 17:29:58 -0800855 *outIsHdrClientComposition =
856 layer->getLayerFE().getCompositionState()->forceClientComposition;
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800857 break;
858 case ui::Dataspace::BT2020_HLG:
859 case ui::Dataspace::BT2020_ITU_HLG:
860 bestDataSpace = ui::Dataspace::DISPLAY_P3;
861 // When there's mixed PQ content and HLG content, we set the HDR
862 // data space to be BT2020_PQ and convert HLG to PQ.
863 if (*outHdrDataSpace == ui::Dataspace::UNKNOWN) {
864 *outHdrDataSpace = ui::Dataspace::BT2020_HLG;
865 }
866 break;
867 default:
868 break;
869 }
870 }
871
872 return bestDataSpace;
873}
874
875compositionengine::Output::ColorProfile Output::pickColorProfile(
876 const compositionengine::CompositionRefreshArgs& refreshArgs) const {
877 if (refreshArgs.outputColorSetting == OutputColorSetting::kUnmanaged) {
878 return ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
879 ui::RenderIntent::COLORIMETRIC,
880 refreshArgs.colorSpaceAgnosticDataspace};
881 }
882
883 ui::Dataspace hdrDataSpace;
884 bool isHdrClientComposition = false;
885 ui::Dataspace bestDataSpace = getBestDataspace(&hdrDataSpace, &isHdrClientComposition);
886
887 switch (refreshArgs.forceOutputColorMode) {
888 case ui::ColorMode::SRGB:
889 bestDataSpace = ui::Dataspace::V0_SRGB;
890 break;
891 case ui::ColorMode::DISPLAY_P3:
892 bestDataSpace = ui::Dataspace::DISPLAY_P3;
893 break;
894 default:
895 break;
896 }
897
898 // respect hdrDataSpace only when there is no legacy HDR support
899 const bool isHdr = hdrDataSpace != ui::Dataspace::UNKNOWN &&
900 !mDisplayColorProfile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
901 if (isHdr) {
902 bestDataSpace = hdrDataSpace;
903 }
904
905 ui::RenderIntent intent;
906 switch (refreshArgs.outputColorSetting) {
907 case OutputColorSetting::kManaged:
908 case OutputColorSetting::kUnmanaged:
909 intent = isHdr ? ui::RenderIntent::TONE_MAP_COLORIMETRIC
910 : ui::RenderIntent::COLORIMETRIC;
911 break;
912 case OutputColorSetting::kEnhanced:
913 intent = isHdr ? ui::RenderIntent::TONE_MAP_ENHANCE : ui::RenderIntent::ENHANCE;
914 break;
915 default: // vendor display color setting
916 intent = static_cast<ui::RenderIntent>(refreshArgs.outputColorSetting);
917 break;
918 }
919
920 ui::ColorMode outMode;
921 ui::Dataspace outDataSpace;
922 ui::RenderIntent outRenderIntent;
923 mDisplayColorProfile->getBestColorMode(bestDataSpace, intent, &outDataSpace, &outMode,
924 &outRenderIntent);
925
926 return ColorProfile{outMode, outDataSpace, outRenderIntent,
927 refreshArgs.colorSpaceAgnosticDataspace};
928}
929
Lloyd Piqued0a92a02019-02-19 17:47:26 -0800930void Output::beginFrame() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700931 auto& outputState = editState();
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700932 const bool dirty = !getDirtyRegion().isEmpty();
Lloyd Pique01c77c12019-04-17 12:48:32 -0700933 const bool empty = getOutputLayerCount() == 0;
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700934 const bool wasEmpty = !outputState.lastCompositionHadVisibleLayers;
Lloyd Piqued0a92a02019-02-19 17:47:26 -0800935
936 // If nothing has changed (!dirty), don't recompose.
937 // If something changed, but we don't currently have any visible layers,
938 // and didn't when we last did a composition, then skip it this time.
939 // The second rule does two things:
940 // - When all layers are removed from a display, we'll emit one black
941 // frame, then nothing more until we get new layers.
942 // - When a display is created with a private layer stack, we won't
943 // emit any black frames until a layer is added to the layer stack.
944 const bool mustRecompose = dirty && !(empty && wasEmpty);
945
946 const char flagPrefix[] = {'-', '+'};
947 static_cast<void>(flagPrefix);
948 ALOGV_IF("%s: %s composition for %s (%cdirty %cempty %cwasEmpty)", __FUNCTION__,
949 mustRecompose ? "doing" : "skipping", getName().c_str(), flagPrefix[dirty],
950 flagPrefix[empty], flagPrefix[wasEmpty]);
951
952 mRenderSurface->beginFrame(mustRecompose);
953
954 if (mustRecompose) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700955 outputState.lastCompositionHadVisibleLayers = !empty;
Lloyd Piqued0a92a02019-02-19 17:47:26 -0800956 }
957}
958
Lloyd Pique66d68602019-02-13 14:23:31 -0800959void Output::prepareFrame() {
960 ATRACE_CALL();
961 ALOGV(__FUNCTION__);
962
Vishnu Nair7234fa52022-02-24 14:07:11 -0800963 auto& outputState = editState();
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700964 if (!outputState.isEnabled) {
Lloyd Pique66d68602019-02-13 14:23:31 -0800965 return;
966 }
967
Vishnu Nair7234fa52022-02-24 14:07:11 -0800968 auto changes = chooseCompositionStrategy();
969 outputState.previousDeviceRequestedChanges = changes;
970 if (changes) {
971 applyCompositionStrategy(changes);
972 }
973 finishPrepareFrame();
974}
Lloyd Pique66d68602019-02-13 14:23:31 -0800975
Vishnu Nair7234fa52022-02-24 14:07:11 -0800976std::future<std::optional<android::HWComposer::DeviceRequestedChanges>>
977Output::chooseCompositionStrategyAsync() {
978 return mHwComposerAsyncWorker->send([&]() { return chooseCompositionStrategy(); });
979}
980
981GpuCompositionResult Output::prepareFrameAsync(const CompositionRefreshArgs& refreshArgs) {
982 ATRACE_CALL();
983 ALOGV(__FUNCTION__);
984 auto& state = editState();
985 const auto& previousChanges = state.previousDeviceRequestedChanges;
986 auto hwcResult = chooseCompositionStrategyAsync();
987 applyCompositionStrategy(previousChanges);
988 finishPrepareFrame();
989
990 base::unique_fd bufferFence;
991 std::shared_ptr<renderengine::ExternalTexture> buffer;
992 updateProtectedContentState();
993 const bool dequeueSucceeded = dequeueRenderBuffer(&bufferFence, &buffer);
994 GpuCompositionResult compositionResult;
995 if (dequeueSucceeded) {
996 std::optional<base::unique_fd> optFd =
997 composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
998 if (optFd) {
999 compositionResult.fence = std::move(*optFd);
1000 }
Dan Stoza47437bb2021-01-15 16:21:07 -08001001 }
1002
Vishnu Nair7234fa52022-02-24 14:07:11 -08001003 auto changes = hwcResult.valid() ? hwcResult.get() : std::nullopt;
1004 const bool predictionSucceeded = dequeueSucceeded && changes == previousChanges;
1005 compositionResult.succeeded = predictionSucceeded;
1006 if (!predictionSucceeded) {
1007 ATRACE_NAME("CompositionStrategyPredictionMiss");
1008 if (changes) {
1009 applyCompositionStrategy(changes);
1010 }
1011 finishPrepareFrame();
1012 // Track the dequeued buffer to reuse so we don't need to dequeue another one.
1013 compositionResult.buffer = buffer;
1014 } else {
1015 ATRACE_NAME("CompositionStrategyPredictionHit");
1016 }
1017 state.previousDeviceRequestedChanges = std::move(changes);
1018 return compositionResult;
Lloyd Pique66d68602019-02-13 14:23:31 -08001019}
1020
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001021void Output::devOptRepaintFlash(const compositionengine::CompositionRefreshArgs& refreshArgs) {
1022 if (CC_LIKELY(!refreshArgs.devOptFlashDirtyRegionsDelay)) {
1023 return;
1024 }
1025
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001026 if (getState().isEnabled) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001027 if (const auto dirtyRegion = getDirtyRegion(); !dirtyRegion.isEmpty()) {
Vishnu Nair7234fa52022-02-24 14:07:11 -08001028 base::unique_fd bufferFence;
1029 std::shared_ptr<renderengine::ExternalTexture> buffer;
1030 updateProtectedContentState();
1031 dequeueRenderBuffer(&bufferFence, &buffer);
1032 static_cast<void>(composeSurfaces(dirtyRegion, refreshArgs, buffer, bufferFence));
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001033 mRenderSurface->queueBuffer(base::unique_fd());
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001034 }
1035 }
1036
1037 postFramebuffer();
1038
1039 std::this_thread::sleep_for(*refreshArgs.devOptFlashDirtyRegionsDelay);
1040
1041 prepareFrame();
1042}
1043
Vishnu Nair7234fa52022-02-24 14:07:11 -08001044void Output::finishFrame(const CompositionRefreshArgs& refreshArgs, GpuCompositionResult&& result) {
Lloyd Piqued3d69882019-02-28 16:03:46 -08001045 ATRACE_CALL();
1046 ALOGV(__FUNCTION__);
1047
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001048 if (!getState().isEnabled) {
Lloyd Piqued3d69882019-02-28 16:03:46 -08001049 return;
1050 }
1051
Vishnu Nair7234fa52022-02-24 14:07:11 -08001052 std::optional<base::unique_fd> optReadyFence;
1053 std::shared_ptr<renderengine::ExternalTexture> buffer;
1054 base::unique_fd bufferFence;
1055 if (result.succeeded) {
1056 optReadyFence = std::move(result.fence);
1057 } else {
1058 if (result.bufferAvailable()) {
1059 buffer = std::move(result.buffer);
1060 bufferFence = std::move(result.fence);
1061 } else {
1062 updateProtectedContentState();
1063 if (!dequeueRenderBuffer(&bufferFence, &buffer)) {
1064 return;
1065 }
1066 }
1067 // Repaint the framebuffer (if needed), getting the optional fence for when
1068 // the composition completes.
1069 optReadyFence = composeSurfaces(Region::INVALID_REGION, refreshArgs, buffer, bufferFence);
1070 }
Lloyd Piqued3d69882019-02-28 16:03:46 -08001071 if (!optReadyFence) {
1072 return;
1073 }
1074
1075 // swap buffers (presentation)
1076 mRenderSurface->queueBuffer(std::move(*optReadyFence));
1077}
1078
Vishnu Nair7234fa52022-02-24 14:07:11 -08001079void Output::updateProtectedContentState() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001080 const auto& outputState = getState();
Lloyd Piquee9eff972020-05-05 12:36:44 -07001081 auto& renderEngine = getCompositionEngine().getRenderEngine();
1082 const bool supportsProtectedContent = renderEngine.supportsProtectedContent();
1083
1084 // If we the display is secure, protected content support is enabled, and at
1085 // least one layer has protected content, we need to use a secure back
1086 // buffer.
1087 if (outputState.isSecure && supportsProtectedContent) {
1088 auto layers = getOutputLayersOrderedByZ();
1089 bool needsProtected = std::any_of(layers.begin(), layers.end(), [](auto* layer) {
1090 return layer->getLayerFE().getCompositionState()->hasProtectedContent;
1091 });
1092 if (needsProtected != renderEngine.isProtected()) {
1093 renderEngine.useProtectedContext(needsProtected);
1094 }
1095 if (needsProtected != mRenderSurface->isProtected() &&
1096 needsProtected == renderEngine.isProtected()) {
1097 mRenderSurface->setProtected(needsProtected);
1098 }
Peiyong Lin09f910f2020-09-25 10:54:13 -07001099 } else if (!outputState.isSecure && renderEngine.isProtected()) {
1100 renderEngine.useProtectedContext(false);
Lloyd Piquee9eff972020-05-05 12:36:44 -07001101 }
Vishnu Nair7234fa52022-02-24 14:07:11 -08001102}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001103
Vishnu Nair7234fa52022-02-24 14:07:11 -08001104bool Output::dequeueRenderBuffer(base::unique_fd* bufferFence,
1105 std::shared_ptr<renderengine::ExternalTexture>* tex) {
1106 const auto& outputState = getState();
Lloyd Piquee9eff972020-05-05 12:36:44 -07001107
1108 // If we aren't doing client composition on this output, but do have a
1109 // flipClientTarget request for this frame on this output, we still need to
1110 // dequeue a buffer.
Vishnu Nair7234fa52022-02-24 14:07:11 -08001111 if (outputState.usesClientComposition || outputState.flipClientTarget) {
1112 *tex = mRenderSurface->dequeueBuffer(bufferFence);
1113 if (*tex == nullptr) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001114 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
1115 "client composition for this frame",
1116 mName.c_str());
Vishnu Nair7234fa52022-02-24 14:07:11 -08001117 return false;
Lloyd Piquee9eff972020-05-05 12:36:44 -07001118 }
1119 }
Vishnu Nair7234fa52022-02-24 14:07:11 -08001120 return true;
1121}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001122
Vishnu Nair7234fa52022-02-24 14:07:11 -08001123std::optional<base::unique_fd> Output::composeSurfaces(
1124 const Region& debugRegion, const compositionengine::CompositionRefreshArgs& refreshArgs,
1125 std::shared_ptr<renderengine::ExternalTexture> tex, base::unique_fd& fd) {
1126 ATRACE_CALL();
1127 ALOGV(__FUNCTION__);
1128
1129 const auto& outputState = getState();
1130 const TracedOrdinal<bool> hasClientComposition = {"hasClientComposition",
1131 outputState.usesClientComposition};
Lloyd Pique688abd42019-02-15 15:42:24 -08001132 if (!hasClientComposition) {
Lloyd Piquea76ce462020-01-14 13:06:37 -08001133 setExpensiveRenderingExpected(false);
Sally Qi4cabdd02021-08-05 16:45:57 -07001134 return base::unique_fd();
Lloyd Pique688abd42019-02-15 15:42:24 -08001135 }
1136
Vishnu Nair7234fa52022-02-24 14:07:11 -08001137 if (tex == nullptr) {
1138 ALOGW("Buffer not valid for display [%s], bailing out of "
1139 "client composition for this frame",
1140 mName.c_str());
1141 return {};
1142 }
1143
Lloyd Pique688abd42019-02-15 15:42:24 -08001144 ALOGV("hasClientComposition");
1145
Lloyd Pique688abd42019-02-15 15:42:24 -08001146 renderengine::DisplaySettings clientCompositionDisplay;
Angel Aguayob084e0c2021-08-04 23:27:28 +00001147 clientCompositionDisplay.physicalDisplay = outputState.framebufferSpace.getContent();
1148 clientCompositionDisplay.clip = outputState.layerStackSpace.getContent();
Marin Shalamanov68933fb2020-09-10 17:58:12 +02001149 clientCompositionDisplay.orientation =
Angel Aguayob084e0c2021-08-04 23:27:28 +00001150 ui::Transform::toRotationFlags(outputState.displaySpace.getOrientation());
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001151 clientCompositionDisplay.outputDataspace = mDisplayColorProfile->hasWideColorGamut()
1152 ? outputState.dataspace
1153 : ui::Dataspace::UNKNOWN;
John Reckac09e452021-04-07 16:35:37 -04001154
1155 // If we have a valid current display brightness use that, otherwise fall back to the
1156 // display's max desired
Alec Mourib21d94e2022-01-13 17:44:10 -08001157 clientCompositionDisplay.currentLuminanceNits = outputState.displayBrightnessNits > 0.f
John Reckac09e452021-04-07 16:35:37 -04001158 ? outputState.displayBrightnessNits
1159 : mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
Alec Mourib21d94e2022-01-13 17:44:10 -08001160 clientCompositionDisplay.maxLuminance =
1161 mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
Alec Mourif8d093d2022-02-10 15:16:59 -08001162 clientCompositionDisplay.targetLuminanceNits =
1163 outputState.clientTargetBrightness * outputState.displayBrightnessNits;
Lloyd Pique688abd42019-02-15 15:42:24 -08001164
1165 // Compute the global color transform matrix.
Leon Scroggins III745dcaa2022-01-26 11:55:58 -05001166 clientCompositionDisplay.colorTransform = outputState.colorTransformMatrix;
1167 clientCompositionDisplay.deviceHandlesColorTransform =
1168 outputState.usesDeviceComposition || getSkipColorTransform();
Lloyd Pique688abd42019-02-15 15:42:24 -08001169
Lloyd Pique688abd42019-02-15 15:42:24 -08001170 // Generate the client composition requests for the layers on this output.
Vishnu Nair7234fa52022-02-24 14:07:11 -08001171 auto& renderEngine = getCompositionEngine().getRenderEngine();
1172 const bool supportsProtectedContent = renderEngine.supportsProtectedContent();
Robert Carrccab4242021-09-28 16:53:03 -07001173 std::vector<LayerFE*> clientCompositionLayersFE;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001174 std::vector<LayerFE::LayerSettings> clientCompositionLayers =
Lloyd Pique688abd42019-02-15 15:42:24 -08001175 generateClientCompositionRequests(supportsProtectedContent,
Robert Carrccab4242021-09-28 16:53:03 -07001176 clientCompositionDisplay.outputDataspace,
1177 clientCompositionLayersFE);
Lloyd Pique688abd42019-02-15 15:42:24 -08001178 appendRegionFlashRequests(debugRegion, clientCompositionLayers);
1179
Vishnu Nair7234fa52022-02-24 14:07:11 -08001180 OutputCompositionState& outputCompositionState = editState();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001181 // Check if the client composition requests were rendered into the provided graphic buffer. If
1182 // so, we can reuse the buffer and avoid client composition.
1183 if (mClientCompositionRequestCache) {
Alec Mouria90a5702021-04-16 16:36:21 +00001184 if (mClientCompositionRequestCache->exists(tex->getBuffer()->getId(),
1185 clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001186 clientCompositionLayers)) {
Vishnu Nair7234fa52022-02-24 14:07:11 -08001187 ATRACE_NAME("ClientCompositionCacheHit");
Vishnu Nair9b079a22020-01-21 14:36:08 -08001188 outputCompositionState.reusedClientComposition = true;
1189 setExpensiveRenderingExpected(false);
Sally Qi4cabdd02021-08-05 16:45:57 -07001190 return base::unique_fd();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001191 }
Vishnu Nair7234fa52022-02-24 14:07:11 -08001192 ATRACE_NAME("ClientCompositionCacheMiss");
Alec Mouria90a5702021-04-16 16:36:21 +00001193 mClientCompositionRequestCache->add(tex->getBuffer()->getId(), clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001194 clientCompositionLayers);
1195 }
1196
Lloyd Pique688abd42019-02-15 15:42:24 -08001197 // We boost GPU frequency here because there will be color spaces conversion
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001198 // or complex GPU shaders and it's expensive. We boost the GPU frequency so that
1199 // GPU composition can finish in time. We must reset GPU frequency afterwards,
1200 // because high frequency consumes extra battery.
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001201 const bool expensiveBlurs =
1202 refreshArgs.blursAreExpensive && mLayerRequestingBackgroundBlur != nullptr;
Lloyd Pique688abd42019-02-15 15:42:24 -08001203 const bool expensiveRenderingExpected =
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001204 clientCompositionDisplay.outputDataspace == ui::Dataspace::DISPLAY_P3 || expensiveBlurs;
Lloyd Pique688abd42019-02-15 15:42:24 -08001205 if (expensiveRenderingExpected) {
1206 setExpensiveRenderingExpected(true);
1207 }
1208
Sally Qi59a9f502021-10-12 18:53:23 +00001209 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
1210 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001211 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00001212 std::back_inserter(clientRenderEngineLayers),
1213 [](LayerFE::LayerSettings& settings) -> renderengine::LayerSettings {
1214 return settings;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001215 });
1216
Alec Mourie4034bb2019-11-19 12:45:54 -08001217 const nsecs_t renderEngineStart = systemTime();
Alec Mouri1684c702021-02-04 12:27:26 -08001218 // Only use the framebuffer cache when rendering to an internal display
1219 // TODO(b/173560331): This is only to help mitigate memory leaks from virtual displays because
1220 // right now we don't have a concrete eviction policy for output buffers: GLESRenderEngine
1221 // bounds its framebuffer cache but Skia RenderEngine has no current policy. The best fix is
1222 // probably to encapsulate the output buffer into a structure that dispatches resource cleanup
1223 // over to RenderEngine, in which case this flag can be removed from the drawLayers interface.
Dominik Laskowski29fa1462021-04-27 15:51:50 -07001224 const bool useFramebufferCache = outputState.layerFilter.toInternalDisplay;
Sally Qi4cabdd02021-08-05 16:45:57 -07001225 auto [status, drawFence] =
1226 renderEngine
Sally Qi59a9f502021-10-12 18:53:23 +00001227 .drawLayers(clientCompositionDisplay, clientRenderEngineLayers, tex,
Sally Qi4cabdd02021-08-05 16:45:57 -07001228 useFramebufferCache, std::move(fd))
1229 .get();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001230
1231 if (status != NO_ERROR && mClientCompositionRequestCache) {
1232 // If rendering was not successful, remove the request from the cache.
Alec Mouria90a5702021-04-16 16:36:21 +00001233 mClientCompositionRequestCache->remove(tex->getBuffer()->getId());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001234 }
1235
Alec Mourie4034bb2019-11-19 12:45:54 -08001236 auto& timeStats = getCompositionEngine().getTimeStats();
Sally Qi4cabdd02021-08-05 16:45:57 -07001237 if (drawFence.get() < 0) {
Alec Mourie4034bb2019-11-19 12:45:54 -08001238 timeStats.recordRenderEngineDuration(renderEngineStart, systemTime());
1239 } else {
1240 timeStats.recordRenderEngineDuration(renderEngineStart,
1241 std::make_shared<FenceTime>(
Sally Qi4cabdd02021-08-05 16:45:57 -07001242 new Fence(dup(drawFence.get()))));
Alec Mourie4034bb2019-11-19 12:45:54 -08001243 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001244
Robert Carrccab4242021-09-28 16:53:03 -07001245 if (clientCompositionLayersFE.size() > 0) {
1246 sp<Fence> clientCompFence = new Fence(dup(drawFence.get()));
1247 for (auto clientComposedLayer : clientCompositionLayersFE) {
1248 clientComposedLayer->setWasClientComposed(clientCompFence);
1249 }
1250 }
1251
Sally Qi4cabdd02021-08-05 16:45:57 -07001252 return std::move(drawFence);
Lloyd Pique688abd42019-02-15 15:42:24 -08001253}
1254
Vishnu Nair9b079a22020-01-21 14:36:08 -08001255std::vector<LayerFE::LayerSettings> Output::generateClientCompositionRequests(
Robert Carrccab4242021-09-28 16:53:03 -07001256 bool supportsProtectedContent, ui::Dataspace outputDataspace, std::vector<LayerFE*>& outLayerFEs) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08001257 std::vector<LayerFE::LayerSettings> clientCompositionLayers;
Lloyd Pique688abd42019-02-15 15:42:24 -08001258 ALOGV("Rendering client layers");
1259
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001260 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001261 const Region viewportRegion(outputState.layerStackSpace.getContent());
Lloyd Pique688abd42019-02-15 15:42:24 -08001262 bool firstLayer = true;
Lloyd Pique688abd42019-02-15 15:42:24 -08001263
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001264 bool disableBlurs = false;
Huihong Luo91ac3b52021-04-08 11:07:41 -07001265 sp<GraphicBuffer> previousOverrideBuffer = nullptr;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001266
Lloyd Pique01c77c12019-04-17 12:48:32 -07001267 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001268 const auto& layerState = layer->getState();
Lloyd Piquede196652020-01-22 17:29:58 -08001269 const auto* layerFEState = layer->getLayerFE().getCompositionState();
Lloyd Pique688abd42019-02-15 15:42:24 -08001270 auto& layerFE = layer->getLayerFE();
1271
Lloyd Piquea2468662019-03-07 21:31:06 -08001272 const Region clip(viewportRegion.intersect(layerState.visibleRegion));
Lloyd Pique688abd42019-02-15 15:42:24 -08001273 ALOGV("Layer: %s", layerFE.getDebugName());
1274 if (clip.isEmpty()) {
1275 ALOGV(" Skipping for empty clip");
1276 firstLayer = false;
1277 continue;
1278 }
1279
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001280 disableBlurs |= layerFEState->sidebandStream != nullptr;
1281
Vishnu Naira483b4a2019-12-12 15:07:52 -08001282 const bool clientComposition = layer->requiresClientComposition();
Lloyd Pique688abd42019-02-15 15:42:24 -08001283
1284 // We clear the client target for non-client composed layers if
1285 // requested by the HWC. We skip this if the layer is not an opaque
1286 // rectangle, as by definition the layer must blend with whatever is
1287 // underneath. We also skip the first layer as the buffer target is
1288 // guaranteed to start out cleared.
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001289 const bool clearClientComposition =
Lloyd Piquede196652020-01-22 17:29:58 -08001290 layerState.clearClientTarget && layerFEState->isOpaque && !firstLayer;
Lloyd Pique688abd42019-02-15 15:42:24 -08001291
1292 ALOGV(" Composition type: client %d clear %d", clientComposition, clearClientComposition);
1293
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001294 // If the layer casts a shadow but the content casting the shadow is occluded, skip
1295 // composing the non-shadow content and only draw the shadows.
1296 const bool realContentIsVisible = clientComposition &&
1297 !layerState.visibleRegion.subtract(layerState.shadowRegion).isEmpty();
1298
Lloyd Pique688abd42019-02-15 15:42:24 -08001299 if (clientComposition || clearClientComposition) {
Dan Stoza6166c312021-01-15 16:34:05 -08001300 std::vector<LayerFE::LayerSettings> results;
1301 if (layer->getState().overrideInfo.buffer != nullptr) {
Alec Mouria90a5702021-04-16 16:36:21 +00001302 if (layer->getState().overrideInfo.buffer->getBuffer() != previousOverrideBuffer) {
Huihong Luo91ac3b52021-04-08 11:07:41 -07001303 results = layer->getOverrideCompositionList();
Alec Mouria90a5702021-04-16 16:36:21 +00001304 previousOverrideBuffer = layer->getState().overrideInfo.buffer->getBuffer();
Huihong Luo91ac3b52021-04-08 11:07:41 -07001305 ALOGV("Replacing [%s] with override in RE", layer->getLayerFE().getDebugName());
1306 } else {
1307 ALOGV("Skipping redundant override buffer for [%s] in RE",
1308 layer->getLayerFE().getDebugName());
1309 }
Dan Stoza6166c312021-01-15 16:34:05 -08001310 } else {
Alec Mourif54453c2021-05-13 16:28:28 -07001311 LayerFE::ClientCompositionTargetSettings::BlurSetting blurSetting = disableBlurs
1312 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled
1313 : (layer->getState().overrideInfo.disableBackgroundBlur
1314 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::
1315 BlurRegionsOnly
1316 : LayerFE::ClientCompositionTargetSettings::BlurSetting::
1317 Enabled);
1318 compositionengine::LayerFE::ClientCompositionTargetSettings
1319 targetSettings{.clip = clip,
1320 .needsFiltering = layer->needsFiltering() ||
1321 outputState.needsFiltering,
1322 .isSecure = outputState.isSecure,
1323 .supportsProtectedContent = supportsProtectedContent,
Angel Aguayob084e0c2021-08-04 23:27:28 +00001324 .viewport = outputState.layerStackSpace.getContent(),
Alec Mourif54453c2021-05-13 16:28:28 -07001325 .dataspace = outputDataspace,
1326 .realContentIsVisible = realContentIsVisible,
1327 .clearContent = !clientComposition,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001328 .blurSetting = blurSetting,
1329 .whitePointNits = layerState.whitePointNits};
Dan Stoza6166c312021-01-15 16:34:05 -08001330 results = layerFE.prepareClientCompositionList(targetSettings);
1331 if (realContentIsVisible && !results.empty()) {
1332 layer->editState().clientCompositionTimestamp = systemTime();
1333 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001334 }
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001335
Robert Carrccab4242021-09-28 16:53:03 -07001336 outLayerFEs.push_back(&layerFE);
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001337 clientCompositionLayers.insert(clientCompositionLayers.end(),
1338 std::make_move_iterator(results.begin()),
1339 std::make_move_iterator(results.end()));
1340 results.clear();
Lloyd Pique688abd42019-02-15 15:42:24 -08001341 }
1342
1343 firstLayer = false;
1344 }
1345
1346 return clientCompositionLayers;
1347}
1348
1349void Output::appendRegionFlashRequests(
Vishnu Nair9b079a22020-01-21 14:36:08 -08001350 const Region& flashRegion, std::vector<LayerFE::LayerSettings>& clientCompositionLayers) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001351 if (flashRegion.isEmpty()) {
1352 return;
1353 }
1354
Vishnu Nair9b079a22020-01-21 14:36:08 -08001355 LayerFE::LayerSettings layerSettings;
Lloyd Pique688abd42019-02-15 15:42:24 -08001356 layerSettings.source.buffer.buffer = nullptr;
1357 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
1358 layerSettings.alpha = half(1.0);
1359
1360 for (const auto& rect : flashRegion) {
1361 layerSettings.geometry.boundaries = rect.toFloatRect();
1362 clientCompositionLayers.push_back(layerSettings);
1363 }
1364}
1365
1366void Output::setExpensiveRenderingExpected(bool) {
1367 // The base class does nothing with this call.
1368}
1369
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001370void Output::postFramebuffer() {
1371 ATRACE_CALL();
1372 ALOGV(__FUNCTION__);
1373
1374 if (!getState().isEnabled) {
1375 return;
1376 }
1377
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001378 auto& outputState = editState();
1379 outputState.dirtyRegion.clear();
Lloyd Piqued3d69882019-02-28 16:03:46 -08001380 mRenderSurface->flip();
1381
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001382 auto frame = presentAndGetFrameFences();
1383
Lloyd Pique7d90ba52019-08-08 11:57:53 -07001384 mRenderSurface->onPresentDisplayCompleted();
1385
Lloyd Pique01c77c12019-04-17 12:48:32 -07001386 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001387 // The layer buffer from the previous frame (if any) is released
1388 // by HWC only when the release fence from this frame (if any) is
1389 // signaled. Always get the release fence from HWC first.
1390 sp<Fence> releaseFence = Fence::NO_FENCE;
1391
1392 if (auto hwcLayer = layer->getHwcLayer()) {
1393 if (auto f = frame.layerFences.find(hwcLayer); f != frame.layerFences.end()) {
1394 releaseFence = f->second;
1395 }
1396 }
1397
1398 // If the layer was client composited in the previous frame, we
1399 // need to merge with the previous client target acquire fence.
1400 // Since we do not track that, always merge with the current
1401 // client target acquire fence when it is available, even though
1402 // this is suboptimal.
1403 // TODO(b/121291683): Track previous frame client target acquire fence.
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001404 if (outputState.usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001405 releaseFence =
1406 Fence::merge("LayerRelease", releaseFence, frame.clientTargetAcquireFence);
1407 }
Sally Qi59a9f502021-10-12 18:53:23 +00001408 layer->getLayerFE().onLayerDisplayed(
1409 ftl::yield<renderengine::RenderEngineResult>(
1410 {NO_ERROR, base::unique_fd(releaseFence->dup())})
1411 .share());
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001412 }
1413
1414 // We've got a list of layers needing fences, that are disjoint with
Lloyd Pique01c77c12019-04-17 12:48:32 -07001415 // OutputLayersOrderedByZ. The best we can do is to
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001416 // supply them with the present fence.
1417 for (auto& weakLayer : mReleasedLayers) {
1418 if (auto layer = weakLayer.promote(); layer != nullptr) {
Sally Qi59a9f502021-10-12 18:53:23 +00001419 layer->onLayerDisplayed(ftl::yield<renderengine::RenderEngineResult>(
1420 {NO_ERROR, base::unique_fd(frame.presentFence->dup())})
1421 .share());
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001422 }
1423 }
1424
1425 // Clear out the released layers now that we're done with them.
1426 mReleasedLayers.clear();
1427}
1428
Alec Mouriaa831582021-06-07 16:23:01 -07001429void Output::renderCachedSets(const CompositionRefreshArgs& refreshArgs) {
Dan Stoza6166c312021-01-15 16:34:05 -08001430 if (mPlanner) {
Dominik Laskowskie0e0cde2021-07-30 10:42:05 -07001431 mPlanner->renderCachedSets(getState(), refreshArgs.scheduledFrameTime);
Dan Stoza6166c312021-01-15 16:34:05 -08001432 }
1433}
1434
Lloyd Pique32cbe282018-10-19 13:09:22 -07001435void Output::dirtyEntireOutput() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001436 auto& outputState = editState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001437 outputState.dirtyRegion.set(outputState.displaySpace.getBoundsAsRect());
Lloyd Pique32cbe282018-10-19 13:09:22 -07001438}
1439
Vishnu Nair7234fa52022-02-24 14:07:11 -08001440std::optional<android::HWComposer::DeviceRequestedChanges> Output::chooseCompositionStrategy() {
Lloyd Pique66d68602019-02-13 14:23:31 -08001441 // The base output implementation can only do client composition
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001442 auto& outputState = editState();
1443 outputState.usesClientComposition = true;
1444 outputState.usesDeviceComposition = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001445 outputState.reusedClientComposition = false;
Vishnu Nair7234fa52022-02-24 14:07:11 -08001446 return {};
Lloyd Pique66d68602019-02-13 14:23:31 -08001447}
1448
Lloyd Pique688abd42019-02-15 15:42:24 -08001449bool Output::getSkipColorTransform() const {
1450 return true;
1451}
1452
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001453compositionengine::Output::FrameFences Output::presentAndGetFrameFences() {
1454 compositionengine::Output::FrameFences result;
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001455 if (getState().usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001456 result.clientTargetAcquireFence = mRenderSurface->getClientTargetAcquireFence();
1457 }
1458 return result;
1459}
1460
Vishnu Nair7234fa52022-02-24 14:07:11 -08001461void Output::setPredictCompositionStrategy(bool predict) {
1462 if (predict) {
1463 mHwComposerAsyncWorker = std::make_unique<HwcAsyncWorker>();
1464 } else {
1465 mHwComposerAsyncWorker.reset(nullptr);
1466 }
1467}
1468
1469bool Output::canPredictCompositionStrategy(const CompositionRefreshArgs& refreshArgs) {
1470 if (!getState().isEnabled || !mHwComposerAsyncWorker) {
1471 ALOGV("canPredictCompositionStrategy disabled");
1472 return false;
1473 }
1474
1475 if (!getState().previousDeviceRequestedChanges) {
1476 ALOGV("canPredictCompositionStrategy previous changes not available");
1477 return false;
1478 }
1479
1480 if (!mRenderSurface->supportsCompositionStrategyPrediction()) {
1481 ALOGV("canPredictCompositionStrategy surface does not support");
1482 return false;
1483 }
1484
1485 if (refreshArgs.devOptFlashDirtyRegionsDelay) {
1486 ALOGV("canPredictCompositionStrategy devOptFlashDirtyRegionsDelay");
1487 return false;
1488 }
1489
1490 // If no layer uses clientComposition, then don't predict composition strategy
1491 // because we have less work to do in parallel.
1492 if (!anyLayersRequireClientComposition()) {
1493 ALOGV("canPredictCompositionStrategy no layer uses clientComposition");
1494 return false;
1495 }
1496
1497 if (!refreshArgs.updatingOutputGeometryThisFrame) {
1498 return true;
1499 }
1500
1501 ALOGV("canPredictCompositionStrategy updatingOutputGeometryThisFrame");
1502 return false;
1503}
1504
1505bool Output::anyLayersRequireClientComposition() const {
1506 const auto layers = getOutputLayersOrderedByZ();
1507 return std::any_of(layers.begin(), layers.end(),
1508 [](const auto& layer) { return layer->requiresClientComposition(); });
1509}
1510
1511void Output::finishPrepareFrame() {
1512 const auto& state = getState();
1513 if (mPlanner) {
1514 mPlanner->reportFinalPlan(getOutputLayersOrderedByZ());
1515 }
1516 mRenderSurface->prepareFrame(state.usesClientComposition, state.usesDeviceComposition);
1517}
1518
Lloyd Piquefeb73d72018-12-04 17:23:44 -08001519} // namespace impl
1520} // namespace android::compositionengine