blob: 641bd8d1c30119b9457c4763b05831086edf4af8 [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
Peiyong Lincbc184f2018-08-22 13:24:10 -070027#include <renderengine/RenderEngine.h>
David Sodman0c69cad2017-08-21 12:12:51 -070028
29#include <gui/BufferItem.h>
30#include <gui/BufferQueue.h>
31#include <gui/LayerDebugInfo.h>
32#include <gui/Surface.h>
33
34#include <ui/DebugUtils.h>
35
36#include <utils/Errors.h>
37#include <utils/Log.h>
38#include <utils/NativeHandle.h>
39#include <utils/StopWatch.h>
40#include <utils/Trace.h>
41
42#include <cutils/compiler.h>
43#include <cutils/native_handle.h>
44#include <cutils/properties.h>
45
46#include <math.h>
47#include <stdlib.h>
48#include <mutex>
49
50namespace android {
51
Lloyd Pique42ab75e2018-09-12 20:46:03 -070052BufferLayer::BufferLayer(const LayerCreationArgs& args)
53 : Layer(args), mTextureName(args.flinger->getNewTexture()) {
54 ALOGV("Creating Layer %s", args.name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070055
Peiyong Lin833074a2018-08-28 11:53:54 -070056 mTexture.init(renderengine::Texture::TEXTURE_EXTERNAL, mTextureName);
David Sodman0c69cad2017-08-21 12:12:51 -070057
Lloyd Pique42ab75e2018-09-12 20:46:03 -070058 mPremultipliedAlpha = !(args.flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070059
Lloyd Pique42ab75e2018-09-12 20:46:03 -070060 mPotentialCursor = args.flags & ISurfaceComposerClient::eCursorWindow;
61 mProtectedByApp = args.flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070062}
63
64BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070065 mFlinger->deleteTextureAsync(mTextureName);
66
David Sodman6f65f3e2017-11-03 14:28:09 -070067 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070068 ALOGE("Found stale hardware composer layers when destroying "
69 "surface flinger layer %s",
70 mName.string());
71 destroyAllHwcLayers();
72 }
Yiwei Zhangdc224042018-10-18 15:34:00 -070073
Yiwei Zhang9689e2f2018-05-11 12:33:23 -070074 mTimeStats.onDestroy(getSequence());
David Sodman0c69cad2017-08-21 12:12:51 -070075}
76
David Sodmaneb085e02017-10-05 18:49:04 -070077void BufferLayer::useSurfaceDamage() {
78 if (mFlinger->mForceFullDamage) {
79 surfaceDamageRegion = Region::INVALID_REGION;
80 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070081 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070082 }
83}
84
85void BufferLayer::useEmptyDamage() {
86 surfaceDamageRegion.clear();
87}
88
Marissa Wallfd668622018-05-10 10:21:13 -070089bool BufferLayer::isOpaque(const Layer::State& s) const {
90 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
91 // layer's opaque flag.
92 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
93 return false;
94 }
95
96 // if the layer has the opaque flag, then we're always opaque,
97 // otherwise we use the current buffer's format.
98 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -070099}
100
101bool BufferLayer::isVisible() const {
102 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800103 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700104}
105
106bool BufferLayer::isFixedSize() const {
107 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
108}
109
David Sodman0c69cad2017-08-21 12:12:51 -0700110static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800111 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
112 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
113 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 -0700114 mat4 tr;
115
116 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
117 tr = tr * rot90;
118 }
119 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
120 tr = tr * flipH;
121 }
122 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
123 tr = tr * flipV;
124 }
125 return inverse(tr);
126}
127
128/*
129 * onDraw will draw the current layer onto the presentable buffer
130 */
131void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
Marissa Wall61c58622018-07-18 10:12:20 -0700132 bool useIdentityTransform) {
David Sodman0c69cad2017-08-21 12:12:51 -0700133 ATRACE_CALL();
134
David Sodman0cf8f8d2017-12-20 18:19:45 -0800135 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700136 // the texture has not been created yet, this Layer has
137 // in fact never been drawn into. This happens frequently with
138 // SurfaceView because the WindowManager can't know when the client
139 // has drawn the first time.
140
141 // If there is nothing under us, we paint the screen in black, otherwise
142 // we just skip this update.
143
144 // figure out if there is something below us
145 Region under;
146 bool finished = false;
147 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
148 if (finished || layer == static_cast<BufferLayer const*>(this)) {
149 finished = true;
150 return;
151 }
152 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
153 });
154 // if not everything below us is covered, we plug the holes!
155 Region holes(clip.subtract(under));
156 if (!holes.isEmpty()) {
157 clearWithOpenGL(renderArea, 0, 0, 0, 1);
158 }
159 return;
160 }
161
162 // Bind the current buffer to the GL texture, and wait for it to be
163 // ready for us to draw into.
Marissa Wallfd668622018-05-10 10:21:13 -0700164 status_t err = bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700165 if (err != NO_ERROR) {
166 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
167 // Go ahead and draw the buffer anyway; no matter what we do the screen
168 // is probably going to have something visibly wrong.
169 }
170
171 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
172
Lloyd Pique144e1162017-12-20 16:44:52 -0800173 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700174
175 if (!blackOutLayer) {
176 // TODO: we could be more subtle with isFixedSize()
Chia-I Wu5f6664c2018-08-28 11:01:44 -0700177 const bool useFiltering = needsFiltering(renderArea) || isFixedSize();
David Sodman0c69cad2017-08-21 12:12:51 -0700178
179 // Query the texture matrix given our current filtering mode.
180 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700181 setFilteringEnabled(useFiltering);
182 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700183
184 if (getTransformToDisplayInverse()) {
185 /*
186 * the code below applies the primary display's inverse transform to
187 * the texture transform
188 */
189 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
190 mat4 tr = inverseOrientation(transform);
191
192 /**
193 * TODO(b/36727915): This is basically a hack.
194 *
195 * Ensure that regardless of the parent transformation,
196 * this buffer is always transformed from native display
197 * orientation to display orientation. For example, in the case
198 * of a camera where the buffer remains in native orientation,
199 * we want the pixels to always be upright.
200 */
201 sp<Layer> p = mDrawingParent.promote();
202 if (p != nullptr) {
203 const auto parentTransform = p->getTransform();
204 tr = tr * inverseOrientation(parentTransform.getOrientation());
205 }
206
207 // and finally apply it to the original texture matrix
208 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
209 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
210 }
211
212 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800213 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700214 mTexture.setFiltering(useFiltering);
215 mTexture.setMatrix(textureMatrix);
216
217 engine.setupLayerTexturing(mTexture);
218 } else {
219 engine.setupLayerBlackedOut();
220 }
221 drawWithOpenGL(renderArea, useIdentityTransform);
222 engine.disableTexturing();
223}
224
Marissa Wallfd668622018-05-10 10:21:13 -0700225bool BufferLayer::isHdrY410() const {
226 // pixel format is HDR Y410 masquerading as RGBA_1010102
227 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
228 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
229 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700230}
231
Dominik Laskowski075d3172018-05-24 15:50:06 -0700232void BufferLayer::setPerFrameData(DisplayId displayId, const ui::Transform& transform,
233 const Rect& viewport, int32_t supportedPerFrameMetadata) {
David Sodman0c69cad2017-08-21 12:12:51 -0700234 // Apply this display's projection's viewport to the visible region
235 // before giving it to the HWC HAL.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700236 Region visible = transform.transform(visibleRegion.intersect(viewport));
237
David Sodman15094112018-10-11 09:39:37 -0700238 if (!hasHwcLayer(displayId)) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700239 ALOGE("[%s] failed to setPerFrameData: no HWC layer found for display %" PRIu64,
David Sodman15094112018-10-11 09:39:37 -0700240 mName.string(), displayId);
241 return;
242 }
243 auto& hwcInfo = getBE().mHwcLayers[displayId];
244 auto& hwcLayer = hwcInfo.layer;
245 auto error = hwcLayer->setVisibleRegion(visible);
246 if (error != HWC2::Error::None) {
247 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
248 to_string(error).c_str(), static_cast<int32_t>(error));
249 visible.dump(LOG_TAG);
250 }
David Sodmanba340492018-08-05 21:51:33 -0700251 getBE().compositionInfo.hwc.visibleRegion = visible;
David Sodman15094112018-10-11 09:39:37 -0700252
253 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
254 if (error != HWC2::Error::None) {
255 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
256 to_string(error).c_str(), static_cast<int32_t>(error));
257 surfaceDamageRegion.dump(LOG_TAG);
258 }
David Sodmanba340492018-08-05 21:51:33 -0700259 getBE().compositionInfo.hwc.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700260
261 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800262 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700263 setCompositionType(displayId, HWC2::Composition::Sideband);
David Sodman15094112018-10-11 09:39:37 -0700264 ALOGV("[%s] Requesting Sideband composition", mName.string());
265 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
266 if (error != HWC2::Error::None) {
267 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
268 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
269 static_cast<int32_t>(error));
270 }
David Sodmanba340492018-08-05 21:51:33 -0700271 getBE().compositionInfo.compositionType = HWC2::Composition::Sideband;
David Sodman0c69cad2017-08-21 12:12:51 -0700272 return;
273 }
274
David Sodman15094112018-10-11 09:39:37 -0700275 // Device or Cursor layers
276 if (mPotentialCursor) {
277 ALOGV("[%s] Requesting Cursor composition", mName.string());
278 setCompositionType(displayId, HWC2::Composition::Cursor);
279 } else {
280 ALOGV("[%s] Requesting Device composition", mName.string());
281 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700282 }
283
David Sodman15094112018-10-11 09:39:37 -0700284 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
285 error = hwcLayer->setDataspace(mCurrentDataSpace);
286 if (error != HWC2::Error::None) {
287 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
288 to_string(error).c_str(), static_cast<int32_t>(error));
289 }
290
291 const HdrMetadata& metadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700292 error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
David Sodman15094112018-10-11 09:39:37 -0700293 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
294 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
295 to_string(error).c_str(), static_cast<int32_t>(error));
296 }
297
298 error = hwcLayer->setColorTransform(getColorTransform());
299 if (error != HWC2::Error::None) {
300 ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
301 to_string(error).c_str(), static_cast<int32_t>(error));
302 }
David Sodmanba340492018-08-05 21:51:33 -0700303 getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
304 getBE().compositionInfo.hwc.hdrMetadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700305 getBE().compositionInfo.hwc.supportedPerFrameMetadata = supportedPerFrameMetadata;
Peiyong Lind3788632018-09-18 16:01:31 -0700306 getBE().compositionInfo.hwc.colorTransform = getColorTransform();
Lloyd Pique074e8122018-07-26 12:57:23 -0700307
Dominik Laskowski075d3172018-05-24 15:50:06 -0700308 setHwcLayerBuffer(displayId);
David Sodman0c69cad2017-08-21 12:12:51 -0700309}
310
Marissa Wallfd668622018-05-10 10:21:13 -0700311bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
312 if (mBufferLatched) {
313 Mutex::Autolock lock(mFrameEventHistoryMutex);
314 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700315 }
Marissa Wallfd668622018-05-10 10:21:13 -0700316 mRefreshPending = false;
317 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700318}
319
Dominik Laskowski075d3172018-05-24 15:50:06 -0700320bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
321 const std::shared_ptr<FenceTime>& glDoneFence,
Marissa Wallfd668622018-05-10 10:21:13 -0700322 const std::shared_ptr<FenceTime>& presentFence,
323 const CompositorTiming& compositorTiming) {
324 // mFrameLatencyNeeded is true when a new frame was latched for the
325 // composition.
326 if (!mFrameLatencyNeeded) return false;
327
328 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700329 {
Marissa Wallfd668622018-05-10 10:21:13 -0700330 Mutex::Autolock lock(mFrameEventHistoryMutex);
331 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
332 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700333 }
334
Marissa Wallfd668622018-05-10 10:21:13 -0700335 // Update mFrameTracker.
336 nsecs_t desiredPresentTime = getDesiredPresentTime();
337 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
338
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700339 const int32_t layerID = getSequence();
340 mTimeStats.setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700341
342 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
343 if (frameReadyFence->isValid()) {
344 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
345 } else {
346 // There was no fence for this frame, so assume that it was ready
347 // to be presented at the desired present time.
348 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700349 }
Marissa Wallfd668622018-05-10 10:21:13 -0700350
351 if (presentFence->isValid()) {
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700352 mTimeStats.setPresentFence(layerID, mCurrentFrameNumber, presentFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700353 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski075d3172018-05-24 15:50:06 -0700354 } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700355 // The HWC doesn't support present fences, so use the refresh
356 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700357 const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700358 mTimeStats.setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700359 mFrameTracker.setActualPresentTime(actualPresentTime);
360 }
361
362 mFrameTracker.advanceFrame();
363 mFrameLatencyNeeded = false;
364 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700365}
366
Alec Mouri86770e52018-09-24 22:40:58 +0000367Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,
368 const sp<Fence>& releaseFence) {
Marissa Wallfd668622018-05-10 10:21:13 -0700369 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700370
Marissa Wallfd668622018-05-10 10:21:13 -0700371 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700372
Marissa Wallfd668622018-05-10 10:21:13 -0700373 if (sidebandStreamDirtyRegion) {
374 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700375 }
376
Marissa Wallfd668622018-05-10 10:21:13 -0700377 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700378
Marissa Wallfd668622018-05-10 10:21:13 -0700379 if (!hasReadyFrame()) {
380 return dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700381 }
David Sodman0c69cad2017-08-21 12:12:51 -0700382
Marissa Wallfd668622018-05-10 10:21:13 -0700383 // if we've already called updateTexImage() without going through
384 // a composition step, we have to skip this layer at this point
385 // because we cannot call updateTeximage() without a corresponding
386 // compositionComplete() call.
387 // we'll trigger an update in onPreComposition().
388 if (mRefreshPending) {
389 return dirtyRegion;
390 }
391
392 // If the head buffer's acquire fence hasn't signaled yet, return and
393 // try again later
394 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700395 mFlinger->signalLayerUpdate();
Marissa Wallfd668622018-05-10 10:21:13 -0700396 return dirtyRegion;
397 }
398
399 // Capture the old state of the layer for comparisons later
400 const State& s(getDrawingState());
401 const bool oldOpacity = isOpaque(s);
402 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
403
404 if (!allTransactionsSignaled()) {
405 mFlinger->signalLayerUpdate();
406 return dirtyRegion;
407 }
408
Alec Mouri86770e52018-09-24 22:40:58 +0000409 status_t err = updateTexImage(recomputeVisibleRegions, latchTime, releaseFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700410 if (err != NO_ERROR) {
411 return dirtyRegion;
412 }
413
414 err = updateActiveBuffer();
415 if (err != NO_ERROR) {
416 return dirtyRegion;
417 }
418
419 mBufferLatched = true;
420
421 err = updateFrameNumber(latchTime);
422 if (err != NO_ERROR) {
423 return dirtyRegion;
424 }
425
426 mRefreshPending = true;
427 mFrameLatencyNeeded = true;
428 if (oldBuffer == nullptr) {
429 // the first time we receive a buffer, we need to trigger a
430 // geometry invalidation.
431 recomputeVisibleRegions = true;
432 }
433
434 ui::Dataspace dataSpace = getDrawingDataSpace();
435 // treat modern dataspaces as legacy dataspaces whenever possible, until
436 // we can trust the buffer producers
437 switch (dataSpace) {
438 case ui::Dataspace::V0_SRGB:
439 dataSpace = ui::Dataspace::SRGB;
440 break;
441 case ui::Dataspace::V0_SRGB_LINEAR:
442 dataSpace = ui::Dataspace::SRGB_LINEAR;
443 break;
444 case ui::Dataspace::V0_JFIF:
445 dataSpace = ui::Dataspace::JFIF;
446 break;
447 case ui::Dataspace::V0_BT601_625:
448 dataSpace = ui::Dataspace::BT601_625;
449 break;
450 case ui::Dataspace::V0_BT601_525:
451 dataSpace = ui::Dataspace::BT601_525;
452 break;
453 case ui::Dataspace::V0_BT709:
454 dataSpace = ui::Dataspace::BT709;
455 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
Marissa Wall61c58622018-07-18 10:12:20 -0700507 return getTransform().transform(Region(Rect(getActiveWidth(s), getActiveHeight(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 {
523 return hasDrawingBuffer() || getSidebandStreamChanged() || getAutoRefresh();
524}
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() {
555 auto headFrameNumber = getHeadFrameNumber();
556 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
Marissa Wallfd668622018-05-10 10:21:13 -0700602bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
603 return mNeedsFiltering || renderArea.needsFiltering();
Chia-I Wu692e0832018-06-05 15:46:58 -0700604}
605
David Sodman41fdfc92017-11-06 16:09:56 -0800606void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700607 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700608 const State& s(getDrawingState());
609
David Sodman9eeae692017-11-02 10:53:32 -0700610 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700611
612 /*
613 * NOTE: the way we compute the texture coordinates here produces
614 * different results than when we take the HWC path -- in the later case
615 * the "source crop" is rounded to texel boundaries.
616 * This can produce significantly different results when the texture
617 * is scaled by a large amount.
618 *
619 * The GL code below is more logical (imho), and the difference with
620 * HWC is due to a limitation of the HWC API to integers -- a question
621 * is suspend is whether we should ignore this problem or revert to
622 * GL composition when a buffer scaling is applied (maybe with some
623 * minimal value)? Or, we could make GL behave like HWC -- but this feel
624 * like more of a hack.
625 */
Dan Stoza80d61162017-12-20 15:57:52 -0800626 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700627
Peiyong Linefefaac2018-08-17 12:27:51 -0700628 ui::Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800629 Rect win = bounds;
David Sodman0c69cad2017-08-21 12:12:51 -0700630
Marissa Wall61c58622018-07-18 10:12:20 -0700631 float left = float(win.left) / float(getActiveWidth(s));
632 float top = float(win.top) / float(getActiveHeight(s));
633 float right = float(win.right) / float(getActiveWidth(s));
634 float bottom = float(win.bottom) / float(getActiveHeight(s));
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
bohu21566132018-03-27 14:36:34 -0700645 auto& engine(mFlinger->getRenderEngine());
646 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
647 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700648 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800649
Chia-I Wu692e0832018-06-05 15:46:58 -0700650 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700651 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800652 }
bohu21566132018-03-27 14:36:34 -0700653
654 engine.drawMesh(getBE().mMesh);
655 engine.disableBlending();
656
657 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700658}
659
David Sodman0c69cad2017-08-21 12:12:51 -0700660uint64_t BufferLayer::getHeadFrameNumber() const {
Marissa Wallfd668622018-05-10 10:21:13 -0700661 if (hasDrawingBuffer()) {
662 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700663 } else {
664 return mCurrentFrameNumber;
665 }
666}
667
David Sodman0c69cad2017-08-21 12:12:51 -0700668} // namespace android
669
670#if defined(__gl_h_)
671#error "don't include gl/gl.h in this file"
672#endif
673
674#if defined(__gl2_h_)
675#error "don't include gl2/gl2.h in this file"
676#endif