blob: bb456138d6bc7f34e730a88fa9a46ede75ccd5c6 [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>
Melody Hsu793f8362024-01-08 20:00:35 +000019#include <common/FlagManager.h>
Vishnu Nairbe0ad902024-06-27 23:38:43 +000020#include <common/trace.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070021#include <compositionengine/CompositionEngine.h>
Lloyd Piquef8cf14d2019-02-28 16:03:12 -080022#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070023#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080024#include <compositionengine/LayerFE.h>
Lloyd Pique9755fb72019-03-26 14:44:40 -070025#include <compositionengine/LayerFECompositionState.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070026#include <compositionengine/RenderSurface.h>
Vishnu Naira3140382022-02-24 14:07:11 -080027#include <compositionengine/impl/HwcAsyncWorker.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070028#include <compositionengine/impl/Output.h>
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070029#include <compositionengine/impl/OutputCompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080030#include <compositionengine/impl/OutputLayer.h>
Lloyd Piquea38ea7e2019-04-16 18:10:26 -070031#include <compositionengine/impl/OutputLayerCompositionState.h>
Dan Stoza269dc4d2021-01-15 15:07:43 -080032#include <compositionengine/impl/planner/Planner.h>
Leon Scroggins III370b8b52022-12-08 13:20:45 -050033#include <ftl/algorithm.h>
Sally Qi59a9f502021-10-12 18:53:23 +000034#include <ftl/future.h>
Leon Scroggins III370b8b52022-12-08 13:20:45 -050035#include <scheduler/FrameTargeter.h>
36#include <scheduler/Time.h>
Dan Stoza269dc4d2021-01-15 15:07:43 -080037
Chavi Weingarten545da0e2023-02-09 14:55:57 +000038#include <optional>
Alec Mouria90a5702021-04-16 16:36:21 +000039#include <thread>
40
41#include "renderengine/ExternalTexture.h"
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080042
43// TODO(b/129481165): remove the #pragma below and fix conversion issues
44#pragma clang diagnostic push
45#pragma clang diagnostic ignored "-Wconversion"
46
Lloyd Pique688abd42019-02-15 15:42:24 -080047#include <renderengine/DisplaySettings.h>
48#include <renderengine/RenderEngine.h>
Lloyd Pique3b5a69e2020-01-16 17:51:01 -080049
50// TODO(b/129481165): remove the #pragma below and fix conversion issues
51#pragma clang diagnostic pop // ignored "-Wconversion"
52
Dan Stoza269dc4d2021-01-15 15:07:43 -080053#include <android-base/properties.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070054#include <ui/DebugUtils.h>
Lloyd Pique688abd42019-02-15 15:42:24 -080055#include <ui/HdrCapabilities.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070056
Lloyd Pique688abd42019-02-15 15:42:24 -080057#include "TracedOrdinal.h"
58
Leon Scroggins III9a0afda2022-01-11 16:53:09 -050059using aidl::android::hardware::graphics::composer3::Composition;
60
Lloyd Piquefeb73d72018-12-04 17:23:44 -080061namespace android::compositionengine {
62
63Output::~Output() = default;
64
65namespace impl {
Vishnu Nair9cf89262022-02-26 09:17:49 -080066using CompositionStrategyPredictionState =
67 OutputCompositionState::CompositionStrategyPredictionState;
Lloyd Piquec29e4c62019-03-07 21:48:19 -080068namespace {
69
70template <typename T>
71class Reversed {
72public:
73 explicit Reversed(const T& container) : mContainer(container) {}
74 auto begin() { return mContainer.rbegin(); }
75 auto end() { return mContainer.rend(); }
76
77private:
78 const T& mContainer;
79};
80
81// Helper for enumerating over a container in reverse order
82template <typename T>
83Reversed<T> reversed(const T& c) {
84 return Reversed<T>(c);
85}
86
Marin Shalamanovb15d2272020-09-17 21:41:52 +020087struct ScaleVector {
88 float x;
89 float y;
90};
91
92// Returns a ScaleVector (x, y) such that from.scale(x, y) = to',
93// where to' will have the same size as "to". In the case where "from" and "to"
94// start at the origin to'=to.
95ScaleVector getScale(const Rect& from, const Rect& to) {
96 return {.x = static_cast<float>(to.width()) / from.width(),
97 .y = static_cast<float>(to.height()) / from.height()};
98}
99
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800100} // namespace
101
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700102std::shared_ptr<Output> createOutput(
103 const compositionengine::CompositionEngine& compositionEngine) {
104 return createOutputTemplated<Output>(compositionEngine);
105}
Lloyd Pique32cbe282018-10-19 13:09:22 -0700106
107Output::~Output() = default;
108
Lloyd Pique32cbe282018-10-19 13:09:22 -0700109bool Output::isValid() const {
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700110 return mDisplayColorProfile && mDisplayColorProfile->isValid() && mRenderSurface &&
111 mRenderSurface->isValid();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700112}
113
Lloyd Pique6c564cf2019-05-17 17:31:36 -0700114std::optional<DisplayId> Output::getDisplayId() const {
115 return {};
116}
117
Lloyd Pique32cbe282018-10-19 13:09:22 -0700118const std::string& Output::getName() const {
119 return mName;
120}
121
122void Output::setName(const std::string& name) {
123 mName = name;
Leon Scroggins III5a655b82022-09-07 13:17:09 -0400124 auto displayIdOpt = getDisplayId();
Leon Scroggins IIIc03d4652023-01-05 13:03:53 -0500125 mNamePlusId = displayIdOpt ? base::StringPrintf("%s (%s)", mName.c_str(),
126 to_string(*displayIdOpt).c_str())
127 : mName;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700128}
129
130void Output::setCompositionEnabled(bool enabled) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700131 auto& outputState = editState();
132 if (outputState.isEnabled == enabled) {
Lloyd Pique32cbe282018-10-19 13:09:22 -0700133 return;
134 }
135
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700136 outputState.isEnabled = enabled;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700137 dirtyEntireOutput();
138}
139
Alec Mouri023c1882021-05-08 16:36:33 -0700140void Output::setLayerCachingEnabled(bool enabled) {
141 if (enabled == (mPlanner != nullptr)) {
142 return;
143 }
144
145 if (enabled) {
Alec Mouridf6201b2021-06-01 16:20:42 -0700146 mPlanner = std::make_unique<planner::Planner>(getCompositionEngine().getRenderEngine());
Alec Mouri023c1882021-05-08 16:36:33 -0700147 if (mRenderSurface) {
148 mPlanner->setDisplaySize(mRenderSurface->getSize());
149 }
150 } else {
151 mPlanner.reset();
152 }
Alec Mouric773472b2021-05-19 14:29:05 -0700153
154 for (auto* outputLayer : getOutputLayersOrderedByZ()) {
155 if (!outputLayer) {
156 continue;
157 }
158
159 outputLayer->editState().overrideInfo = {};
160 }
Alec Mouri023c1882021-05-08 16:36:33 -0700161}
162
Ady Abrahamdb036a82021-07-16 14:18:34 -0700163void Output::setLayerCachingTexturePoolEnabled(bool enabled) {
164 if (mPlanner) {
165 mPlanner->setTexturePoolEnabled(enabled);
166 }
167}
168
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200169void Output::setProjection(ui::Rotation orientation, const Rect& layerStackSpaceRect,
170 const Rect& orientedDisplaySpaceRect) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700171 auto& outputState = editState();
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200172
Angel Aguayob084e0c2021-08-04 23:27:28 +0000173 outputState.displaySpace.setOrientation(orientation);
174 LOG_FATAL_IF(outputState.displaySpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200175 "The display bounds are unknown.");
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200176
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200177 // Compute orientedDisplaySpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000178 ui::Size orientedSize = outputState.displaySpace.getBounds();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200179 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200180 std::swap(orientedSize.width, orientedSize.height);
181 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000182 outputState.orientedDisplaySpace.setBounds(orientedSize);
183 outputState.orientedDisplaySpace.setContent(orientedDisplaySpaceRect);
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200184
185 // Compute displaySpace.content
186 const uint32_t transformOrientationFlags = ui::Transform::toRotationFlags(orientation);
187 ui::Transform rotation;
188 if (transformOrientationFlags != ui::Transform::ROT_INVALID) {
Angel Aguayob084e0c2021-08-04 23:27:28 +0000189 const auto displaySize = outputState.displaySpace.getBoundsAsRect();
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200190 rotation.set(transformOrientationFlags, displaySize.width(), displaySize.height());
191 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000192 outputState.displaySpace.setContent(rotation.transform(orientedDisplaySpaceRect));
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200193
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200194 // Compute framebufferSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000195 outputState.framebufferSpace.setOrientation(orientation);
196 LOG_FATAL_IF(outputState.framebufferSpace.getBoundsAsRect() == Rect::INVALID_RECT,
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200197 "The framebuffer bounds are unknown.");
Angel Aguayob084e0c2021-08-04 23:27:28 +0000198 const auto scale = getScale(outputState.displaySpace.getBoundsAsRect(),
199 outputState.framebufferSpace.getBoundsAsRect());
200 outputState.framebufferSpace.setContent(
201 outputState.displaySpace.getContent().scale(scale.x, scale.y));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200202
203 // Compute layerStackSpace
Angel Aguayob084e0c2021-08-04 23:27:28 +0000204 outputState.layerStackSpace.setContent(layerStackSpaceRect);
205 outputState.layerStackSpace.setBounds(
206 ui::Size(layerStackSpaceRect.getWidth(), layerStackSpaceRect.getHeight()));
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200207
Marin Shalamanov68933fb2020-09-10 17:58:12 +0200208 outputState.transform = outputState.layerStackSpace.getTransform(outputState.displaySpace);
209 outputState.needsFiltering = outputState.transform.needsBilinearFiltering();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700210 dirtyEntireOutput();
211}
212
Alec Mouricdf16792021-12-10 13:16:06 -0800213void Output::setNextBrightness(float brightness) {
214 editState().displayBrightness = brightness;
215}
216
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200217void Output::setDisplaySize(const ui::Size& size) {
Lloyd Pique31cb2942018-10-19 17:23:03 -0700218 mRenderSurface->setDisplaySize(size);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200219
220 auto& state = editState();
221
222 // Update framebuffer space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000223 const ui::Size newBounds(size);
224 state.framebufferSpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200225
226 // Update display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000227 state.displaySpace.setBounds(newBounds);
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200228 state.transform = state.layerStackSpace.getTransform(state.displaySpace);
229
230 // Update oriented display space
Angel Aguayob084e0c2021-08-04 23:27:28 +0000231 const auto orientation = state.displaySpace.getOrientation();
Marin Shalamanovb15d2272020-09-17 21:41:52 +0200232 ui::Size orientedSize = size;
233 if (orientation == ui::ROTATION_90 || orientation == ui::ROTATION_270) {
234 std::swap(orientedSize.width, orientedSize.height);
235 }
Angel Aguayob084e0c2021-08-04 23:27:28 +0000236 const ui::Size newOrientedBounds(orientedSize);
237 state.orientedDisplaySpace.setBounds(newOrientedBounds);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700238
Dan Stoza6166c312021-01-15 16:34:05 -0800239 if (mPlanner) {
240 mPlanner->setDisplaySize(size);
241 }
242
Lloyd Pique32cbe282018-10-19 13:09:22 -0700243 dirtyEntireOutput();
244}
245
Garfield Tan54edd912020-10-21 16:31:41 -0700246ui::Transform::RotationFlags Output::getTransformHint() const {
247 return static_cast<ui::Transform::RotationFlags>(getState().transform.getOrientation());
248}
249
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700250void Output::setLayerFilter(ui::LayerFilter filter) {
251 editState().layerFilter = filter;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700252 dirtyEntireOutput();
253}
254
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800255void Output::setColorTransform(const compositionengine::CompositionRefreshArgs& args) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700256 auto& colorTransformMatrix = editState().colorTransformMatrix;
257 if (!args.colorTransformMatrix || colorTransformMatrix == args.colorTransformMatrix) {
Lloyd Pique77f79a22019-04-29 15:55:40 -0700258 return;
259 }
260
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700261 colorTransformMatrix = *args.colorTransformMatrix;
Lloyd Piqueef958122019-02-05 18:00:12 -0800262
263 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700264}
265
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800266void Output::setColorProfile(const ColorProfile& colorProfile) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700267 auto& outputState = editState();
268 if (outputState.colorMode == colorProfile.mode &&
269 outputState.dataspace == colorProfile.dataspace &&
Alec Mouri88790f32023-07-21 01:25:14 +0000270 outputState.renderIntent == colorProfile.renderIntent) {
Lloyd Piqueef958122019-02-05 18:00:12 -0800271 return;
272 }
273
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700274 outputState.colorMode = colorProfile.mode;
275 outputState.dataspace = colorProfile.dataspace;
276 outputState.renderIntent = colorProfile.renderIntent;
Lloyd Pique32cbe282018-10-19 13:09:22 -0700277
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800278 mRenderSurface->setBufferDataspace(colorProfile.dataspace);
Lloyd Pique31cb2942018-10-19 17:23:03 -0700279
Lloyd Pique32cbe282018-10-19 13:09:22 -0700280 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d)",
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800281 decodeColorMode(colorProfile.mode).c_str(), colorProfile.mode,
282 decodeRenderIntent(colorProfile.renderIntent).c_str(), colorProfile.renderIntent);
Lloyd Piqueef958122019-02-05 18:00:12 -0800283
284 dirtyEntireOutput();
Lloyd Pique32cbe282018-10-19 13:09:22 -0700285}
286
John Reckac09e452021-04-07 16:35:37 -0400287void Output::setDisplayBrightness(float sdrWhitePointNits, float displayBrightnessNits) {
288 auto& outputState = editState();
289 if (outputState.sdrWhitePointNits == sdrWhitePointNits &&
290 outputState.displayBrightnessNits == displayBrightnessNits) {
291 // Nothing changed
292 return;
293 }
294 outputState.sdrWhitePointNits = sdrWhitePointNits;
295 outputState.displayBrightnessNits = displayBrightnessNits;
296 dirtyEntireOutput();
297}
298
Lloyd Pique32cbe282018-10-19 13:09:22 -0700299void Output::dump(std::string& out) const {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700300 base::StringAppendF(&out, "Output \"%s\"", mName.c_str());
301 out.append("\n Composition Output State:\n");
Lloyd Pique32cbe282018-10-19 13:09:22 -0700302
303 dumpBase(out);
304}
305
306void Output::dumpBase(std::string& out) const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700307 dumpState(out);
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700308 out += '\n';
Lloyd Pique31cb2942018-10-19 17:23:03 -0700309
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700310 if (mDisplayColorProfile) {
311 mDisplayColorProfile->dump(out);
312 } else {
313 out.append(" No display color profile!\n");
314 }
315
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700316 out += '\n';
317
Lloyd Pique31cb2942018-10-19 17:23:03 -0700318 if (mRenderSurface) {
319 mRenderSurface->dump(out);
320 } else {
321 out.append(" No render surface!\n");
322 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800323
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700324 base::StringAppendF(&out, "\n %zu Layers\n", getOutputLayerCount());
Lloyd Pique01c77c12019-04-17 12:48:32 -0700325 for (const auto* outputLayer : getOutputLayersOrderedByZ()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800326 if (!outputLayer) {
327 continue;
328 }
329 outputLayer->dump(out);
330 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700331}
332
Dan Stoza269dc4d2021-01-15 15:07:43 -0800333void Output::dumpPlannerInfo(const Vector<String16>& args, std::string& out) const {
334 if (!mPlanner) {
Dominik Laskowski0acc3842022-04-07 11:23:42 -0700335 out.append("Planner is disabled\n");
Dan Stoza269dc4d2021-01-15 15:07:43 -0800336 return;
337 }
338 base::StringAppendF(&out, "Planner info for display [%s]\n", mName.c_str());
339 mPlanner->dump(args, out);
340}
341
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700342compositionengine::DisplayColorProfile* Output::getDisplayColorProfile() const {
343 return mDisplayColorProfile.get();
344}
345
346void Output::setDisplayColorProfile(std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
347 mDisplayColorProfile = std::move(mode);
348}
349
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800350const Output::ReleasedLayers& Output::getReleasedLayersForTest() const {
351 return mReleasedLayers;
352}
353
Lloyd Pique3d0c02e2018-10-19 18:38:12 -0700354void Output::setDisplayColorProfileForTest(
355 std::unique_ptr<compositionengine::DisplayColorProfile> mode) {
356 mDisplayColorProfile = std::move(mode);
357}
358
Lloyd Pique31cb2942018-10-19 17:23:03 -0700359compositionengine::RenderSurface* Output::getRenderSurface() const {
360 return mRenderSurface.get();
361}
362
363void Output::setRenderSurface(std::unique_ptr<compositionengine::RenderSurface> surface) {
364 mRenderSurface = std::move(surface);
Dan Stoza6166c312021-01-15 16:34:05 -0800365 const auto size = mRenderSurface->getSize();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000366 editState().framebufferSpace.setBounds(size);
Dan Stoza6166c312021-01-15 16:34:05 -0800367 if (mPlanner) {
368 mPlanner->setDisplaySize(size);
369 }
Lloyd Pique31cb2942018-10-19 17:23:03 -0700370 dirtyEntireOutput();
371}
372
Vishnu Nair9b079a22020-01-21 14:36:08 -0800373void Output::cacheClientCompositionRequests(uint32_t cacheSize) {
374 if (cacheSize == 0) {
375 mClientCompositionRequestCache.reset();
376 } else {
377 mClientCompositionRequestCache = std::make_unique<ClientCompositionRequestCache>(cacheSize);
378 }
379};
380
Lloyd Pique31cb2942018-10-19 17:23:03 -0700381void Output::setRenderSurfaceForTest(std::unique_ptr<compositionengine::RenderSurface> surface) {
382 mRenderSurface = std::move(surface);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700383}
384
Dominik Laskowski8da6b0e2021-05-12 15:34:13 -0700385Region Output::getDirtyRegion() const {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700386 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +0000387 return outputState.dirtyRegion.intersect(outputState.layerStackSpace.getContent());
Lloyd Pique32cbe282018-10-19 13:09:22 -0700388}
389
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700390bool Output::includesLayer(ui::LayerFilter filter) const {
391 return getState().layerFilter.includes(filter);
Lloyd Pique32cbe282018-10-19 13:09:22 -0700392}
393
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700394bool Output::includesLayer(const sp<LayerFE>& layerFE) const {
Lloyd Piquede196652020-01-22 17:29:58 -0800395 const auto* layerFEState = layerFE->getCompositionState();
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700396 return layerFEState && includesLayer(layerFEState->outputFilter);
Lloyd Pique66c20c42019-03-07 21:44:02 -0800397}
398
Lloyd Piquedf336d92019-03-07 21:38:42 -0800399std::unique_ptr<compositionengine::OutputLayer> Output::createOutputLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800400 const sp<LayerFE>& layerFE) const {
401 return impl::createOutputLayer(*this, layerFE);
Lloyd Piquecc01a452018-12-04 17:24:00 -0800402}
403
Lloyd Piquede196652020-01-22 17:29:58 -0800404compositionengine::OutputLayer* Output::getOutputLayerForLayer(const sp<LayerFE>& layerFE) const {
405 auto index = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700406 return index ? getOutputLayerOrderedByZByIndex(*index) : nullptr;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800407}
408
Lloyd Pique01c77c12019-04-17 12:48:32 -0700409std::optional<size_t> Output::findCurrentOutputLayerForLayer(
Lloyd Piquede196652020-01-22 17:29:58 -0800410 const sp<compositionengine::LayerFE>& layer) const {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700411 for (size_t i = 0; i < getOutputLayerCount(); i++) {
412 auto outputLayer = getOutputLayerOrderedByZByIndex(i);
Lloyd Piquede196652020-01-22 17:29:58 -0800413 if (outputLayer && &outputLayer->getLayerFE() == layer.get()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700414 return i;
415 }
416 }
417 return std::nullopt;
Lloyd Piquecc01a452018-12-04 17:24:00 -0800418}
419
Lloyd Piquec7ef21b2019-01-29 18:43:00 -0800420void Output::setReleasedLayers(Output::ReleasedLayers&& layers) {
421 mReleasedLayers = std::move(layers);
422}
423
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800424void Output::prepare(const compositionengine::CompositionRefreshArgs& refreshArgs,
425 LayerFESet& geomSnapshots) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000426 SFTRACE_CALL();
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800427 ALOGV(__FUNCTION__);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800428
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800429 rebuildLayerStacks(refreshArgs, geomSnapshots);
Brian Lindahl439afad2022-11-14 11:16:55 -0700430 uncacheBuffers(refreshArgs.bufferIdsToUncache);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800431}
432
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400433ftl::Future<std::monostate> Output::present(
434 const compositionengine::CompositionRefreshArgs& refreshArgs) {
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500435 const auto stringifyExpectedPresentTime = [this, &refreshArgs]() -> std::string {
436 return ftl::Optional(getDisplayId())
437 .and_then(PhysicalDisplayId::tryCast)
438 .and_then([&refreshArgs](PhysicalDisplayId id) {
439 return refreshArgs.frameTargets.get(id);
440 })
441 .transform([](const auto& frameTargetPtr) {
442 return frameTargetPtr.get()->expectedPresentTime();
443 })
444 .transform([](TimePoint expectedPresentTime) {
445 return base::StringPrintf(" vsyncIn %.2fms",
446 ticks<std::milli, float>(expectedPresentTime -
447 TimePoint::now()));
448 })
449 .or_else([] {
450 // There is no vsync for this output.
451 return std::make_optional(std::string());
452 })
453 .value();
454 };
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000455 SFTRACE_FORMAT("%s for %s%s", __func__, mNamePlusId.c_str(),
456 stringifyExpectedPresentTime().c_str());
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800457 ALOGV(__FUNCTION__);
458
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800459 updateColorProfile(refreshArgs);
Dan Stoza269dc4d2021-01-15 15:07:43 -0800460 updateCompositionState(refreshArgs);
461 planComposition();
462 writeCompositionState(refreshArgs);
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800463 setColorTransform(refreshArgs);
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800464 beginFrame();
Vishnu Naira3140382022-02-24 14:07:11 -0800465
Xiang Wangaab31162024-03-12 19:48:08 -0700466 if (isPowerHintSessionEnabled()) {
467 // always reset the flag before the composition prediction
468 setHintSessionRequiresRenderEngine(false);
469 }
Vishnu Naira3140382022-02-24 14:07:11 -0800470 GpuCompositionResult result;
471 const bool predictCompositionStrategy = canPredictCompositionStrategy(refreshArgs);
472 if (predictCompositionStrategy) {
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +0000473 result = prepareFrameAsync();
Vishnu Naira3140382022-02-24 14:07:11 -0800474 } else {
475 prepareFrame();
476 }
477
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800478 devOptRepaintFlash(refreshArgs);
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +0000479 finishFrame(std::move(result));
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400480 ftl::Future<std::monostate> future;
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -0400481 const bool flushEvenWhenDisabled = !refreshArgs.bufferIdsToUncache.empty();
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400482 if (mOffloadPresent) {
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -0400483 future = presentFrameAndReleaseLayersAsync(flushEvenWhenDisabled);
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400484
485 // Only offload for this frame. The next frame will determine whether it
486 // needs to be offloaded. Leave the HwcAsyncWorker in place. For one thing,
487 // it is currently presenting. Further, it may be needed next frame, and
488 // we don't want to churn.
489 mOffloadPresent = false;
490 } else {
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -0400491 presentFrameAndReleaseLayers(flushEvenWhenDisabled);
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400492 future = ftl::yield<std::monostate>({});
493 }
Alec Mouriaa831582021-06-07 16:23:01 -0700494 renderCachedSets(refreshArgs);
Leon Scroggins III2f60d732022-09-12 14:42:38 -0400495 return future;
496}
497
498void Output::offloadPresentNextFrame() {
499 mOffloadPresent = true;
500 updateHwcAsyncWorker();
Lloyd Piqued7b429f2019-03-07 21:11:02 -0800501}
502
Brian Lindahl439afad2022-11-14 11:16:55 -0700503void Output::uncacheBuffers(std::vector<uint64_t> const& bufferIdsToUncache) {
504 if (bufferIdsToUncache.empty()) {
505 return;
506 }
507 for (auto outputLayer : getOutputLayersOrderedByZ()) {
508 outputLayer->uncacheBuffers(bufferIdsToUncache);
509 }
510}
511
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800512void Output::rebuildLayerStacks(const compositionengine::CompositionRefreshArgs& refreshArgs,
513 LayerFESet& layerFESet) {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700514 auto& outputState = editState();
515
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800516 // Do nothing if this output is not enabled or there is no need to perform this update
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700517 if (!outputState.isEnabled || CC_LIKELY(!refreshArgs.updatingOutputGeometryThisFrame)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800518 return;
519 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000520 SFTRACE_CALL();
Vishnu Naird9a640b2023-07-21 14:20:27 +0000521 ALOGV(__FUNCTION__);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800522
523 // Process the layers to determine visibility and coverage
524 compositionengine::Output::CoverageState coverage{layerFESet};
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000525 coverage.aboveCoveredLayersExcludingOverlays = refreshArgs.hasTrustedPresentationListener
526 ? std::make_optional<Region>()
527 : std::nullopt;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800528 collectVisibleLayers(refreshArgs, coverage);
529
530 // Compute the resulting coverage for this output, and store it for later
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700531 const ui::Transform& tr = outputState.transform;
Angel Aguayob084e0c2021-08-04 23:27:28 +0000532 Region undefinedRegion{outputState.displaySpace.getBoundsAsRect()};
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800533 undefinedRegion.subtractSelf(tr.transform(coverage.aboveOpaqueLayers));
534
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700535 outputState.undefinedRegion = undefinedRegion;
536 outputState.dirtyRegion.orSelf(coverage.dirtyRegion);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800537}
538
539void Output::collectVisibleLayers(const compositionengine::CompositionRefreshArgs& refreshArgs,
540 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800541 // Evaluate the layers from front to back to determine what is visible. This
542 // also incrementally calculates the coverage information for each layer as
543 // well as the entire output.
Lloyd Piquede196652020-01-22 17:29:58 -0800544 for (auto layer : reversed(refreshArgs.layers)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700545 // Incrementally process the coverage for each layer
546 ensureOutputLayerIfVisible(layer, coverage);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800547
548 // TODO(b/121291683): Stop early if the output is completely covered and
549 // no more layers could even be visible underneath the ones on top.
550 }
551
Lloyd Pique01c77c12019-04-17 12:48:32 -0700552 setReleasedLayers(refreshArgs);
553
554 finalizePendingOutputLayers();
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800555}
556
Lloyd Piquede196652020-01-22 17:29:58 -0800557void Output::ensureOutputLayerIfVisible(sp<compositionengine::LayerFE>& layerFE,
Lloyd Pique01c77c12019-04-17 12:48:32 -0700558 compositionengine::Output::CoverageState& coverage) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800559 // Ensure we have a snapshot of the basic geometry layer state. Limit the
560 // snapshots to once per frame for each candidate layer, as layers may
561 // appear on multiple outputs.
562 if (!coverage.latchedLayers.count(layerFE)) {
563 coverage.latchedLayers.insert(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800564 }
565
Dominik Laskowski29fa1462021-04-27 15:51:50 -0700566 // Only consider the layers on this output
567 if (!includesLayer(layerFE)) {
Lloyd Piquede196652020-01-22 17:29:58 -0800568 return;
569 }
570
571 // Obtain a read-only pointer to the front-end layer state
572 const auto* layerFEState = layerFE->getCompositionState();
573 if (CC_UNLIKELY(!layerFEState)) {
574 return;
575 }
576
577 // handle hidden surfaces by setting the visible region to empty
578 if (CC_UNLIKELY(!layerFEState->isVisible)) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700579 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800580 }
581
Vishnu Naird47bcee2023-02-24 18:08:51 +0000582 bool computeAboveCoveredExcludingOverlays = coverage.aboveCoveredLayersExcludingOverlays &&
583 !layerFEState->outputFilter.toInternalDisplay;
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000584
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800585 /*
586 * opaqueRegion: area of a surface that is fully opaque.
587 */
588 Region opaqueRegion;
589
590 /*
591 * visibleRegion: area of a surface that is visible on screen and not fully
592 * transparent. This is essentially the layer's footprint minus the opaque
593 * regions above it. Areas covered by a translucent surface are considered
594 * visible.
595 */
596 Region visibleRegion;
597
598 /*
599 * coveredRegion: area of a surface that is covered by all visible regions
600 * above it (which includes the translucent areas).
601 */
602 Region coveredRegion;
603
604 /*
605 * transparentRegion: area of a surface that is hinted to be completely
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500606 * transparent.
607 * This is used to tell when the layer has no visible non-transparent
608 * regions and can be removed from the layer list. It does not affect the
609 * visibleRegion of this layer or any layers beneath it. The hint may not
610 * be correct if apps don't respect the SurfaceView restrictions (which,
611 * sadly, some don't).
612 *
613 * In addition, it is used on DISPLAY_DECORATION layers to specify the
614 * blockingRegion, allowing the DPU to skip it to save power. Once we have
615 * hardware that supports a blockingRegion on frames with AFBC, it may be
616 * useful to use this for other layers, too, so long as we can prevent
617 * regressions on b/7179570.
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800618 */
619 Region transparentRegion;
620
Vishnu Naira483b4a2019-12-12 15:07:52 -0800621 /*
622 * shadowRegion: Region cast by the layer's shadow.
623 */
624 Region shadowRegion;
625
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000626 /**
627 * covered region above excluding internal display overlay layers
628 */
629 std::optional<Region> coveredRegionExcludingDisplayOverlays = std::nullopt;
630
Lloyd Piquede196652020-01-22 17:29:58 -0800631 const ui::Transform& tr = layerFEState->geomLayerTransform;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800632
633 // Get the visible region
634 // TODO(b/121291683): Is it worth creating helper methods on LayerFEState
635 // for computations like this?
Lloyd Piquede196652020-01-22 17:29:58 -0800636 const Rect visibleRect(tr.transform(layerFEState->geomLayerBounds));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800637 visibleRegion.set(visibleRect);
638
Vishnu Naird9e4f462023-10-06 04:05:45 +0000639 if (layerFEState->shadowSettings.length > 0.0f) {
Vishnu Naira483b4a2019-12-12 15:07:52 -0800640 // if the layer casts a shadow, offset the layers visible region and
641 // calculate the shadow region.
Vishnu Naird9e4f462023-10-06 04:05:45 +0000642 const auto inset = static_cast<int32_t>(ceilf(layerFEState->shadowSettings.length) * -1.0f);
Vishnu Naira483b4a2019-12-12 15:07:52 -0800643 Rect visibleRectWithShadows(visibleRect);
644 visibleRectWithShadows.inset(inset, inset, inset, inset);
645 visibleRegion.set(visibleRectWithShadows);
646 shadowRegion = visibleRegion.subtract(visibleRect);
647 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800648
649 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700650 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800651 }
652
653 // Remove the transparent area from the visible region
Lloyd Piquede196652020-01-22 17:29:58 -0800654 if (!layerFEState->isOpaque) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800655 if (tr.preserveRects()) {
Alec Mourie60f0b92022-06-10 19:15:20 +0000656 // Clip the transparent region to geomLayerBounds first
657 // The transparent region may be influenced by applications, for
658 // instance, by overriding ViewGroup#gatherTransparentRegion with a
659 // custom view. Once the layer stack -> display mapping is known, we
660 // must guard against very wrong inputs to prevent underflow or
661 // overflow errors. We do this here by constraining the transparent
662 // region to be within the pre-transform layer bounds, since the
663 // layer bounds are expected to play nicely with the full
664 // transform.
665 const Region clippedTransparentRegionHint =
666 layerFEState->transparentRegionHint.intersect(
667 Rect(layerFEState->geomLayerBounds));
668
669 if (clippedTransparentRegionHint.isEmpty()) {
670 if (!layerFEState->transparentRegionHint.isEmpty()) {
671 ALOGD("Layer: %s had an out of bounds transparent region",
672 layerFE->getDebugName());
673 layerFEState->transparentRegionHint.dump("transparentRegionHint");
674 }
675 transparentRegion.clear();
676 } else {
677 transparentRegion = tr.transform(clippedTransparentRegionHint);
678 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800679 } else {
680 // transformation too complex, can't do the
681 // transparent region optimization.
682 transparentRegion.clear();
683 }
684 }
685
686 // compute the opaque region
Lloyd Pique0a456232020-01-16 17:51:13 -0800687 const auto layerOrientation = tr.getOrientation();
Lloyd Piquede196652020-01-22 17:29:58 -0800688 if (layerFEState->isOpaque && ((layerOrientation & ui::Transform::ROT_INVALID) == 0)) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800689 // If we one of the simple category of transforms (0/90/180/270 rotation
690 // + any flip), then the opaque region is the layer's footprint.
691 // Otherwise we don't try and compute the opaque region since there may
692 // be errors at the edges, and we treat the entire layer as
693 // translucent.
Vishnu Naira483b4a2019-12-12 15:07:52 -0800694 opaqueRegion.set(visibleRect);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800695 }
696
697 // Clip the covered region to the visible region
698 coveredRegion = coverage.aboveCoveredLayers.intersect(visibleRegion);
699
700 // Update accumAboveCoveredLayers for next (lower) layer
701 coverage.aboveCoveredLayers.orSelf(visibleRegion);
702
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000703 if (CC_UNLIKELY(computeAboveCoveredExcludingOverlays)) {
704 coveredRegionExcludingDisplayOverlays =
705 coverage.aboveCoveredLayersExcludingOverlays->intersect(visibleRegion);
706 coverage.aboveCoveredLayersExcludingOverlays->orSelf(visibleRegion);
707 }
708
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800709 // subtract the opaque region covered by the layers above us
710 visibleRegion.subtractSelf(coverage.aboveOpaqueLayers);
711
712 if (visibleRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700713 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800714 }
715
716 // Get coverage information for the layer as previously displayed,
717 // also taking over ownership from mOutputLayersorderedByZ.
Lloyd Piquede196652020-01-22 17:29:58 -0800718 auto prevOutputLayerIndex = findCurrentOutputLayerForLayer(layerFE);
Lloyd Pique01c77c12019-04-17 12:48:32 -0700719 auto prevOutputLayer =
720 prevOutputLayerIndex ? getOutputLayerOrderedByZByIndex(*prevOutputLayerIndex) : nullptr;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800721
722 // Get coverage information for the layer as previously displayed
723 // TODO(b/121291683): Define kEmptyRegion as a constant in Region.h
724 const Region kEmptyRegion;
725 const Region& oldVisibleRegion =
726 prevOutputLayer ? prevOutputLayer->getState().visibleRegion : kEmptyRegion;
727 const Region& oldCoveredRegion =
728 prevOutputLayer ? prevOutputLayer->getState().coveredRegion : kEmptyRegion;
729
730 // compute this layer's dirty region
731 Region dirty;
Lloyd Piquede196652020-01-22 17:29:58 -0800732 if (layerFEState->contentDirty) {
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800733 // we need to invalidate the whole region
734 dirty = visibleRegion;
735 // as well, as the old visible region
736 dirty.orSelf(oldVisibleRegion);
737 } else {
738 /* compute the exposed region:
739 * the exposed region consists of two components:
740 * 1) what's VISIBLE now and was COVERED before
741 * 2) what's EXPOSED now less what was EXPOSED before
742 *
743 * note that (1) is conservative, we start with the whole visible region
744 * but only keep what used to be covered by something -- which mean it
745 * may have been exposed.
746 *
747 * (2) handles areas that were not covered by anything but got exposed
748 * because of a resize.
749 *
750 */
751 const Region newExposed = visibleRegion - coveredRegion;
752 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
753 dirty = (visibleRegion & oldCoveredRegion) | (newExposed - oldExposed);
754 }
755 dirty.subtractSelf(coverage.aboveOpaqueLayers);
756
757 // accumulate to the screen dirty region
758 coverage.dirtyRegion.orSelf(dirty);
759
760 // Update accumAboveOpaqueLayers for next (lower) layer
761 coverage.aboveOpaqueLayers.orSelf(opaqueRegion);
762
763 // Compute the visible non-transparent region
764 Region visibleNonTransparentRegion = visibleRegion.subtract(transparentRegion);
765
Vishnu Naira483b4a2019-12-12 15:07:52 -0800766 // Perform the final check to see if this layer is visible on this output
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800767 // TODO(b/121291683): Why does this not use visibleRegion? (see outputSpaceVisibleRegion below)
Lloyd Piquea38ea7e2019-04-16 18:10:26 -0700768 const auto& outputState = getState();
769 Region drawRegion(outputState.transform.transform(visibleNonTransparentRegion));
Angel Aguayob084e0c2021-08-04 23:27:28 +0000770 drawRegion.andSelf(outputState.displaySpace.getBoundsAsRect());
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800771 if (drawRegion.isEmpty()) {
Lloyd Pique01c77c12019-04-17 12:48:32 -0700772 return;
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800773 }
774
Vishnu Naira483b4a2019-12-12 15:07:52 -0800775 Region visibleNonShadowRegion = visibleRegion.subtract(shadowRegion);
776
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800777 // The layer is visible. Either reuse the existing outputLayer if we have
778 // one, or create a new one if we do not.
Lloyd Piquede196652020-01-22 17:29:58 -0800779 auto result = ensureOutputLayer(prevOutputLayerIndex, layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800780
781 // Store the layer coverage information into the layer state as some of it
782 // is useful later.
783 auto& outputLayerState = result->editState();
784 outputLayerState.visibleRegion = visibleRegion;
785 outputLayerState.visibleNonTransparentRegion = visibleNonTransparentRegion;
786 outputLayerState.coveredRegion = coveredRegion;
Marin Shalamanov6ad317c2020-07-29 23:34:07 +0200787 outputLayerState.outputSpaceVisibleRegion = outputState.transform.transform(
Angel Aguayob084e0c2021-08-04 23:27:28 +0000788 visibleNonShadowRegion.intersect(outputState.layerStackSpace.getContent()));
Vishnu Naira483b4a2019-12-12 15:07:52 -0800789 outputLayerState.shadowRegion = shadowRegion;
Leon Scroggins III9a0afda2022-01-11 16:53:09 -0500790 outputLayerState.outputSpaceBlockingRegionHint =
Leon Scroggins III7f7ad2c2022-03-17 17:06:20 -0400791 layerFEState->compositionType == Composition::DISPLAY_DECORATION
792 ? outputState.transform.transform(
793 transparentRegion.intersect(outputState.layerStackSpace.getContent()))
794 : Region();
Chavi Weingarten545da0e2023-02-09 14:55:57 +0000795 if (CC_UNLIKELY(computeAboveCoveredExcludingOverlays)) {
796 outputLayerState.coveredRegionExcludingDisplayOverlays =
797 std::move(coveredRegionExcludingDisplayOverlays);
798 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -0800799}
800
801void Output::setReleasedLayers(const compositionengine::CompositionRefreshArgs&) {
802 // The base class does nothing with this call.
803}
804
Dan Stoza269dc4d2021-01-15 15:07:43 -0800805void Output::updateCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000806 SFTRACE_CALL();
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800807 ALOGV(__FUNCTION__);
808
Alec Mourif9a2a2c2019-11-12 12:46:02 -0800809 if (!getState().isEnabled) {
810 return;
811 }
812
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800813 mLayerRequestingBackgroundBlur = findLayerRequestingBackgroundComposition();
814 bool forceClientComposition = mLayerRequestingBackgroundBlur != nullptr;
815
Sally Qi0abc4a52024-09-26 16:13:06 -0700816 auto* properties = getOverlaySupport();
817
Lloyd Pique01c77c12019-04-17 12:48:32 -0700818 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique7a234912019-10-03 11:54:27 -0700819 layer->updateCompositionState(refreshArgs.updatingGeometryThisFrame,
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800820 refreshArgs.devOptForceClientComposition ||
Snild Dolkow9e217d62020-04-22 15:53:42 +0200821 forceClientComposition,
Sally Qi0abc4a52024-09-26 16:13:06 -0700822 refreshArgs.internalDisplayRotationFlags,
823 properties ? properties->lutProperties : std::nullopt);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800824
825 if (mLayerRequestingBackgroundBlur == layer) {
826 forceClientComposition = false;
827 }
Dan Stoza269dc4d2021-01-15 15:07:43 -0800828 }
829}
Lloyd Pique3eb1b212019-03-07 21:15:40 -0800830
Dan Stoza269dc4d2021-01-15 15:07:43 -0800831void Output::planComposition() {
832 if (!mPlanner || !getState().isEnabled) {
833 return;
834 }
835
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000836 SFTRACE_CALL();
Dan Stoza269dc4d2021-01-15 15:07:43 -0800837 ALOGV(__FUNCTION__);
838
839 mPlanner->plan(getOutputLayersOrderedByZ());
840}
841
842void Output::writeCompositionState(const compositionengine::CompositionRefreshArgs& refreshArgs) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +0000843 SFTRACE_CALL();
Dan Stoza269dc4d2021-01-15 15:07:43 -0800844 ALOGV(__FUNCTION__);
845
846 if (!getState().isEnabled) {
847 return;
848 }
849
Leon Scroggins III370b8b52022-12-08 13:20:45 -0500850 if (auto frameTargetPtrOpt = ftl::Optional(getDisplayId())
851 .and_then(PhysicalDisplayId::tryCast)
852 .and_then([&refreshArgs](PhysicalDisplayId id) {
853 return refreshArgs.frameTargets.get(id);
854 })) {
855 editState().earliestPresentTime = frameTargetPtrOpt->get()->earliestPresentTime();
856 editState().expectedPresentTime = frameTargetPtrOpt->get()->expectedPresentTime().ns();
857 }
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() {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001086 SFTRACE_CALL();
Lloyd Pique66d68602019-02-13 14:23:31 -08001087 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 IIIa3ba7fa2024-05-22 16:34:52 -04001106ftl::Future<std::monostate> Output::presentFrameAndReleaseLayersAsync(bool flushEvenWhenDisabled) {
Yi Kong9dce90f2024-08-14 07:06:52 +08001107 return ftl::Future<bool>(mHwComposerAsyncWorker->send([this, flushEvenWhenDisabled]() {
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -04001108 presentFrameAndReleaseLayers(flushEvenWhenDisabled);
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001109 return true;
Yi Kong9dce90f2024-08-14 07:06:52 +08001110 }))
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001111 .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 Nairbe0ad902024-06-27 23:38:43 +00001121 SFTRACE_CALL();
Vishnu Naira3140382022-02-24 14:07:11 -08001122 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) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001151 SFTRACE_NAME("CompositionStrategyPredictionMiss");
Vishnu Naira3140382022-02-24 14:07:11 -08001152 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 {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001160 SFTRACE_NAME("CompositionStrategyPredictionHit");
Vishnu Naira3140382022-02-24 14:07:11 -08001161 }
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));
Alec Mourif97df4d2023-09-06 02:10:05 +00001179 mRenderSurface->queueBuffer(base::unique_fd(), getHdrSdrRatio(buffer));
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001180 }
1181 }
1182
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -04001183 constexpr bool kFlushEvenWhenDisabled = false;
1184 presentFrameAndReleaseLayers(kFlushEvenWhenDisabled);
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001185
1186 std::this_thread::sleep_for(*refreshArgs.devOptFlashDirtyRegionsDelay);
1187
1188 prepareFrame();
1189}
1190
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001191void Output::finishFrame(GpuCompositionResult&& result) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001192 SFTRACE_CALL();
Lloyd Piqued3d69882019-02-28 16:03:46 -08001193 ALOGV(__FUNCTION__);
Vishnu Nair9cf89262022-02-26 09:17:49 -08001194 const auto& outputState = getState();
1195 if (!outputState.isEnabled) {
Lloyd Piqued3d69882019-02-28 16:03:46 -08001196 return;
1197 }
1198
Vishnu Naira3140382022-02-24 14:07:11 -08001199 std::optional<base::unique_fd> optReadyFence;
1200 std::shared_ptr<renderengine::ExternalTexture> buffer;
1201 base::unique_fd bufferFence;
Vishnu Nair9cf89262022-02-26 09:17:49 -08001202 if (outputState.strategyPrediction == CompositionStrategyPredictionState::SUCCESS) {
Vishnu Naira3140382022-02-24 14:07:11 -08001203 optReadyFence = std::move(result.fence);
1204 } else {
1205 if (result.bufferAvailable()) {
1206 buffer = std::move(result.buffer);
1207 bufferFence = std::move(result.fence);
1208 } else {
1209 updateProtectedContentState();
1210 if (!dequeueRenderBuffer(&bufferFence, &buffer)) {
1211 return;
1212 }
1213 }
1214 // Repaint the framebuffer (if needed), getting the optional fence for when
1215 // the composition completes.
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001216 optReadyFence = composeSurfaces(Region::INVALID_REGION, buffer, bufferFence);
Vishnu Naira3140382022-02-24 14:07:11 -08001217 }
Lloyd Piqued3d69882019-02-28 16:03:46 -08001218 if (!optReadyFence) {
1219 return;
1220 }
Xiang Wangcb50bbd2024-04-18 16:57:54 -07001221 if (isPowerHintSessionEnabled() && !isPowerHintSessionGpuReportingEnabled()) {
Matt Buckley50c44062022-01-17 20:48:10 +00001222 // 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)
Alec Mourif97df4d2023-09-06 02:10:05 +00001227 mRenderSurface->queueBuffer(std::move(*optReadyFence), getHdrSdrRatio(buffer));
Lloyd Piqued3d69882019-02-28 16:03:46 -08001228}
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
Chavi Weingarten18fa7c62023-11-28 21:16:03 +00001235 bool isProtected;
1236 if (FlagManager::getInstance().display_protected()) {
1237 isProtected = outputState.isProtected;
1238 } else {
1239 isProtected = outputState.isSecure;
1240 }
1241
1242 // We need to set the render surface as protected (DRM) if all the following conditions are met:
1243 // 1. The display is protected (in legacy, check if the display is secure)
1244 // 2. Protected content is supported
1245 // 3. At least one layer has protected content.
1246 if (isProtected && supportsProtectedContent) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001247 auto layers = getOutputLayersOrderedByZ();
1248 bool needsProtected = std::any_of(layers.begin(), layers.end(), [](auto* layer) {
Eason Chiu45099662023-10-23 08:55:48 +08001249 return layer->getLayerFE().getCompositionState()->hasProtectedContent &&
1250 (!FlagManager::getInstance().protected_if_client() ||
1251 layer->requiresClientComposition());
Lloyd Piquee9eff972020-05-05 12:36:44 -07001252 });
Patrick Williams8aed5d22022-10-31 22:18:10 +00001253 if (needsProtected != mRenderSurface->isProtected()) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001254 mRenderSurface->setProtected(needsProtected);
1255 }
1256 }
Vishnu Naira3140382022-02-24 14:07:11 -08001257}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001258
Vishnu Naira3140382022-02-24 14:07:11 -08001259bool Output::dequeueRenderBuffer(base::unique_fd* bufferFence,
1260 std::shared_ptr<renderengine::ExternalTexture>* tex) {
1261 const auto& outputState = getState();
Lloyd Piquee9eff972020-05-05 12:36:44 -07001262
1263 // If we aren't doing client composition on this output, but do have a
1264 // flipClientTarget request for this frame on this output, we still need to
1265 // dequeue a buffer.
Vishnu Naira3140382022-02-24 14:07:11 -08001266 if (outputState.usesClientComposition || outputState.flipClientTarget) {
1267 *tex = mRenderSurface->dequeueBuffer(bufferFence);
1268 if (*tex == nullptr) {
Lloyd Piquee9eff972020-05-05 12:36:44 -07001269 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
1270 "client composition for this frame",
1271 mName.c_str());
Vishnu Naira3140382022-02-24 14:07:11 -08001272 return false;
Lloyd Piquee9eff972020-05-05 12:36:44 -07001273 }
1274 }
Vishnu Naira3140382022-02-24 14:07:11 -08001275 return true;
1276}
Lloyd Piquee9eff972020-05-05 12:36:44 -07001277
Vishnu Naira3140382022-02-24 14:07:11 -08001278std::optional<base::unique_fd> Output::composeSurfaces(
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001279 const Region& debugRegion, std::shared_ptr<renderengine::ExternalTexture> tex,
1280 base::unique_fd& fd) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001281 SFTRACE_CALL();
Vishnu Naira3140382022-02-24 14:07:11 -08001282 ALOGV(__FUNCTION__);
1283
1284 const auto& outputState = getState();
Leon Scroggins III042fdba2023-01-04 10:53:07 -05001285 const TracedOrdinal<bool> hasClientComposition = {
1286 base::StringPrintf("hasClientComposition %s", mNamePlusId.c_str()),
1287 outputState.usesClientComposition};
Lloyd Pique688abd42019-02-15 15:42:24 -08001288 if (!hasClientComposition) {
Lloyd Piquea76ce462020-01-14 13:06:37 -08001289 setExpensiveRenderingExpected(false);
Sally Qi4cabdd02021-08-05 16:45:57 -07001290 return base::unique_fd();
Lloyd Pique688abd42019-02-15 15:42:24 -08001291 }
1292
Vishnu Naira3140382022-02-24 14:07:11 -08001293 if (tex == nullptr) {
1294 ALOGW("Buffer not valid for display [%s], bailing out of "
1295 "client composition for this frame",
1296 mName.c_str());
1297 return {};
1298 }
1299
Lloyd Pique688abd42019-02-15 15:42:24 -08001300 ALOGV("hasClientComposition");
1301
Patrick Williams7584c6a2022-10-29 02:10:58 +00001302 renderengine::DisplaySettings clientCompositionDisplay =
Alec Mourif97df4d2023-09-06 02:10:05 +00001303 generateClientCompositionDisplaySettings(tex);
Lloyd Pique688abd42019-02-15 15:42:24 -08001304
Lloyd Pique688abd42019-02-15 15:42:24 -08001305 // Generate the client composition requests for the layers on this output.
Vishnu Naira3140382022-02-24 14:07:11 -08001306 auto& renderEngine = getCompositionEngine().getRenderEngine();
1307 const bool supportsProtectedContent = renderEngine.supportsProtectedContent();
Robert Carrccab4242021-09-28 16:53:03 -07001308 std::vector<LayerFE*> clientCompositionLayersFE;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001309 std::vector<LayerFE::LayerSettings> clientCompositionLayers =
Lloyd Pique688abd42019-02-15 15:42:24 -08001310 generateClientCompositionRequests(supportsProtectedContent,
Robert Carrccab4242021-09-28 16:53:03 -07001311 clientCompositionDisplay.outputDataspace,
1312 clientCompositionLayersFE);
Lloyd Pique688abd42019-02-15 15:42:24 -08001313 appendRegionFlashRequests(debugRegion, clientCompositionLayers);
1314
Vishnu Naira3140382022-02-24 14:07:11 -08001315 OutputCompositionState& outputCompositionState = editState();
Vishnu Nair9b079a22020-01-21 14:36:08 -08001316 // Check if the client composition requests were rendered into the provided graphic buffer. If
1317 // so, we can reuse the buffer and avoid client composition.
1318 if (mClientCompositionRequestCache) {
Alec Mouria90a5702021-04-16 16:36:21 +00001319 if (mClientCompositionRequestCache->exists(tex->getBuffer()->getId(),
1320 clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001321 clientCompositionLayers)) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001322 SFTRACE_NAME("ClientCompositionCacheHit");
Vishnu Nair9b079a22020-01-21 14:36:08 -08001323 outputCompositionState.reusedClientComposition = true;
1324 setExpensiveRenderingExpected(false);
Vishnu Nair3a49f0a2022-07-29 21:52:53 +00001325 // b/239944175 pass the fence associated with the buffer.
1326 return base::unique_fd(std::move(fd));
Vishnu Nair9b079a22020-01-21 14:36:08 -08001327 }
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001328 SFTRACE_NAME("ClientCompositionCacheMiss");
Alec Mouria90a5702021-04-16 16:36:21 +00001329 mClientCompositionRequestCache->add(tex->getBuffer()->getId(), clientCompositionDisplay,
Vishnu Nair9b079a22020-01-21 14:36:08 -08001330 clientCompositionLayers);
1331 }
1332
Lloyd Pique688abd42019-02-15 15:42:24 -08001333 // We boost GPU frequency here because there will be color spaces conversion
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08001334 // or complex GPU shaders and it's expensive. We boost the GPU frequency so that
1335 // GPU composition can finish in time. We must reset GPU frequency afterwards,
1336 // because high frequency consumes extra battery.
Carlos Martinez Romeroe5d57ea2022-11-15 19:14:36 +00001337 const bool expensiveRenderingExpected =
Leon Scroggins IIIcf17ebc2022-03-03 14:54:00 -05001338 std::any_of(clientCompositionLayers.begin(), clientCompositionLayers.end(),
1339 [outputDataspace =
1340 clientCompositionDisplay.outputDataspace](const auto& layer) {
1341 return layer.sourceDataspace != outputDataspace;
1342 });
Lloyd Pique688abd42019-02-15 15:42:24 -08001343 if (expensiveRenderingExpected) {
1344 setExpensiveRenderingExpected(true);
1345 }
1346
Sally Qi59a9f502021-10-12 18:53:23 +00001347 std::vector<renderengine::LayerSettings> clientRenderEngineLayers;
1348 clientRenderEngineLayers.reserve(clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001349 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Sally Qi59a9f502021-10-12 18:53:23 +00001350 std::back_inserter(clientRenderEngineLayers),
1351 [](LayerFE::LayerSettings& settings) -> renderengine::LayerSettings {
1352 return settings;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001353 });
1354
Alec Mourie4034bb2019-11-19 12:45:54 -08001355 const nsecs_t renderEngineStart = systemTime();
Patrick Williams2e9748f2022-08-09 22:48:18 +00001356 auto fenceResult = renderEngine
1357 .drawLayers(clientCompositionDisplay, clientRenderEngineLayers, tex,
Alec Mourif29700f2023-08-17 21:53:31 +00001358 std::move(fd))
Patrick Williams2e9748f2022-08-09 22:48:18 +00001359 .get();
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001360
1361 if (mClientCompositionRequestCache && fenceStatus(fenceResult) != NO_ERROR) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08001362 // If rendering was not successful, remove the request from the cache.
Alec Mouria90a5702021-04-16 16:36:21 +00001363 mClientCompositionRequestCache->remove(tex->getBuffer()->getId());
Vishnu Nair9b079a22020-01-21 14:36:08 -08001364 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001365 const auto fence = std::move(fenceResult).value_or(Fence::NO_FENCE);
Xiang Wangaab31162024-03-12 19:48:08 -07001366 if (isPowerHintSessionEnabled()) {
1367 if (fence != Fence::NO_FENCE && fence->isValid() &&
1368 !outputCompositionState.reusedClientComposition) {
1369 setHintSessionRequiresRenderEngine(true);
Xiang Wangcb50bbd2024-04-18 16:57:54 -07001370 if (isPowerHintSessionGpuReportingEnabled()) {
Xiang Wangaab31162024-03-12 19:48:08 -07001371 // the order of the two calls here matters as we should check if the previously
1372 // tracked fence has signaled first and archive the previous start time
1373 setHintSessionGpuStart(TimePoint::now());
1374 setHintSessionGpuFence(
1375 std::make_unique<FenceTime>(sp<Fence>::make(dup(fence->get()))));
1376 }
1377 }
1378 }
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001379
Patrick Williams74c0bf62022-11-02 23:59:26 +00001380 if (auto timeStats = getCompositionEngine().getTimeStats()) {
1381 if (fence->isValid()) {
1382 timeStats->recordRenderEngineDuration(renderEngineStart,
1383 std::make_shared<FenceTime>(fence));
1384 } else {
1385 timeStats->recordRenderEngineDuration(renderEngineStart, systemTime());
1386 }
Alec Mourie4034bb2019-11-19 12:45:54 -08001387 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001388
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001389 for (auto* clientComposedLayer : clientCompositionLayersFE) {
1390 clientComposedLayer->setWasClientComposed(fence);
Robert Carrccab4242021-09-28 16:53:03 -07001391 }
1392
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001393 return base::unique_fd(fence->dup());
Lloyd Pique688abd42019-02-15 15:42:24 -08001394}
1395
Alec Mourif97df4d2023-09-06 02:10:05 +00001396renderengine::DisplaySettings Output::generateClientCompositionDisplaySettings(
1397 const std::shared_ptr<renderengine::ExternalTexture>& buffer) const {
Patrick Williams7584c6a2022-10-29 02:10:58 +00001398 const auto& outputState = getState();
1399
1400 renderengine::DisplaySettings clientCompositionDisplay;
Leon Scroggins III5a655b82022-09-07 13:17:09 -04001401 clientCompositionDisplay.namePlusId = mNamePlusId;
Patrick Williams7584c6a2022-10-29 02:10:58 +00001402 clientCompositionDisplay.physicalDisplay = outputState.framebufferSpace.getContent();
1403 clientCompositionDisplay.clip = outputState.layerStackSpace.getContent();
1404 clientCompositionDisplay.orientation =
1405 ui::Transform::toRotationFlags(outputState.displaySpace.getOrientation());
1406 clientCompositionDisplay.outputDataspace = mDisplayColorProfile->hasWideColorGamut()
1407 ? outputState.dataspace
1408 : ui::Dataspace::UNKNOWN;
1409
1410 // If we have a valid current display brightness use that, otherwise fall back to the
1411 // display's max desired
1412 clientCompositionDisplay.currentLuminanceNits = outputState.displayBrightnessNits > 0.f
1413 ? outputState.displayBrightnessNits
1414 : mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
1415 clientCompositionDisplay.maxLuminance =
1416 mDisplayColorProfile->getHdrCapabilities().getDesiredMaxLuminance();
Alec Mourif97df4d2023-09-06 02:10:05 +00001417
1418 float hdrSdrRatioMultiplier = 1.0f / getHdrSdrRatio(buffer);
1419 clientCompositionDisplay.targetLuminanceNits = outputState.clientTargetBrightness *
1420 outputState.displayBrightnessNits * hdrSdrRatioMultiplier;
Patrick Williams7584c6a2022-10-29 02:10:58 +00001421 clientCompositionDisplay.dimmingStage = outputState.clientTargetDimmingStage;
1422 clientCompositionDisplay.renderIntent =
1423 static_cast<aidl::android::hardware::graphics::composer3::RenderIntent>(
1424 outputState.renderIntent);
1425
1426 // Compute the global color transform matrix.
1427 clientCompositionDisplay.colorTransform = outputState.colorTransformMatrix;
Patrick Williams7584c6a2022-10-29 02:10:58 +00001428 clientCompositionDisplay.deviceHandlesColorTransform =
1429 outputState.usesDeviceComposition || getSkipColorTransform();
1430 return clientCompositionDisplay;
1431}
1432
Vishnu Nair9b079a22020-01-21 14:36:08 -08001433std::vector<LayerFE::LayerSettings> Output::generateClientCompositionRequests(
Robert Carrccab4242021-09-28 16:53:03 -07001434 bool supportsProtectedContent, ui::Dataspace outputDataspace, std::vector<LayerFE*>& outLayerFEs) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08001435 std::vector<LayerFE::LayerSettings> clientCompositionLayers;
Lloyd Pique688abd42019-02-15 15:42:24 -08001436 ALOGV("Rendering client layers");
1437
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001438 const auto& outputState = getState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001439 const Region viewportRegion(outputState.layerStackSpace.getContent());
Lloyd Pique688abd42019-02-15 15:42:24 -08001440 bool firstLayer = true;
Lloyd Pique688abd42019-02-15 15:42:24 -08001441
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001442 bool disableBlurs = false;
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001443 uint64_t previousOverrideBufferId = 0;
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001444
Lloyd Pique01c77c12019-04-17 12:48:32 -07001445 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001446 const auto& layerState = layer->getState();
Lloyd Piquede196652020-01-22 17:29:58 -08001447 const auto* layerFEState = layer->getLayerFE().getCompositionState();
Lloyd Pique688abd42019-02-15 15:42:24 -08001448 auto& layerFE = layer->getLayerFE();
Robert Carr05da0082022-05-25 23:29:34 -07001449 layerFE.setWasClientComposed(nullptr);
Lloyd Pique688abd42019-02-15 15:42:24 -08001450
Lloyd Piquea2468662019-03-07 21:31:06 -08001451 const Region clip(viewportRegion.intersect(layerState.visibleRegion));
Lloyd Pique688abd42019-02-15 15:42:24 -08001452 ALOGV("Layer: %s", layerFE.getDebugName());
1453 if (clip.isEmpty()) {
1454 ALOGV(" Skipping for empty clip");
1455 firstLayer = false;
1456 continue;
1457 }
1458
Galia Peycheva66eaf4a2020-11-09 13:17:57 +01001459 disableBlurs |= layerFEState->sidebandStream != nullptr;
1460
Vishnu Naira483b4a2019-12-12 15:07:52 -08001461 const bool clientComposition = layer->requiresClientComposition();
Lloyd Pique688abd42019-02-15 15:42:24 -08001462
1463 // We clear the client target for non-client composed layers if
1464 // requested by the HWC. We skip this if the layer is not an opaque
1465 // rectangle, as by definition the layer must blend with whatever is
1466 // underneath. We also skip the first layer as the buffer target is
1467 // guaranteed to start out cleared.
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001468 const bool clearClientComposition =
Lloyd Piquede196652020-01-22 17:29:58 -08001469 layerState.clearClientTarget && layerFEState->isOpaque && !firstLayer;
Lloyd Pique688abd42019-02-15 15:42:24 -08001470
1471 ALOGV(" Composition type: client %d clear %d", clientComposition, clearClientComposition);
1472
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001473 // If the layer casts a shadow but the content casting the shadow is occluded, skip
1474 // composing the non-shadow content and only draw the shadows.
1475 const bool realContentIsVisible = clientComposition &&
1476 !layerState.visibleRegion.subtract(layerState.shadowRegion).isEmpty();
1477
Lloyd Pique688abd42019-02-15 15:42:24 -08001478 if (clientComposition || clearClientComposition) {
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001479 if (auto overrideSettings = layer->getOverrideCompositionSettings()) {
1480 if (overrideSettings->bufferId != previousOverrideBufferId) {
1481 previousOverrideBufferId = overrideSettings->bufferId;
1482 clientCompositionLayers.push_back(std::move(*overrideSettings));
Huihong Luo91ac3b52021-04-08 11:07:41 -07001483 ALOGV("Replacing [%s] with override in RE", layer->getLayerFE().getDebugName());
1484 } else {
1485 ALOGV("Skipping redundant override buffer for [%s] in RE",
1486 layer->getLayerFE().getDebugName());
1487 }
Dan Stoza6166c312021-01-15 16:34:05 -08001488 } else {
Alec Mourif54453c2021-05-13 16:28:28 -07001489 LayerFE::ClientCompositionTargetSettings::BlurSetting blurSetting = disableBlurs
1490 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::Disabled
1491 : (layer->getState().overrideInfo.disableBackgroundBlur
1492 ? LayerFE::ClientCompositionTargetSettings::BlurSetting::
1493 BlurRegionsOnly
1494 : LayerFE::ClientCompositionTargetSettings::BlurSetting::
1495 Enabled);
Chavi Weingarten18fa7c62023-11-28 21:16:03 +00001496 bool isProtected = supportsProtectedContent;
1497 if (FlagManager::getInstance().display_protected()) {
1498 isProtected = outputState.isProtected && supportsProtectedContent;
1499 }
Alec Mourif54453c2021-05-13 16:28:28 -07001500 compositionengine::LayerFE::ClientCompositionTargetSettings
1501 targetSettings{.clip = clip,
Patrick Williams278a88f2023-01-27 16:52:40 -06001502 .needsFiltering = layer->needsFiltering() ||
Alec Mourif54453c2021-05-13 16:28:28 -07001503 outputState.needsFiltering,
1504 .isSecure = outputState.isSecure,
Chavi Weingarten18fa7c62023-11-28 21:16:03 +00001505 .isProtected = isProtected,
Angel Aguayob084e0c2021-08-04 23:27:28 +00001506 .viewport = outputState.layerStackSpace.getContent(),
Alec Mourif54453c2021-05-13 16:28:28 -07001507 .dataspace = outputDataspace,
1508 .realContentIsVisible = realContentIsVisible,
1509 .clearContent = !clientComposition,
Alec Mouricdf6cbc2021-11-01 17:21:15 -07001510 .blurSetting = blurSetting,
Vishnu Naire14c6b32022-08-06 04:20:15 +00001511 .whitePointNits = layerState.whitePointNits,
1512 .treat170mAsSrgb = outputState.treat170mAsSrgb};
Patrick Williams16d8b2c2022-08-08 17:29:05 +00001513 if (auto clientCompositionSettings =
1514 layerFE.prepareClientComposition(targetSettings)) {
1515 clientCompositionLayers.push_back(std::move(*clientCompositionSettings));
1516 if (realContentIsVisible) {
1517 layer->editState().clientCompositionTimestamp = systemTime();
1518 }
Dan Stoza6166c312021-01-15 16:34:05 -08001519 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001520 }
Vishnu Nairb87d94f2020-02-13 09:17:36 -08001521
Tianhua Sunf91f1402022-05-09 05:45:46 +00001522 if (clientComposition) {
1523 outLayerFEs.push_back(&layerFE);
1524 }
Lloyd Pique688abd42019-02-15 15:42:24 -08001525 }
1526
1527 firstLayer = false;
1528 }
1529
1530 return clientCompositionLayers;
1531}
1532
1533void Output::appendRegionFlashRequests(
Vishnu Nair9b079a22020-01-21 14:36:08 -08001534 const Region& flashRegion, std::vector<LayerFE::LayerSettings>& clientCompositionLayers) {
Lloyd Pique688abd42019-02-15 15:42:24 -08001535 if (flashRegion.isEmpty()) {
1536 return;
1537 }
1538
Vishnu Nair9b079a22020-01-21 14:36:08 -08001539 LayerFE::LayerSettings layerSettings;
Lloyd Pique688abd42019-02-15 15:42:24 -08001540 layerSettings.source.buffer.buffer = nullptr;
1541 layerSettings.source.solidColor = half3(1.0, 0.0, 1.0);
1542 layerSettings.alpha = half(1.0);
1543
1544 for (const auto& rect : flashRegion) {
1545 layerSettings.geometry.boundaries = rect.toFloatRect();
1546 clientCompositionLayers.push_back(layerSettings);
1547 }
1548}
1549
1550void Output::setExpensiveRenderingExpected(bool) {
1551 // The base class does nothing with this call.
1552}
1553
Xiang Wangaab31162024-03-12 19:48:08 -07001554void Output::setHintSessionGpuStart(TimePoint) {
1555 // The base class does nothing with this call.
1556}
1557
Matt Buckley50c44062022-01-17 20:48:10 +00001558void Output::setHintSessionGpuFence(std::unique_ptr<FenceTime>&&) {
1559 // The base class does nothing with this call.
1560}
1561
Xiang Wangaab31162024-03-12 19:48:08 -07001562void Output::setHintSessionRequiresRenderEngine(bool) {
1563 // The base class does nothing with this call.
1564}
1565
Matt Buckley50c44062022-01-17 20:48:10 +00001566bool Output::isPowerHintSessionEnabled() {
1567 return false;
1568}
1569
Xiang Wangcb50bbd2024-04-18 16:57:54 -07001570bool Output::isPowerHintSessionGpuReportingEnabled() {
1571 return false;
1572}
1573
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -04001574void Output::presentFrameAndReleaseLayers(bool flushEvenWhenDisabled) {
Vishnu Nairbe0ad902024-06-27 23:38:43 +00001575 SFTRACE_FORMAT("%s for %s", __func__, mNamePlusId.c_str());
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001576 ALOGV(__FUNCTION__);
1577
1578 if (!getState().isEnabled) {
Leon Scroggins IIIa3ba7fa2024-05-22 16:34:52 -04001579 if (flushEvenWhenDisabled && FlagManager::getInstance().flush_buffer_slots_to_uncache()) {
1580 // Some commands, like clearing buffer slots, should still be executed
1581 // even if the display is not enabled.
1582 executeCommands();
1583 }
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001584 return;
1585 }
1586
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001587 auto& outputState = editState();
1588 outputState.dirtyRegion.clear();
Lloyd Piqued3d69882019-02-28 16:03:46 -08001589
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001590 auto frame = presentFrame();
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001591
Lloyd Pique7d90ba52019-08-08 11:57:53 -07001592 mRenderSurface->onPresentDisplayCompleted();
1593
Lloyd Pique01c77c12019-04-17 12:48:32 -07001594 for (auto* layer : getOutputLayersOrderedByZ()) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001595 // The layer buffer from the previous frame (if any) is released
1596 // by HWC only when the release fence from this frame (if any) is
1597 // signaled. Always get the release fence from HWC first.
1598 sp<Fence> releaseFence = Fence::NO_FENCE;
1599
1600 if (auto hwcLayer = layer->getHwcLayer()) {
1601 if (auto f = frame.layerFences.find(hwcLayer); f != frame.layerFences.end()) {
1602 releaseFence = f->second;
1603 }
1604 }
1605
1606 // If the layer was client composited in the previous frame, we
1607 // need to merge with the previous client target acquire fence.
1608 // Since we do not track that, always merge with the current
1609 // client target acquire fence when it is available, even though
1610 // this is suboptimal.
1611 // TODO(b/121291683): Track previous frame client target acquire fence.
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001612 if (outputState.usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001613 releaseFence =
1614 Fence::merge("LayerRelease", releaseFence, frame.clientTargetAcquireFence);
1615 }
Melody Hsu0077fde2024-10-17 21:42:50 +00001616 layer->getLayerFE().setReleaseFence(releaseFence);
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001617 }
1618
1619 // We've got a list of layers needing fences, that are disjoint with
Lloyd Pique01c77c12019-04-17 12:48:32 -07001620 // OutputLayersOrderedByZ. The best we can do is to
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001621 // supply them with the present fence.
1622 for (auto& weakLayer : mReleasedLayers) {
Dominik Laskowskibb448ce2022-05-07 15:52:55 -07001623 if (const auto layer = weakLayer.promote()) {
Melody Hsu0077fde2024-10-17 21:42:50 +00001624 layer->setReleaseFence(frame.presentFence);
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001625 }
1626 }
1627
1628 // Clear out the released layers now that we're done with them.
1629 mReleasedLayers.clear();
1630}
1631
Alec Mouriaa831582021-06-07 16:23:01 -07001632void Output::renderCachedSets(const CompositionRefreshArgs& refreshArgs) {
Leon Scroggins III43b5d522023-04-10 15:53:45 -04001633 const auto& outputState = getState();
1634 if (mPlanner && outputState.isEnabled) {
1635 mPlanner->renderCachedSets(outputState, refreshArgs.scheduledFrameTime,
1636 outputState.usesDeviceComposition || getSkipColorTransform());
Dan Stoza6166c312021-01-15 16:34:05 -08001637 }
1638}
1639
Lloyd Pique32cbe282018-10-19 13:09:22 -07001640void Output::dirtyEntireOutput() {
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001641 auto& outputState = editState();
Angel Aguayob084e0c2021-08-04 23:27:28 +00001642 outputState.dirtyRegion.set(outputState.displaySpace.getBoundsAsRect());
Lloyd Pique32cbe282018-10-19 13:09:22 -07001643}
1644
Vishnu Naira3140382022-02-24 14:07:11 -08001645void Output::resetCompositionStrategy() {
Lloyd Pique66d68602019-02-13 14:23:31 -08001646 // The base output implementation can only do client composition
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001647 auto& outputState = editState();
1648 outputState.usesClientComposition = true;
1649 outputState.usesDeviceComposition = false;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001650 outputState.reusedClientComposition = false;
Lloyd Pique66d68602019-02-13 14:23:31 -08001651}
1652
Lloyd Pique688abd42019-02-15 15:42:24 -08001653bool Output::getSkipColorTransform() const {
1654 return true;
1655}
1656
Leon Scroggins IIIc1623d12023-11-06 15:31:05 -05001657compositionengine::Output::FrameFences Output::presentFrame() {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001658 compositionengine::Output::FrameFences result;
Lloyd Piquea38ea7e2019-04-16 18:10:26 -07001659 if (getState().usesClientComposition) {
Lloyd Pique35fca9d2019-02-13 14:24:11 -08001660 result.clientTargetAcquireFence = mRenderSurface->getClientTargetAcquireFence();
1661 }
1662 return result;
1663}
1664
Vishnu Naira3140382022-02-24 14:07:11 -08001665void Output::setPredictCompositionStrategy(bool predict) {
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001666 mPredictCompositionStrategy = predict;
1667 updateHwcAsyncWorker();
1668}
1669
1670void Output::updateHwcAsyncWorker() {
1671 if (mPredictCompositionStrategy || mOffloadPresent) {
1672 if (!mHwComposerAsyncWorker) {
1673 mHwComposerAsyncWorker = std::make_unique<HwcAsyncWorker>();
1674 }
Vishnu Naira3140382022-02-24 14:07:11 -08001675 } else {
1676 mHwComposerAsyncWorker.reset(nullptr);
1677 }
1678}
1679
Alec Mouridda07d92022-04-25 22:39:25 +00001680void Output::setTreat170mAsSrgb(bool enable) {
1681 editState().treat170mAsSrgb = enable;
1682}
1683
Sally Qi0abc4a52024-09-26 16:13:06 -07001684const aidl::android::hardware::graphics::composer3::OverlayProperties* Output::getOverlaySupport() {
1685 return nullptr;
1686}
1687
Vishnu Naira3140382022-02-24 14:07:11 -08001688bool Output::canPredictCompositionStrategy(const CompositionRefreshArgs& refreshArgs) {
Robert Carrec8ccca2022-05-04 09:36:14 -07001689 uint64_t lastOutputLayerHash = getState().lastOutputLayerHash;
1690 uint64_t outputLayerHash = getState().outputLayerHash;
1691 editState().lastOutputLayerHash = outputLayerHash;
1692
Leon Scroggins III2f60d732022-09-12 14:42:38 -04001693 if (!getState().isEnabled || !mPredictCompositionStrategy) {
Vishnu Naira3140382022-02-24 14:07:11 -08001694 ALOGV("canPredictCompositionStrategy disabled");
1695 return false;
1696 }
1697
1698 if (!getState().previousDeviceRequestedChanges) {
1699 ALOGV("canPredictCompositionStrategy previous changes not available");
1700 return false;
1701 }
1702
1703 if (!mRenderSurface->supportsCompositionStrategyPrediction()) {
1704 ALOGV("canPredictCompositionStrategy surface does not support");
1705 return false;
1706 }
1707
1708 if (refreshArgs.devOptFlashDirtyRegionsDelay) {
1709 ALOGV("canPredictCompositionStrategy devOptFlashDirtyRegionsDelay");
1710 return false;
1711 }
1712
Robert Carrec8ccca2022-05-04 09:36:14 -07001713 if (lastOutputLayerHash != outputLayerHash) {
1714 ALOGV("canPredictCompositionStrategy output layers changed");
1715 return false;
1716 }
1717
Vishnu Naira3140382022-02-24 14:07:11 -08001718 // If no layer uses clientComposition, then don't predict composition strategy
1719 // because we have less work to do in parallel.
1720 if (!anyLayersRequireClientComposition()) {
1721 ALOGV("canPredictCompositionStrategy no layer uses clientComposition");
1722 return false;
1723 }
1724
Robert Carrec8ccca2022-05-04 09:36:14 -07001725 return true;
Vishnu Naira3140382022-02-24 14:07:11 -08001726}
1727
1728bool Output::anyLayersRequireClientComposition() const {
1729 const auto layers = getOutputLayersOrderedByZ();
1730 return std::any_of(layers.begin(), layers.end(),
1731 [](const auto& layer) { return layer->requiresClientComposition(); });
1732}
1733
1734void Output::finishPrepareFrame() {
1735 const auto& state = getState();
1736 if (mPlanner) {
1737 mPlanner->reportFinalPlan(getOutputLayersOrderedByZ());
1738 }
1739 mRenderSurface->prepareFrame(state.usesClientComposition, state.usesDeviceComposition);
1740}
1741
Chavi Weingarten09fa1d62022-08-17 21:57:04 +00001742bool Output::mustRecompose() const {
1743 return mMustRecompose;
1744}
1745
Alec Mourif97df4d2023-09-06 02:10:05 +00001746float Output::getHdrSdrRatio(const std::shared_ptr<renderengine::ExternalTexture>& buffer) const {
1747 if (buffer == nullptr) {
1748 return 1.0f;
1749 }
1750
1751 if (!FlagManager::getInstance().fp16_client_target()) {
1752 return 1.0f;
1753 }
1754
1755 if (getState().displayBrightnessNits < 0.0f || getState().sdrWhitePointNits <= 0.0f ||
1756 buffer->getPixelFormat() != PIXEL_FORMAT_RGBA_FP16 ||
1757 (static_cast<int32_t>(getState().dataspace) &
1758 static_cast<int32_t>(ui::Dataspace::RANGE_MASK)) !=
1759 static_cast<int32_t>(ui::Dataspace::RANGE_EXTENDED)) {
1760 return 1.0f;
1761 }
1762
1763 return getState().displayBrightnessNits / getState().sdrWhitePointNits;
1764}
1765
Lloyd Piquefeb73d72018-12-04 17:23:44 -08001766} // namespace impl
1767} // namespace android::compositionengine