blob: 65308a619d7ff7e5bade22a6164cd4cc34812c2f [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
Alec Mouri86770e52018-09-24 22:40:58 +0000368Region 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
Marissa Wallfd668622018-05-10 10:21:13 -0700372 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700373
Marissa Wallfd668622018-05-10 10:21:13 -0700374 if (sidebandStreamDirtyRegion) {
375 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700376 }
377
Marissa Wallfd668622018-05-10 10:21:13 -0700378 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700379
Marissa Wallfd668622018-05-10 10:21:13 -0700380 if (!hasReadyFrame()) {
381 return dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700382 }
David Sodman0c69cad2017-08-21 12:12:51 -0700383
Marissa Wallfd668622018-05-10 10:21:13 -0700384 // if we've already called updateTexImage() without going through
385 // a composition step, we have to skip this layer at this point
386 // because we cannot call updateTeximage() without a corresponding
387 // compositionComplete() call.
388 // we'll trigger an update in onPreComposition().
389 if (mRefreshPending) {
390 return dirtyRegion;
391 }
392
393 // If the head buffer's acquire fence hasn't signaled yet, return and
394 // try again later
395 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700396 mFlinger->signalLayerUpdate();
Marissa Wallfd668622018-05-10 10:21:13 -0700397 return dirtyRegion;
398 }
399
400 // Capture the old state of the layer for comparisons later
401 const State& s(getDrawingState());
402 const bool oldOpacity = isOpaque(s);
403 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
404
405 if (!allTransactionsSignaled()) {
406 mFlinger->signalLayerUpdate();
407 return dirtyRegion;
408 }
409
Alec Mouri86770e52018-09-24 22:40:58 +0000410 status_t err = updateTexImage(recomputeVisibleRegions, latchTime, releaseFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700411 if (err != NO_ERROR) {
412 return dirtyRegion;
413 }
414
415 err = updateActiveBuffer();
416 if (err != NO_ERROR) {
417 return dirtyRegion;
418 }
419
420 mBufferLatched = true;
421
422 err = updateFrameNumber(latchTime);
423 if (err != NO_ERROR) {
424 return dirtyRegion;
425 }
426
427 mRefreshPending = true;
428 mFrameLatencyNeeded = true;
429 if (oldBuffer == nullptr) {
430 // the first time we receive a buffer, we need to trigger a
431 // geometry invalidation.
432 recomputeVisibleRegions = true;
433 }
434
435 ui::Dataspace dataSpace = getDrawingDataSpace();
Peiyong Lin14724e62018-12-05 07:27:30 -0800436 // translate legacy dataspaces to modern dataspaces
Marissa Wallfd668622018-05-10 10:21:13 -0700437 switch (dataSpace) {
Peiyong Lin14724e62018-12-05 07:27:30 -0800438 case ui::Dataspace::SRGB:
439 dataSpace = ui::Dataspace::V0_SRGB;
Marissa Wallfd668622018-05-10 10:21:13 -0700440 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800441 case ui::Dataspace::SRGB_LINEAR:
442 dataSpace = ui::Dataspace::V0_SRGB_LINEAR;
Marissa Wallfd668622018-05-10 10:21:13 -0700443 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800444 case ui::Dataspace::JFIF:
445 dataSpace = ui::Dataspace::V0_JFIF;
Marissa Wallfd668622018-05-10 10:21:13 -0700446 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800447 case ui::Dataspace::BT601_625:
448 dataSpace = ui::Dataspace::V0_BT601_625;
Marissa Wallfd668622018-05-10 10:21:13 -0700449 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800450 case ui::Dataspace::BT601_525:
451 dataSpace = ui::Dataspace::V0_BT601_525;
Marissa Wallfd668622018-05-10 10:21:13 -0700452 break;
Peiyong Lin14724e62018-12-05 07:27:30 -0800453 case ui::Dataspace::BT709:
454 dataSpace = ui::Dataspace::V0_BT709;
Marissa Wallfd668622018-05-10 10:21:13 -0700455 break;
456 default:
457 break;
458 }
459 mCurrentDataSpace = dataSpace;
460
461 Rect crop(getDrawingCrop());
462 const uint32_t transform(getDrawingTransform());
463 const uint32_t scalingMode(getDrawingScalingMode());
464 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
465 (scalingMode != mCurrentScalingMode)) {
466 mCurrentCrop = crop;
467 mCurrentTransform = transform;
468 mCurrentScalingMode = scalingMode;
469 recomputeVisibleRegions = true;
470 }
471
472 if (oldBuffer != nullptr) {
473 uint32_t bufWidth = mActiveBuffer->getWidth();
474 uint32_t bufHeight = mActiveBuffer->getHeight();
475 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
476 recomputeVisibleRegions = true;
477 }
478 }
479
480 if (oldOpacity != isOpaque(s)) {
481 recomputeVisibleRegions = true;
482 }
483
484 // Remove any sync points corresponding to the buffer which was just
485 // latched
486 {
487 Mutex::Autolock lock(mLocalSyncPointMutex);
488 auto point = mLocalSyncPoints.begin();
489 while (point != mLocalSyncPoints.end()) {
490 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
491 // This sync point must have been added since we started
492 // latching. Don't drop it yet.
493 ++point;
494 continue;
495 }
496
497 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
498 point = mLocalSyncPoints.erase(point);
499 } else {
500 ++point;
501 }
502 }
503 }
504
505 // FIXME: postedRegion should be dirty & bounds
506 // transform the dirty region to window-manager space
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800507 return getTransform().transform(Region(getBufferSize(s)));
Marissa Wallfd668622018-05-10 10:21:13 -0700508}
509
510// transaction
511void BufferLayer::notifyAvailableFrames() {
512 auto headFrameNumber = getHeadFrameNumber();
513 bool headFenceSignaled = fenceHasSignaled();
514 Mutex::Autolock lock(mLocalSyncPointMutex);
515 for (auto& point : mLocalSyncPoints) {
516 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
517 point->setFrameAvailable();
518 }
David Sodman0c69cad2017-08-21 12:12:51 -0700519 }
520}
521
Marissa Wallfd668622018-05-10 10:21:13 -0700522bool BufferLayer::hasReadyFrame() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700523 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
Marissa Wallfd668622018-05-10 10:21:13 -0700524}
525
526uint32_t BufferLayer::getEffectiveScalingMode() const {
527 if (mOverrideScalingMode >= 0) {
528 return mOverrideScalingMode;
529 }
530
531 return mCurrentScalingMode;
532}
533
534bool BufferLayer::isProtected() const {
535 const sp<GraphicBuffer>& buffer(mActiveBuffer);
536 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
537}
538
539bool BufferLayer::latchUnsignaledBuffers() {
540 static bool propertyLoaded = false;
541 static bool latch = false;
542 static std::mutex mutex;
543 std::lock_guard<std::mutex> lock(mutex);
544 if (!propertyLoaded) {
545 char value[PROPERTY_VALUE_MAX] = {};
546 property_get("debug.sf.latch_unsignaled", value, "0");
547 latch = atoi(value);
548 propertyLoaded = true;
549 }
550 return latch;
551}
552
553// h/w composer set-up
554bool BufferLayer::allTransactionsSignaled() {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800555 auto headFrameNumber = getHeadFrameNumber();
Marissa Wallfd668622018-05-10 10:21:13 -0700556 bool matchingFramesFound = false;
557 bool allTransactionsApplied = true;
558 Mutex::Autolock lock(mLocalSyncPointMutex);
559
560 for (auto& point : mLocalSyncPoints) {
561 if (point->getFrameNumber() > headFrameNumber) {
562 break;
563 }
564 matchingFramesFound = true;
565
566 if (!point->frameIsAvailable()) {
567 // We haven't notified the remote layer that the frame for
568 // this point is available yet. Notify it now, and then
569 // abort this attempt to latch.
570 point->setFrameAvailable();
571 allTransactionsApplied = false;
572 break;
573 }
574
575 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
576 }
577 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700578}
579
580// As documented in libhardware header, formats in the range
581// 0x100 - 0x1FF are specific to the HAL implementation, and
582// are known to have no alpha channel
583// TODO: move definition for device-specific range into
584// hardware.h, instead of using hard-coded values here.
585#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
586
587bool BufferLayer::getOpacityForFormat(uint32_t format) {
588 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
589 return true;
590 }
591 switch (format) {
592 case HAL_PIXEL_FORMAT_RGBA_8888:
593 case HAL_PIXEL_FORMAT_BGRA_8888:
594 case HAL_PIXEL_FORMAT_RGBA_FP16:
595 case HAL_PIXEL_FORMAT_RGBA_1010102:
596 return false;
597 }
598 // in all other case, we have no blending (also for unknown formats)
599 return true;
600}
601
Peiyong Linc2020ca2019-01-10 11:36:12 -0800602bool BufferLayer::needsFiltering() const {
603 const auto displayFrame = getBE().compositionInfo.hwc.displayFrame;
604 const auto sourceCrop = getBE().compositionInfo.hwc.sourceCrop;
605 return mNeedsFiltering || sourceCrop.getHeight() != displayFrame.getHeight() ||
606 sourceCrop.getWidth() != displayFrame.getWidth();
Chia-I Wu692e0832018-06-05 15:46:58 -0700607}
608
Alec Mouri79108df2019-02-04 19:33:44 +0000609void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
610 ATRACE_CALL();
611 const State& s(getDrawingState());
612
613 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
614
615 /*
616 * NOTE: the way we compute the texture coordinates here produces
617 * different results than when we take the HWC path -- in the later case
618 * the "source crop" is rounded to texel boundaries.
619 * This can produce significantly different results when the texture
620 * is scaled by a large amount.
621 *
622 * The GL code below is more logical (imho), and the difference with
623 * HWC is due to a limitation of the HWC API to integers -- a question
624 * is suspend is whether we should ignore this problem or revert to
625 * GL composition when a buffer scaling is applied (maybe with some
626 * minimal value)? Or, we could make GL behave like HWC -- but this feel
627 * like more of a hack.
628 */
629 const Rect bounds{computeBounds()}; // Rounds from FloatRect
630
631 Rect win = bounds;
632 const int bufferWidth = getBufferSize(s).getWidth();
633 const int bufferHeight = getBufferSize(s).getHeight();
634
635 const float left = float(win.left) / float(bufferWidth);
636 const float top = float(win.top) / float(bufferHeight);
637 const float right = float(win.right) / float(bufferWidth);
638 const float bottom = float(win.bottom) / float(bufferHeight);
639
640 // TODO: we probably want to generate the texture coords with the mesh
641 // here we assume that we only have 4 vertices
642 renderengine::Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
643 // flip texcoords vertically because BufferLayerConsumer expects them to be in GL convention
644 texCoords[0] = vec2(left, 1.0f - top);
645 texCoords[1] = vec2(left, 1.0f - bottom);
646 texCoords[2] = vec2(right, 1.0f - bottom);
647 texCoords[3] = vec2(right, 1.0f - top);
648
649 const auto roundedCornerState = getRoundedCornerState();
650 const auto cropRect = roundedCornerState.cropRect;
651 setupRoundedCornersCropCoordinates(win, cropRect);
652
653 auto& engine(mFlinger->getRenderEngine());
654 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
655 getColor(), roundedCornerState.radius);
656 engine.setSourceDataSpace(mCurrentDataSpace);
657
658 if (isHdrY410()) {
659 engine.setSourceY410BT2020(true);
660 }
661
662 engine.setupCornerRadiusCropSize(cropRect.getWidth(), cropRect.getHeight());
663
664 engine.drawMesh(getBE().mMesh);
665 engine.disableBlending();
666
667 engine.setSourceY410BT2020(false);
668}
669
David Sodman0c69cad2017-08-21 12:12:51 -0700670uint64_t BufferLayer::getHeadFrameNumber() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800671 if (hasFrameUpdate()) {
Marissa Wallfd668622018-05-10 10:21:13 -0700672 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700673 } else {
674 return mCurrentFrameNumber;
675 }
676}
677
Vishnu Nair60356342018-11-13 13:00:45 -0800678Rect BufferLayer::getBufferSize(const State& s) const {
679 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
680 // we cannot determine the buffer size.
681 if ((s.sidebandStream != nullptr) ||
682 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
683 return Rect(getActiveWidth(s), getActiveHeight(s));
684 }
685
686 if (mActiveBuffer == nullptr) {
687 return Rect::INVALID_RECT;
688 }
689
690 uint32_t bufWidth = mActiveBuffer->getWidth();
691 uint32_t bufHeight = mActiveBuffer->getHeight();
692
693 // Undo any transformations on the buffer and return the result.
694 if (mCurrentTransform & ui::Transform::ROT_90) {
695 std::swap(bufWidth, bufHeight);
696 }
697
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800698 if (getTransformToDisplayInverse()) {
Vishnu Nair60356342018-11-13 13:00:45 -0800699 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
700 if (invTransform & ui::Transform::ROT_90) {
701 std::swap(bufWidth, bufHeight);
702 }
703 }
704
705 return Rect(bufWidth, bufHeight);
706}
707
Lloyd Piquefeb73d72018-12-04 17:23:44 -0800708std::shared_ptr<compositionengine::Layer> BufferLayer::getCompositionLayer() const {
709 return mCompositionLayer;
710}
711
David Sodman0c69cad2017-08-21 12:12:51 -0700712} // namespace android
713
714#if defined(__gl_h_)
715#error "don't include gl/gl.h in this file"
716#endif
717
718#if defined(__gl2_h_)
719#error "don't include gl2/gl2.h in this file"
720#endif