blob: 4e4d7dd371a1dd19736286ed72735c9b247eed68 [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
22#include "BufferLayer.h"
23#include "Colorizer.h"
24#include "DisplayDevice.h"
25#include "LayerRejecter.h"
David Sodman0c69cad2017-08-21 12:12:51 -070026
Yiwei Zhang7e666a52018-11-15 13:33:42 -080027#include "TimeStats/TimeStats.h"
28
Peiyong Lincbc184f2018-08-22 13:24:10 -070029#include <renderengine/RenderEngine.h>
David Sodman0c69cad2017-08-21 12:12:51 -070030
31#include <gui/BufferItem.h>
32#include <gui/BufferQueue.h>
33#include <gui/LayerDebugInfo.h>
34#include <gui/Surface.h>
35
36#include <ui/DebugUtils.h>
37
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
44#include <cutils/compiler.h>
45#include <cutils/native_handle.h>
46#include <cutils/properties.h>
47
48#include <math.h>
49#include <stdlib.h>
50#include <mutex>
51
52namespace android {
53
Lloyd Pique42ab75e2018-09-12 20:46:03 -070054BufferLayer::BufferLayer(const LayerCreationArgs& args)
55 : Layer(args), mTextureName(args.flinger->getNewTexture()) {
56 ALOGV("Creating Layer %s", args.name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070057
Peiyong Lin833074a2018-08-28 11:53:54 -070058 mTexture.init(renderengine::Texture::TEXTURE_EXTERNAL, mTextureName);
David Sodman0c69cad2017-08-21 12:12:51 -070059
Lloyd Pique42ab75e2018-09-12 20:46:03 -070060 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070061
Lloyd Pique42ab75e2018-09-12 20:46:03 -070062 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
63 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070064}
65
66BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070067 mFlinger->deleteTextureAsync(mTextureName);
68
David Sodman6f65f3e2017-11-03 14:28:09 -070069 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070070 ALOGE("Found stale hardware composer layers when destroying "
71 "surface flinger layer %s",
72 mName.string());
chaviw61626f22018-11-15 16:26:27 -080073 destroyAllHwcLayersPlusChildren();
David Sodman0c69cad2017-08-21 12:12:51 -070074 }
Yiwei Zhangdc224042018-10-18 15:34:00 -070075
Yiwei Zhang7e666a52018-11-15 13:33:42 -080076 mFlinger->mTimeStats->onDestroy(getSequence());
David Sodman0c69cad2017-08-21 12:12:51 -070077}
78
David Sodmaneb085e02017-10-05 18:49:04 -070079void BufferLayer::useSurfaceDamage() {
80 if (mFlinger->mForceFullDamage) {
81 surfaceDamageRegion = Region::INVALID_REGION;
82 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070083 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070084 }
85}
86
87void BufferLayer::useEmptyDamage() {
88 surfaceDamageRegion.clear();
89}
90
Marissa Wallfd668622018-05-10 10:21:13 -070091bool BufferLayer::isOpaque(const Layer::State& s) const {
92 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
93 // layer's opaque flag.
94 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
95 return false;
96 }
97
98 // if the layer has the opaque flag, then we're always opaque,
99 // otherwise we use the current buffer's format.
100 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -0700101}
102
103bool BufferLayer::isVisible() const {
104 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800105 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700106}
107
108bool BufferLayer::isFixedSize() const {
109 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
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
130/*
131 * onDraw will draw the current layer onto the presentable buffer
132 */
133void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
Marissa Wall61c58622018-07-18 10:12:20 -0700134 bool useIdentityTransform) {
David Sodman0c69cad2017-08-21 12:12:51 -0700135 ATRACE_CALL();
136
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 }
154 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
155 });
156 // if not everything below us is covered, we plug the holes!
157 Region holes(clip.subtract(under));
158 if (!holes.isEmpty()) {
159 clearWithOpenGL(renderArea, 0, 0, 0, 1);
160 }
161 return;
162 }
163
164 // Bind the current buffer to the GL texture, and wait for it to be
165 // ready for us to draw into.
Marissa Wallfd668622018-05-10 10:21:13 -0700166 status_t err = bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700167 if (err != NO_ERROR) {
168 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
169 // Go ahead and draw the buffer anyway; no matter what we do the screen
170 // is probably going to have something visibly wrong.
171 }
172
173 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
174
Lloyd Pique144e1162017-12-20 16:44:52 -0800175 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700176
177 if (!blackOutLayer) {
178 // TODO: we could be more subtle with isFixedSize()
Chia-I Wu5f6664c2018-08-28 11:01:44 -0700179 const bool useFiltering = needsFiltering(renderArea) || isFixedSize();
David Sodman0c69cad2017-08-21 12:12:51 -0700180
181 // Query the texture matrix given our current filtering mode.
182 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700183 setFilteringEnabled(useFiltering);
184 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700185
186 if (getTransformToDisplayInverse()) {
187 /*
188 * the code below applies the primary display's inverse transform to
189 * the texture transform
190 */
191 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
192 mat4 tr = inverseOrientation(transform);
193
194 /**
195 * TODO(b/36727915): This is basically a hack.
196 *
197 * Ensure that regardless of the parent transformation,
198 * this buffer is always transformed from native display
199 * orientation to display orientation. For example, in the case
200 * of a camera where the buffer remains in native orientation,
201 * we want the pixels to always be upright.
202 */
203 sp<Layer> p = mDrawingParent.promote();
204 if (p != nullptr) {
205 const auto parentTransform = p->getTransform();
206 tr = tr * inverseOrientation(parentTransform.getOrientation());
207 }
208
209 // and finally apply it to the original texture matrix
210 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
211 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
212 }
213
214 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800215 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700216 mTexture.setFiltering(useFiltering);
217 mTexture.setMatrix(textureMatrix);
218
219 engine.setupLayerTexturing(mTexture);
220 } else {
221 engine.setupLayerBlackedOut();
222 }
223 drawWithOpenGL(renderArea, useIdentityTransform);
224 engine.disableTexturing();
225}
226
Marissa Wallfd668622018-05-10 10:21:13 -0700227bool BufferLayer::isHdrY410() const {
228 // pixel format is HDR Y410 masquerading as RGBA_1010102
229 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
230 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
231 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700232}
233
Dominik Laskowski075d3172018-05-24 15:50:06 -0700234void BufferLayer::setPerFrameData(DisplayId displayId, const ui::Transform& transform,
235 const Rect& viewport, int32_t supportedPerFrameMetadata) {
Dominik Laskowski34157762018-10-31 13:07:19 -0700236 RETURN_IF_NO_HWC_LAYER(displayId);
237
David Sodman0c69cad2017-08-21 12:12:51 -0700238 // Apply this display's projection's viewport to the visible region
239 // before giving it to the HWC HAL.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700240 Region visible = transform.transform(visibleRegion.intersect(viewport));
241
David Sodman15094112018-10-11 09:39:37 -0700242 auto& hwcInfo = getBE().mHwcLayers[displayId];
243 auto& hwcLayer = hwcInfo.layer;
244 auto error = hwcLayer->setVisibleRegion(visible);
245 if (error != HWC2::Error::None) {
246 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
247 to_string(error).c_str(), static_cast<int32_t>(error));
248 visible.dump(LOG_TAG);
249 }
David Sodmanba340492018-08-05 21:51:33 -0700250 getBE().compositionInfo.hwc.visibleRegion = visible;
David Sodman15094112018-10-11 09:39:37 -0700251
252 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
253 if (error != HWC2::Error::None) {
254 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
255 to_string(error).c_str(), static_cast<int32_t>(error));
256 surfaceDamageRegion.dump(LOG_TAG);
257 }
David Sodmanba340492018-08-05 21:51:33 -0700258 getBE().compositionInfo.hwc.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700259
260 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800261 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700262 setCompositionType(displayId, HWC2::Composition::Sideband);
David Sodman15094112018-10-11 09:39:37 -0700263 ALOGV("[%s] Requesting Sideband composition", mName.string());
264 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
265 if (error != HWC2::Error::None) {
266 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
267 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
268 static_cast<int32_t>(error));
269 }
David Sodmanba340492018-08-05 21:51:33 -0700270 getBE().compositionInfo.compositionType = HWC2::Composition::Sideband;
David Sodman0c69cad2017-08-21 12:12:51 -0700271 return;
272 }
273
David Sodman15094112018-10-11 09:39:37 -0700274 // Device or Cursor layers
275 if (mPotentialCursor) {
276 ALOGV("[%s] Requesting Cursor composition", mName.string());
277 setCompositionType(displayId, HWC2::Composition::Cursor);
278 } else {
279 ALOGV("[%s] Requesting Device composition", mName.string());
280 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700281 }
282
David Sodman15094112018-10-11 09:39:37 -0700283 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
284 error = hwcLayer->setDataspace(mCurrentDataSpace);
285 if (error != HWC2::Error::None) {
286 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
287 to_string(error).c_str(), static_cast<int32_t>(error));
288 }
289
290 const HdrMetadata& metadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700291 error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
David Sodman15094112018-10-11 09:39:37 -0700292 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
293 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
294 to_string(error).c_str(), static_cast<int32_t>(error));
295 }
296
297 error = hwcLayer->setColorTransform(getColorTransform());
298 if (error != HWC2::Error::None) {
299 ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
300 to_string(error).c_str(), static_cast<int32_t>(error));
301 }
David Sodmanba340492018-08-05 21:51:33 -0700302 getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
303 getBE().compositionInfo.hwc.hdrMetadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700304 getBE().compositionInfo.hwc.supportedPerFrameMetadata = supportedPerFrameMetadata;
Peiyong Lind3788632018-09-18 16:01:31 -0700305 getBE().compositionInfo.hwc.colorTransform = getColorTransform();
Lloyd Pique074e8122018-07-26 12:57:23 -0700306
Dominik Laskowski075d3172018-05-24 15:50:06 -0700307 setHwcLayerBuffer(displayId);
David Sodman0c69cad2017-08-21 12:12:51 -0700308}
309
Marissa Wallfd668622018-05-10 10:21:13 -0700310bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
311 if (mBufferLatched) {
312 Mutex::Autolock lock(mFrameEventHistoryMutex);
313 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700314 }
Marissa Wallfd668622018-05-10 10:21:13 -0700315 mRefreshPending = false;
316 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700317}
318
Dominik Laskowski075d3172018-05-24 15:50:06 -0700319bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
320 const std::shared_ptr<FenceTime>& glDoneFence,
Marissa Wallfd668622018-05-10 10:21:13 -0700321 const std::shared_ptr<FenceTime>& presentFence,
322 const CompositorTiming& compositorTiming) {
323 // mFrameLatencyNeeded is true when a new frame was latched for the
324 // composition.
325 if (!mFrameLatencyNeeded) return false;
326
327 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700328 {
Marissa Wallfd668622018-05-10 10:21:13 -0700329 Mutex::Autolock lock(mFrameEventHistoryMutex);
330 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
331 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700332 }
333
Marissa Wallfd668622018-05-10 10:21:13 -0700334 // Update mFrameTracker.
335 nsecs_t desiredPresentTime = getDesiredPresentTime();
336 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
337
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700338 const int32_t layerID = getSequence();
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800339 mFlinger->mTimeStats->setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700340
341 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
342 if (frameReadyFence->isValid()) {
343 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
344 } else {
345 // There was no fence for this frame, so assume that it was ready
346 // to be presented at the desired present time.
347 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700348 }
Marissa Wallfd668622018-05-10 10:21:13 -0700349
350 if (presentFence->isValid()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800351 mFlinger->mTimeStats->setPresentFence(layerID, mCurrentFrameNumber, presentFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700352 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski075d3172018-05-24 15:50:06 -0700353 } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700354 // The HWC doesn't support present fences, so use the refresh
355 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700356 const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800357 mFlinger->mTimeStats->setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700358 mFrameTracker.setActualPresentTime(actualPresentTime);
359 }
360
361 mFrameTracker.advanceFrame();
362 mFrameLatencyNeeded = false;
363 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700364}
365
Alec Mouri86770e52018-09-24 22:40:58 +0000366Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,
367 const sp<Fence>& releaseFence) {
Marissa Wallfd668622018-05-10 10:21:13 -0700368 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700369
Marissa Wallfd668622018-05-10 10:21:13 -0700370 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700371
Marissa Wallfd668622018-05-10 10:21:13 -0700372 if (sidebandStreamDirtyRegion) {
373 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700374 }
375
Marissa Wallfd668622018-05-10 10:21:13 -0700376 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700377
Marissa Wallfd668622018-05-10 10:21:13 -0700378 if (!hasReadyFrame()) {
379 return dirtyRegion;
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) {
388 return dirtyRegion;
389 }
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();
Marissa Wallfd668622018-05-10 10:21:13 -0700395 return dirtyRegion;
396 }
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();
405 return dirtyRegion;
406 }
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) {
410 return dirtyRegion;
411 }
412
413 err = updateActiveBuffer();
414 if (err != NO_ERROR) {
415 return dirtyRegion;
416 }
417
418 mBufferLatched = true;
419
420 err = updateFrameNumber(latchTime);
421 if (err != NO_ERROR) {
422 return dirtyRegion;
423 }
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());
462 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
463 (scalingMode != mCurrentScalingMode)) {
464 mCurrentCrop = crop;
465 mCurrentTransform = transform;
466 mCurrentScalingMode = scalingMode;
467 recomputeVisibleRegions = true;
468 }
469
470 if (oldBuffer != nullptr) {
471 uint32_t bufWidth = mActiveBuffer->getWidth();
472 uint32_t bufHeight = mActiveBuffer->getHeight();
473 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
474 recomputeVisibleRegions = true;
475 }
476 }
477
478 if (oldOpacity != isOpaque(s)) {
479 recomputeVisibleRegions = true;
480 }
481
482 // Remove any sync points corresponding to the buffer which was just
483 // latched
484 {
485 Mutex::Autolock lock(mLocalSyncPointMutex);
486 auto point = mLocalSyncPoints.begin();
487 while (point != mLocalSyncPoints.end()) {
488 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
489 // This sync point must have been added since we started
490 // latching. Don't drop it yet.
491 ++point;
492 continue;
493 }
494
495 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
496 point = mLocalSyncPoints.erase(point);
497 } else {
498 ++point;
499 }
500 }
501 }
502
503 // FIXME: postedRegion should be dirty & bounds
504 // transform the dirty region to window-manager space
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800505 return getTransform().transform(Region(getBufferSize(s)));
Marissa Wallfd668622018-05-10 10:21:13 -0700506}
507
508// transaction
509void BufferLayer::notifyAvailableFrames() {
510 auto headFrameNumber = getHeadFrameNumber();
511 bool headFenceSignaled = fenceHasSignaled();
512 Mutex::Autolock lock(mLocalSyncPointMutex);
513 for (auto& point : mLocalSyncPoints) {
514 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
515 point->setFrameAvailable();
516 }
David Sodman0c69cad2017-08-21 12:12:51 -0700517 }
518}
519
Marissa Wallfd668622018-05-10 10:21:13 -0700520bool BufferLayer::hasReadyFrame() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700521 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
Marissa Wallfd668622018-05-10 10:21:13 -0700522}
523
524uint32_t BufferLayer::getEffectiveScalingMode() const {
525 if (mOverrideScalingMode >= 0) {
526 return mOverrideScalingMode;
527 }
528
529 return mCurrentScalingMode;
530}
531
532bool BufferLayer::isProtected() const {
533 const sp<GraphicBuffer>& buffer(mActiveBuffer);
534 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
535}
536
537bool BufferLayer::latchUnsignaledBuffers() {
538 static bool propertyLoaded = false;
539 static bool latch = false;
540 static std::mutex mutex;
541 std::lock_guard<std::mutex> lock(mutex);
542 if (!propertyLoaded) {
543 char value[PROPERTY_VALUE_MAX] = {};
544 property_get("debug.sf.latch_unsignaled", value, "0");
545 latch = atoi(value);
546 propertyLoaded = true;
547 }
548 return latch;
549}
550
551// h/w composer set-up
552bool BufferLayer::allTransactionsSignaled() {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800553 auto headFrameNumber = getHeadFrameNumber();
Marissa Wallfd668622018-05-10 10:21:13 -0700554 bool matchingFramesFound = false;
555 bool allTransactionsApplied = true;
556 Mutex::Autolock lock(mLocalSyncPointMutex);
557
558 for (auto& point : mLocalSyncPoints) {
559 if (point->getFrameNumber() > headFrameNumber) {
560 break;
561 }
562 matchingFramesFound = true;
563
564 if (!point->frameIsAvailable()) {
565 // We haven't notified the remote layer that the frame for
566 // this point is available yet. Notify it now, and then
567 // abort this attempt to latch.
568 point->setFrameAvailable();
569 allTransactionsApplied = false;
570 break;
571 }
572
573 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
574 }
575 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700576}
577
578// As documented in libhardware header, formats in the range
579// 0x100 - 0x1FF are specific to the HAL implementation, and
580// are known to have no alpha channel
581// TODO: move definition for device-specific range into
582// hardware.h, instead of using hard-coded values here.
583#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
584
585bool BufferLayer::getOpacityForFormat(uint32_t format) {
586 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
587 return true;
588 }
589 switch (format) {
590 case HAL_PIXEL_FORMAT_RGBA_8888:
591 case HAL_PIXEL_FORMAT_BGRA_8888:
592 case HAL_PIXEL_FORMAT_RGBA_FP16:
593 case HAL_PIXEL_FORMAT_RGBA_1010102:
594 return false;
595 }
596 // in all other case, we have no blending (also for unknown formats)
597 return true;
598}
599
Marissa Wallfd668622018-05-10 10:21:13 -0700600bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
601 return mNeedsFiltering || renderArea.needsFiltering();
Chia-I Wu692e0832018-06-05 15:46:58 -0700602}
603
David Sodman41fdfc92017-11-06 16:09:56 -0800604void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700605 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700606 const State& s(getDrawingState());
607
David Sodman9eeae692017-11-02 10:53:32 -0700608 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700609
610 /*
611 * NOTE: the way we compute the texture coordinates here produces
612 * different results than when we take the HWC path -- in the later case
613 * the "source crop" is rounded to texel boundaries.
614 * This can produce significantly different results when the texture
615 * is scaled by a large amount.
616 *
617 * The GL code below is more logical (imho), and the difference with
618 * HWC is due to a limitation of the HWC API to integers -- a question
619 * is suspend is whether we should ignore this problem or revert to
620 * GL composition when a buffer scaling is applied (maybe with some
621 * minimal value)? Or, we could make GL behave like HWC -- but this feel
622 * like more of a hack.
623 */
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800624 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700625
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800626 ui::Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800627 Rect win = bounds;
Vishnu Nair88a11f22018-11-28 18:30:57 -0800628 const int bufferWidth = getBufferSize(s).getWidth();
629 const int bufferHeight = getBufferSize(s).getHeight();
David Sodman0c69cad2017-08-21 12:12:51 -0700630
Vishnu Nair88a11f22018-11-28 18:30:57 -0800631 const float left = float(win.left) / float(bufferWidth);
632 const float top = float(win.top) / float(bufferHeight);
633 const float right = float(win.right) / float(bufferWidth);
634 const float bottom = float(win.bottom) / float(bufferHeight);
David Sodman0c69cad2017-08-21 12:12:51 -0700635
636 // TODO: we probably want to generate the texture coords with the mesh
637 // here we assume that we only have 4 vertices
Peiyong Lin833074a2018-08-28 11:53:54 -0700638 renderengine::Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
Chia-I Wu1be50b52018-08-29 10:44:48 -0700639 // flip texcoords vertically because BufferLayerConsumer expects them to be in GL convention
David Sodman0c69cad2017-08-21 12:12:51 -0700640 texCoords[0] = vec2(left, 1.0f - top);
641 texCoords[1] = vec2(left, 1.0f - bottom);
642 texCoords[2] = vec2(right, 1.0f - bottom);
643 texCoords[3] = vec2(right, 1.0f - top);
644
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800645 const auto roundedCornerState = getRoundedCornerState();
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700646 const auto cropRect = roundedCornerState.cropRect;
647 setupRoundedCornersCropCoordinates(win, cropRect);
648
bohu21566132018-03-27 14:36:34 -0700649 auto& engine(mFlinger->getRenderEngine());
650 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700651 getColor(), roundedCornerState.radius);
Chia-I Wu01591c92018-05-22 12:03:00 -0700652 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800653
Chia-I Wu692e0832018-06-05 15:46:58 -0700654 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700655 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800656 }
bohu21566132018-03-27 14:36:34 -0700657
Lucas Dupin1b6531c2018-07-05 17:18:21 -0700658 engine.setupCornerRadiusCropSize(cropRect.getWidth(), cropRect.getHeight());
659
bohu21566132018-03-27 14:36:34 -0700660 engine.drawMesh(getBE().mMesh);
661 engine.disableBlending();
662
663 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700664}
665
David Sodman0c69cad2017-08-21 12:12:51 -0700666uint64_t BufferLayer::getHeadFrameNumber() const {
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800667 if (hasFrameUpdate()) {
Marissa Wallfd668622018-05-10 10:21:13 -0700668 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700669 } else {
670 return mCurrentFrameNumber;
671 }
672}
673
Vishnu Nair60356342018-11-13 13:00:45 -0800674Rect BufferLayer::getBufferSize(const State& s) const {
675 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
676 // we cannot determine the buffer size.
677 if ((s.sidebandStream != nullptr) ||
678 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
679 return Rect(getActiveWidth(s), getActiveHeight(s));
680 }
681
682 if (mActiveBuffer == nullptr) {
683 return Rect::INVALID_RECT;
684 }
685
686 uint32_t bufWidth = mActiveBuffer->getWidth();
687 uint32_t bufHeight = mActiveBuffer->getHeight();
688
689 // Undo any transformations on the buffer and return the result.
690 if (mCurrentTransform & ui::Transform::ROT_90) {
691 std::swap(bufWidth, bufHeight);
692 }
693
Lloyd Pique0449b0f2018-12-20 16:23:45 -0800694 if (getTransformToDisplayInverse()) {
Vishnu Nair60356342018-11-13 13:00:45 -0800695 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
696 if (invTransform & ui::Transform::ROT_90) {
697 std::swap(bufWidth, bufHeight);
698 }
699 }
700
701 return Rect(bufWidth, bufHeight);
702}
703
David Sodman0c69cad2017-08-21 12:12:51 -0700704} // namespace android
705
706#if defined(__gl_h_)
707#error "don't include gl/gl.h in this file"
708#endif
709
710#if defined(__gl2_h_)
711#error "don't include gl2/gl2.h in this file"
712#endif