blob: 64842450faf6e6779b96aa8cb52d49dc42a06819 [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"
26#include "clz.h"
27
28#include "RenderEngine/RenderEngine.h"
29
30#include <gui/BufferItem.h>
31#include <gui/BufferQueue.h>
32#include <gui/LayerDebugInfo.h>
33#include <gui/Surface.h>
34
35#include <ui/DebugUtils.h>
36
37#include <utils/Errors.h>
38#include <utils/Log.h>
39#include <utils/NativeHandle.h>
40#include <utils/StopWatch.h>
41#include <utils/Trace.h>
42
43#include <cutils/compiler.h>
44#include <cutils/native_handle.h>
45#include <cutils/properties.h>
46
47#include <math.h>
48#include <stdlib.h>
49#include <mutex>
50
51namespace android {
52
53BufferLayer::BufferLayer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name,
54 uint32_t w, uint32_t h, uint32_t flags)
55 : Layer(flinger, client, name, w, h, flags),
Marissa Wallfd668622018-05-10 10:21:13 -070056 mTextureName(mFlinger->getNewTexture()),
David Sodman0c69cad2017-08-21 12:12:51 -070057 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
58 mBufferLatched(false),
David Sodman0c69cad2017-08-21 12:12:51 -070059 mRefreshPending(false) {
David Sodman0c69cad2017-08-21 12:12:51 -070060 ALOGV("Creating Layer %s", name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070061
David Sodman0c69cad2017-08-21 12:12:51 -070062 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
63
Marissa Wallfd668622018-05-10 10:21:13 -070064 mPremultipliedAlpha = !(flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070065
Marissa Wallfd668622018-05-10 10:21:13 -070066 mPotentialCursor = flags & ISurfaceComposerClient::eCursorWindow;
67 mProtectedByApp = flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070068
69 // drawing state & current state are identical
70 mDrawingState = mCurrentState;
71}
72
73BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070074 mFlinger->deleteTextureAsync(mTextureName);
75
David Sodman6f65f3e2017-11-03 14:28:09 -070076 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070077 ALOGE("Found stale hardware composer layers when destroying "
78 "surface flinger layer %s",
79 mName.string());
80 destroyAllHwcLayers();
81 }
David Sodman0c69cad2017-08-21 12:12:51 -070082}
83
David Sodmaneb085e02017-10-05 18:49:04 -070084void BufferLayer::useSurfaceDamage() {
85 if (mFlinger->mForceFullDamage) {
86 surfaceDamageRegion = Region::INVALID_REGION;
87 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070088 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070089 }
90}
91
92void BufferLayer::useEmptyDamage() {
93 surfaceDamageRegion.clear();
94}
95
Marissa Wallfd668622018-05-10 10:21:13 -070096bool BufferLayer::isOpaque(const Layer::State& s) const {
97 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
98 // layer's opaque flag.
99 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
100 return false;
101 }
102
103 // if the layer has the opaque flag, then we're always opaque,
104 // otherwise we use the current buffer's format.
105 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -0700106}
107
108bool BufferLayer::isVisible() const {
109 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800110 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700111}
112
113bool BufferLayer::isFixedSize() const {
114 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
115}
116
David Sodman0c69cad2017-08-21 12:12:51 -0700117static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800118 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
119 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
120 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 -0700121 mat4 tr;
122
123 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
124 tr = tr * rot90;
125 }
126 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
127 tr = tr * flipH;
128 }
129 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
130 tr = tr * flipV;
131 }
132 return inverse(tr);
133}
134
135/*
136 * onDraw will draw the current layer onto the presentable buffer
137 */
138void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
139 bool useIdentityTransform) const {
140 ATRACE_CALL();
141
David Sodmanca10ed22018-04-16 14:10:25 -0700142 CompositionInfo& compositionInfo = getBE().compositionInfo;
143
David Sodman0cf8f8d2017-12-20 18:19:45 -0800144 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700145 // the texture has not been created yet, this Layer has
146 // in fact never been drawn into. This happens frequently with
147 // SurfaceView because the WindowManager can't know when the client
148 // has drawn the first time.
149
150 // If there is nothing under us, we paint the screen in black, otherwise
151 // we just skip this update.
152
153 // figure out if there is something below us
154 Region under;
155 bool finished = false;
156 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
157 if (finished || layer == static_cast<BufferLayer const*>(this)) {
158 finished = true;
159 return;
160 }
161 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
162 });
163 // if not everything below us is covered, we plug the holes!
164 Region holes(clip.subtract(under));
165 if (!holes.isEmpty()) {
166 clearWithOpenGL(renderArea, 0, 0, 0, 1);
167 }
168 return;
169 }
170
171 // Bind the current buffer to the GL texture, and wait for it to be
172 // ready for us to draw into.
Marissa Wallfd668622018-05-10 10:21:13 -0700173 status_t err = bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700174 if (err != NO_ERROR) {
175 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
176 // Go ahead and draw the buffer anyway; no matter what we do the screen
177 // is probably going to have something visibly wrong.
178 }
179
180 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
181
Lloyd Pique144e1162017-12-20 16:44:52 -0800182 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700183
184 if (!blackOutLayer) {
185 // TODO: we could be more subtle with isFixedSize()
186 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
187
188 // Query the texture matrix given our current filtering mode.
189 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700190 setFilteringEnabled(useFiltering);
191 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700192
193 if (getTransformToDisplayInverse()) {
194 /*
195 * the code below applies the primary display's inverse transform to
196 * the texture transform
197 */
198 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
199 mat4 tr = inverseOrientation(transform);
200
201 /**
202 * TODO(b/36727915): This is basically a hack.
203 *
204 * Ensure that regardless of the parent transformation,
205 * this buffer is always transformed from native display
206 * orientation to display orientation. For example, in the case
207 * of a camera where the buffer remains in native orientation,
208 * we want the pixels to always be upright.
209 */
210 sp<Layer> p = mDrawingParent.promote();
211 if (p != nullptr) {
212 const auto parentTransform = p->getTransform();
213 tr = tr * inverseOrientation(parentTransform.getOrientation());
214 }
215
216 // and finally apply it to the original texture matrix
217 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
218 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
219 }
220
221 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800222 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700223 mTexture.setFiltering(useFiltering);
224 mTexture.setMatrix(textureMatrix);
David Sodmanca10ed22018-04-16 14:10:25 -0700225 compositionInfo.re.texture = mTexture;
David Sodman0c69cad2017-08-21 12:12:51 -0700226
227 engine.setupLayerTexturing(mTexture);
228 } else {
229 engine.setupLayerBlackedOut();
230 }
231 drawWithOpenGL(renderArea, useIdentityTransform);
232 engine.disableTexturing();
233}
234
David Sodmanca10ed22018-04-16 14:10:25 -0700235void BufferLayer::drawNow(const RenderArea& renderArea, bool useIdentityTransform) const {
236 CompositionInfo& compositionInfo = getBE().compositionInfo;
237 auto& engine(mFlinger->getRenderEngine());
238
239 draw(renderArea, useIdentityTransform);
240
241 engine.setupLayerTexturing(compositionInfo.re.texture);
242 engine.setupLayerBlending(compositionInfo.re.preMultipliedAlpha, compositionInfo.re.opaque,
243 false, compositionInfo.re.color);
244 engine.setSourceDataSpace(compositionInfo.hwc.dataspace);
245 engine.setSourceY410BT2020(compositionInfo.re.Y410BT2020);
246 engine.drawMesh(getBE().getMesh());
247 engine.disableBlending();
248 engine.disableTexturing();
249 engine.setSourceY410BT2020(false);
250}
251
Marissa Wallfd668622018-05-10 10:21:13 -0700252bool BufferLayer::isHdrY410() const {
253 // pixel format is HDR Y410 masquerading as RGBA_1010102
254 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
255 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
256 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700257}
258
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700259void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
David Sodman0c69cad2017-08-21 12:12:51 -0700260 // Apply this display's projection's viewport to the visible region
261 // before giving it to the HWC HAL.
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700262 const Transform& tr = display->getTransform();
263 const auto& viewport = display->getViewport();
David Sodman0c69cad2017-08-21 12:12:51 -0700264 Region visible = tr.transform(visibleRegion.intersect(viewport));
Dominik Laskowski7e045462018-05-30 13:02:02 -0700265 const auto displayId = display->getId();
Lloyd Pique074e8122018-07-26 12:57:23 -0700266 if (!hasHwcLayer(displayId)) {
267 ALOGE("[%s] failed to setPerFrameData: no HWC layer found (%d)",
268 mName.string(), displayId);
269 return;
270 }
271 auto& hwcInfo = getBE().mHwcLayers[displayId];
272 auto& hwcLayer = hwcInfo.layer;
273 auto error = hwcLayer->setVisibleRegion(visible);
274 if (error != HWC2::Error::None) {
275 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
276 to_string(error).c_str(), static_cast<int32_t>(error));
277 visible.dump(LOG_TAG);
278 }
David Sodman0c69cad2017-08-21 12:12:51 -0700279
Lloyd Pique074e8122018-07-26 12:57:23 -0700280 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
281 if (error != HWC2::Error::None) {
282 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
283 to_string(error).c_str(), static_cast<int32_t>(error));
284 surfaceDamageRegion.dump(LOG_TAG);
285 }
David Sodman0c69cad2017-08-21 12:12:51 -0700286
287 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800288 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700289 setCompositionType(displayId, HWC2::Composition::Sideband);
Lloyd Pique074e8122018-07-26 12:57:23 -0700290 ALOGV("[%s] Requesting Sideband composition", mName.string());
291 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
292 if (error != HWC2::Error::None) {
293 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
294 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
295 static_cast<int32_t>(error));
296 }
David Sodman0c69cad2017-08-21 12:12:51 -0700297 return;
298 }
299
David Sodman0c69cad2017-08-21 12:12:51 -0700300 // Device or Cursor layers
301 if (mPotentialCursor) {
302 ALOGV("[%s] Requesting Cursor composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700303 setCompositionType(displayId, HWC2::Composition::Cursor);
David Sodman0c69cad2017-08-21 12:12:51 -0700304 } else {
305 ALOGV("[%s] Requesting Device composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700306 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700307 }
308
Lloyd Pique074e8122018-07-26 12:57:23 -0700309 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
310 error = hwcLayer->setDataspace(mCurrentDataSpace);
311 if (error != HWC2::Error::None) {
312 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
313 to_string(error).c_str(), static_cast<int32_t>(error));
314 }
315
Marissa Wallfd668622018-05-10 10:21:13 -0700316 const HdrMetadata& metadata = getDrawingHdrMetadata();
Lloyd Pique074e8122018-07-26 12:57:23 -0700317 error = hwcLayer->setPerFrameMetadata(display->getSupportedPerFrameMetadata(), metadata);
318 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
319 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
320 to_string(error).c_str(), static_cast<int32_t>(error));
321 }
322
Marissa Wallfd668622018-05-10 10:21:13 -0700323 setHwcLayerBuffer(display);
David Sodman0c69cad2017-08-21 12:12:51 -0700324}
325
Marissa Wallfd668622018-05-10 10:21:13 -0700326bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
327 if (mBufferLatched) {
328 Mutex::Autolock lock(mFrameEventHistoryMutex);
329 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700330 }
Marissa Wallfd668622018-05-10 10:21:13 -0700331 mRefreshPending = false;
332 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700333}
334
Marissa Wallfd668622018-05-10 10:21:13 -0700335bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
336 const std::shared_ptr<FenceTime>& presentFence,
337 const CompositorTiming& compositorTiming) {
338 // mFrameLatencyNeeded is true when a new frame was latched for the
339 // composition.
340 if (!mFrameLatencyNeeded) return false;
341
342 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700343 {
Marissa Wallfd668622018-05-10 10:21:13 -0700344 Mutex::Autolock lock(mFrameEventHistoryMutex);
345 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
346 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700347 }
348
Marissa Wallfd668622018-05-10 10:21:13 -0700349 // Update mFrameTracker.
350 nsecs_t desiredPresentTime = getDesiredPresentTime();
351 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
352
353 const std::string layerName(getName().c_str());
354 mTimeStats.setDesiredTime(layerName, mCurrentFrameNumber, desiredPresentTime);
355
356 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
357 if (frameReadyFence->isValid()) {
358 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
359 } else {
360 // There was no fence for this frame, so assume that it was ready
361 // to be presented at the desired present time.
362 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700363 }
Marissa Wallfd668622018-05-10 10:21:13 -0700364
365 if (presentFence->isValid()) {
366 mTimeStats.setPresentFence(layerName, mCurrentFrameNumber, presentFence);
367 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
368 } else if (mFlinger->getHwComposer().isConnected(HWC_DISPLAY_PRIMARY)) {
369 // The HWC doesn't support present fences, so use the refresh
370 // timestamp instead.
371 const nsecs_t actualPresentTime =
372 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
373 mTimeStats.setPresentTime(layerName, mCurrentFrameNumber, actualPresentTime);
374 mFrameTracker.setActualPresentTime(actualPresentTime);
375 }
376
377 mFrameTracker.advanceFrame();
378 mFrameLatencyNeeded = false;
379 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700380}
381
Marissa Wallfd668622018-05-10 10:21:13 -0700382Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
383 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700384
Marissa Wallfd668622018-05-10 10:21:13 -0700385 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700386
Marissa Wallfd668622018-05-10 10:21:13 -0700387 if (sidebandStreamDirtyRegion) {
388 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700389 }
390
Marissa Wallfd668622018-05-10 10:21:13 -0700391 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700392
Marissa Wallfd668622018-05-10 10:21:13 -0700393 if (!hasReadyFrame()) {
394 return dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700395 }
David Sodman0c69cad2017-08-21 12:12:51 -0700396
Marissa Wallfd668622018-05-10 10:21:13 -0700397 // if we've already called updateTexImage() without going through
398 // a composition step, we have to skip this layer at this point
399 // because we cannot call updateTeximage() without a corresponding
400 // compositionComplete() call.
401 // we'll trigger an update in onPreComposition().
402 if (mRefreshPending) {
403 return dirtyRegion;
404 }
405
406 // If the head buffer's acquire fence hasn't signaled yet, return and
407 // try again later
408 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700409 mFlinger->signalLayerUpdate();
Marissa Wallfd668622018-05-10 10:21:13 -0700410 return dirtyRegion;
411 }
412
413 // Capture the old state of the layer for comparisons later
414 const State& s(getDrawingState());
415 const bool oldOpacity = isOpaque(s);
416 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
417
418 if (!allTransactionsSignaled()) {
419 mFlinger->signalLayerUpdate();
420 return dirtyRegion;
421 }
422
423 status_t err = updateTexImage(recomputeVisibleRegions, latchTime);
424 if (err != NO_ERROR) {
425 return dirtyRegion;
426 }
427
428 err = updateActiveBuffer();
429 if (err != NO_ERROR) {
430 return dirtyRegion;
431 }
432
433 mBufferLatched = true;
434
435 err = updateFrameNumber(latchTime);
436 if (err != NO_ERROR) {
437 return dirtyRegion;
438 }
439
440 mRefreshPending = true;
441 mFrameLatencyNeeded = true;
442 if (oldBuffer == nullptr) {
443 // the first time we receive a buffer, we need to trigger a
444 // geometry invalidation.
445 recomputeVisibleRegions = true;
446 }
447
448 ui::Dataspace dataSpace = getDrawingDataSpace();
449 // treat modern dataspaces as legacy dataspaces whenever possible, until
450 // we can trust the buffer producers
451 switch (dataSpace) {
452 case ui::Dataspace::V0_SRGB:
453 dataSpace = ui::Dataspace::SRGB;
454 break;
455 case ui::Dataspace::V0_SRGB_LINEAR:
456 dataSpace = ui::Dataspace::SRGB_LINEAR;
457 break;
458 case ui::Dataspace::V0_JFIF:
459 dataSpace = ui::Dataspace::JFIF;
460 break;
461 case ui::Dataspace::V0_BT601_625:
462 dataSpace = ui::Dataspace::BT601_625;
463 break;
464 case ui::Dataspace::V0_BT601_525:
465 dataSpace = ui::Dataspace::BT601_525;
466 break;
467 case ui::Dataspace::V0_BT709:
468 dataSpace = ui::Dataspace::BT709;
469 break;
470 default:
471 break;
472 }
473 mCurrentDataSpace = dataSpace;
474
475 Rect crop(getDrawingCrop());
476 const uint32_t transform(getDrawingTransform());
477 const uint32_t scalingMode(getDrawingScalingMode());
478 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
479 (scalingMode != mCurrentScalingMode)) {
480 mCurrentCrop = crop;
481 mCurrentTransform = transform;
482 mCurrentScalingMode = scalingMode;
483 recomputeVisibleRegions = true;
484 }
485
486 if (oldBuffer != nullptr) {
487 uint32_t bufWidth = mActiveBuffer->getWidth();
488 uint32_t bufHeight = mActiveBuffer->getHeight();
489 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
490 recomputeVisibleRegions = true;
491 }
492 }
493
494 if (oldOpacity != isOpaque(s)) {
495 recomputeVisibleRegions = true;
496 }
497
498 // Remove any sync points corresponding to the buffer which was just
499 // latched
500 {
501 Mutex::Autolock lock(mLocalSyncPointMutex);
502 auto point = mLocalSyncPoints.begin();
503 while (point != mLocalSyncPoints.end()) {
504 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
505 // This sync point must have been added since we started
506 // latching. Don't drop it yet.
507 ++point;
508 continue;
509 }
510
511 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
512 point = mLocalSyncPoints.erase(point);
513 } else {
514 ++point;
515 }
516 }
517 }
518
519 // FIXME: postedRegion should be dirty & bounds
520 // transform the dirty region to window-manager space
Marissa Wallf58c14b2018-07-24 10:50:43 -0700521 return getTransform().transform(Region(Rect(s.active_legacy.w, s.active_legacy.h)));
Marissa Wallfd668622018-05-10 10:21:13 -0700522}
523
524// transaction
525void BufferLayer::notifyAvailableFrames() {
526 auto headFrameNumber = getHeadFrameNumber();
527 bool headFenceSignaled = fenceHasSignaled();
528 Mutex::Autolock lock(mLocalSyncPointMutex);
529 for (auto& point : mLocalSyncPoints) {
530 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
531 point->setFrameAvailable();
532 }
David Sodman0c69cad2017-08-21 12:12:51 -0700533 }
534}
535
Marissa Wallfd668622018-05-10 10:21:13 -0700536bool BufferLayer::hasReadyFrame() const {
537 return hasDrawingBuffer() || getSidebandStreamChanged() || getAutoRefresh();
538}
539
540uint32_t BufferLayer::getEffectiveScalingMode() const {
541 if (mOverrideScalingMode >= 0) {
542 return mOverrideScalingMode;
543 }
544
545 return mCurrentScalingMode;
546}
547
548bool BufferLayer::isProtected() const {
549 const sp<GraphicBuffer>& buffer(mActiveBuffer);
550 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
551}
552
553bool BufferLayer::latchUnsignaledBuffers() {
554 static bool propertyLoaded = false;
555 static bool latch = false;
556 static std::mutex mutex;
557 std::lock_guard<std::mutex> lock(mutex);
558 if (!propertyLoaded) {
559 char value[PROPERTY_VALUE_MAX] = {};
560 property_get("debug.sf.latch_unsignaled", value, "0");
561 latch = atoi(value);
562 propertyLoaded = true;
563 }
564 return latch;
565}
566
567// h/w composer set-up
568bool BufferLayer::allTransactionsSignaled() {
569 auto headFrameNumber = getHeadFrameNumber();
570 bool matchingFramesFound = false;
571 bool allTransactionsApplied = true;
572 Mutex::Autolock lock(mLocalSyncPointMutex);
573
574 for (auto& point : mLocalSyncPoints) {
575 if (point->getFrameNumber() > headFrameNumber) {
576 break;
577 }
578 matchingFramesFound = true;
579
580 if (!point->frameIsAvailable()) {
581 // We haven't notified the remote layer that the frame for
582 // this point is available yet. Notify it now, and then
583 // abort this attempt to latch.
584 point->setFrameAvailable();
585 allTransactionsApplied = false;
586 break;
587 }
588
589 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
590 }
591 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700592}
593
594// As documented in libhardware header, formats in the range
595// 0x100 - 0x1FF are specific to the HAL implementation, and
596// are known to have no alpha channel
597// TODO: move definition for device-specific range into
598// hardware.h, instead of using hard-coded values here.
599#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
600
601bool BufferLayer::getOpacityForFormat(uint32_t format) {
602 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
603 return true;
604 }
605 switch (format) {
606 case HAL_PIXEL_FORMAT_RGBA_8888:
607 case HAL_PIXEL_FORMAT_BGRA_8888:
608 case HAL_PIXEL_FORMAT_RGBA_FP16:
609 case HAL_PIXEL_FORMAT_RGBA_1010102:
610 return false;
611 }
612 // in all other case, we have no blending (also for unknown formats)
613 return true;
614}
615
Marissa Wallfd668622018-05-10 10:21:13 -0700616bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
617 return mNeedsFiltering || renderArea.needsFiltering();
Chia-I Wu692e0832018-06-05 15:46:58 -0700618}
619
David Sodman41fdfc92017-11-06 16:09:56 -0800620void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700621 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700622 const State& s(getDrawingState());
623
David Sodman9eeae692017-11-02 10:53:32 -0700624 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700625
626 /*
627 * NOTE: the way we compute the texture coordinates here produces
628 * different results than when we take the HWC path -- in the later case
629 * the "source crop" is rounded to texel boundaries.
630 * This can produce significantly different results when the texture
631 * is scaled by a large amount.
632 *
633 * The GL code below is more logical (imho), and the difference with
634 * HWC is due to a limitation of the HWC API to integers -- a question
635 * is suspend is whether we should ignore this problem or revert to
636 * GL composition when a buffer scaling is applied (maybe with some
637 * minimal value)? Or, we could make GL behave like HWC -- but this feel
638 * like more of a hack.
639 */
Dan Stoza80d61162017-12-20 15:57:52 -0800640 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700641
642 Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800643 Rect win = bounds;
Marissa Wallf58c14b2018-07-24 10:50:43 -0700644 if (!s.finalCrop_legacy.isEmpty()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700645 win = t.transform(win);
Marissa Wallf58c14b2018-07-24 10:50:43 -0700646 if (!win.intersect(s.finalCrop_legacy, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700647 win.clear();
648 }
649 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800650 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700651 win.clear();
652 }
653 }
654
Marissa Wallf58c14b2018-07-24 10:50:43 -0700655 float left = float(win.left) / float(s.active_legacy.w);
656 float top = float(win.top) / float(s.active_legacy.h);
657 float right = float(win.right) / float(s.active_legacy.w);
658 float bottom = float(win.bottom) / float(s.active_legacy.h);
David Sodman0c69cad2017-08-21 12:12:51 -0700659
660 // TODO: we probably want to generate the texture coords with the mesh
661 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700662 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700663 texCoords[0] = vec2(left, 1.0f - top);
664 texCoords[1] = vec2(left, 1.0f - bottom);
665 texCoords[2] = vec2(right, 1.0f - bottom);
666 texCoords[3] = vec2(right, 1.0f - top);
667
bohu21566132018-03-27 14:36:34 -0700668 auto& engine(mFlinger->getRenderEngine());
669 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
670 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700671 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800672
Chia-I Wu692e0832018-06-05 15:46:58 -0700673 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700674 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800675 }
bohu21566132018-03-27 14:36:34 -0700676
677 engine.drawMesh(getBE().mMesh);
678 engine.disableBlending();
679
680 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700681}
682
David Sodman0c69cad2017-08-21 12:12:51 -0700683uint64_t BufferLayer::getHeadFrameNumber() const {
Marissa Wallfd668622018-05-10 10:21:13 -0700684 if (hasDrawingBuffer()) {
685 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700686 } else {
687 return mCurrentFrameNumber;
688 }
689}
690
David Sodman0c69cad2017-08-21 12:12:51 -0700691} // namespace android
692
693#if defined(__gl_h_)
694#error "don't include gl/gl.h in this file"
695#endif
696
697#if defined(__gl2_h_)
698#error "don't include gl2/gl2.h in this file"
699#endif