blob: 1b2b180c521d05375d4cb6cb027aa9d698554248 [file] [log] [blame]
David Sodman0c69cad2017-08-21 12:12:51 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#undef LOG_TAG
19#define LOG_TAG "BufferLayer"
20#define ATRACE_TAG ATRACE_TAG_GRAPHICS
21
Lloyd Piquefeb73d72018-12-04 17:23:44 -080022#include <cmath>
23#include <cstdlib>
24#include <mutex>
25
26#include <compositionengine/CompositionEngine.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080027#include <compositionengine/Display.h>
Lloyd Piquefeb73d72018-12-04 17:23:44 -080028#include <compositionengine/Layer.h>
29#include <compositionengine/LayerCreationArgs.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080030#include <compositionengine/OutputLayer.h>
Lloyd Pique0b785d82018-12-04 17:25:27 -080031#include <compositionengine/impl/LayerCompositionState.h>
Lloyd Pique37c2c9b2018-12-04 17:25:10 -080032#include <compositionengine/impl/OutputLayerCompositionState.h>
Lloyd Piquefeb73d72018-12-04 17:23:44 -080033#include <cutils/compiler.h>
34#include <cutils/native_handle.h>
35#include <cutils/properties.h>
36#include <gui/BufferItem.h>
37#include <gui/BufferQueue.h>
38#include <gui/LayerDebugInfo.h>
39#include <gui/Surface.h>
40#include <renderengine/RenderEngine.h>
41#include <ui/DebugUtils.h>
42#include <utils/Errors.h>
43#include <utils/Log.h>
44#include <utils/NativeHandle.h>
45#include <utils/StopWatch.h>
46#include <utils/Trace.h>
47
David Sodman0c69cad2017-08-21 12:12:51 -070048#include "BufferLayer.h"
49#include "Colorizer.h"
50#include "DisplayDevice.h"
51#include "LayerRejecter.h"
David Sodman0c69cad2017-08-21 12:12:51 -070052
Yiwei Zhang7e666a52018-11-15 13:33:42 -080053#include "TimeStats/TimeStats.h"
54
David Sodman0c69cad2017-08-21 12:12:51 -070055namespace android {
56
Lloyd Pique42ab75e2018-09-12 20:46:03 -070057BufferLayer::BufferLayer(const LayerCreationArgs& args)
Lloyd Piquefeb73d72018-12-04 17:23:44 -080058 : Layer(args),
59 mTextureName(args.flinger->getNewTexture()),
60 mCompositionLayer{mFlinger->getCompositionEngine().createLayer(
61 compositionengine::LayerCreationArgs{this})} {
Lloyd Pique42ab75e2018-09-12 20:46:03 -070062 ALOGV("Creating Layer %s", args.name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070063
Lloyd Pique42ab75e2018-09-12 20:46:03 -070064 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070065
Lloyd Pique42ab75e2018-09-12 20:46:03 -070066 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
67 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070068}
69
70BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070071 mFlinger->deleteTextureAsync(mTextureName);
Yiwei Zhang7e666a52018-11-15 13:33:42 -080072 mFlinger->mTimeStats->onDestroy(getSequence());
David Sodman0c69cad2017-08-21 12:12:51 -070073}
74
David Sodmaneb085e02017-10-05 18:49:04 -070075void BufferLayer::useSurfaceDamage() {
76 if (mFlinger->mForceFullDamage) {
77 surfaceDamageRegion = Region::INVALID_REGION;
78 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070079 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070080 }
81}
82
83void BufferLayer::useEmptyDamage() {
84 surfaceDamageRegion.clear();
85}
86
Marissa Wallfd668622018-05-10 10:21:13 -070087bool BufferLayer::isOpaque(const Layer::State& s) const {
88 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
89 // layer's opaque flag.
Lloyd Pique0b785d82018-12-04 17:25:27 -080090 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
Marissa Wallfd668622018-05-10 10:21:13 -070091 return false;
92 }
93
94 // if the layer has the opaque flag, then we're always opaque,
95 // otherwise we use the current buffer's format.
96 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -070097}
98
99bool BufferLayer::isVisible() const {
100 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
Lloyd Pique0b785d82018-12-04 17:25:27 -0800101 (mActiveBuffer != nullptr || mSidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700102}
103
104bool BufferLayer::isFixedSize() const {
105 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
106}
107
Lloyd Piquea83776c2019-01-29 18:42:32 -0800108bool BufferLayer::usesSourceCrop() const {
109 return true;
110}
111
David Sodman0c69cad2017-08-21 12:12:51 -0700112static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800113 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
114 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
115 const mat4 rot90(0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
David Sodman0c69cad2017-08-21 12:12:51 -0700116 mat4 tr;
117
118 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
119 tr = tr * rot90;
120 }
121 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
122 tr = tr * flipH;
123 }
124 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
125 tr = tr * flipV;
126 }
127 return inverse(tr);
128}
129
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000130bool BufferLayer::prepareClientLayer(const RenderArea& renderArea, const Region& clip,
131 bool useIdentityTransform, Region& clearRegion,
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800132 const bool supportProtectedContent,
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000133 renderengine::LayerSettings& layer) {
David Sodman0c69cad2017-08-21 12:12:51 -0700134 ATRACE_CALL();
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800135 Layer::prepareClientLayer(renderArea, clip, useIdentityTransform, clearRegion,
136 supportProtectedContent, layer);
David Sodman0cf8f8d2017-12-20 18:19:45 -0800137 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700138 // the texture has not been created yet, this Layer has
139 // in fact never been drawn into. This happens frequently with
140 // SurfaceView because the WindowManager can't know when the client
141 // has drawn the first time.
142
143 // If there is nothing under us, we paint the screen in black, otherwise
144 // we just skip this update.
145
146 // figure out if there is something below us
147 Region under;
148 bool finished = false;
149 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
150 if (finished || layer == static_cast<BufferLayer const*>(this)) {
151 finished = true;
152 return;
153 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000154 under.orSelf(layer->visibleRegion);
David Sodman0c69cad2017-08-21 12:12:51 -0700155 });
156 // if not everything below us is covered, we plug the holes!
157 Region holes(clip.subtract(under));
158 if (!holes.isEmpty()) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000159 clearRegion.orSelf(holes);
David Sodman0c69cad2017-08-21 12:12:51 -0700160 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000161 return false;
David Sodman0c69cad2017-08-21 12:12:51 -0700162 }
Peiyong Lin8f28a1d2019-02-07 17:25:12 -0800163 bool blackOutLayer =
164 (isProtected() && !supportProtectedContent) || (isSecure() && !renderArea.isSecure());
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000165 const State& s(getDrawingState());
David Sodman0c69cad2017-08-21 12:12:51 -0700166 if (!blackOutLayer) {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000167 layer.source.buffer.buffer = mActiveBuffer;
168 layer.source.buffer.isOpaque = isOpaque(s);
169 layer.source.buffer.fence = mActiveBufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000170 layer.source.buffer.textureName = mTextureName;
171 layer.source.buffer.usePremultipliedAlpha = getPremultipledAlpha();
172 layer.source.buffer.isY410BT2020 = isHdrY410();
David Sodman0c69cad2017-08-21 12:12:51 -0700173 // TODO: we could be more subtle with isFixedSize()
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800174 const bool useFiltering = needsFiltering(renderArea.getDisplayDevice()) ||
175 renderArea.needsFiltering() || isFixedSize();
David Sodman0c69cad2017-08-21 12:12:51 -0700176
177 // Query the texture matrix given our current filtering mode.
178 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700179 setFilteringEnabled(useFiltering);
180 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700181
182 if (getTransformToDisplayInverse()) {
183 /*
184 * the code below applies the primary display's inverse transform to
185 * the texture transform
186 */
187 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
188 mat4 tr = inverseOrientation(transform);
189
190 /**
191 * TODO(b/36727915): This is basically a hack.
192 *
193 * Ensure that regardless of the parent transformation,
194 * this buffer is always transformed from native display
195 * orientation to display orientation. For example, in the case
196 * of a camera where the buffer remains in native orientation,
197 * we want the pixels to always be upright.
198 */
199 sp<Layer> p = mDrawingParent.promote();
200 if (p != nullptr) {
201 const auto parentTransform = p->getTransform();
202 tr = tr * inverseOrientation(parentTransform.getOrientation());
203 }
204
205 // and finally apply it to the original texture matrix
206 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
207 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
208 }
209
Vishnu Nair4351ad52019-02-11 14:13:02 -0800210 const Rect win{getBounds()};
Marissa Wall290ad082019-03-06 13:23:47 -0800211 float bufferWidth = getBufferSize(s).getWidth();
212 float bufferHeight = getBufferSize(s).getHeight();
213
214 // BufferStateLayers can have a "buffer size" of [0, 0, -1, -1] when no display frame has
215 // been set and there is no parent layer bounds. In that case, the scale is meaningless so
216 // ignore them.
217 if (!getBufferSize(s).isValid()) {
218 bufferWidth = float(win.right) - float(win.left);
219 bufferHeight = float(win.bottom) - float(win.top);
220 }
David Sodman0c69cad2017-08-21 12:12:51 -0700221
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000222 const float scaleHeight = (float(win.bottom) - float(win.top)) / bufferHeight;
223 const float scaleWidth = (float(win.right) - float(win.left)) / bufferWidth;
224 const float translateY = float(win.top) / bufferHeight;
225 const float translateX = float(win.left) / bufferWidth;
226
227 // Flip y-coordinates because GLConsumer expects OpenGL convention.
228 mat4 tr = mat4::translate(vec4(.5, .5, 0, 1)) * mat4::scale(vec4(1, -1, 1, 1)) *
229 mat4::translate(vec4(-.5, -.5, 0, 1)) *
230 mat4::translate(vec4(translateX, translateY, 0, 1)) *
231 mat4::scale(vec4(scaleWidth, scaleHeight, 1.0, 1.0));
232
233 layer.source.buffer.useTextureFiltering = useFiltering;
234 layer.source.buffer.textureTransform = mat4(static_cast<const float*>(textureMatrix)) * tr;
David Sodman0c69cad2017-08-21 12:12:51 -0700235 } else {
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000236 // If layer is blacked out, force alpha to 1 so that we draw a black color
237 // layer.
238 layer.source.buffer.buffer = nullptr;
239 layer.alpha = 1.0;
David Sodman0c69cad2017-08-21 12:12:51 -0700240 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +0000241
242 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700243}
244
Marissa Wallfd668622018-05-10 10:21:13 -0700245bool BufferLayer::isHdrY410() const {
246 // pixel format is HDR Y410 masquerading as RGBA_1010102
247 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
248 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
Lloyd Pique0b785d82018-12-04 17:25:27 -0800249 mActiveBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700250}
251
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800252void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& displayDevice,
253 const ui::Transform& transform, const Rect& viewport,
Peiyong Linc502cb72019-03-01 15:00:23 -0800254 int32_t supportedPerFrameMetadata,
255 const ui::Dataspace targetDataspace) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800256 RETURN_IF_NO_HWC_LAYER(displayDevice);
Dominik Laskowski34157762018-10-31 13:07:19 -0700257
David Sodman0c69cad2017-08-21 12:12:51 -0700258 // Apply this display's projection's viewport to the visible region
259 // before giving it to the HWC HAL.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700260 Region visible = transform.transform(visibleRegion.intersect(viewport));
261
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800262 const auto outputLayer = findOutputLayerForDisplay(displayDevice);
263 LOG_FATAL_IF(!outputLayer || !outputLayer->getState().hwc);
264
265 auto& hwcLayer = (*outputLayer->getState().hwc).hwcLayer;
David Sodman15094112018-10-11 09:39:37 -0700266 auto error = hwcLayer->setVisibleRegion(visible);
267 if (error != HWC2::Error::None) {
268 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
269 to_string(error).c_str(), static_cast<int32_t>(error));
270 visible.dump(LOG_TAG);
271 }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800272 outputLayer->editState().visibleRegion = visible;
David Sodman15094112018-10-11 09:39:37 -0700273
Lloyd Pique0b785d82018-12-04 17:25:27 -0800274 auto& layerCompositionState = getCompositionLayer()->editState().frontEnd;
275
David Sodman15094112018-10-11 09:39:37 -0700276 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
277 if (error != HWC2::Error::None) {
278 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
279 to_string(error).c_str(), static_cast<int32_t>(error));
280 surfaceDamageRegion.dump(LOG_TAG);
281 }
Lloyd Pique0b785d82018-12-04 17:25:27 -0800282 layerCompositionState.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700283
284 // Sideband layers
Lloyd Pique0b785d82018-12-04 17:25:27 -0800285 if (layerCompositionState.sidebandStream.get()) {
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800286 setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::SIDEBAND);
David Sodman15094112018-10-11 09:39:37 -0700287 ALOGV("[%s] Requesting Sideband composition", mName.string());
Lloyd Pique0b785d82018-12-04 17:25:27 -0800288 error = hwcLayer->setSidebandStream(layerCompositionState.sidebandStream->handle());
David Sodman15094112018-10-11 09:39:37 -0700289 if (error != HWC2::Error::None) {
290 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
Lloyd Pique0b785d82018-12-04 17:25:27 -0800291 layerCompositionState.sidebandStream->handle(), to_string(error).c_str(),
David Sodman15094112018-10-11 09:39:37 -0700292 static_cast<int32_t>(error));
293 }
Lloyd Pique0b785d82018-12-04 17:25:27 -0800294 layerCompositionState.compositionType = Hwc2::IComposerClient::Composition::SIDEBAND;
David Sodman0c69cad2017-08-21 12:12:51 -0700295 return;
296 }
297
David Sodman15094112018-10-11 09:39:37 -0700298 // Device or Cursor layers
299 if (mPotentialCursor) {
300 ALOGV("[%s] Requesting Cursor composition", mName.string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800301 setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::CURSOR);
David Sodman15094112018-10-11 09:39:37 -0700302 } else {
303 ALOGV("[%s] Requesting Device composition", mName.string());
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800304 setCompositionType(displayDevice, Hwc2::IComposerClient::Composition::DEVICE);
David Sodman0c69cad2017-08-21 12:12:51 -0700305 }
306
Peiyong Lin34ea5b92019-03-15 18:40:15 -0700307 ui::Dataspace dataspace = isColorSpaceAgnostic() && targetDataspace != ui::Dataspace::UNKNOWN
308 ? targetDataspace
309 : mCurrentDataSpace;
Peiyong Linc502cb72019-03-01 15:00:23 -0800310 error = hwcLayer->setDataspace(dataspace);
David Sodman15094112018-10-11 09:39:37 -0700311 if (error != HWC2::Error::None) {
Peiyong Linc502cb72019-03-01 15:00:23 -0800312 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), dataspace,
David Sodman15094112018-10-11 09:39:37 -0700313 to_string(error).c_str(), static_cast<int32_t>(error));
314 }
315
316 const HdrMetadata& metadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700317 error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
David Sodman15094112018-10-11 09:39:37 -0700318 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
319 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
320 to_string(error).c_str(), static_cast<int32_t>(error));
321 }
322
323 error = hwcLayer->setColorTransform(getColorTransform());
324 if (error != HWC2::Error::None) {
325 ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
326 to_string(error).c_str(), static_cast<int32_t>(error));
327 }
Lloyd Pique0b785d82018-12-04 17:25:27 -0800328 layerCompositionState.dataspace = mCurrentDataSpace;
329 layerCompositionState.colorTransform = getColorTransform();
330 layerCompositionState.hdrMetadata = metadata;
Lloyd Pique074e8122018-07-26 12:57:23 -0700331
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800332 setHwcLayerBuffer(displayDevice);
David Sodman0c69cad2017-08-21 12:12:51 -0700333}
334
Marissa Wallfd668622018-05-10 10:21:13 -0700335bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
336 if (mBufferLatched) {
337 Mutex::Autolock lock(mFrameEventHistoryMutex);
338 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700339 }
Marissa Wallfd668622018-05-10 10:21:13 -0700340 mRefreshPending = false;
341 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700342}
343
Dominik Laskowski075d3172018-05-24 15:50:06 -0700344bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
345 const std::shared_ptr<FenceTime>& glDoneFence,
Marissa Wallfd668622018-05-10 10:21:13 -0700346 const std::shared_ptr<FenceTime>& presentFence,
347 const CompositorTiming& compositorTiming) {
348 // mFrameLatencyNeeded is true when a new frame was latched for the
349 // composition.
350 if (!mFrameLatencyNeeded) return false;
351
352 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700353 {
Marissa Wallfd668622018-05-10 10:21:13 -0700354 Mutex::Autolock lock(mFrameEventHistoryMutex);
355 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
356 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700357 }
358
Marissa Wallfd668622018-05-10 10:21:13 -0700359 // Update mFrameTracker.
360 nsecs_t desiredPresentTime = getDesiredPresentTime();
361 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
362
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700363 const int32_t layerID = getSequence();
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800364 mFlinger->mTimeStats->setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700365
366 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
367 if (frameReadyFence->isValid()) {
368 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
369 } else {
370 // There was no fence for this frame, so assume that it was ready
371 // to be presented at the desired present time.
372 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700373 }
Marissa Wallfd668622018-05-10 10:21:13 -0700374
375 if (presentFence->isValid()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800376 mFlinger->mTimeStats->setPresentFence(layerID, mCurrentFrameNumber, presentFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700377 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski075d3172018-05-24 15:50:06 -0700378 } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700379 // The HWC doesn't support present fences, so use the refresh
380 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700381 const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800382 mFlinger->mTimeStats->setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700383 mFrameTracker.setActualPresentTime(actualPresentTime);
384 }
385
386 mFrameTracker.advanceFrame();
387 mFrameLatencyNeeded = false;
388 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700389}
390
Alec Mouri56e538f2019-01-14 15:22:01 -0800391bool BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
Marissa Wallfd668622018-05-10 10:21:13 -0700392 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700393
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800394 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700395
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800396 if (refreshRequired) {
397 return refreshRequired;
David Sodman0c69cad2017-08-21 12:12:51 -0700398 }
399
Marissa Wallfd668622018-05-10 10:21:13 -0700400 if (!hasReadyFrame()) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800401 return false;
David Sodman0c69cad2017-08-21 12:12:51 -0700402 }
David Sodman0c69cad2017-08-21 12:12:51 -0700403
Marissa Wallfd668622018-05-10 10:21:13 -0700404 // if we've already called updateTexImage() without going through
405 // a composition step, we have to skip this layer at this point
406 // because we cannot call updateTeximage() without a corresponding
407 // compositionComplete() call.
408 // we'll trigger an update in onPreComposition().
409 if (mRefreshPending) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800410 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700411 }
412
413 // If the head buffer's acquire fence hasn't signaled yet, return and
414 // try again later
415 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700416 mFlinger->signalLayerUpdate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800417 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700418 }
419
420 // Capture the old state of the layer for comparisons later
421 const State& s(getDrawingState());
422 const bool oldOpacity = isOpaque(s);
423 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
424
425 if (!allTransactionsSignaled()) {
426 mFlinger->signalLayerUpdate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800427 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700428 }
429
Alec Mouri56e538f2019-01-14 15:22:01 -0800430 status_t err = updateTexImage(recomputeVisibleRegions, latchTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700431 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800432 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700433 }
434
435 err = updateActiveBuffer();
436 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800437 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700438 }
439
440 mBufferLatched = true;
441
442 err = updateFrameNumber(latchTime);
443 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800444 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700445 }
446
447 mRefreshPending = true;
448 mFrameLatencyNeeded = true;
449 if (oldBuffer == nullptr) {
450 // the first time we receive a buffer, we need to trigger a
451 // geometry invalidation.
452 recomputeVisibleRegions = true;
453 }
454
455 ui::Dataspace dataSpace = getDrawingDataSpace();
Peiyong Lin14724e62018-12-05 07:27:30 -0800456 // translate legacy dataspaces to modern dataspaces
Marissa Wallfd668622018-05-10 10:21:13 -0700457 switch (dataSpace) {
Peiyong Lin14724e62018-12-05 07:27:30 -0800458 case ui::Dataspace::SRGB:
459 dataSpace = ui::Dataspace::V0_SRGB;
Marissa Wallfd668622018-05-10 10:21:13 -0700460 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800461 case ui::Dataspace::SRGB_LINEAR:
462 dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
Marissa Wallfd668622018-05-10 10:21:13 -0700463 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800464 case ui::Dataspace::JFIF:
465 dataSpace = ui::Dataspace::V0_JFIF;
Marissa Wallfd668622018-05-10 10:21:13 -0700466 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800467 case ui::Dataspace::BT601_625:
468 dataSpace = ui::Dataspace::V0_BT601_625;
Marissa Wallfd668622018-05-10 10:21:13 -0700469 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800470 case ui::Dataspace::BT601_525:
471 dataSpace = ui::Dataspace::V0_BT601_525;
Marissa Wallfd668622018-05-10 10:21:13 -0700472 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800473 case ui::Dataspace::BT709:
474 dataSpace = ui::Dataspace::V0_BT709;
Marissa Wallfd668622018-05-10 10:21:13 -0700475 break;
476 default:
477 break;
478 }
479 mCurrentDataSpace = dataSpace;
480
481 Rect crop(getDrawingCrop());
482 const uint32_t transform(getDrawingTransform());
483 const uint32_t scalingMode(getDrawingScalingMode());
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800484 const bool transformToDisplayInverse(getTransformToDisplayInverse());
Marissa Wallfd668622018-05-10 10:21:13 -0700485 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800486 (scalingMode != mCurrentScalingMode) ||
487 (transformToDisplayInverse != mTransformToDisplayInverse)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700488 mCurrentCrop = crop;
489 mCurrentTransform = transform;
490 mCurrentScalingMode = scalingMode;
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800491 mTransformToDisplayInverse = transformToDisplayInverse;
Marissa Wallfd668622018-05-10 10:21:13 -0700492 recomputeVisibleRegions = true;
493 }
494
495 if (oldBuffer != nullptr) {
496 uint32_t bufWidth = mActiveBuffer->getWidth();
497 uint32_t bufHeight = mActiveBuffer->getHeight();
498 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
499 recomputeVisibleRegions = true;
500 }
501 }
502
503 if (oldOpacity != isOpaque(s)) {
504 recomputeVisibleRegions = true;
505 }
506
507 // Remove any sync points corresponding to the buffer which was just
508 // latched
509 {
510 Mutex::Autolock lock(mLocalSyncPointMutex);
511 auto point = mLocalSyncPoints.begin();
512 while (point != mLocalSyncPoints.end()) {
513 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
514 // This sync point must have been added since we started
515 // latching. Don't drop it yet.
516 ++point;
517 continue;
518 }
519
520 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
521 point = mLocalSyncPoints.erase(point);
522 } else {
523 ++point;
524 }
525 }
526 }
527
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800528 return true;
Marissa Wallfd668622018-05-10 10:21:13 -0700529}
530
531// transaction
532void BufferLayer::notifyAvailableFrames() {
533 auto headFrameNumber = getHeadFrameNumber();
534 bool headFenceSignaled = fenceHasSignaled();
535 Mutex::Autolock lock(mLocalSyncPointMutex);
536 for (auto& point : mLocalSyncPoints) {
537 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
538 point->setFrameAvailable();
539 }
David Sodman0c69cad2017-08-21 12:12:51 -0700540 }
541}
542
Marissa Wallfd668622018-05-10 10:21:13 -0700543bool BufferLayer::hasReadyFrame() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700544 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
Marissa Wallfd668622018-05-10 10:21:13 -0700545}
546
547uint32_t BufferLayer::getEffectiveScalingMode() const {
548 if (mOverrideScalingMode >= 0) {
549 return mOverrideScalingMode;
550 }
551
552 return mCurrentScalingMode;
553}
554
555bool BufferLayer::isProtected() const {
556 const sp<GraphicBuffer>& buffer(mActiveBuffer);
557 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
558}
559
560bool BufferLayer::latchUnsignaledBuffers() {
561 static bool propertyLoaded = false;
562 static bool latch = false;
563 static std::mutex mutex;
564 std::lock_guard<std::mutex> lock(mutex);
565 if (!propertyLoaded) {
566 char value[PROPERTY_VALUE_MAX] = {};
567 property_get("debug.sf.latch_unsignaled", value, "0");
568 latch = atoi(value);
569 propertyLoaded = true;
570 }
571 return latch;
572}
573
574// h/w composer set-up
575bool BufferLayer::allTransactionsSignaled() {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800576 auto headFrameNumber = getHeadFrameNumber();
Marissa Wallfd668622018-05-10 10:21:13 -0700577 bool matchingFramesFound = false;
578 bool allTransactionsApplied = true;
579 Mutex::Autolock lock(mLocalSyncPointMutex);
580
581 for (auto& point : mLocalSyncPoints) {
582 if (point->getFrameNumber() > headFrameNumber) {
583 break;
584 }
585 matchingFramesFound = true;
586
587 if (!point->frameIsAvailable()) {
588 // We haven't notified the remote layer that the frame for
589 // this point is available yet. Notify it now, and then
590 // abort this attempt to latch.
591 point->setFrameAvailable();
592 allTransactionsApplied = false;
593 break;
594 }
595
596 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
597 }
598 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700599}
600
601// As documented in libhardware header, formats in the range
602// 0x100 - 0x1FF are specific to the HAL implementation, and
603// are known to have no alpha channel
604// TODO: move definition for device-specific range into
605// hardware.h, instead of using hard-coded values here.
606#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
607
608bool BufferLayer::getOpacityForFormat(uint32_t format) {
609 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
610 return true;
611 }
612 switch (format) {
613 case HAL_PIXEL_FORMAT_RGBA_8888:
614 case HAL_PIXEL_FORMAT_BGRA_8888:
615 case HAL_PIXEL_FORMAT_RGBA_FP16:
616 case HAL_PIXEL_FORMAT_RGBA_1010102:
617 return false;
618 }
619 // in all other case, we have no blending (also for unknown formats)
620 return true;
621}
622
Lloyd Pique37c2c9b2018-12-04 17:25:10 -0800623bool BufferLayer::needsFiltering(const sp<const DisplayDevice>& displayDevice) const {
624 // If we are not capturing based on the state of a known display device, we
625 // only return mNeedsFiltering
626 if (displayDevice == nullptr) {
627 return mNeedsFiltering;
628 }
629
630 const auto outputLayer = findOutputLayerForDisplay(displayDevice);
631 if (outputLayer == nullptr) {
632 return mNeedsFiltering;
633 }
634
635 const auto& compositionState = outputLayer->getState();
636 const auto displayFrame = compositionState.displayFrame;
637 const auto sourceCrop = compositionState.sourceCrop;
Peiyong Linc2020ca2019-01-10 11:36:12 -0800638 return mNeedsFiltering || sourceCrop.getHeight() != displayFrame.getHeight() ||
639 sourceCrop.getWidth() != displayFrame.getWidth();
Chia-I Wu692e0832018-06-05 15:46:58 -0700640}
641
David Sodman0c69cad2017-08-21 12:12:51 -0700642uint64_t BufferLayer::getHeadFrameNumber() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800643 if (hasFrameUpdate()) {
Marissa Wallfd668622018-05-10 10:21:13 -0700644 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700645 } else {
646 return mCurrentFrameNumber;
647 }
648}
649
Vishnu Nair60356342018-11-13 13:00:45 -0800650Rect BufferLayer::getBufferSize(const State& s) const {
651 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
652 // we cannot determine the buffer size.
653 if ((s.sidebandStream != nullptr) ||
654 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
655 return Rect(getActiveWidth(s), getActiveHeight(s));
656 }
657
658 if (mActiveBuffer == nullptr) {
659 return Rect::INVALID_RECT;
660 }
661
662 uint32_t bufWidth = mActiveBuffer->getWidth();
663 uint32_t bufHeight = mActiveBuffer->getHeight();
664
665 // Undo any transformations on the buffer and return the result.
666 if (mCurrentTransform & ui::Transform::ROT_90) {
667 std::swap(bufWidth, bufHeight);
668 }
669
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800670 if (getTransformToDisplayInverse()) {
Vishnu Nair60356342018-11-13 13:00:45 -0800671 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
672 if (invTransform & ui::Transform::ROT_90) {
673 std::swap(bufWidth, bufHeight);
674 }
675 }
676
677 return Rect(bufWidth, bufHeight);
678}
679
Lloyd Piquefeb73d72018-12-04 17:23:44 -0800680std::shared_ptr<compositionengine::Layer> BufferLayer::getCompositionLayer() const {
681 return mCompositionLayer;
682}
683
Vishnu Nair4351ad52019-02-11 14:13:02 -0800684FloatRect BufferLayer::computeSourceBounds(const FloatRect& parentBounds) const {
685 const State& s(getDrawingState());
686
687 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
688 // we cannot determine the buffer size.
689 if ((s.sidebandStream != nullptr) ||
690 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
691 return FloatRect(0, 0, getActiveWidth(s), getActiveHeight(s));
692 }
693
694 if (mActiveBuffer == nullptr) {
695 return parentBounds;
696 }
697
698 uint32_t bufWidth = mActiveBuffer->getWidth();
699 uint32_t bufHeight = mActiveBuffer->getHeight();
700
701 // Undo any transformations on the buffer and return the result.
702 if (mCurrentTransform & ui::Transform::ROT_90) {
703 std::swap(bufWidth, bufHeight);
704 }
705
706 if (getTransformToDisplayInverse()) {
707 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
708 if (invTransform & ui::Transform::ROT_90) {
709 std::swap(bufWidth, bufHeight);
710 }
711 }
712
713 return FloatRect(0, 0, bufWidth, bufHeight);
714}
715
David Sodman0c69cad2017-08-21 12:12:51 -0700716} // namespace android
717
718#if defined(__gl_h_)
719#error "don't include gl/gl.h in this file"
720#endif
721
722#if defined(__gl2_h_)
723#error "don't include gl2/gl2.h in this file"
724#endif