blob: 7caae989cdea1d174209793bd7a265844007ad2d [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) {
Dominik Laskowski34157762018-10-31 13:07:19 -0700234 RETURN_IF_NO_HWC_LAYER(displayId);
235
David Sodman0c69cad2017-08-21 12:12:51 -0700236 // Apply this display's projection's viewport to the visible region
237 // before giving it to the HWC HAL.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700238 Region visible = transform.transform(visibleRegion.intersect(viewport));
239
David Sodman15094112018-10-11 09:39:37 -0700240 auto& hwcInfo = getBE().mHwcLayers[displayId];
241 auto& hwcLayer = hwcInfo.layer;
242 auto error = hwcLayer->setVisibleRegion(visible);
243 if (error != HWC2::Error::None) {
244 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
245 to_string(error).c_str(), static_cast<int32_t>(error));
246 visible.dump(LOG_TAG);
247 }
David Sodmanba340492018-08-05 21:51:33 -0700248 getBE().compositionInfo.hwc.visibleRegion = visible;
David Sodman15094112018-10-11 09:39:37 -0700249
250 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
251 if (error != HWC2::Error::None) {
252 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
253 to_string(error).c_str(), static_cast<int32_t>(error));
254 surfaceDamageRegion.dump(LOG_TAG);
255 }
David Sodmanba340492018-08-05 21:51:33 -0700256 getBE().compositionInfo.hwc.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700257
258 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800259 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700260 setCompositionType(displayId, HWC2::Composition::Sideband);
David Sodman15094112018-10-11 09:39:37 -0700261 ALOGV("[%s] Requesting Sideband composition", mName.string());
262 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
263 if (error != HWC2::Error::None) {
264 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
265 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
266 static_cast<int32_t>(error));
267 }
David Sodmanba340492018-08-05 21:51:33 -0700268 getBE().compositionInfo.compositionType = HWC2::Composition::Sideband;
David Sodman0c69cad2017-08-21 12:12:51 -0700269 return;
270 }
271
David Sodman15094112018-10-11 09:39:37 -0700272 // Device or Cursor layers
273 if (mPotentialCursor) {
274 ALOGV("[%s] Requesting Cursor composition", mName.string());
275 setCompositionType(displayId, HWC2::Composition::Cursor);
276 } else {
277 ALOGV("[%s] Requesting Device composition", mName.string());
278 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700279 }
280
David Sodman15094112018-10-11 09:39:37 -0700281 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
282 error = hwcLayer->setDataspace(mCurrentDataSpace);
283 if (error != HWC2::Error::None) {
284 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
285 to_string(error).c_str(), static_cast<int32_t>(error));
286 }
287
288 const HdrMetadata& metadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700289 error = hwcLayer->setPerFrameMetadata(supportedPerFrameMetadata, metadata);
David Sodman15094112018-10-11 09:39:37 -0700290 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
291 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
292 to_string(error).c_str(), static_cast<int32_t>(error));
293 }
294
295 error = hwcLayer->setColorTransform(getColorTransform());
296 if (error != HWC2::Error::None) {
297 ALOGE("[%s] Failed to setColorTransform: %s (%d)", mName.string(),
298 to_string(error).c_str(), static_cast<int32_t>(error));
299 }
David Sodmanba340492018-08-05 21:51:33 -0700300 getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
301 getBE().compositionInfo.hwc.hdrMetadata = getDrawingHdrMetadata();
Dominik Laskowski075d3172018-05-24 15:50:06 -0700302 getBE().compositionInfo.hwc.supportedPerFrameMetadata = supportedPerFrameMetadata;
Peiyong Lind3788632018-09-18 16:01:31 -0700303 getBE().compositionInfo.hwc.colorTransform = getColorTransform();
Lloyd Pique074e8122018-07-26 12:57:23 -0700304
Dominik Laskowski075d3172018-05-24 15:50:06 -0700305 setHwcLayerBuffer(displayId);
David Sodman0c69cad2017-08-21 12:12:51 -0700306}
307
Marissa Wallfd668622018-05-10 10:21:13 -0700308bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
309 if (mBufferLatched) {
310 Mutex::Autolock lock(mFrameEventHistoryMutex);
311 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700312 }
Marissa Wallfd668622018-05-10 10:21:13 -0700313 mRefreshPending = false;
314 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700315}
316
Dominik Laskowski075d3172018-05-24 15:50:06 -0700317bool BufferLayer::onPostComposition(const std::optional<DisplayId>& displayId,
318 const std::shared_ptr<FenceTime>& glDoneFence,
Marissa Wallfd668622018-05-10 10:21:13 -0700319 const std::shared_ptr<FenceTime>& presentFence,
320 const CompositorTiming& compositorTiming) {
321 // mFrameLatencyNeeded is true when a new frame was latched for the
322 // composition.
323 if (!mFrameLatencyNeeded) return false;
324
325 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700326 {
Marissa Wallfd668622018-05-10 10:21:13 -0700327 Mutex::Autolock lock(mFrameEventHistoryMutex);
328 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
329 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700330 }
331
Marissa Wallfd668622018-05-10 10:21:13 -0700332 // Update mFrameTracker.
333 nsecs_t desiredPresentTime = getDesiredPresentTime();
334 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
335
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700336 const int32_t layerID = getSequence();
337 mTimeStats.setDesiredTime(layerID, mCurrentFrameNumber, desiredPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700338
339 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
340 if (frameReadyFence->isValid()) {
341 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
342 } else {
343 // There was no fence for this frame, so assume that it was ready
344 // to be presented at the desired present time.
345 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700346 }
Marissa Wallfd668622018-05-10 10:21:13 -0700347
348 if (presentFence->isValid()) {
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700349 mTimeStats.setPresentFence(layerID, mCurrentFrameNumber, presentFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700350 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
Dominik Laskowski075d3172018-05-24 15:50:06 -0700351 } else if (displayId && mFlinger->getHwComposer().isConnected(*displayId)) {
Marissa Wallfd668622018-05-10 10:21:13 -0700352 // The HWC doesn't support present fences, so use the refresh
353 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700354 const nsecs_t actualPresentTime = mFlinger->getHwComposer().getRefreshTimestamp(*displayId);
Yiwei Zhang9689e2f2018-05-11 12:33:23 -0700355 mTimeStats.setPresentTime(layerID, mCurrentFrameNumber, actualPresentTime);
Marissa Wallfd668622018-05-10 10:21:13 -0700356 mFrameTracker.setActualPresentTime(actualPresentTime);
357 }
358
359 mFrameTracker.advanceFrame();
360 mFrameLatencyNeeded = false;
361 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700362}
363
Alec Mouri86770e52018-09-24 22:40:58 +0000364Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime,
365 const sp<Fence>& releaseFence) {
Marissa Wallfd668622018-05-10 10:21:13 -0700366 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700367
Marissa Wallfd668622018-05-10 10:21:13 -0700368 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700369
Marissa Wallfd668622018-05-10 10:21:13 -0700370 if (sidebandStreamDirtyRegion) {
371 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700372 }
373
Marissa Wallfd668622018-05-10 10:21:13 -0700374 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700375
Marissa Wallfd668622018-05-10 10:21:13 -0700376 if (!hasReadyFrame()) {
377 return dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700378 }
David Sodman0c69cad2017-08-21 12:12:51 -0700379
Marissa Wallfd668622018-05-10 10:21:13 -0700380 // if we've already called updateTexImage() without going through
381 // a composition step, we have to skip this layer at this point
382 // because we cannot call updateTeximage() without a corresponding
383 // compositionComplete() call.
384 // we'll trigger an update in onPreComposition().
385 if (mRefreshPending) {
386 return dirtyRegion;
387 }
388
389 // If the head buffer's acquire fence hasn't signaled yet, return and
390 // try again later
391 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700392 mFlinger->signalLayerUpdate();
Marissa Wallfd668622018-05-10 10:21:13 -0700393 return dirtyRegion;
394 }
395
396 // Capture the old state of the layer for comparisons later
397 const State& s(getDrawingState());
398 const bool oldOpacity = isOpaque(s);
399 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
400
401 if (!allTransactionsSignaled()) {
402 mFlinger->signalLayerUpdate();
403 return dirtyRegion;
404 }
405
Alec Mouri86770e52018-09-24 22:40:58 +0000406 status_t err = updateTexImage(recomputeVisibleRegions, latchTime, releaseFence);
Marissa Wallfd668622018-05-10 10:21:13 -0700407 if (err != NO_ERROR) {
408 return dirtyRegion;
409 }
410
411 err = updateActiveBuffer();
412 if (err != NO_ERROR) {
413 return dirtyRegion;
414 }
415
416 mBufferLatched = true;
417
418 err = updateFrameNumber(latchTime);
419 if (err != NO_ERROR) {
420 return dirtyRegion;
421 }
422
423 mRefreshPending = true;
424 mFrameLatencyNeeded = true;
425 if (oldBuffer == nullptr) {
426 // the first time we receive a buffer, we need to trigger a
427 // geometry invalidation.
428 recomputeVisibleRegions = true;
429 }
430
431 ui::Dataspace dataSpace = getDrawingDataSpace();
432 // treat modern dataspaces as legacy dataspaces whenever possible, until
433 // we can trust the buffer producers
434 switch (dataSpace) {
435 case ui::Dataspace::V0_SRGB:
436 dataSpace = ui::Dataspace::SRGB;
437 break;
438 case ui::Dataspace::V0_SRGB_LINEAR:
439 dataSpace = ui::Dataspace::SRGB_LINEAR;
440 break;
441 case ui::Dataspace::V0_JFIF:
442 dataSpace = ui::Dataspace::JFIF;
443 break;
444 case ui::Dataspace::V0_BT601_625:
445 dataSpace = ui::Dataspace::BT601_625;
446 break;
447 case ui::Dataspace::V0_BT601_525:
448 dataSpace = ui::Dataspace::BT601_525;
449 break;
450 case ui::Dataspace::V0_BT709:
451 dataSpace = ui::Dataspace::BT709;
452 break;
453 default:
454 break;
455 }
456 mCurrentDataSpace = dataSpace;
457
458 Rect crop(getDrawingCrop());
459 const uint32_t transform(getDrawingTransform());
460 const uint32_t scalingMode(getDrawingScalingMode());
461 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
462 (scalingMode != mCurrentScalingMode)) {
463 mCurrentCrop = crop;
464 mCurrentTransform = transform;
465 mCurrentScalingMode = scalingMode;
466 recomputeVisibleRegions = true;
467 }
468
469 if (oldBuffer != nullptr) {
470 uint32_t bufWidth = mActiveBuffer->getWidth();
471 uint32_t bufHeight = mActiveBuffer->getHeight();
472 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
473 recomputeVisibleRegions = true;
474 }
475 }
476
477 if (oldOpacity != isOpaque(s)) {
478 recomputeVisibleRegions = true;
479 }
480
481 // Remove any sync points corresponding to the buffer which was just
482 // latched
483 {
484 Mutex::Autolock lock(mLocalSyncPointMutex);
485 auto point = mLocalSyncPoints.begin();
486 while (point != mLocalSyncPoints.end()) {
487 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
488 // This sync point must have been added since we started
489 // latching. Don't drop it yet.
490 ++point;
491 continue;
492 }
493
494 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
495 point = mLocalSyncPoints.erase(point);
496 } else {
497 ++point;
498 }
499 }
500 }
501
502 // FIXME: postedRegion should be dirty & bounds
503 // transform the dirty region to window-manager space
Vishnu Nair88a11f22018-11-28 18:30:57 -0800504 return getTransform().transform(Region(getBufferSize(s)));
Marissa Wallfd668622018-05-10 10:21:13 -0700505}
506
507// transaction
508void BufferLayer::notifyAvailableFrames() {
509 auto headFrameNumber = getHeadFrameNumber();
510 bool headFenceSignaled = fenceHasSignaled();
511 Mutex::Autolock lock(mLocalSyncPointMutex);
512 for (auto& point : mLocalSyncPoints) {
513 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
514 point->setFrameAvailable();
515 }
David Sodman0c69cad2017-08-21 12:12:51 -0700516 }
517}
518
Marissa Wallfd668622018-05-10 10:21:13 -0700519bool BufferLayer::hasReadyFrame() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700520 return hasFrameUpdate() || getSidebandStreamChanged() || getAutoRefresh();
Marissa Wallfd668622018-05-10 10:21:13 -0700521}
522
523uint32_t BufferLayer::getEffectiveScalingMode() const {
524 if (mOverrideScalingMode >= 0) {
525 return mOverrideScalingMode;
526 }
527
528 return mCurrentScalingMode;
529}
530
531bool BufferLayer::isProtected() const {
532 const sp<GraphicBuffer>& buffer(mActiveBuffer);
533 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
534}
535
536bool BufferLayer::latchUnsignaledBuffers() {
537 static bool propertyLoaded = false;
538 static bool latch = false;
539 static std::mutex mutex;
540 std::lock_guard<std::mutex> lock(mutex);
541 if (!propertyLoaded) {
542 char value[PROPERTY_VALUE_MAX] = {};
543 property_get("debug.sf.latch_unsignaled", value, "0");
544 latch = atoi(value);
545 propertyLoaded = true;
546 }
547 return latch;
548}
549
550// h/w composer set-up
551bool BufferLayer::allTransactionsSignaled() {
552 auto headFrameNumber = getHeadFrameNumber();
553 bool matchingFramesFound = false;
554 bool allTransactionsApplied = true;
555 Mutex::Autolock lock(mLocalSyncPointMutex);
556
557 for (auto& point : mLocalSyncPoints) {
558 if (point->getFrameNumber() > headFrameNumber) {
559 break;
560 }
561 matchingFramesFound = true;
562
563 if (!point->frameIsAvailable()) {
564 // We haven't notified the remote layer that the frame for
565 // this point is available yet. Notify it now, and then
566 // abort this attempt to latch.
567 point->setFrameAvailable();
568 allTransactionsApplied = false;
569 break;
570 }
571
572 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
573 }
574 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700575}
576
577// As documented in libhardware header, formats in the range
578// 0x100 - 0x1FF are specific to the HAL implementation, and
579// are known to have no alpha channel
580// TODO: move definition for device-specific range into
581// hardware.h, instead of using hard-coded values here.
582#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
583
584bool BufferLayer::getOpacityForFormat(uint32_t format) {
585 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
586 return true;
587 }
588 switch (format) {
589 case HAL_PIXEL_FORMAT_RGBA_8888:
590 case HAL_PIXEL_FORMAT_BGRA_8888:
591 case HAL_PIXEL_FORMAT_RGBA_FP16:
592 case HAL_PIXEL_FORMAT_RGBA_1010102:
593 return false;
594 }
595 // in all other case, we have no blending (also for unknown formats)
596 return true;
597}
598
Marissa Wallfd668622018-05-10 10:21:13 -0700599bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
600 return mNeedsFiltering || renderArea.needsFiltering();
Chia-I Wu692e0832018-06-05 15:46:58 -0700601}
602
David Sodman41fdfc92017-11-06 16:09:56 -0800603void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700604 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700605 const State& s(getDrawingState());
606
David Sodman9eeae692017-11-02 10:53:32 -0700607 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700608
609 /*
610 * NOTE: the way we compute the texture coordinates here produces
611 * different results than when we take the HWC path -- in the later case
612 * the "source crop" is rounded to texel boundaries.
613 * This can produce significantly different results when the texture
614 * is scaled by a large amount.
615 *
616 * The GL code below is more logical (imho), and the difference with
617 * HWC is due to a limitation of the HWC API to integers -- a question
618 * is suspend is whether we should ignore this problem or revert to
619 * GL composition when a buffer scaling is applied (maybe with some
620 * minimal value)? Or, we could make GL behave like HWC -- but this feel
621 * like more of a hack.
622 */
Dan Stoza80d61162017-12-20 15:57:52 -0800623 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700624
Peiyong Linefefaac2018-08-17 12:27:51 -0700625 ui::Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800626 Rect win = bounds;
Vishnu Nair88a11f22018-11-28 18:30:57 -0800627 const int bufferWidth = getBufferSize(s).getWidth();
628 const int bufferHeight = getBufferSize(s).getHeight();
David Sodman0c69cad2017-08-21 12:12:51 -0700629
Vishnu Nair88a11f22018-11-28 18:30:57 -0800630 const float left = float(win.left) / float(bufferWidth);
631 const float top = float(win.top) / float(bufferHeight);
632 const float right = float(win.right) / float(bufferWidth);
633 const float bottom = float(win.bottom) / float(bufferHeight);
David Sodman0c69cad2017-08-21 12:12:51 -0700634
635 // TODO: we probably want to generate the texture coords with the mesh
636 // here we assume that we only have 4 vertices
Peiyong Lin833074a2018-08-28 11:53:54 -0700637 renderengine::Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
Chia-I Wu1be50b52018-08-29 10:44:48 -0700638 // flip texcoords vertically because BufferLayerConsumer expects them to be in GL convention
David Sodman0c69cad2017-08-21 12:12:51 -0700639 texCoords[0] = vec2(left, 1.0f - top);
640 texCoords[1] = vec2(left, 1.0f - bottom);
641 texCoords[2] = vec2(right, 1.0f - bottom);
642 texCoords[3] = vec2(right, 1.0f - top);
643
bohu21566132018-03-27 14:36:34 -0700644 auto& engine(mFlinger->getRenderEngine());
645 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
646 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700647 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800648
Chia-I Wu692e0832018-06-05 15:46:58 -0700649 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700650 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800651 }
bohu21566132018-03-27 14:36:34 -0700652
653 engine.drawMesh(getBE().mMesh);
654 engine.disableBlending();
655
656 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700657}
658
David Sodman0c69cad2017-08-21 12:12:51 -0700659uint64_t BufferLayer::getHeadFrameNumber() const {
Marissa Wall024a1912018-08-13 13:55:35 -0700660 if (hasFrameUpdate()) {
Marissa Wallfd668622018-05-10 10:21:13 -0700661 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700662 } else {
663 return mCurrentFrameNumber;
664 }
665}
666
Vishnu Nair60356342018-11-13 13:00:45 -0800667Rect BufferLayer::getBufferSize(const State& s) const {
668 // If we have a sideband stream, or we are scaling the buffer then return the layer size since
669 // we cannot determine the buffer size.
670 if ((s.sidebandStream != nullptr) ||
671 (getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE)) {
672 return Rect(getActiveWidth(s), getActiveHeight(s));
673 }
674
675 if (mActiveBuffer == nullptr) {
676 return Rect::INVALID_RECT;
677 }
678
679 uint32_t bufWidth = mActiveBuffer->getWidth();
680 uint32_t bufHeight = mActiveBuffer->getHeight();
681
682 // Undo any transformations on the buffer and return the result.
683 if (mCurrentTransform & ui::Transform::ROT_90) {
684 std::swap(bufWidth, bufHeight);
685 }
686
687 if (getTransformToDisplayInverse()) {
688 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
689 if (invTransform & ui::Transform::ROT_90) {
690 std::swap(bufWidth, bufHeight);
691 }
692 }
693
694 return Rect(bufWidth, bufHeight);
695}
696
David Sodman0c69cad2017-08-21 12:12:51 -0700697} // namespace android
698
699#if defined(__gl_h_)
700#error "don't include gl/gl.h in this file"
701#endif
702
703#if defined(__gl2_h_)
704#error "don't include gl2/gl2.h in this file"
705#endif