blob: 168dd79a0194717694286970831fc4019c6c547f [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>
27#include <compositionengine/Layer.h>
28#include <compositionengine/LayerCreationArgs.h>
29#include <cutils/compiler.h>
30#include <cutils/native_handle.h>
31#include <cutils/properties.h>
32#include <gui/BufferItem.h>
33#include <gui/BufferQueue.h>
34#include <gui/LayerDebugInfo.h>
35#include <gui/Surface.h>
36#include <renderengine/RenderEngine.h>
37#include <ui/DebugUtils.h>
38#include <utils/Errors.h>
39#include <utils/Log.h>
40#include <utils/NativeHandle.h>
41#include <utils/StopWatch.h>
42#include <utils/Trace.h>
43
David Sodman0c69cad2017-08-21 12:12:51 -070044#include "BufferLayer.h"
45#include "Colorizer.h"
46#include "DisplayDevice.h"
47#include "LayerRejecter.h"
David Sodman0c69cad2017-08-21 12:12:51 -070048
Yiwei Zhang7e666a52018-11-15 13:33:42 -080049#include "TimeStats/TimeStats.h"
50
David Sodman0c69cad2017-08-21 12:12:51 -070051namespace android {
52
Lloyd Pique42ab75e2018-09-12 20:46:03 -070053BufferLayer::BufferLayer(const LayerCreationArgs& args)
Lloyd Piquefeb73d72018-12-04 17:23:44 -080054 : Layer(args),
55 mTextureName(args.flinger->getNewTexture()),
56 mCompositionLayer{mFlinger->getCompositionEngine().createLayer(
57 compositionengine::LayerCreationArgs{this})} {
Lloyd Pique42ab75e2018-09-12 20:46:03 -070058 ALOGV("Creating Layer %s", args.name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070059
Alec Mouri79108df2019-02-04 19:33:44 +000060 mTexture.init(renderengine::Texture::TEXTURE_EXTERNAL, mTextureName);
61
Lloyd Pique42ab75e2018-09-12 20:46:03 -070062 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070063
Lloyd Pique42ab75e2018-09-12 20:46:03 -070064 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
65 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070066}
67
68BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070069 mFlinger->deleteTextureAsync(mTextureName);
70
David Sodman6f65f3e2017-11-03 14:28:09 -070071 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070072 ALOGE("Found stale hardware composer layers when destroying "
73 "surface flinger layer %s",
74 mName.string());
chaviw61626f22018-11-15 16:26:27 -080075 destroyAllHwcLayersPlusChildren();
David Sodman0c69cad2017-08-21 12:12:51 -070076 }
Yiwei Zhangdc224042018-10-18 15:34:00 -070077
Yiwei Zhang7e666a52018-11-15 13:33:42 -080078 mFlinger->mTimeStats->onDestroy(getSequence());
David Sodman0c69cad2017-08-21 12:12:51 -070079}
80
David Sodmaneb085e02017-10-05 18:49:04 -070081void BufferLayer::useSurfaceDamage() {
82 if (mFlinger->mForceFullDamage) {
83 surfaceDamageRegion = Region::INVALID_REGION;
84 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070085 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070086 }
87}
88
89void BufferLayer::useEmptyDamage() {
90 surfaceDamageRegion.clear();
91}
92
Marissa Wallfd668622018-05-10 10:21:13 -070093bool BufferLayer::isOpaque(const Layer::State& s) const {
94 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
95 // layer's opaque flag.
96 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
97 return false;
98 }
99
100 // if the layer has the opaque flag, then we're always opaque,
101 // otherwise we use the current buffer's format.
102 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -0700103}
104
105bool BufferLayer::isVisible() const {
106 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800107 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700108}
109
110bool BufferLayer::isFixedSize() const {
111 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
112}
113
David Sodman0c69cad2017-08-21 12:12:51 -0700114static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800115 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
116 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
117 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 -0700118 mat4 tr;
119
120 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
121 tr = tr * rot90;
122 }
123 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
124 tr = tr * flipH;
125 }
126 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
127 tr = tr * flipV;
128 }
129 return inverse(tr);
130}
131
Alec Mouri79108df2019-02-04 19:33:44 +0000132/*
133 * onDraw will draw the current layer onto the presentable buffer
134 */
135void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
136 bool useIdentityTransform) {
David Sodman0c69cad2017-08-21 12:12:51 -0700137 ATRACE_CALL();
Alec Mouri79108df2019-02-04 19:33:44 +0000138
David Sodman0cf8f8d2017-12-20 18:19:45 -0800139 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700140 // the texture has not been created yet, this Layer has
141 // in fact never been drawn into. This happens frequently with
142 // SurfaceView because the WindowManager can't know when the client
143 // has drawn the first time.
144
145 // If there is nothing under us, we paint the screen in black, otherwise
146 // we just skip this update.
147
148 // figure out if there is something below us
149 Region under;
150 bool finished = false;
151 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
152 if (finished || layer == static_cast<BufferLayer const*>(this)) {
153 finished = true;
154 return;
155 }
Alec Mouri79108df2019-02-04 19:33:44 +0000156 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
David Sodman0c69cad2017-08-21 12:12:51 -0700157 });
158 // if not everything below us is covered, we plug the holes!
159 Region holes(clip.subtract(under));
160 if (!holes.isEmpty()) {
Alec Mouri79108df2019-02-04 19:33:44 +0000161 clearWithOpenGL(renderArea, 0, 0, 0, 1);
David Sodman0c69cad2017-08-21 12:12:51 -0700162 }
Alec Mouri79108df2019-02-04 19:33:44 +0000163 return;
David Sodman0c69cad2017-08-21 12:12:51 -0700164 }
Alec Mouri79108df2019-02-04 19:33:44 +0000165
166 // Bind the current buffer to the GL texture, and wait for it to be
167 // ready for us to draw into.
168 status_t err = bindTextureImage();
169 if (err != NO_ERROR) {
170 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
171 // Go ahead and draw the buffer anyway; no matter what we do the screen
172 // is probably going to have something visibly wrong.
173 }
174
David Sodman0c69cad2017-08-21 12:12:51 -0700175 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
Alec Mouri79108df2019-02-04 19:33:44 +0000176
177 auto& engine(mFlinger->getRenderEngine());
178
David Sodman0c69cad2017-08-21 12:12:51 -0700179 if (!blackOutLayer) {
180 // TODO: we could be more subtle with isFixedSize()
Peiyong Linc2020ca2019-01-10 11:36:12 -0800181 const bool useFiltering = needsFiltering() || renderArea.needsFiltering() || isFixedSize();
David Sodman0c69cad2017-08-21 12:12:51 -0700182
183 // Query the texture matrix given our current filtering mode.
184 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700185 setFilteringEnabled(useFiltering);
186 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700187
188 if (getTransformToDisplayInverse()) {
189 /*
190 * the code below applies the primary display's inverse transform to
191 * the texture transform
192 */
193 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
194 mat4 tr = inverseOrientation(transform);
195
196 /**
197 * TODO(b/36727915): This is basically a hack.
198 *
199 * Ensure that regardless of the parent transformation,
200 * this buffer is always transformed from native display
201 * orientation to display orientation. For example, in the case
202 * of a camera where the buffer remains in native orientation,
203 * we want the pixels to always be upright.
204 */
205 sp<Layer> p = mDrawingParent.promote();
206 if (p != nullptr) {
207 const auto parentTransform = p->getTransform();
208 tr = tr * inverseOrientation(parentTransform.getOrientation());
209 }
210
211 // and finally apply it to the original texture matrix
212 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
213 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
214 }
215
Alec Mouri79108df2019-02-04 19:33:44 +0000216 // Set things up for texturing.
217 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
218 mTexture.setFiltering(useFiltering);
219 mTexture.setMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700220
Alec Mouri79108df2019-02-04 19:33:44 +0000221 engine.setupLayerTexturing(mTexture);
David Sodman0c69cad2017-08-21 12:12:51 -0700222 } else {
Alec Mouri79108df2019-02-04 19:33:44 +0000223 engine.setupLayerBlackedOut();
David Sodman0c69cad2017-08-21 12:12:51 -0700224 }
Alec Mouri79108df2019-02-04 19:33:44 +0000225 drawWithOpenGL(renderArea, useIdentityTransform);
226 engine.disableTexturing();
David Sodman0c69cad2017-08-21 12:12:51 -0700227}
228
Marissa Wallfd668622018-05-10 10:21:13 -0700229bool BufferLayer::isHdrY410() const {
230 // pixel format is HDR Y410 masquerading as RGBA_1010102
231 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
232 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
233 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700234}
235
Dominik Laskowski075d3172018-05-24 15:50:06 -0700236void BufferLayer::setPerFrameData(DisplayId displayId, const ui::Transform& transform,
237 const Rect& viewport, int32_t supportedPerFrameMetadata) {
Dominik Laskowski34157762018-10-31 13:07:19 -0700238 RETURN_IF_NO_HWC_LAYER(displayId);
239
David Sodman0c69cad2017-08-21 12:12:51 -0700240 // Apply this display's projection's viewport to the visible region
241 // before giving it to the HWC HAL.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700242 Region visible = transform.transform(visibleRegion.intersect(viewport));
243
David Sodman15094112018-10-11 09:39:37 -0700244 auto& hwcInfo = getBE().mHwcLayers[displayId];
245 auto& hwcLayer = hwcInfo.layer;
246 auto error = hwcLayer->setVisibleRegion(visible);
247 if (error != HWC2::Error::None) {
248 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
249 to_string(error).c_str(), static_cast<int32_t>(error));
250 visible.dump(LOG_TAG);
251 }
David Sodmanba340492018-08-05 21:51:33 -0700252 getBE().compositionInfo.hwc.visibleRegion = visible;
David Sodman15094112018-10-11 09:39:37 -0700253
254 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
255 if (error != HWC2::Error::None) {
256 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
257 to_string(error).c_str(), static_cast<int32_t>(error));
258 surfaceDamageRegion.dump(LOG_TAG);
259 }
David Sodmanba340492018-08-05 21:51:33 -0700260 getBE().compositionInfo.hwc.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700261
262 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800263 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700264 setCompositionType(displayId, HWC2::Composition::Sideband);
David Sodman15094112018-10-11 09:39:37 -0700265 ALOGV("[%s] Requesting Sideband composition", mName.string());
266 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
267 if (error != HWC2::Error::None) {
268 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
269 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
270 static_cast<int32_t>(error));
271 }
David Sodmanba340492018-08-05 21:51:33 -0700272 getBE().compositionInfo.compositionType = HWC2::Composition::Sideband;
David Sodman0c69cad2017-08-21 12:12:51 -0700273 return;
274 }
275
David Sodman15094112018-10-11 09:39:37 -0700276 // Device or Cursor layers
277 if (mPotentialCursor) {
278 ALOGV("[%s] Requesting Cursor composition", mName.string());
279 setCompositionType(displayId, HWC2::Composition::Cursor);
280 } else {
281 ALOGV("[%s] Requesting Device composition", mName.string());
282 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700283 }
284
David Sodman15094112018-10-11 09:39:37 -0700285 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
286 error = hwcLayer->setDataspace(mCurrentDataSpace);
287 if (error != HWC2::Error::None) {
288 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
289 to_string(error).c_str(), static_cast<int32_t>(error));
290 }
291
292 const HdrMetadata& metadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700293 error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
David Sodman15094112018-10-11 09:39:37 -0700294 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
295 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
296 to_string(error).c_str(), static_cast<int32_t>(error));
297 }
298
299 error = hwcLayer->setColorTransform(getColorTransform());
300 if (error != HWC2::Error::None) {
301 ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
302 to_string(error).c_str(), static_cast<int32_t>(error));
303 }
David Sodmanba340492018-08-05 21:51:33 -0700304 getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
305 getBE().compositionInfo.hwc.hdrMetadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700306 getBE().compositionInfo.hwc.supportedPerFrameMetadata = supportedPerFrameMetadata;
Peiyong Lind3788632018-09-18 16:01:31 -0700307 getBE().compositionInfo.hwc.colorTransform = getColorTransform();
Lloyd Pique074e8122018-07-26 12:57:23 -0700308
Dominik Laskowski075d3172018-05-24 15:50:06 -0700309 setHwcLayerBuffer(displayId);
David Sodman0c69cad2017-08-21 12:12:51 -0700310}
311
Marissa Wallfd668622018-05-10 10:21:13 -0700312bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
313 if (mBufferLatched) {
314 Mutex::Autolock lock(mFrameEventHistoryMutex);
315 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700316 }
Marissa Wallfd668622018-05-10 10:21:13 -0700317 mRefreshPending = false;
318 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700319}
320
Dominik Laskowski075d3172018-05-24 15:50:06 -0700321bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
322 const std::shared_ptr<FenceTime>& glDoneFence,
Marissa Wallfd668622018-05-10 10:21:13 -0700323 const std::shared_ptr<FenceTime>& presentFence,
324 const CompositorTiming& compositorTiming) {
325 // mFrameLatencyNeeded is true when a new frame was latched for the
326 // composition.
327 if (!mFrameLatencyNeeded) return false;
328
329 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700330 {
Marissa Wallfd668622018-05-10 10:21:13 -0700331 Mutex::Autolock lock(mFrameEventHistoryMutex);
332 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
333 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700334 }
335
Marissa Wallfd668622018-05-10 10:21:13 -0700336 // Update mFrameTracker.
337 nsecs_t desiredPresentTime = getDesiredPresentTime();
338 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
339
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700340 const int32_t layerID = getSequence();
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800341 mFlinger->mTimeStats->setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700342
343 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
344 if (frameReadyFence->isValid()) {
345 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
346 } else {
347 // There was no fence for this frame, so assume that it was ready
348 // to be presented at the desired present time.
349 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700350 }
Marissa Wallfd668622018-05-10 10:21:13 -0700351
352 if (presentFence->isValid()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800353 mFlinger->mTimeStats->setPresentFence(layerID, mCurrentFrameNumber, presentFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700354 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski075d3172018-05-24 15:50:06 -0700355 } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700356 // The HWC doesn't support present fences, so use the refresh
357 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700358 const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800359 mFlinger->mTimeStats->setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700360 mFrameTracker.setActualPresentTime(actualPresentTime);
361 }
362
363 mFrameTracker.advanceFrame();
364 mFrameLatencyNeeded = false;
365 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700366}
367
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800368bool BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,
369 const sp<Fence>& releaseFence) {
Marissa Wallfd668622018-05-10 10:21:13 -0700370 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700371
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800372 bool refreshRequired = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700373
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800374 if (refreshRequired) {
375 return refreshRequired;
David Sodman0c69cad2017-08-21 12:12:51 -0700376 }
377
Marissa Wallfd668622018-05-10 10:21:13 -0700378 if (!hasReadyFrame()) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800379 return false;
David Sodman0c69cad2017-08-21 12:12:51 -0700380 }
David Sodman0c69cad2017-08-21 12:12:51 -0700381
Marissa Wallfd668622018-05-10 10:21:13 -0700382 // if we've already called updateTexImage() without going through
383 // a composition step, we have to skip this layer at this point
384 // because we cannot call updateTeximage() without a corresponding
385 // compositionComplete() call.
386 // we'll trigger an update in onPreComposition().
387 if (mRefreshPending) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800388 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700389 }
390
391 // If the head buffer's acquire fence hasn't signaled yet, return and
392 // try again later
393 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700394 mFlinger->signalLayerUpdate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800395 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700396 }
397
398 // Capture the old state of the layer for comparisons later
399 const State& s(getDrawingState());
400 const bool oldOpacity = isOpaque(s);
401 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
402
403 if (!allTransactionsSignaled()) {
404 mFlinger->signalLayerUpdate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800405 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700406 }
407
Alec Mouri86770e52018-09-24 22:40:58 +0000408 status_t err = updateTexImage(recomputeVisibleRegions, latchTime, releaseFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700409 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800410 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700411 }
412
413 err = updateActiveBuffer();
414 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800415 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700416 }
417
418 mBufferLatched = true;
419
420 err = updateFrameNumber(latchTime);
421 if (err != NO_ERROR) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800422 return false;
Marissa Wallfd668622018-05-10 10:21:13 -0700423 }
424
425 mRefreshPending = true;
426 mFrameLatencyNeeded = true;
427 if (oldBuffer == nullptr) {
428 // the first time we receive a buffer, we need to trigger a
429 // geometry invalidation.
430 recomputeVisibleRegions = true;
431 }
432
433 ui::Dataspace dataSpace = getDrawingDataSpace();
Peiyong Lin14724e62018-12-05 07:27:30 -0800434 // translate legacy dataspaces to modern dataspaces
Marissa Wallfd668622018-05-10 10:21:13 -0700435 switch (dataSpace) {
Peiyong Lin14724e62018-12-05 07:27:30 -0800436 case ui::Dataspace::SRGB:
437 dataSpace = ui::Dataspace::V0_SRGB;
Marissa Wallfd668622018-05-10 10:21:13 -0700438 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800439 case ui::Dataspace::SRGB_LINEAR:
440 dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
Marissa Wallfd668622018-05-10 10:21:13 -0700441 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800442 case ui::Dataspace::JFIF:
443 dataSpace = ui::Dataspace::V0_JFIF;
Marissa Wallfd668622018-05-10 10:21:13 -0700444 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800445 case ui::Dataspace::BT601_625:
446 dataSpace = ui::Dataspace::V0_BT601_625;
Marissa Wallfd668622018-05-10 10:21:13 -0700447 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800448 case ui::Dataspace::BT601_525:
449 dataSpace = ui::Dataspace::V0_BT601_525;
Marissa Wallfd668622018-05-10 10:21:13 -0700450 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800451 case ui::Dataspace::BT709:
452 dataSpace = ui::Dataspace::V0_BT709;
Marissa Wallfd668622018-05-10 10:21:13 -0700453 break;
454 default:
455 break;
456 }
457 mCurrentDataSpace = dataSpace;
458
459 Rect crop(getDrawingCrop());
460 const uint32_t transform(getDrawingTransform());
461 const uint32_t scalingMode(getDrawingScalingMode());
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800462 const bool transformToDisplayInverse(getTransformToDisplayInverse());
Marissa Wallfd668622018-05-10 10:21:13 -0700463 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800464 (scalingMode != mCurrentScalingMode) ||
465 (transformToDisplayInverse != mTransformToDisplayInverse)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700466 mCurrentCrop = crop;
467 mCurrentTransform = transform;
468 mCurrentScalingMode = scalingMode;
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800469 mTransformToDisplayInverse = transformToDisplayInverse;
Marissa Wallfd668622018-05-10 10:21:13 -0700470 recomputeVisibleRegions = true;
471 }
472
473 if (oldBuffer != nullptr) {
474 uint32_t bufWidth = mActiveBuffer->getWidth();
475 uint32_t bufHeight = mActiveBuffer->getHeight();
476 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
477 recomputeVisibleRegions = true;
478 }
479 }
480
481 if (oldOpacity != isOpaque(s)) {
482 recomputeVisibleRegions = true;
483 }
484
485 // Remove any sync points corresponding to the buffer which was just
486 // latched
487 {
488 Mutex::Autolock lock(mLocalSyncPointMutex);
489 auto point = mLocalSyncPoints.begin();
490 while (point != mLocalSyncPoints.end()) {
491 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
492 // This sync point must have been added since we started
493 // latching. Don't drop it yet.
494 ++point;
495 continue;
496 }
497
498 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
499 point = mLocalSyncPoints.erase(point);
500 } else {
501 ++point;
502 }
503 }
504 }
505
Vishnu Nair6194e2e2019-02-06 12:58:39 -0800506 return true;
Marissa Wallfd668622018-05-10 10:21:13 -0700507}
508
509// transaction
510void BufferLayer::notifyAvailableFrames() {
511 auto headFrameNumber = getHeadFrameNumber();
512 bool headFenceSignaled = fenceHasSignaled();
513 Mutex::Autolock lock(mLocalSyncPointMutex);
514 for (auto& point : mLocalSyncPoints) {
515 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
516 point->setFrameAvailable();
517 }
David Sodman0c69cad2017-08-21 12:12:51 -0700518 }
519}
520
Marissa Wallfd668622018-05-10 10:21:13 -0700521bool BufferLayer::hasReadyFrame() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700522 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
Marissa Wallfd668622018-05-10 10:21:13 -0700523}
524
525uint32_t BufferLayer::getEffectiveScalingMode() const {
526 if (mOverrideScalingMode >= 0) {
527 return mOverrideScalingMode;
528 }
529
530 return mCurrentScalingMode;
531}
532
533bool BufferLayer::isProtected() const {
534 const sp<GraphicBuffer>& buffer(mActiveBuffer);
535 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
536}
537
538bool BufferLayer::latchUnsignaledBuffers() {
539 static bool propertyLoaded = false;
540 static bool latch = false;
541 static std::mutex mutex;
542 std::lock_guard<std::mutex> lock(mutex);
543 if (!propertyLoaded) {
544 char value[PROPERTY_VALUE_MAX] = {};
545 property_get("debug.sf.latch_unsignaled", value, "0");
546 latch = atoi(value);
547 propertyLoaded = true;
548 }
549 return latch;
550}
551
552// h/w composer set-up
553bool BufferLayer::allTransactionsSignaled() {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800554 auto headFrameNumber = getHeadFrameNumber();
Marissa Wallfd668622018-05-10 10:21:13 -0700555 bool matchingFramesFound = false;
556 bool allTransactionsApplied = true;
557 Mutex::Autolock lock(mLocalSyncPointMutex);
558
559 for (auto& point : mLocalSyncPoints) {
560 if (point->getFrameNumber() > headFrameNumber) {
561 break;
562 }
563 matchingFramesFound = true;
564
565 if (!point->frameIsAvailable()) {
566 // We haven't notified the remote layer that the frame for
567 // this point is available yet. Notify it now, and then
568 // abort this attempt to latch.
569 point->setFrameAvailable();
570 allTransactionsApplied = false;
571 break;
572 }
573
574 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
575 }
576 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700577}
578
579// As documented in libhardware header, formats in the range
580// 0x100 - 0x1FF are specific to the HAL implementation, and
581// are known to have no alpha channel
582// TODO: move definition for device-specific range into
583// hardware.h, instead of using hard-coded values here.
584#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
585
586bool BufferLayer::getOpacityForFormat(uint32_t format) {
587 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
588 return true;
589 }
590 switch (format) {
591 case HAL_PIXEL_FORMAT_RGBA_8888:
592 case HAL_PIXEL_FORMAT_BGRA_8888:
593 case HAL_PIXEL_FORMAT_RGBA_FP16:
594 case HAL_PIXEL_FORMAT_RGBA_1010102:
595 return false;
596 }
597 // in all other case, we have no blending (also for unknown formats)
598 return true;
599}
600
Peiyong Linc2020ca2019-01-10 11:36:12 -0800601bool BufferLayer::needsFiltering() const {
602 const auto displayFrame = getBE().compositionInfo.hwc.displayFrame;
603 const auto sourceCrop = getBE().compositionInfo.hwc.sourceCrop;
604 return mNeedsFiltering || sourceCrop.getHeight() != displayFrame.getHeight() ||
605 sourceCrop.getWidth() != displayFrame.getWidth();
Chia-I Wu692e0832018-06-05 15:46:58 -0700606}
607
Alec Mouri79108df2019-02-04 19:33:44 +0000608void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
609 ATRACE_CALL();
610 const State& s(getDrawingState());
611
612 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
613
614 /*
615 * NOTE: the way we compute the texture coordinates here produces
616 * different results than when we take the HWC path -- in the later case
617 * the "source crop" is rounded to texel boundaries.
618 * This can produce significantly different results when the texture
619 * is scaled by a large amount.
620 *
621 * The GL code below is more logical (imho), and the difference with
622 * HWC is due to a limitation of the HWC API to integers -- a question
623 * is suspend is whether we should ignore this problem or revert to
624 * GL composition when a buffer scaling is applied (maybe with some
625 * minimal value)? Or, we could make GL behave like HWC -- but this feel
626 * like more of a hack.
627 */
628 const Rect bounds{computeBounds()}; // Rounds from FloatRect
629
630 Rect win = bounds;
631 const int bufferWidth = getBufferSize(s).getWidth();
632 const int bufferHeight = getBufferSize(s).getHeight();
633
634 const float left = float(win.left) / float(bufferWidth);
635 const float top = float(win.top) / float(bufferHeight);
636 const float right = float(win.right) / float(bufferWidth);
637 const float bottom = float(win.bottom) / float(bufferHeight);
638
639 // TODO: we probably want to generate the texture coords with the mesh
640 // here we assume that we only have 4 vertices
641 renderengine::Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
642 // flip texcoords vertically because BufferLayerConsumer expects them to be in GL convention
643 texCoords[0] = vec2(left, 1.0f - top);
644 texCoords[1] = vec2(left, 1.0f - bottom);
645 texCoords[2] = vec2(right, 1.0f - bottom);
646 texCoords[3] = vec2(right, 1.0f - top);
647
648 const auto roundedCornerState = getRoundedCornerState();
649 const auto cropRect = roundedCornerState.cropRect;
650 setupRoundedCornersCropCoordinates(win, cropRect);
651
652 auto& engine(mFlinger->getRenderEngine());
653 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
654 getColor(), roundedCornerState.radius);
655 engine.setSourceDataSpace(mCurrentDataSpace);
656
657 if (isHdrY410()) {
658 engine.setSourceY410BT2020(true);
659 }
660
661 engine.setupCornerRadiusCropSize(cropRect.getWidth(), cropRect.getHeight());
662
663 engine.drawMesh(getBE().mMesh);
664 engine.disableBlending();
665
666 engine.setSourceY410BT2020(false);
667}
668
David Sodman0c69cad2017-08-21 12:12:51 -0700669uint64_t BufferLayer::getHeadFrameNumber() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800670 if (hasFrameUpdate()) {
Marissa Wallfd668622018-05-10 10:21:13 -0700671 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700672 } else {
673 return mCurrentFrameNumber;
674 }
675}
676
Vishnu Nair60356342018-11-13 13:00:45 -0800677Rect BufferLayer::getBufferSize(const State& s) const {
678 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
679 // we cannot determine the buffer size.
680 if ((s.sidebandStream != nullptr) ||
681 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
682 return Rect(getActiveWidth(s), getActiveHeight(s));
683 }
684
685 if (mActiveBuffer == nullptr) {
686 return Rect::INVALID_RECT;
687 }
688
689 uint32_t bufWidth = mActiveBuffer->getWidth();
690 uint32_t bufHeight = mActiveBuffer->getHeight();
691
692 // Undo any transformations on the buffer and return the result.
693 if (mCurrentTransform & ui::Transform::ROT_90) {
694 std::swap(bufWidth, bufHeight);
695 }
696
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800697 if (getTransformToDisplayInverse()) {
Vishnu Nair60356342018-11-13 13:00:45 -0800698 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
699 if (invTransform & ui::Transform::ROT_90) {
700 std::swap(bufWidth, bufHeight);
701 }
702 }
703
704 return Rect(bufWidth, bufHeight);
705}
706
Lloyd Piquefeb73d72018-12-04 17:23:44 -0800707std::shared_ptr<compositionengine::Layer> BufferLayer::getCompositionLayer() const {
708 return mCompositionLayer;
709}
710
David Sodman0c69cad2017-08-21 12:12:51 -0700711} // namespace android
712
713#if defined(__gl_h_)
714#error "don't include gl/gl.h in this file"
715#endif
716
717#if defined(__gl2_h_)
718#error "don't include gl2/gl2.h in this file"
719#endif