blob: e4d757810acb28cfda41cf42b9b3eb20490ee3ca [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 Naira3140382022-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>
Leon Scroggins III5a655b82022-09-07 13:17:09 -040032#include <gui/TraceUtils.h>
Dan Stoza269dc4d2021-01-15 15:07:43 -080033
Chavi Weingarten545da0e2023-02-09 14:55:57 +000034#include <optional>
Alec Mouria90a5702021-04-16 16:36:21 +000035#include <thread>
36
37#include "renderengine/ExternalTexture.h"
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080038
39// TODO(b/129481165): remove the #pragma below and fix conversion issues
40#pragma clang diagnostic push
41#pragma clang diagnostic ignored "-Wconversion"
42
Lloyd Pique688abd42019-02-15 15:42:24 -080043#include <renderengine/DisplaySettings.h>
44#include <renderengine/RenderEngine.h>
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080045
46// TODO(b/129481165): remove the #pragma below and fix conversion issues
47#pragma clang diagnostic pop // ignored "-Wconversion"
48
Dan Stoza269dc4d2021-01-15 15:07:43 -080049#include <android-base/properties.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070050#include <ui/DebugUtils.h>
Lloyd Pique688abd42019-02-15 15:42:24 -080051#include <ui/HdrCapabilities.h>
Lloyd Pique66d68602019-02-13 14:23:31 -080052#include <utils/Trace.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070053
Lloyd Pique688abd42019-02-15 15:42:24 -080054#include "TracedOrdinal.h"
55
Leon Scroggins III9a0afda2022-01-11 16:53:09 -050056using aidl::android::hardware::graphics::composer3::Composition;
57
Lloyd Piquefeb73d72018-12-04 17:23:44 -080058namespace android::compositionengine {
59
60Output::~Output() = default;
61
62namespace impl {
Vishnu Nair9cf89262022-02-26 09:17:49 -080063using CompositionStrategyPredictionState =
64 OutputCompositionState::CompositionStrategyPredictionState;
Lloyd Piquec29e4c62019-03-07 21:48:19 -080065namespace {
66
67template <typename T>
68class Reversed {
69public:
70 explicit Reversed(const T& container) : mContainer(container) {}
71 auto begin() { return mContainer.rbegin(); }
72 auto end() { return mContainer.rend(); }
73
74private:
75 const T& mContainer;
76};
77
78// Helper for enumerating over a container in reverse order
79template <typename T>
80Reversed<T> reversed(const T& c) {
81 return Reversed<T>(c);
82}
83
Marin Shalamanovb15d2272020-09-17 21:41:52 +020084struct ScaleVector {
85 float x;
86 float y;
87};
88
89// Returns a ScaleVector (x, y) such that from.scale(x, y) = to',
90// where to' will have the same size as "to". In the case where "from" and "to"
91// start at the origin to'=to.
92ScaleVector getScale(const Rect& from, const Rect& to) {
93 return {.x = static_cast<float>(to.width()) / from.width(),
94 .y = static_cast<float>(to.height()) / from.height()};
95}
96
Lloyd Piquec29e4c62019-03-07 21:48:19 -080097} // namespace
98
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070099std::shared_ptr<Output> createOutput(
100 const compositionengine::CompositionEngine& compositionEngine) {
101 return createOutputTemplated<Output>(compositionEngine);
102}
Lloyd Pique32cbe282018-10-19 13:09:22 -0700103
104Output::~Output() = default;
105
Lloyd Pique32cbe282018-10-19 13:09:22 -0700106bool Output::isValid() const {
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700107 return mDisplayColorProfile && mDisplayColorProfile->isValid() && mRenderSurface &&
108 mRenderSurface->isValid();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700109}
110
Lloyd Pique6c564cf2019-05-17 17:31:36 -0700111std::optional<DisplayId> Output::getDisplayId() const {
112 return {};
113}
114
Lloyd Pique32cbe282018-10-19 13:09:22 -0700115const std::string& Output::getName() const {
116 return mName;
117}
118
119void Output::setName(const std::string& name) {
120 mName = name;
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400121 auto displayIdOpt = getDisplayId();
Leon Scroggins IIIc03d4652023-01-05 13:03:53 -0500122 mNamePlusId = displayIdOpt ? base::StringPrintf("%s (%s)", mName.c_str(),
123 to_string(*displayIdOpt).c_str())
124 : mName;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700125}
126
127void Output::setCompositionEnabled(bool enabled) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700128 auto& outputState = editState();
129 if (outputState.isEnabled == enabled) {
Lloyd Pique32cbe282018-10-19 13:09:22 -0700130 return;
131 }
132
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700133 outputState.isEnabled = enabled;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700134 dirtyEntireOutput();
135}
136
Alec Mouri023c1882021-05-08 16:36:33 -0700137void Output::setLayerCachingEnabled(bool enabled) {
138 if (enabled == (mPlanner != nullptr)) {
139 return;
140 }
141
142 if (enabled) {
Alec Mouridf6201b2021-06-01 16:20:42 -0700143 mPlanner = std::make_unique<planner::Planner>(getCompositionEngine().getRenderEngine());
Alec Mouri023c1882021-05-08 16:36:33 -0700144 if (mRenderSurface) {
145 mPlanner->setDisplaySize(mRenderSurface->getSize());
146 }
147 } else {
148 mPlanner.reset();
149 }
Alec Mouric773472b2021-05-19 14:29:05 -0700150
151 for (auto* outputLayer : getOutputLayersOrderedByZ()) {
152 if (!outputLayer) {
153 continue;
154 }
155
156 outputLayer->editState().overrideInfo = {};
157 }
Alec Mouri023c1882021-05-08 16:36:33 -0700158}
159
Ady Abrahamdb036a82021-07-16 14:18:34 -0700160void Output::setLayerCachingTexturePoolEnabled(bool enabled) {
161 if (mPlanner) {
162 mPlanner->setTexturePoolEnabled(enabled);
163 }
164}
165
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200166void Output::setProjection(ui::Rotation orientation, const Rect& layerStackSpaceRect,
167 const Rect& orientedDisplaySpaceRect) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700168 auto& outputState = editState();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200169
Angel Aguayob084e0c2021-08-04 23:27:28 +0000170 outputState.displaySpace.setOrientation(orientation);
171 LOG_FATAL_IF(outputState.displaySpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200172 "The display bounds are unknown.");
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200173
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200174 // Compute orientedDisplaySpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000175 ui::Size orientedSize = outputState.displaySpace.getBounds();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200176 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200177 std::swap(orientedSize.width, orientedSize.height);
178 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000179 outputState.orientedDisplaySpace.setBounds(orientedSize);
180 outputState.orientedDisplaySpace.setContent(orientedDisplaySpaceRect);
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200181
182 // Compute displaySpace.content
183 const uint32_t transformOrientationFlags = ui::Transform::toRotationFlags(orientation);
184 ui::Transform rotation;
185 if (transformOrientationFlags != ui::Transform::ROT_INVALID) {
Angel Aguayob084e0c2021-08-04 23:27:28 +0000186 const auto displaySize = outputState.displaySpace.getBoundsAsRect();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200187 rotation.set(transformOrientationFlags, displaySize.width(), displaySize.height());
188 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000189 outputState.displaySpace.setContent(rotation.transform(orientedDisplaySpaceRect));
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200190
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200191 // Compute framebufferSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000192 outputState.framebufferSpace.setOrientation(orientation);
193 LOG_FATAL_IF(outputState.framebufferSpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200194 "The framebuffer bounds are unknown.");
Angel Aguayob084e0c2021-08-04 23:27:28 +0000195 const auto scale = getScale(outputState.displaySpace.getBoundsAsRect(),
196 outputState.framebufferSpace.getBoundsAsRect());
197 outputState.framebufferSpace.setContent(
198 outputState.displaySpace.getContent().scale(scale.x, scale.y));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200199
200 // Compute layerStackSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000201 outputState.layerStackSpace.setContent(layerStackSpaceRect);
202 outputState.layerStackSpace.setBounds(
203 ui::Size(layerStackSpaceRect.getWidth(), layerStackSpaceRect.getHeight()));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200204
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200205 outputState.transform = outputState.layerStackSpace.getTransform(outputState.displaySpace);
206 outputState.needsFiltering = outputState.transform.needsBilinearFiltering();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700207 dirtyEntireOutput();
208}
209
Alec Mouricdf16792021-12-10 13:16:06 -0800210void Output::setNextBrightness(float brightness) {
211 editState().displayBrightness = brightness;
212}
213
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200214void Output::setDisplaySize(const ui::Size& size) {
Lloyd Pique31cb2942018-10-19 17:23:03 -0700215 mRenderSurface->setDisplaySize(size);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200216
217 auto& state = editState();
218
219 // Update framebuffer space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000220 const ui::Size newBounds(size);
221 state.framebufferSpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200222
223 // Update display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000224 state.displaySpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200225 state.transform = state.layerStackSpace.getTransform(state.displaySpace);
226
227 // Update oriented display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000228 const auto orientation = state.displaySpace.getOrientation();
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200229 ui::Size orientedSize = size;
230 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
231 std::swap(orientedSize.width, orientedSize.height);
232 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000233 const ui::Size newOrientedBounds(orientedSize);
234 state.orientedDisplaySpace.setBounds(newOrientedBounds);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700235
Dan Stoza6166c312021-01-15 16:34:05 -0800236 if (mPlanner) {
237 mPlanner->setDisplaySize(size);
238 }
239
Lloyd Pique32cbe282018-10-19 13:09:22 -0700240 dirtyEntireOutput();
241}
242
Garfield Tan54edd912020-10-21 16:31:41 -0700243ui::Transform::RotationFlags Output::getTransformHint() const {
244 return static_cast<ui::Transform::RotationFlags>(getState().transform.getOrientation());
245}
246
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700247void Output::setLayerFilter(ui::LayerFilter filter) {
248 editState().layerFilter = filter;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700249 dirtyEntireOutput();
250}
251
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800252void Output::setColorTransform(const compositionengine::CompositionRefreshArgs& args) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700253 auto& colorTransformMatrix = editState().colorTransformMatrix;
254 if (!args.colorTransformMatrix || colorTransformMatrix == args.colorTransformMatrix) {
Lloyd Pique77f79a22019-04-29 15:55:40 -0700255 return;
256 }
257
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700258 colorTransformMatrix = *args.colorTransformMatrix;
Lloyd Piqueef958122019-02-05 18:00:12 -0800259
260 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700261}
262
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800263void Output::setColorProfile(const ColorProfile& colorProfile) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700264 auto& outputState = editState();
265 if (outputState.colorMode == colorProfile.mode &&
266 outputState.dataspace == colorProfile.dataspace &&
Alec Mouri88790f32023-07-21 01:25:14 +0000267 outputState.renderIntent == colorProfile.renderIntent) {
Lloyd Piqueef958122019-02-05 18:00:12 -0800268 return;
269 }
270
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700271 outputState.colorMode = colorProfile.mode;
272 outputState.dataspace = colorProfile.dataspace;
273 outputState.renderIntent = colorProfile.renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700274
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800275 mRenderSurface->setBufferDataspace(colorProfile.dataspace);
Lloyd Pique31cb2942018-10-19 17:23:03 -0700276
Lloyd Pique32cbe282018-10-19 13:09:22 -0700277 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d)",
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800278 decodeColorMode(colorProfile.mode).c_str(), colorProfile.mode,
279 decodeRenderIntent(colorProfile.renderIntent).c_str(), colorProfile.renderIntent);
Lloyd Piqueef958122019-02-05 18:00:12 -0800280
281 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700282}
283
John Reckac09e452021-04-07 16:35:37 -0400284void Output::setDisplayBrightness(float sdrWhitePointNits, float displayBrightnessNits) {
285 auto& outputState = editState();
286 if (outputState.sdrWhitePointNits == sdrWhitePointNits &&
287 outputState.displayBrightnessNits == displayBrightnessNits) {
288 // Nothing changed
289 return;
290 }
291 outputState.sdrWhitePointNits = sdrWhitePointNits;
292 outputState.displayBrightnessNits = displayBrightnessNits;
293 dirtyEntireOutput();
294}
295
Lloyd Pique32cbe282018-10-19 13:09:22 -0700296void Output::dump(std::string& out) const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700297 base::StringAppendF(&out, "Output \"%s\"", mName.c_str());
298 out.append("\n Composition Output State:\n");
Lloyd Pique32cbe282018-10-19 13:09:22 -0700299
300 dumpBase(out);
301}
302
303void Output::dumpBase(std::string& out) const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700304 dumpState(out);
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700305 out += '\n';
Lloyd Pique31cb2942018-10-19 17:23:03 -0700306
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700307 if (mDisplayColorProfile) {
308 mDisplayColorProfile->dump(out);
309 } else {
310 out.append(" No display color profile!\n");
311 }
312
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700313 out += '\n';
314
Lloyd Pique31cb2942018-10-19 17:23:03 -0700315 if (mRenderSurface) {
316 mRenderSurface->dump(out);
317 } else {
318 out.append(" No render surface!\n");
319 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800320
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700321 base::StringAppendF(&out, "\n %zu Layers\n", getOutputLayerCount());
Lloyd Pique01c77c12019-04-17 12:48:32 -0700322 for (const auto* outputLayer : getOutputLayersOrderedByZ()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800323 if (!outputLayer) {
324 continue;
325 }
326 outputLayer->dump(out);
327 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700328}
329
Dan Stoza269dc4d2021-01-15 15:07:43 -0800330void Output::dumpPlannerInfo(const Vector<String16>& args, std::string& out) const {
331 if (!mPlanner) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700332 out.append("Planner is disabled\n");
Dan Stoza269dc4d2021-01-15 15:07:43 -0800333 return;
334 }
335 base::StringAppendF(&out, "Planner info for display [%s]\n", mName.c_str());
336 mPlanner->dump(args, out);
337}
338
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700339compositionengine::DisplayColorProfile* Output::getDisplayColorProfile() const {
340 return mDisplayColorProfile.get();
341}
342
343void Output::setDisplayColorProfile(std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
344 mDisplayColorProfile = std::move(mode);
345}
346
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800347const Output::ReleasedLayers& Output::getReleasedLayersForTest() const {
348 return mReleasedLayers;
349}
350
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700351void Output::setDisplayColorProfileForTest(
352 std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
353 mDisplayColorProfile = std::move(mode);
354}
355
Lloyd Pique31cb2942018-10-19 17:23:03 -0700356compositionengine::RenderSurface* Output::getRenderSurface() const {
357 return mRenderSurface.get();
358}
359
360void Output::setRenderSurface(std::unique_ptr<compositionengine::RenderSurface> surface) {
361 mRenderSurface = std::move(surface);
Dan Stoza6166c312021-01-15 16:34:05 -0800362 const auto size = mRenderSurface->getSize();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000363 editState().framebufferSpace.setBounds(size);
Dan Stoza6166c312021-01-15 16:34:05 -0800364 if (mPlanner) {
365 mPlanner->setDisplaySize(size);
366 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700367 dirtyEntireOutput();
368}
369
Vishnu Nair9b079a22020-01-21 14:36:08 -0800370void Output::cacheClientCompositionRequests(uint32_t cacheSize) {
371 if (cacheSize == 0) {
372 mClientCompositionRequestCache.reset();
373 } else {
374 mClientCompositionRequestCache = std::make_unique<ClientCompositionRequestCache>(cacheSize);
375 }
376};
377
Lloyd Pique31cb2942018-10-19 17:23:03 -0700378void Output::setRenderSurfaceForTest(std::unique_ptr<compositionengine::RenderSurface> surface) {
379 mRenderSurface = std::move(surface);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700380}
381
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700382Region Output::getDirtyRegion() const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700383 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000384 return outputState.dirtyRegion.intersect(outputState.layerStackSpace.getContent());
Lloyd Pique32cbe282018-10-19 13:09:22 -0700385}
386
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700387bool Output::includesLayer(ui::LayerFilter filter) const {
388 return getState().layerFilter.includes(filter);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700389}
390
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700391bool Output::includesLayer(const sp<LayerFE>& layerFE) const {
Lloyd Piquede196652020-01-22 17:29:58 -0800392 const auto* layerFEState = layerFE->getCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700393 return layerFEState && includesLayer(layerFEState->outputFilter);
Lloyd Pique66c20c42019-03-07 21:44:02 -0800394}
395
Lloyd Piquedf336d92019-03-07 21:38:42 -0800396std::unique_ptr<compositionengine::OutputLayer> Output::createOutputLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800397 const sp<LayerFE>& layerFE) const {
398 return impl::createOutputLayer(*this, layerFE);
Lloyd Piquecc01a452018-12-04 17:24:00 -0800399}
400
Lloyd Piquede196652020-01-22 17:29:58 -0800401compositionengine::OutputLayer* Output::getOutputLayerForLayer(const sp<LayerFE>& layerFE) const {
402 auto index = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700403 return index ? getOutputLayerOrderedByZByIndex(*index) : nullptr;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800404}
405
Lloyd Pique01c77c12019-04-17 12:48:32 -0700406std::optional<size_t> Output::findCurrentOutputLayerForLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800407 const sp<compositionengine::LayerFE>& layer) const {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700408 for (size_t i = 0; i < getOutputLayerCount(); i++) {
409 auto outputLayer = getOutputLayerOrderedByZByIndex(i);
Lloyd Piquede196652020-01-22 17:29:58 -0800410 if (outputLayer && &outputLayer->getLayerFE() == layer.get()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700411 return i;
412 }
413 }
414 return std::nullopt;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800415}
416
Lloyd Piquec7ef21b2019-01-29 18:43:00 -0800417void Output::setReleasedLayers(Output::ReleasedLayers&& layers) {
418 mReleasedLayers = std::move(layers);
419}
420
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800421void Output::prepare(const compositionengine::CompositionRefreshArgs& refreshArgs,
422 LayerFESet& geomSnapshots) {
423 ATRACE_CALL();
424 ALOGV(__FUNCTION__);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800425
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800426 rebuildLayerStacks(refreshArgs, geomSnapshots);
Brian Lindahl439afad2022-11-14 11:16:55 -0700427 uncacheBuffers(refreshArgs.bufferIdsToUncache);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800428}
429
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400430ftl::Future<std::monostate> Output::present(
431 const compositionengine::CompositionRefreshArgs& refreshArgs) {
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400432 ATRACE_FORMAT("%s for %s", __func__, mNamePlusId.c_str());
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800433 ALOGV(__FUNCTION__);
434
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800435 updateColorProfile(refreshArgs);
Dan Stoza269dc4d2021-01-15 15:07:43 -0800436 updateCompositionState(refreshArgs);
437 planComposition();
438 writeCompositionState(refreshArgs);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800439 setColorTransform(refreshArgs);
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800440 beginFrame();
Vishnu Naira3140382022-02-24 14:07:11 -0800441
442 GpuCompositionResult result;
443 const bool predictCompositionStrategy = canPredictCompositionStrategy(refreshArgs);
444 if (predictCompositionStrategy) {
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +0000445 result = prepareFrameAsync();
Vishnu Naira3140382022-02-24 14:07:11 -0800446 } else {
447 prepareFrame();
448 }
449
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800450 devOptRepaintFlash(refreshArgs);
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +0000451 finishFrame(std::move(result));
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400452 ftl::Future<std::monostate> future;
453 if (mOffloadPresent) {
454 future = presentFrameAndReleaseLayersAsync();
455
456 // Only offload for this frame. The next frame will determine whether it
457 // needs to be offloaded. Leave the HwcAsyncWorker in place. For one thing,
458 // it is currently presenting. Further, it may be needed next frame, and
459 // we don't want to churn.
460 mOffloadPresent = false;
461 } else {
462 presentFrameAndReleaseLayers();
463 future = ftl::yield<std::monostate>({});
464 }
Alec Mouriaa831582021-06-07 16:23:01 -0700465 renderCachedSets(refreshArgs);
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400466 return future;
467}
468
469void Output::offloadPresentNextFrame() {
470 mOffloadPresent = true;
471 updateHwcAsyncWorker();
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800472}
473
Brian Lindahl439afad2022-11-14 11:16:55 -0700474void Output::uncacheBuffers(std::vector<uint64_t> const& bufferIdsToUncache) {
475 if (bufferIdsToUncache.empty()) {
476 return;
477 }
478 for (auto outputLayer : getOutputLayersOrderedByZ()) {
479 outputLayer->uncacheBuffers(bufferIdsToUncache);
480 }
481}
482
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800483void Output::rebuildLayerStacks(const compositionengine::CompositionRefreshArgs& refreshArgs,
484 LayerFESet& layerFESet) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700485 auto& outputState = editState();
486
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800487 // Do nothing if this output is not enabled or there is no need to perform this update
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700488 if (!outputState.isEnabled || CC_LIKELY(!refreshArgs.updatingOutputGeometryThisFrame)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800489 return;
490 }
Vishnu Naird9a640b2023-07-21 14:20:27 +0000491 ATRACE_CALL();
492 ALOGV(__FUNCTION__);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800493
494 // Process the layers to determine visibility and coverage
495 compositionengine::Output::CoverageState coverage{layerFESet};
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000496 coverage.aboveCoveredLayersExcludingOverlays = refreshArgs.hasTrustedPresentationListener
497 ? std::make_optional<Region>()
498 : std::nullopt;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800499 collectVisibleLayers(refreshArgs, coverage);
500
501 // Compute the resulting coverage for this output, and store it for later
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700502 const ui::Transform& tr = outputState.transform;
Angel Aguayob084e0c2021-08-04 23:27:28 +0000503 Region undefinedRegion{outputState.displaySpace.getBoundsAsRect()};
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800504 undefinedRegion.subtractSelf(tr.transform(coverage.aboveOpaqueLayers));
505
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700506 outputState.undefinedRegion = undefinedRegion;
507 outputState.dirtyRegion.orSelf(coverage.dirtyRegion);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800508}
509
510void Output::collectVisibleLayers(const compositionengine::CompositionRefreshArgs& refreshArgs,
511 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800512 // Evaluate the layers from front to back to determine what is visible. This
513 // also incrementally calculates the coverage information for each layer as
514 // well as the entire output.
Lloyd Piquede196652020-01-22 17:29:58 -0800515 for (auto layer : reversed(refreshArgs.layers)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700516 // Incrementally process the coverage for each layer
517 ensureOutputLayerIfVisible(layer, coverage);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800518
519 // TODO(b/121291683): Stop early if the output is completely covered and
520 // no more layers could even be visible underneath the ones on top.
521 }
522
Lloyd Pique01c77c12019-04-17 12:48:32 -0700523 setReleasedLayers(refreshArgs);
524
525 finalizePendingOutputLayers();
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800526}
527
Lloyd Piquede196652020-01-22 17:29:58 -0800528void Output::ensureOutputLayerIfVisible(sp<compositionengine::LayerFE>& layerFE,
Lloyd Pique01c77c12019-04-17 12:48:32 -0700529 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800530 // Ensure we have a snapshot of the basic geometry layer state. Limit the
531 // snapshots to once per frame for each candidate layer, as layers may
532 // appear on multiple outputs.
533 if (!coverage.latchedLayers.count(layerFE)) {
534 coverage.latchedLayers.insert(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800535 }
536
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700537 // Only consider the layers on this output
538 if (!includesLayer(layerFE)) {
Lloyd Piquede196652020-01-22 17:29:58 -0800539 return;
540 }
541
542 // Obtain a read-only pointer to the front-end layer state
543 const auto* layerFEState = layerFE->getCompositionState();
544 if (CC_UNLIKELY(!layerFEState)) {
545 return;
546 }
547
548 // handle hidden surfaces by setting the visible region to empty
549 if (CC_UNLIKELY(!layerFEState->isVisible)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700550 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800551 }
552
Vishnu Naird47bcee2023-02-24 18:08:51 +0000553 bool computeAboveCoveredExcludingOverlays = coverage.aboveCoveredLayersExcludingOverlays &&
554 !layerFEState->outputFilter.toInternalDisplay;
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000555
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800556 /*
557 * opaqueRegion: area of a surface that is fully opaque.
558 */
559 Region opaqueRegion;
560
561 /*
562 * visibleRegion: area of a surface that is visible on screen and not fully
563 * transparent. This is essentially the layer's footprint minus the opaque
564 * regions above it. Areas covered by a translucent surface are considered
565 * visible.
566 */
567 Region visibleRegion;
568
569 /*
570 * coveredRegion: area of a surface that is covered by all visible regions
571 * above it (which includes the translucent areas).
572 */
573 Region coveredRegion;
574
575 /*
576 * transparentRegion: area of a surface that is hinted to be completely
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500577 * transparent.
578 * This is used to tell when the layer has no visible non-transparent
579 * regions and can be removed from the layer list. It does not affect the
580 * visibleRegion of this layer or any layers beneath it. The hint may not
581 * be correct if apps don't respect the SurfaceView restrictions (which,
582 * sadly, some don't).
583 *
584 * In addition, it is used on DISPLAY_DECORATION layers to specify the
585 * blockingRegion, allowing the DPU to skip it to save power. Once we have
586 * hardware that supports a blockingRegion on frames with AFBC, it may be
587 * useful to use this for other layers, too, so long as we can prevent
588 * regressions on b/7179570.
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800589 */
590 Region transparentRegion;
591
Vishnu Naira483b4a2019-12-12 15:07:52 -0800592 /*
593 * shadowRegion: Region cast by the layer's shadow.
594 */
595 Region shadowRegion;
596
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000597 /**
598 * covered region above excluding internal display overlay layers
599 */
600 std::optional<Region> coveredRegionExcludingDisplayOverlays = std::nullopt;
601
Lloyd Piquede196652020-01-22 17:29:58 -0800602 const ui::Transform& tr = layerFEState->geomLayerTransform;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800603
604 // Get the visible region
605 // TODO(b/121291683): Is it worth creating helper methods on LayerFEState
606 // for computations like this?
Lloyd Piquede196652020-01-22 17:29:58 -0800607 const Rect visibleRect(tr.transform(layerFEState->geomLayerBounds));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800608 visibleRegion.set(visibleRect);
609
Vishnu Naird9e4f462023-10-06 04:05:45 +0000610 if (layerFEState->shadowSettings.length > 0.0f) {
Vishnu Naira483b4a2019-12-12 15:07:52 -0800611 // if the layer casts a shadow, offset the layers visible region and
612 // calculate the shadow region.
Vishnu Naird9e4f462023-10-06 04:05:45 +0000613 const auto inset = static_cast<int32_t>(ceilf(layerFEState->shadowSettings.length) * -1.0f);
Vishnu Naira483b4a2019-12-12 15:07:52 -0800614 Rect visibleRectWithShadows(visibleRect);
615 visibleRectWithShadows.inset(inset, inset, inset, inset);
616 visibleRegion.set(visibleRectWithShadows);
617 shadowRegion = visibleRegion.subtract(visibleRect);
618 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800619
620 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700621 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800622 }
623
624 // Remove the transparent area from the visible region
Lloyd Piquede196652020-01-22 17:29:58 -0800625 if (!layerFEState->isOpaque) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800626 if (tr.preserveRects()) {
Alec Mourie60f0b92022-06-10 19:15:20 +0000627 // Clip the transparent region to geomLayerBounds first
628 // The transparent region may be influenced by applications, for
629 // instance, by overriding ViewGroup#gatherTransparentRegion with a
630 // custom view. Once the layer stack -> display mapping is known, we
631 // must guard against very wrong inputs to prevent underflow or
632 // overflow errors. We do this here by constraining the transparent
633 // region to be within the pre-transform layer bounds, since the
634 // layer bounds are expected to play nicely with the full
635 // transform.
636 const Region clippedTransparentRegionHint =
637 layerFEState->transparentRegionHint.intersect(
638 Rect(layerFEState->geomLayerBounds));
639
640 if (clippedTransparentRegionHint.isEmpty()) {
641 if (!layerFEState->transparentRegionHint.isEmpty()) {
642 ALOGD("Layer: %s had an out of bounds transparent region",
643 layerFE->getDebugName());
644 layerFEState->transparentRegionHint.dump("transparentRegionHint");
645 }
646 transparentRegion.clear();
647 } else {
648 transparentRegion = tr.transform(clippedTransparentRegionHint);
649 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800650 } else {
651 // transformation too complex, can't do the
652 // transparent region optimization.
653 transparentRegion.clear();
654 }
655 }
656
657 // compute the opaque region
Lloyd Pique0a456232020-01-16 17:51:13 -0800658 const auto layerOrientation = tr.getOrientation();
Lloyd Piquede196652020-01-22 17:29:58 -0800659 if (layerFEState->isOpaque && ((layerOrientation & ui::Transform::ROT_INVALID) == 0)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800660 // If we one of the simple category of transforms (0/90/180/270 rotation
661 // + any flip), then the opaque region is the layer's footprint.
662 // Otherwise we don't try and compute the opaque region since there may
663 // be errors at the edges, and we treat the entire layer as
664 // translucent.
Vishnu Naira483b4a2019-12-12 15:07:52 -0800665 opaqueRegion.set(visibleRect);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800666 }
667
668 // Clip the covered region to the visible region
669 coveredRegion = coverage.aboveCoveredLayers.intersect(visibleRegion);
670
671 // Update accumAboveCoveredLayers for next (lower) layer
672 coverage.aboveCoveredLayers.orSelf(visibleRegion);
673
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000674 if (CC_UNLIKELY(computeAboveCoveredExcludingOverlays)) {
675 coveredRegionExcludingDisplayOverlays =
676 coverage.aboveCoveredLayersExcludingOverlays->intersect(visibleRegion);
677 coverage.aboveCoveredLayersExcludingOverlays->orSelf(visibleRegion);
678 }
679
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800680 // subtract the opaque region covered by the layers above us
681 visibleRegion.subtractSelf(coverage.aboveOpaqueLayers);
682
683 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700684 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800685 }
686
687 // Get coverage information for the layer as previously displayed,
688 // also taking over ownership from mOutputLayersorderedByZ.
Lloyd Piquede196652020-01-22 17:29:58 -0800689 auto prevOutputLayerIndex = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700690 auto prevOutputLayer =
691 prevOutputLayerIndex ? getOutputLayerOrderedByZByIndex(*prevOutputLayerIndex) : nullptr;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800692
693 // Get coverage information for the layer as previously displayed
694 // TODO(b/121291683): Define kEmptyRegion as a constant in Region.h
695 const Region kEmptyRegion;
696 const Region& oldVisibleRegion =
697 prevOutputLayer ? prevOutputLayer->getState().visibleRegion : kEmptyRegion;
698 const Region& oldCoveredRegion =
699 prevOutputLayer ? prevOutputLayer->getState().coveredRegion : kEmptyRegion;
700
701 // compute this layer's dirty region
702 Region dirty;
Lloyd Piquede196652020-01-22 17:29:58 -0800703 if (layerFEState->contentDirty) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800704 // we need to invalidate the whole region
705 dirty = visibleRegion;
706 // as well, as the old visible region
707 dirty.orSelf(oldVisibleRegion);
708 } else {
709 /* compute the exposed region:
710 * the exposed region consists of two components:
711 * 1) what's VISIBLE now and was COVERED before
712 * 2) what's EXPOSED now less what was EXPOSED before
713 *
714 * note that (1) is conservative, we start with the whole visible region
715 * but only keep what used to be covered by something -- which mean it
716 * may have been exposed.
717 *
718 * (2) handles areas that were not covered by anything but got exposed
719 * because of a resize.
720 *
721 */
722 const Region newExposed = visibleRegion - coveredRegion;
723 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
724 dirty = (visibleRegion & oldCoveredRegion) | (newExposed - oldExposed);
725 }
726 dirty.subtractSelf(coverage.aboveOpaqueLayers);
727
728 // accumulate to the screen dirty region
729 coverage.dirtyRegion.orSelf(dirty);
730
731 // Update accumAboveOpaqueLayers for next (lower) layer
732 coverage.aboveOpaqueLayers.orSelf(opaqueRegion);
733
734 // Compute the visible non-transparent region
735 Region visibleNonTransparentRegion = visibleRegion.subtract(transparentRegion);
736
Vishnu Naira483b4a2019-12-12 15:07:52 -0800737 // Perform the final check to see if this layer is visible on this output
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800738 // TODO(b/121291683): Why does this not use visibleRegion? (see outputSpaceVisibleRegion below)
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700739 const auto& outputState = getState();
740 Region drawRegion(outputState.transform.transform(visibleNonTransparentRegion));
Angel Aguayob084e0c2021-08-04 23:27:28 +0000741 drawRegion.andSelf(outputState.displaySpace.getBoundsAsRect());
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800742 if (drawRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700743 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800744 }
745
Vishnu Naira483b4a2019-12-12 15:07:52 -0800746 Region visibleNonShadowRegion = visibleRegion.subtract(shadowRegion);
747
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800748 // The layer is visible. Either reuse the existing outputLayer if we have
749 // one, or create a new one if we do not.
Lloyd Piquede196652020-01-22 17:29:58 -0800750 auto result = ensureOutputLayer(prevOutputLayerIndex, layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800751
752 // Store the layer coverage information into the layer state as some of it
753 // is useful later.
754 auto& outputLayerState = result->editState();
755 outputLayerState.visibleRegion = visibleRegion;
756 outputLayerState.visibleNonTransparentRegion = visibleNonTransparentRegion;
757 outputLayerState.coveredRegion = coveredRegion;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200758 outputLayerState.outputSpaceVisibleRegion = outputState.transform.transform(
Angel Aguayob084e0c2021-08-04 23:27:28 +0000759 visibleNonShadowRegion.intersect(outputState.layerStackSpace.getContent()));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800760 outputLayerState.shadowRegion = shadowRegion;
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500761 outputLayerState.outputSpaceBlockingRegionHint =
Leon Scroggins III7f7ad2c2022-03-17 17:06:20 -0400762 layerFEState->compositionType == Composition::DISPLAY_DECORATION
763 ? outputState.transform.transform(
764 transparentRegion.intersect(outputState.layerStackSpace.getContent()))
765 : Region();
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000766 if (CC_UNLIKELY(computeAboveCoveredExcludingOverlays)) {
767 outputLayerState.coveredRegionExcludingDisplayOverlays =
768 std::move(coveredRegionExcludingDisplayOverlays);
769 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800770}
771
772void Output::setReleasedLayers(const compositionengine::CompositionRefreshArgs&) {
773 // The base class does nothing with this call.
774}
775
Dan Stoza269dc4d2021-01-15 15:07:43 -0800776void Output::updateCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800777 ATRACE_CALL();
778 ALOGV(__FUNCTION__);
779
Alec Mourif9a2a2c2019-11-12 12:46:02 -0800780 if (!getState().isEnabled) {
781 return;
782 }
783
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800784 mLayerRequestingBackgroundBlur = findLayerRequestingBackgroundComposition();
785 bool forceClientComposition = mLayerRequestingBackgroundBlur != nullptr;
786
Lloyd Pique01c77c12019-04-17 12:48:32 -0700787 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique7a234912019-10-03 11:54:27 -0700788 layer->updateCompositionState(refreshArgs.updatingGeometryThisFrame,
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800789 refreshArgs.devOptForceClientComposition ||
Snild Dolkow9e217d62020-04-22 15:53:42 +0200790 forceClientComposition,
791 refreshArgs.internalDisplayRotationFlags);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800792
793 if (mLayerRequestingBackgroundBlur == layer) {
794 forceClientComposition = false;
795 }
Dan Stoza269dc4d2021-01-15 15:07:43 -0800796 }
Tianhao Yao67dd7122022-02-22 17:48:33 +0000797
798 updateCompositionStateForBorder(refreshArgs);
799}
800
801void Output::updateCompositionStateForBorder(
802 const compositionengine::CompositionRefreshArgs& refreshArgs) {
803 std::unordered_map<int32_t, const Region*> layerVisibleRegionMap;
804 // Store a map of layerId to their computed visible region.
805 for (auto* layer : getOutputLayersOrderedByZ()) {
806 int layerId = (layer->getLayerFE()).getSequence();
807 layerVisibleRegionMap[layerId] = &((layer->getState()).visibleRegion);
808 }
809 OutputCompositionState& outputCompositionState = editState();
810 outputCompositionState.borderInfoList.clear();
811 bool clientComposeTopLayer = false;
812 for (const auto& borderInfo : refreshArgs.borderInfoList) {
813 renderengine::BorderRenderInfo info;
814 for (const auto& id : borderInfo.layerIds) {
815 info.combinedRegion.orSelf(*(layerVisibleRegionMap[id]));
816 }
Tianhao Yao10cea3c2022-03-30 01:37:22 +0000817
818 if (!info.combinedRegion.isEmpty()) {
819 info.width = borderInfo.width;
820 info.color = borderInfo.color;
821 outputCompositionState.borderInfoList.emplace_back(std::move(info));
822 clientComposeTopLayer = true;
823 }
Tianhao Yao67dd7122022-02-22 17:48:33 +0000824 }
825
826 // In this situation we must client compose the top layer instead of using hwc
827 // because we want to draw the border above all else.
828 // This could potentially cause a bit of a performance regression if the top
829 // layer would have been rendered using hwc originally.
830 // TODO(b/227656283): Measure system's performance before enabling the border feature
831 if (clientComposeTopLayer) {
832 auto topLayer = getOutputLayerOrderedByZByIndex(getOutputLayerCount() - 1);
833 (topLayer->editState()).forceClientComposition = true;
834 }
Dan Stoza269dc4d2021-01-15 15:07:43 -0800835}
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800836
Dan Stoza269dc4d2021-01-15 15:07:43 -0800837void Output::planComposition() {
838 if (!mPlanner || !getState().isEnabled) {
839 return;
840 }
841
842 ATRACE_CALL();
843 ALOGV(__FUNCTION__);
844
845 mPlanner->plan(getOutputLayersOrderedByZ());
846}
847
848void Output::writeCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
849 ATRACE_CALL();
850 ALOGV(__FUNCTION__);
851
852 if (!getState().isEnabled) {
853 return;
854 }
855
Ady Abraham3645e642021-04-20 18:39:00 -0700856 editState().earliestPresentTime = refreshArgs.earliestPresentTime;
Ady Abraham43065bd2021-12-10 17:22:15 -0800857 editState().expectedPresentTime = refreshArgs.expectedPresentTime;
ramindani4aac32c2023-10-30 14:13:30 -0700858 editState().frameInterval = refreshArgs.frameInterval;
jimmyshiu4e211772023-06-15 15:18:38 +0000859 editState().powerCallback = refreshArgs.powerCallback;
Ady Abraham3645e642021-04-20 18:39:00 -0700860
Leon Scroggins III2e74a4c2021-04-09 13:41:14 -0400861 compositionengine::OutputLayer* peekThroughLayer = nullptr;
Dan Stoza6166c312021-01-15 16:34:05 -0800862 sp<GraphicBuffer> previousOverride = nullptr;
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400863 bool includeGeometry = refreshArgs.updatingGeometryThisFrame;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400864 uint32_t z = 0;
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400865 bool overrideZ = false;
Robert Carrec8ccca2022-05-04 09:36:14 -0700866 uint64_t outputLayerHash = 0;
Dan Stoza269dc4d2021-01-15 15:07:43 -0800867 for (auto* layer : getOutputLayersOrderedByZ()) {
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400868 if (layer == peekThroughLayer) {
869 // No longer needed, although it should not show up again, so
870 // resetting it is not truly needed either.
871 peekThroughLayer = nullptr;
872
873 // peekThroughLayer was already drawn ahead of its z order.
874 continue;
875 }
Dan Stoza6166c312021-01-15 16:34:05 -0800876 bool skipLayer = false;
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400877 const auto& overrideInfo = layer->getState().overrideInfo;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400878 if (overrideInfo.buffer != nullptr) {
879 if (previousOverride && overrideInfo.buffer->getBuffer() == previousOverride) {
Dan Stoza6166c312021-01-15 16:34:05 -0800880 ALOGV("Skipping redundant buffer");
881 skipLayer = true;
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400882 } else {
883 // First layer with the override buffer.
884 if (overrideInfo.peekThroughLayer) {
885 peekThroughLayer = overrideInfo.peekThroughLayer;
Leon Scroggins IIId305ef22021-04-06 09:53:26 -0400886
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400887 // Draw peekThroughLayer first.
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400888 overrideZ = true;
889 includeGeometry = true;
890 constexpr bool isPeekingThrough = true;
891 peekThroughLayer->writeStateToHWC(includeGeometry, false, z++, overrideZ,
892 isPeekingThrough);
Robert Carrec8ccca2022-05-04 09:36:14 -0700893 outputLayerHash ^= android::hashCombine(
894 reinterpret_cast<uint64_t>(&peekThroughLayer->getLayerFE()),
895 z, includeGeometry, overrideZ, isPeekingThrough,
896 peekThroughLayer->requiresClientComposition());
Leon Scroggins IIIe2ee0402021-04-02 16:59:37 -0400897 }
898
899 previousOverride = overrideInfo.buffer->getBuffer();
Dan Stoza6166c312021-01-15 16:34:05 -0800900 }
Dan Stoza6166c312021-01-15 16:34:05 -0800901 }
902
Leon Scroggins III9aa25c22021-04-15 15:30:19 -0400903 constexpr bool isPeekingThrough = false;
904 layer->writeStateToHWC(includeGeometry, skipLayer, z++, overrideZ, isPeekingThrough);
Robert Carrec8ccca2022-05-04 09:36:14 -0700905 if (!skipLayer) {
906 outputLayerHash ^= android::hashCombine(
907 reinterpret_cast<uint64_t>(&layer->getLayerFE()),
908 z, includeGeometry, overrideZ, isPeekingThrough,
909 layer->requiresClientComposition());
910 }
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800911 }
Robert Carrec8ccca2022-05-04 09:36:14 -0700912 editState().outputLayerHash = outputLayerHash;
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800913}
914
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800915compositionengine::OutputLayer* Output::findLayerRequestingBackgroundComposition() const {
916 compositionengine::OutputLayer* layerRequestingBgComposition = nullptr;
917 for (auto* layer : getOutputLayersOrderedByZ()) {
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -0400918 const auto* compState = layer->getLayerFE().getCompositionState();
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100919
920 // If any layer has a sideband stream, we will disable blurs. In that case, we don't
921 // want to force client composition because of the blur.
922 if (compState->sidebandStream != nullptr) {
923 return nullptr;
924 }
Leon Scroggins IIIc1dbfcb2022-03-21 16:48:10 -0400925
926 // If RenderEngine cannot render protected content, we cannot blur.
927 if (compState->hasProtectedContent &&
928 !getCompositionEngine().getRenderEngine().supportsProtectedContent()) {
929 return nullptr;
930 }
Lucas Dupin084a6d42021-08-26 22:10:29 +0000931 if (compState->isOpaque) {
932 continue;
933 }
Galia Peycheva66eaf4a2020-11-09 13:17:57 +0100934 if (compState->backgroundBlurRadius > 0 || compState->blurRegions.size() > 0) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800935 layerRequestingBgComposition = layer;
936 }
937 }
938 return layerRequestingBgComposition;
939}
940
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800941void Output::updateColorProfile(const compositionengine::CompositionRefreshArgs& refreshArgs) {
942 setColorProfile(pickColorProfile(refreshArgs));
943}
944
945// Returns a data space that fits all visible layers. The returned data space
946// can only be one of
947// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
948// - Dataspace::DISPLAY_P3
949// - Dataspace::DISPLAY_BT2020
950// The returned HDR data space is one of
951// - Dataspace::UNKNOWN
952// - Dataspace::BT2020_HLG
953// - Dataspace::BT2020_PQ
954ui::Dataspace Output::getBestDataspace(ui::Dataspace* outHdrDataSpace,
955 bool* outIsHdrClientComposition) const {
956 ui::Dataspace bestDataSpace = ui::Dataspace::V0_SRGB;
957 *outHdrDataSpace = ui::Dataspace::UNKNOWN;
958
Vishnu Naire14c6b32022-08-06 04:20:15 +0000959 // An Output's layers may be stale when it is disabled. As a consequence, the layers returned by
960 // getOutputLayersOrderedByZ may not be in a valid state and it is not safe to access their
961 // properties. Return a default dataspace value in this case.
962 if (!getState().isEnabled) {
963 return ui::Dataspace::V0_SRGB;
964 }
965
Lloyd Pique01c77c12019-04-17 12:48:32 -0700966 for (const auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Piquede196652020-01-22 17:29:58 -0800967 switch (layer->getLayerFE().getCompositionState()->dataspace) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800968 case ui::Dataspace::V0_SCRGB:
969 case ui::Dataspace::V0_SCRGB_LINEAR:
970 case ui::Dataspace::BT2020:
971 case ui::Dataspace::BT2020_ITU:
972 case ui::Dataspace::BT2020_LINEAR:
973 case ui::Dataspace::DISPLAY_BT2020:
974 bestDataSpace = ui::Dataspace::DISPLAY_BT2020;
975 break;
976 case ui::Dataspace::DISPLAY_P3:
977 bestDataSpace = ui::Dataspace::DISPLAY_P3;
978 break;
979 case ui::Dataspace::BT2020_PQ:
980 case ui::Dataspace::BT2020_ITU_PQ:
981 bestDataSpace = ui::Dataspace::DISPLAY_P3;
982 *outHdrDataSpace = ui::Dataspace::BT2020_PQ;
Lloyd Piquede196652020-01-22 17:29:58 -0800983 *outIsHdrClientComposition =
984 layer->getLayerFE().getCompositionState()->forceClientComposition;
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800985 break;
986 case ui::Dataspace::BT2020_HLG:
987 case ui::Dataspace::BT2020_ITU_HLG:
988 bestDataSpace = ui::Dataspace::DISPLAY_P3;
989 // When there's mixed PQ content and HLG content, we set the HDR
Sally Qi37d07c02023-10-05 17:32:32 +0000990 // data space to be BT2020_HLG and convert PQ to HLG.
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800991 if (*outHdrDataSpace == ui::Dataspace::UNKNOWN) {
992 *outHdrDataSpace = ui::Dataspace::BT2020_HLG;
993 }
994 break;
995 default:
996 break;
997 }
998 }
999
1000 return bestDataSpace;
1001}
1002
1003compositionengine::Output::ColorProfile Output::pickColorProfile(
1004 const compositionengine::CompositionRefreshArgs& refreshArgs) const {
1005 if (refreshArgs.outputColorSetting == OutputColorSetting::kUnmanaged) {
1006 return ColorProfile{ui::ColorMode::NATIVE, ui::Dataspace::UNKNOWN,
Alec Mouri88790f32023-07-21 01:25:14 +00001007 ui::RenderIntent::COLORIMETRIC};
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001008 }
1009
1010 ui::Dataspace hdrDataSpace;
1011 bool isHdrClientComposition = false;
1012 ui::Dataspace bestDataSpace = getBestDataspace(&hdrDataSpace, &isHdrClientComposition);
1013
1014 switch (refreshArgs.forceOutputColorMode) {
1015 case ui::ColorMode::SRGB:
1016 bestDataSpace = ui::Dataspace::V0_SRGB;
1017 break;
1018 case ui::ColorMode::DISPLAY_P3:
1019 bestDataSpace = ui::Dataspace::DISPLAY_P3;
1020 break;
1021 default:
1022 break;
1023 }
1024
1025 // respect hdrDataSpace only when there is no legacy HDR support
1026 const bool isHdr = hdrDataSpace != ui::Dataspace::UNKNOWN &&
1027 !mDisplayColorProfile->hasLegacyHdrSupport(hdrDataSpace) && !isHdrClientComposition;
1028 if (isHdr) {
1029 bestDataSpace = hdrDataSpace;
1030 }
1031
1032 ui::RenderIntent intent;
1033 switch (refreshArgs.outputColorSetting) {
1034 case OutputColorSetting::kManaged:
1035 case OutputColorSetting::kUnmanaged:
1036 intent = isHdr ? ui::RenderIntent::TONE_MAP_COLORIMETRIC
1037 : ui::RenderIntent::COLORIMETRIC;
1038 break;
1039 case OutputColorSetting::kEnhanced:
1040 intent = isHdr ? ui::RenderIntent::TONE_MAP_ENHANCE : ui::RenderIntent::ENHANCE;
1041 break;
1042 default: // vendor display color setting
1043 intent = static_cast<ui::RenderIntent>(refreshArgs.outputColorSetting);
1044 break;
1045 }
1046
1047 ui::ColorMode outMode;
1048 ui::Dataspace outDataSpace;
1049 ui::RenderIntent outRenderIntent;
1050 mDisplayColorProfile->getBestColorMode(bestDataSpace, intent, &outDataSpace, &outMode,
1051 &outRenderIntent);
1052
Alec Mouri88790f32023-07-21 01:25:14 +00001053 return ColorProfile{outMode, outDataSpace, outRenderIntent};
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001054}
1055
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001056void Output::beginFrame() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001057 auto& outputState = editState();
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001058 const bool dirty = !getDirtyRegion().isEmpty();
Lloyd Pique01c77c12019-04-17 12:48:32 -07001059 const bool empty = getOutputLayerCount() == 0;
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001060 const bool wasEmpty = !outputState.lastCompositionHadVisibleLayers;
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001061
1062 // If nothing has changed (!dirty), don't recompose.
1063 // If something changed, but we don't currently have any visible layers,
1064 // and didn't when we last did a composition, then skip it this time.
1065 // The second rule does two things:
1066 // - When all layers are removed from a display, we'll emit one black
1067 // frame, then nothing more until we get new layers.
1068 // - When a display is created with a private layer stack, we won't
1069 // emit any black frames until a layer is added to the layer stack.
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001070 mMustRecompose = dirty && !(empty && wasEmpty);
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001071
1072 const char flagPrefix[] = {'-', '+'};
1073 static_cast<void>(flagPrefix);
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001074 ALOGV("%s: %s composition for %s (%cdirty %cempty %cwasEmpty)", __func__,
1075 mMustRecompose ? "doing" : "skipping", getName().c_str(), flagPrefix[dirty],
1076 flagPrefix[empty], flagPrefix[wasEmpty]);
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001077
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001078 mRenderSurface->beginFrame(mMustRecompose);
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001079
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001080 if (mMustRecompose) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001081 outputState.lastCompositionHadVisibleLayers = !empty;
Lloyd Piqued0a92a02019-02-19 17:47:26 -08001082 }
1083}
1084
Lloyd Pique66d68602019-02-13 14:23:31 -08001085void Output::prepareFrame() {
1086 ATRACE_CALL();
1087 ALOGV(__FUNCTION__);
1088
Vishnu Naira3140382022-02-24 14:07:11 -08001089 auto& outputState = editState();
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001090 if (!outputState.isEnabled) {
Lloyd Pique66d68602019-02-13 14:23:31 -08001091 return;
1092 }
1093
Vishnu Naira3140382022-02-24 14:07:11 -08001094 std::optional<android::HWComposer::DeviceRequestedChanges> changes;
1095 bool success = chooseCompositionStrategy(&changes);
1096 resetCompositionStrategy();
Vishnu Nair9cf89262022-02-26 09:17:49 -08001097 outputState.strategyPrediction = CompositionStrategyPredictionState::DISABLED;
Vishnu Naira3140382022-02-24 14:07:11 -08001098 outputState.previousDeviceRequestedChanges = changes;
1099 outputState.previousDeviceRequestedSuccess = success;
1100 if (success) {
1101 applyCompositionStrategy(changes);
1102 }
1103 finishPrepareFrame();
1104}
Lloyd Pique66d68602019-02-13 14:23:31 -08001105
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001106ftl::Future<std::monostate> Output::presentFrameAndReleaseLayersAsync() {
1107 return ftl::Future<bool>(std::move(mHwComposerAsyncWorker->send([&]() {
1108 presentFrameAndReleaseLayers();
1109 return true;
1110 })))
1111 .then([](bool) { return std::monostate{}; });
1112}
1113
Vishnu Naira3140382022-02-24 14:07:11 -08001114std::future<bool> Output::chooseCompositionStrategyAsync(
1115 std::optional<android::HWComposer::DeviceRequestedChanges>* changes) {
1116 return mHwComposerAsyncWorker->send(
1117 [&, changes]() { return chooseCompositionStrategy(changes); });
1118}
1119
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001120GpuCompositionResult Output::prepareFrameAsync() {
Vishnu Naira3140382022-02-24 14:07:11 -08001121 ATRACE_CALL();
1122 ALOGV(__FUNCTION__);
1123 auto& state = editState();
1124 const auto& previousChanges = state.previousDeviceRequestedChanges;
1125 std::optional<android::HWComposer::DeviceRequestedChanges> changes;
1126 resetCompositionStrategy();
1127 auto hwcResult = chooseCompositionStrategyAsync(&changes);
1128 if (state.previousDeviceRequestedSuccess) {
1129 applyCompositionStrategy(previousChanges);
1130 }
1131 finishPrepareFrame();
1132
1133 base::unique_fd bufferFence;
1134 std::shared_ptr<renderengine::ExternalTexture> buffer;
1135 updateProtectedContentState();
1136 const bool dequeueSucceeded = dequeueRenderBuffer(&bufferFence, &buffer);
1137 GpuCompositionResult compositionResult;
1138 if (dequeueSucceeded) {
1139 std::optional<base::unique_fd> optFd =
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001140 composeSurfaces(Region::INVALID_REGION, buffer, bufferFence);
Vishnu Naira3140382022-02-24 14:07:11 -08001141 if (optFd) {
1142 compositionResult.fence = std::move(*optFd);
1143 }
Dan Stoza47437bb2021-01-15 16:21:07 -08001144 }
1145
Vishnu Naira3140382022-02-24 14:07:11 -08001146 auto chooseCompositionSuccess = hwcResult.get();
1147 const bool predictionSucceeded = dequeueSucceeded && changes == previousChanges;
Vishnu Nair9cf89262022-02-26 09:17:49 -08001148 state.strategyPrediction = predictionSucceeded ? CompositionStrategyPredictionState::SUCCESS
1149 : CompositionStrategyPredictionState::FAIL;
Vishnu Naira3140382022-02-24 14:07:11 -08001150 if (!predictionSucceeded) {
1151 ATRACE_NAME("CompositionStrategyPredictionMiss");
1152 resetCompositionStrategy();
1153 if (chooseCompositionSuccess) {
1154 applyCompositionStrategy(changes);
1155 }
1156 finishPrepareFrame();
1157 // Track the dequeued buffer to reuse so we don't need to dequeue another one.
1158 compositionResult.buffer = buffer;
1159 } else {
1160 ATRACE_NAME("CompositionStrategyPredictionHit");
1161 }
1162 state.previousDeviceRequestedChanges = std::move(changes);
1163 state.previousDeviceRequestedSuccess = chooseCompositionSuccess;
1164 return compositionResult;
Lloyd Pique66d68602019-02-13 14:23:31 -08001165}
1166
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001167void Output::devOptRepaintFlash(const compositionengine::CompositionRefreshArgs& refreshArgs) {
1168 if (CC_LIKELY(!refreshArgs.devOptFlashDirtyRegionsDelay)) {
1169 return;
1170 }
1171
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001172 if (getState().isEnabled) {
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001173 if (const auto dirtyRegion = getDirtyRegion(); !dirtyRegion.isEmpty()) {
Vishnu Naira3140382022-02-24 14:07:11 -08001174 base::unique_fd bufferFence;
1175 std::shared_ptr<renderengine::ExternalTexture> buffer;
1176 updateProtectedContentState();
1177 dequeueRenderBuffer(&bufferFence, &buffer);
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001178 static_cast<void>(composeSurfaces(dirtyRegion, buffer, bufferFence));
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -07001179 mRenderSurface->queueBuffer(base::unique_fd());
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001180 }
1181 }
1182
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001183 presentFrameAndReleaseLayers();
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001184
1185 std::this_thread::sleep_for(*refreshArgs.devOptFlashDirtyRegionsDelay);
1186
1187 prepareFrame();
1188}
1189
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001190void Output::finishFrame(GpuCompositionResult&& result) {
Lloyd Piqued3d69882019-02-28 16:03:46 -08001191 ATRACE_CALL();
1192 ALOGV(__FUNCTION__);
Vishnu Nair9cf89262022-02-26 09:17:49 -08001193 const auto& outputState = getState();
1194 if (!outputState.isEnabled) {
Lloyd Piqued3d69882019-02-28 16:03:46 -08001195 return;
1196 }
1197
Vishnu Naira3140382022-02-24 14:07:11 -08001198 std::optional<base::unique_fd> optReadyFence;
1199 std::shared_ptr<renderengine::ExternalTexture> buffer;
1200 base::unique_fd bufferFence;
Vishnu Nair9cf89262022-02-26 09:17:49 -08001201 if (outputState.strategyPrediction == CompositionStrategyPredictionState::SUCCESS) {
Vishnu Naira3140382022-02-24 14:07:11 -08001202 optReadyFence = std::move(result.fence);
1203 } else {
1204 if (result.bufferAvailable()) {
1205 buffer = std::move(result.buffer);
1206 bufferFence = std::move(result.fence);
1207 } else {
1208 updateProtectedContentState();
1209 if (!dequeueRenderBuffer(&bufferFence, &buffer)) {
1210 return;
1211 }
1212 }
1213 // Repaint the framebuffer (if needed), getting the optional fence for when
1214 // the composition completes.
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001215 optReadyFence = composeSurfaces(Region::INVALID_REGION, buffer, bufferFence);
Vishnu Naira3140382022-02-24 14:07:11 -08001216 }
Lloyd Piqued3d69882019-02-28 16:03:46 -08001217 if (!optReadyFence) {
1218 return;
1219 }
1220
Matt Buckley50c44062022-01-17 20:48:10 +00001221 if (isPowerHintSessionEnabled()) {
1222 // get fence end time to know when gpu is complete in display
Ady Abrahamd11bade2022-08-01 16:18:03 -07001223 setHintSessionGpuFence(
1224 std::make_unique<FenceTime>(sp<Fence>::make(dup(optReadyFence->get()))));
Matt Buckley50c44062022-01-17 20:48:10 +00001225 }
Lloyd Piqued3d69882019-02-28 16:03:46 -08001226 // swap buffers (presentation)
1227 mRenderSurface->queueBuffer(std::move(*optReadyFence));
1228}
1229
Vishnu Naira3140382022-02-24 14:07:11 -08001230void Output::updateProtectedContentState() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001231 const auto& outputState = getState();
Lloyd Piquee9eff972020-05-05 12:36:44 -07001232 auto& renderEngine = getCompositionEngine().getRenderEngine();
1233 const bool supportsProtectedContent = renderEngine.supportsProtectedContent();
1234
1235 // If we the display is secure, protected content support is enabled, and at
1236 // least one layer has protected content, we need to use a secure back
1237 // buffer.
1238 if (outputState.isSecure && supportsProtectedContent) {
1239 auto layers = getOutputLayersOrderedByZ();
1240 bool needsProtected = std::any_of(layers.begin(), layers.end(), [](auto* layer) {
1241 return layer->getLayerFE().getCompositionState()->hasProtectedContent;
1242 });
Patrick Williams8aed5d22022-10-31 22:18:10 +00001243 if (needsProtected != mRenderSurface->isProtected()) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001244 mRenderSurface->setProtected(needsProtected);
1245 }
1246 }
Vishnu Naira3140382022-02-24 14:07:11 -08001247}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001248
Vishnu Naira3140382022-02-24 14:07:11 -08001249bool Output::dequeueRenderBuffer(base::unique_fd* bufferFence,
1250 std::shared_ptr<renderengine::ExternalTexture>* tex) {
1251 const auto& outputState = getState();
Lloyd Piquee9eff972020-05-05 12:36:44 -07001252
1253 // If we aren't doing client composition on this output, but do have a
1254 // flipClientTarget request for this frame on this output, we still need to
1255 // dequeue a buffer.
Vishnu Naira3140382022-02-24 14:07:11 -08001256 if (outputState.usesClientComposition || outputState.flipClientTarget) {
1257 *tex = mRenderSurface->dequeueBuffer(bufferFence);
1258 if (*tex == nullptr) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001259 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
1260 "client composition for this frame",
1261 mName.c_str());
Vishnu Naira3140382022-02-24 14:07:11 -08001262 return false;
Lloyd Piquee9eff972020-05-05 12:36:44 -07001263 }
1264 }
Vishnu Naira3140382022-02-24 14:07:11 -08001265 return true;
1266}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001267
Vishnu Naira3140382022-02-24 14:07:11 -08001268std::optional<base::unique_fd> Output::composeSurfaces(
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001269 const Region& debugRegion, std::shared_ptr<renderengine::ExternalTexture> tex,
1270 base::unique_fd& fd) {
Vishnu Naira3140382022-02-24 14:07:11 -08001271 ATRACE_CALL();
1272 ALOGV(__FUNCTION__);
1273
1274 const auto& outputState = getState();
Leon Scroggins III042fdba2023-01-04 10:53:07 -05001275 const TracedOrdinal<bool> hasClientComposition = {
1276 base::StringPrintf("hasClientComposition %s", mNamePlusId.c_str()),
1277 outputState.usesClientComposition};
Lloyd Pique688abd42019-02-15 15:42:24 -08001278 if (!hasClientComposition) {
Lloyd Piquea76ce462020-01-14 13:06:37 -08001279 setExpensiveRenderingExpected(false);
Sally Qi4cabdd02021-08-05 16:45:57 -07001280 return base::unique_fd();
Lloyd Pique688abd42019-02-15 15:42:24 -08001281 }
1282
Vishnu Naira3140382022-02-24 14:07:11 -08001283 if (tex == nullptr) {
1284 ALOGW("Buffer not valid for display [%s], bailing out of "
1285 "client composition for this frame",
1286 mName.c_str());
1287 return {};
1288 }
1289
Lloyd Pique688abd42019-02-15 15:42:24 -08001290 ALOGV("hasClientComposition");
1291
Patrick Williams7584c6a2022-10-29 02:10:58 +00001292 renderengine::DisplaySettings clientCompositionDisplay =
1293 generateClientCompositionDisplaySettings();
Lloyd Pique688abd42019-02-15 15:42:24 -08001294
Lloyd Pique688abd42019-02-15 15:42:24 -08001295 // Generate the client composition requests for the layers on this output.
Vishnu Naira3140382022-02-24 14:07:11 -08001296 auto& renderEngine = getCompositionEngine().getRenderEngine();
1297 const bool supportsProtectedContent = renderEngine.supportsProtectedContent();
Robert Carrccab4242021-09-28 16:53:03 -07001298 std::vector<LayerFE*> clientCompositionLayersFE;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001299 std::vector<LayerFE::LayerSettings> clientCompositionLayers =
Lloyd Pique688abd42019-02-15 15:42:24 -08001300 generateClientCompositionRequests(supportsProtectedContent,
Robert Carrccab4242021-09-28 16:53:03 -07001301 clientCompositionDisplay.outputDataspace,
1302 clientCompositionLayersFE);
Lloyd Pique688abd42019-02-15 15:42:24 -08001303 appendRegionFlashRequests(debugRegion, clientCompositionLayers);
1304
Vishnu Naira3140382022-02-24 14:07:11 -08001305 OutputCompositionState& outputCompositionState = editState();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001306 // Check if the client composition requests were rendered into the provided graphic buffer. If
1307 // so, we can reuse the buffer and avoid client composition.
1308 if (mClientCompositionRequestCache) {
Alec Mouria90a5702021-04-16 16:36:21 +00001309 if (mClientCompositionRequestCache->exists(tex->getBuffer()->getId(),
1310 clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001311 clientCompositionLayers)) {
Vishnu Naira3140382022-02-24 14:07:11 -08001312 ATRACE_NAME("ClientCompositionCacheHit");
Vishnu Nair9b079a22020-01-21 14:36:08 -08001313 outputCompositionState.reusedClientComposition = true;
1314 setExpensiveRenderingExpected(false);
Vishnu Nair3a49f0a2022-07-29 21:52:53 +00001315 // b/239944175 pass the fence associated with the buffer.
1316 return base::unique_fd(std::move(fd));
Vishnu Nair9b079a22020-01-21 14:36:08 -08001317 }
Vishnu Naira3140382022-02-24 14:07:11 -08001318 ATRACE_NAME("ClientCompositionCacheMiss");
Alec Mouria90a5702021-04-16 16:36:21 +00001319 mClientCompositionRequestCache->add(tex->getBuffer()->getId(), clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001320 clientCompositionLayers);
1321 }
1322
Lloyd Pique688abd42019-02-15 15:42:24 -08001323 // We boost GPU frequency here because there will be color spaces conversion
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001324 // or complex GPU shaders and it's expensive. We boost the GPU frequency so that
1325 // GPU composition can finish in time. We must reset GPU frequency afterwards,
1326 // because high frequency consumes extra battery.
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001327 const bool expensiveRenderingExpected =
Leon Scroggins IIIcf17ebc2022-03-03 14:54:00 -05001328 std::any_of(clientCompositionLayers.begin(), clientCompositionLayers.end(),
1329 [outputDataspace =
1330 clientCompositionDisplay.outputDataspace](const auto& layer) {
1331 return layer.sourceDataspace != outputDataspace;
1332 });
Lloyd Pique688abd42019-02-15 15:42:24 -08001333 if (expensiveRenderingExpected) {
1334 setExpensiveRenderingExpected(true);
1335 }
1336
Sally Qi59a9f502021-10-12 18:53:23 +00001337 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
1338 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001339 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00001340 std::back_inserter(clientRenderEngineLayers),
1341 [](LayerFE::LayerSettings& settings) -> renderengine::LayerSettings {
1342 return settings;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001343 });
1344
Alec Mourie4034bb2019-11-19 12:45:54 -08001345 const nsecs_t renderEngineStart = systemTime();
Patrick Williams2e9748f2022-08-09 22:48:18 +00001346 auto fenceResult = renderEngine
1347 .drawLayers(clientCompositionDisplay, clientRenderEngineLayers, tex,
Alec Mourif29700f2023-08-17 21:53:31 +00001348 std::move(fd))
Patrick Williams2e9748f2022-08-09 22:48:18 +00001349 .get();
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001350
1351 if (mClientCompositionRequestCache && fenceStatus(fenceResult) != NO_ERROR) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08001352 // If rendering was not successful, remove the request from the cache.
Alec Mouria90a5702021-04-16 16:36:21 +00001353 mClientCompositionRequestCache->remove(tex->getBuffer()->getId());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001354 }
1355
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001356 const auto fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
1357
Patrick Williams74c0bf62022-11-02 23:59:26 +00001358 if (auto timeStats = getCompositionEngine().getTimeStats()) {
1359 if (fence->isValid()) {
1360 timeStats->recordRenderEngineDuration(renderEngineStart,
1361 std::make_shared<FenceTime>(fence));
1362 } else {
1363 timeStats->recordRenderEngineDuration(renderEngineStart, systemTime());
1364 }
Alec Mourie4034bb2019-11-19 12:45:54 -08001365 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001366
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001367 for (auto* clientComposedLayer : clientCompositionLayersFE) {
1368 clientComposedLayer->setWasClientComposed(fence);
Robert Carrccab4242021-09-28 16:53:03 -07001369 }
1370
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001371 return base::unique_fd(fence->dup());
Lloyd Pique688abd42019-02-15 15:42:24 -08001372}
1373
Patrick Williams7584c6a2022-10-29 02:10:58 +00001374renderengine::DisplaySettings Output::generateClientCompositionDisplaySettings() const {
1375 const auto& outputState = getState();
1376
1377 renderengine::DisplaySettings clientCompositionDisplay;
Leon Scroggins III5a655b82022-09-07 13:17:09 -04001378 clientCompositionDisplay.namePlusId = mNamePlusId;
Patrick Williams7584c6a2022-10-29 02:10:58 +00001379 clientCompositionDisplay.physicalDisplay = outputState.framebufferSpace.getContent();
1380 clientCompositionDisplay.clip = outputState.layerStackSpace.getContent();
1381 clientCompositionDisplay.orientation =
1382 ui::Transform::toRotationFlags(outputState.displaySpace.getOrientation());
1383 clientCompositionDisplay.outputDataspace = mDisplayColorProfile->hasWideColorGamut()
1384 ? outputState.dataspace
1385 : ui::Dataspace::UNKNOWN;
1386
1387 // If we have a valid current display brightness use that, otherwise fall back to the
1388 // display's max desired
1389 clientCompositionDisplay.currentLuminanceNits = outputState.displayBrightnessNits > 0.f
1390 ? outputState.displayBrightnessNits
1391 : mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
1392 clientCompositionDisplay.maxLuminance =
1393 mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
1394 clientCompositionDisplay.targetLuminanceNits =
1395 outputState.clientTargetBrightness * outputState.displayBrightnessNits;
1396 clientCompositionDisplay.dimmingStage = outputState.clientTargetDimmingStage;
1397 clientCompositionDisplay.renderIntent =
1398 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(
1399 outputState.renderIntent);
1400
1401 // Compute the global color transform matrix.
1402 clientCompositionDisplay.colorTransform = outputState.colorTransformMatrix;
1403 for (auto& info : outputState.borderInfoList) {
1404 renderengine::BorderRenderInfo borderInfo;
1405 borderInfo.width = info.width;
1406 borderInfo.color = info.color;
1407 borderInfo.combinedRegion = info.combinedRegion;
1408 clientCompositionDisplay.borderInfoList.emplace_back(std::move(borderInfo));
1409 }
1410 clientCompositionDisplay.deviceHandlesColorTransform =
1411 outputState.usesDeviceComposition || getSkipColorTransform();
1412 return clientCompositionDisplay;
1413}
1414
Vishnu Nair9b079a22020-01-21 14:36:08 -08001415std::vector<LayerFE::LayerSettings> Output::generateClientCompositionRequests(
Robert Carrccab4242021-09-28 16:53:03 -07001416 bool supportsProtectedContent, ui::Dataspace outputDataspace, std::vector<LayerFE*>& outLayerFEs) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08001417 std::vector<LayerFE::LayerSettings> clientCompositionLayers;
Lloyd Pique688abd42019-02-15 15:42:24 -08001418 ALOGV("Rendering client layers");
1419
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001420 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001421 const Region viewportRegion(outputState.layerStackSpace.getContent());
Lloyd Pique688abd42019-02-15 15:42:24 -08001422 bool firstLayer = true;
Lloyd Pique688abd42019-02-15 15:42:24 -08001423
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001424 bool disableBlurs = false;
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001425 uint64_t previousOverrideBufferId = 0;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001426
Lloyd Pique01c77c12019-04-17 12:48:32 -07001427 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001428 const auto& layerState = layer->getState();
Lloyd Piquede196652020-01-22 17:29:58 -08001429 const auto* layerFEState = layer->getLayerFE().getCompositionState();
Lloyd Pique688abd42019-02-15 15:42:24 -08001430 auto& layerFE = layer->getLayerFE();
Robert Carr05da0082022-05-25 23:29:34 -07001431 layerFE.setWasClientComposed(nullptr);
Lloyd Pique688abd42019-02-15 15:42:24 -08001432
Lloyd Piquea2468662019-03-07 21:31:06 -08001433 const Region clip(viewportRegion.intersect(layerState.visibleRegion));
Lloyd Pique688abd42019-02-15 15:42:24 -08001434 ALOGV("Layer: %s", layerFE.getDebugName());
1435 if (clip.isEmpty()) {
1436 ALOGV(" Skipping for empty clip");
1437 firstLayer = false;
1438 continue;
1439 }
1440
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001441 disableBlurs |= layerFEState->sidebandStream != nullptr;
1442
Vishnu Naira483b4a2019-12-12 15:07:52 -08001443 const bool clientComposition = layer->requiresClientComposition();
Lloyd Pique688abd42019-02-15 15:42:24 -08001444
1445 // We clear the client target for non-client composed layers if
1446 // requested by the HWC. We skip this if the layer is not an opaque
1447 // rectangle, as by definition the layer must blend with whatever is
1448 // underneath. We also skip the first layer as the buffer target is
1449 // guaranteed to start out cleared.
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001450 const bool clearClientComposition =
Lloyd Piquede196652020-01-22 17:29:58 -08001451 layerState.clearClientTarget && layerFEState->isOpaque && !firstLayer;
Lloyd Pique688abd42019-02-15 15:42:24 -08001452
1453 ALOGV(" Composition type: client %d clear %d", clientComposition, clearClientComposition);
1454
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001455 // If the layer casts a shadow but the content casting the shadow is occluded, skip
1456 // composing the non-shadow content and only draw the shadows.
1457 const bool realContentIsVisible = clientComposition &&
1458 !layerState.visibleRegion.subtract(layerState.shadowRegion).isEmpty();
1459
Lloyd Pique688abd42019-02-15 15:42:24 -08001460 if (clientComposition || clearClientComposition) {
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001461 if (auto overrideSettings = layer->getOverrideCompositionSettings()) {
1462 if (overrideSettings->bufferId != previousOverrideBufferId) {
1463 previousOverrideBufferId = overrideSettings->bufferId;
1464 clientCompositionLayers.push_back(std::move(*overrideSettings));
Huihong Luo91ac3b52021-04-08 11:07:41 -07001465 ALOGV("Replacing [%s] with override in RE", layer->getLayerFE().getDebugName());
1466 } else {
1467 ALOGV("Skipping redundant override buffer for [%s] in RE",
1468 layer->getLayerFE().getDebugName());
1469 }
Dan Stoza6166c312021-01-15 16:34:05 -08001470 } else {
Alec Mourif54453c2021-05-13 16:28:28 -07001471 LayerFE::ClientCompositionTargetSettings::BlurSetting blurSetting = disableBlurs
1472 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled
1473 : (layer->getState().overrideInfo.disableBackgroundBlur
1474 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::
1475 BlurRegionsOnly
1476 : LayerFE::ClientCompositionTargetSettings::BlurSetting::
1477 Enabled);
1478 compositionengine::LayerFE::ClientCompositionTargetSettings
1479 targetSettings{.clip = clip,
Patrick Williams278a88f2023-01-27 16:52:40 -06001480 .needsFiltering = layer->needsFiltering() ||
Alec Mourif54453c2021-05-13 16:28:28 -07001481 outputState.needsFiltering,
1482 .isSecure = outputState.isSecure,
1483 .supportsProtectedContent = supportsProtectedContent,
Angel Aguayob084e0c2021-08-04 23:27:28 +00001484 .viewport = outputState.layerStackSpace.getContent(),
Alec Mourif54453c2021-05-13 16:28:28 -07001485 .dataspace = outputDataspace,
1486 .realContentIsVisible = realContentIsVisible,
1487 .clearContent = !clientComposition,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001488 .blurSetting = blurSetting,
Vishnu Naire14c6b32022-08-06 04:20:15 +00001489 .whitePointNits = layerState.whitePointNits,
1490 .treat170mAsSrgb = outputState.treat170mAsSrgb};
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001491 if (auto clientCompositionSettings =
1492 layerFE.prepareClientComposition(targetSettings)) {
1493 clientCompositionLayers.push_back(std::move(*clientCompositionSettings));
1494 if (realContentIsVisible) {
1495 layer->editState().clientCompositionTimestamp = systemTime();
1496 }
Dan Stoza6166c312021-01-15 16:34:05 -08001497 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001498 }
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001499
Tianhua Sunf91f1402022-05-09 05:45:46 +00001500 if (clientComposition) {
1501 outLayerFEs.push_back(&layerFE);
1502 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001503 }
1504
1505 firstLayer = false;
1506 }
1507
1508 return clientCompositionLayers;
1509}
1510
1511void Output::appendRegionFlashRequests(
Vishnu Nair9b079a22020-01-21 14:36:08 -08001512 const Region& flashRegion, std::vector<LayerFE::LayerSettings>& clientCompositionLayers) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001513 if (flashRegion.isEmpty()) {
1514 return;
1515 }
1516
Vishnu Nair9b079a22020-01-21 14:36:08 -08001517 LayerFE::LayerSettings layerSettings;
Lloyd Pique688abd42019-02-15 15:42:24 -08001518 layerSettings.source.buffer.buffer = nullptr;
1519 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
1520 layerSettings.alpha = half(1.0);
1521
1522 for (const auto& rect : flashRegion) {
1523 layerSettings.geometry.boundaries = rect.toFloatRect();
1524 clientCompositionLayers.push_back(layerSettings);
1525 }
1526}
1527
1528void Output::setExpensiveRenderingExpected(bool) {
1529 // The base class does nothing with this call.
1530}
1531
Matt Buckley50c44062022-01-17 20:48:10 +00001532void Output::setHintSessionGpuFence(std::unique_ptr<FenceTime>&&) {
1533 // The base class does nothing with this call.
1534}
1535
1536bool Output::isPowerHintSessionEnabled() {
1537 return false;
1538}
1539
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001540void Output::presentFrameAndReleaseLayers() {
Leon Scroggins III5a655b82022-09-07 13:17:09 -04001541 ATRACE_FORMAT("%s for %s", __func__, mNamePlusId.c_str());
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001542 ALOGV(__FUNCTION__);
1543
1544 if (!getState().isEnabled) {
1545 return;
1546 }
1547
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001548 auto& outputState = editState();
1549 outputState.dirtyRegion.clear();
Lloyd Piqued3d69882019-02-28 16:03:46 -08001550
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001551 auto frame = presentFrame();
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001552
Lloyd Pique7d90ba52019-08-08 11:57:53 -07001553 mRenderSurface->onPresentDisplayCompleted();
1554
Lloyd Pique01c77c12019-04-17 12:48:32 -07001555 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001556 // The layer buffer from the previous frame (if any) is released
1557 // by HWC only when the release fence from this frame (if any) is
1558 // signaled. Always get the release fence from HWC first.
1559 sp<Fence> releaseFence = Fence::NO_FENCE;
1560
1561 if (auto hwcLayer = layer->getHwcLayer()) {
1562 if (auto f = frame.layerFences.find(hwcLayer); f != frame.layerFences.end()) {
1563 releaseFence = f->second;
1564 }
1565 }
1566
1567 // If the layer was client composited in the previous frame, we
1568 // need to merge with the previous client target acquire fence.
1569 // Since we do not track that, always merge with the current
1570 // client target acquire fence when it is available, even though
1571 // this is suboptimal.
1572 // TODO(b/121291683): Track previous frame client target acquire fence.
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001573 if (outputState.usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001574 releaseFence =
1575 Fence::merge("LayerRelease", releaseFence, frame.clientTargetAcquireFence);
1576 }
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001577 layer->getLayerFE()
1578 .onLayerDisplayed(ftl::yield<FenceResult>(std::move(releaseFence)).share(),
1579 outputState.layerFilter.layerStack);
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001580 }
1581
1582 // We've got a list of layers needing fences, that are disjoint with
Lloyd Pique01c77c12019-04-17 12:48:32 -07001583 // OutputLayersOrderedByZ. The best we can do is to
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001584 // supply them with the present fence.
1585 for (auto& weakLayer : mReleasedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001586 if (const auto layer = weakLayer.promote()) {
Vishnu Nair7ee4f462023-04-19 09:54:09 -07001587 layer->onLayerDisplayed(ftl::yield<FenceResult>(frame.presentFence).share(),
1588 outputState.layerFilter.layerStack);
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001589 }
1590 }
1591
1592 // Clear out the released layers now that we're done with them.
1593 mReleasedLayers.clear();
1594}
1595
Alec Mouriaa831582021-06-07 16:23:01 -07001596void Output::renderCachedSets(const CompositionRefreshArgs& refreshArgs) {
Leon Scroggins III43b5d522023-04-10 15:53:45 -04001597 const auto& outputState = getState();
1598 if (mPlanner && outputState.isEnabled) {
1599 mPlanner->renderCachedSets(outputState, refreshArgs.scheduledFrameTime,
1600 outputState.usesDeviceComposition || getSkipColorTransform());
Dan Stoza6166c312021-01-15 16:34:05 -08001601 }
1602}
1603
Lloyd Pique32cbe282018-10-19 13:09:22 -07001604void Output::dirtyEntireOutput() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001605 auto& outputState = editState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001606 outputState.dirtyRegion.set(outputState.displaySpace.getBoundsAsRect());
Lloyd Pique32cbe282018-10-19 13:09:22 -07001607}
1608
Vishnu Naira3140382022-02-24 14:07:11 -08001609void Output::resetCompositionStrategy() {
Lloyd Pique66d68602019-02-13 14:23:31 -08001610 // The base output implementation can only do client composition
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001611 auto& outputState = editState();
1612 outputState.usesClientComposition = true;
1613 outputState.usesDeviceComposition = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001614 outputState.reusedClientComposition = false;
Lloyd Pique66d68602019-02-13 14:23:31 -08001615}
1616
Lloyd Pique688abd42019-02-15 15:42:24 -08001617bool Output::getSkipColorTransform() const {
1618 return true;
1619}
1620
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001621compositionengine::Output::FrameFences Output::presentFrame() {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001622 compositionengine::Output::FrameFences result;
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001623 if (getState().usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001624 result.clientTargetAcquireFence = mRenderSurface->getClientTargetAcquireFence();
1625 }
1626 return result;
1627}
1628
Vishnu Naira3140382022-02-24 14:07:11 -08001629void Output::setPredictCompositionStrategy(bool predict) {
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001630 mPredictCompositionStrategy = predict;
1631 updateHwcAsyncWorker();
1632}
1633
1634void Output::updateHwcAsyncWorker() {
1635 if (mPredictCompositionStrategy || mOffloadPresent) {
1636 if (!mHwComposerAsyncWorker) {
1637 mHwComposerAsyncWorker = std::make_unique<HwcAsyncWorker>();
1638 }
Vishnu Naira3140382022-02-24 14:07:11 -08001639 } else {
1640 mHwComposerAsyncWorker.reset(nullptr);
1641 }
1642}
1643
Alec Mouridda07d92022-04-25 22:39:25 +00001644void Output::setTreat170mAsSrgb(bool enable) {
1645 editState().treat170mAsSrgb = enable;
1646}
1647
Vishnu Naira3140382022-02-24 14:07:11 -08001648bool Output::canPredictCompositionStrategy(const CompositionRefreshArgs& refreshArgs) {
Robert Carrec8ccca2022-05-04 09:36:14 -07001649 uint64_t lastOutputLayerHash = getState().lastOutputLayerHash;
1650 uint64_t outputLayerHash = getState().outputLayerHash;
1651 editState().lastOutputLayerHash = outputLayerHash;
1652
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001653 if (!getState().isEnabled || !mPredictCompositionStrategy) {
Vishnu Naira3140382022-02-24 14:07:11 -08001654 ALOGV("canPredictCompositionStrategy disabled");
1655 return false;
1656 }
1657
1658 if (!getState().previousDeviceRequestedChanges) {
1659 ALOGV("canPredictCompositionStrategy previous changes not available");
1660 return false;
1661 }
1662
1663 if (!mRenderSurface->supportsCompositionStrategyPrediction()) {
1664 ALOGV("canPredictCompositionStrategy surface does not support");
1665 return false;
1666 }
1667
1668 if (refreshArgs.devOptFlashDirtyRegionsDelay) {
1669 ALOGV("canPredictCompositionStrategy devOptFlashDirtyRegionsDelay");
1670 return false;
1671 }
1672
Robert Carrec8ccca2022-05-04 09:36:14 -07001673 if (lastOutputLayerHash != outputLayerHash) {
1674 ALOGV("canPredictCompositionStrategy output layers changed");
1675 return false;
1676 }
1677
Vishnu Naira3140382022-02-24 14:07:11 -08001678 // If no layer uses clientComposition, then don't predict composition strategy
1679 // because we have less work to do in parallel.
1680 if (!anyLayersRequireClientComposition()) {
1681 ALOGV("canPredictCompositionStrategy no layer uses clientComposition");
1682 return false;
1683 }
1684
Robert Carrec8ccca2022-05-04 09:36:14 -07001685 return true;
Vishnu Naira3140382022-02-24 14:07:11 -08001686}
1687
1688bool Output::anyLayersRequireClientComposition() const {
1689 const auto layers = getOutputLayersOrderedByZ();
1690 return std::any_of(layers.begin(), layers.end(),
1691 [](const auto& layer) { return layer->requiresClientComposition(); });
1692}
1693
1694void Output::finishPrepareFrame() {
1695 const auto& state = getState();
1696 if (mPlanner) {
1697 mPlanner->reportFinalPlan(getOutputLayersOrderedByZ());
1698 }
1699 mRenderSurface->prepareFrame(state.usesClientComposition, state.usesDeviceComposition);
1700}
1701
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001702bool Output::mustRecompose() const {
1703 return mMustRecompose;
1704}
1705
Lloyd Piquefeb73d72018-12-04 17:23:44 -08001706} // namespace impl
1707} // namespace android::compositionengine