blob: d0ccabbe4ba9220b622fa1329cc97adbd20c08ff [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
52BufferLayer::BufferLayer(SurfaceFlinger* flinger, const sp<Client>& client, const String8& name,
53 uint32_t w, uint32_t h, uint32_t flags)
54 : Layer(flinger, client, name, w, h, flags),
Marissa Wallfd668622018-05-10 10:21:13 -070055 mTextureName(mFlinger->getNewTexture()),
David Sodman0c69cad2017-08-21 12:12:51 -070056 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
57 mBufferLatched(false),
David Sodman0c69cad2017-08-21 12:12:51 -070058 mRefreshPending(false) {
David Sodman0c69cad2017-08-21 12:12:51 -070059 ALOGV("Creating Layer %s", name.string());
David Sodman0c69cad2017-08-21 12:12:51 -070060
David Sodman0c69cad2017-08-21 12:12:51 -070061 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
62
Marissa Wallfd668622018-05-10 10:21:13 -070063 mPremultipliedAlpha = !(flags & ISurfaceComposerClient::eNonPremultiplied);
David Sodman0c69cad2017-08-21 12:12:51 -070064
Marissa Wallfd668622018-05-10 10:21:13 -070065 mPotentialCursor = flags & ISurfaceComposerClient::eCursorWindow;
66 mProtectedByApp = flags & ISurfaceComposerClient::eProtectedByApp;
David Sodman0c69cad2017-08-21 12:12:51 -070067
68 // drawing state & current state are identical
69 mDrawingState = mCurrentState;
70}
71
72BufferLayer::~BufferLayer() {
David Sodman0c69cad2017-08-21 12:12:51 -070073 mFlinger->deleteTextureAsync(mTextureName);
74
David Sodman6f65f3e2017-11-03 14:28:09 -070075 if (!getBE().mHwcLayers.empty()) {
David Sodman0c69cad2017-08-21 12:12:51 -070076 ALOGE("Found stale hardware composer layers when destroying "
77 "surface flinger layer %s",
78 mName.string());
79 destroyAllHwcLayers();
80 }
David Sodman0c69cad2017-08-21 12:12:51 -070081}
82
David Sodmaneb085e02017-10-05 18:49:04 -070083void BufferLayer::useSurfaceDamage() {
84 if (mFlinger->mForceFullDamage) {
85 surfaceDamageRegion = Region::INVALID_REGION;
86 } else {
Marissa Wallfd668622018-05-10 10:21:13 -070087 surfaceDamageRegion = getDrawingSurfaceDamage();
David Sodmaneb085e02017-10-05 18:49:04 -070088 }
89}
90
91void BufferLayer::useEmptyDamage() {
92 surfaceDamageRegion.clear();
93}
94
Marissa Wallfd668622018-05-10 10:21:13 -070095bool BufferLayer::isOpaque(const Layer::State& s) const {
96 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
97 // layer's opaque flag.
98 if ((getBE().compositionInfo.hwc.sidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
99 return false;
100 }
101
102 // if the layer has the opaque flag, then we're always opaque,
103 // otherwise we use the current buffer's format.
104 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || getOpacityForFormat(getPixelFormat());
David Sodman0c69cad2017-08-21 12:12:51 -0700105}
106
107bool BufferLayer::isVisible() const {
108 return !(isHiddenByPolicy()) && getAlpha() > 0.0f &&
David Sodman0cf8f8d2017-12-20 18:19:45 -0800109 (mActiveBuffer != nullptr || getBE().compositionInfo.hwc.sidebandStream != nullptr);
David Sodman0c69cad2017-08-21 12:12:51 -0700110}
111
112bool BufferLayer::isFixedSize() const {
113 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
114}
115
David Sodman0c69cad2017-08-21 12:12:51 -0700116static constexpr mat4 inverseOrientation(uint32_t transform) {
David Sodman41fdfc92017-11-06 16:09:56 -0800117 const mat4 flipH(-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1);
118 const mat4 flipV(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1);
119 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 -0700120 mat4 tr;
121
122 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
123 tr = tr * rot90;
124 }
125 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
126 tr = tr * flipH;
127 }
128 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
129 tr = tr * flipV;
130 }
131 return inverse(tr);
132}
133
134/*
135 * onDraw will draw the current layer onto the presentable buffer
136 */
137void BufferLayer::onDraw(const RenderArea& renderArea, const Region& clip,
Marissa Wall61c58622018-07-18 10:12:20 -0700138 bool useIdentityTransform) {
David Sodman0c69cad2017-08-21 12:12:51 -0700139 ATRACE_CALL();
140
David Sodmanca10ed22018-04-16 14:10:25 -0700141 CompositionInfo& compositionInfo = getBE().compositionInfo;
142
David Sodman0cf8f8d2017-12-20 18:19:45 -0800143 if (CC_UNLIKELY(mActiveBuffer == 0)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700144 // the texture has not been created yet, this Layer has
145 // in fact never been drawn into. This happens frequently with
146 // SurfaceView because the WindowManager can't know when the client
147 // has drawn the first time.
148
149 // If there is nothing under us, we paint the screen in black, otherwise
150 // we just skip this update.
151
152 // figure out if there is something below us
153 Region under;
154 bool finished = false;
155 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
156 if (finished || layer == static_cast<BufferLayer const*>(this)) {
157 finished = true;
158 return;
159 }
160 under.orSelf(renderArea.getTransform().transform(layer->visibleRegion));
161 });
162 // if not everything below us is covered, we plug the holes!
163 Region holes(clip.subtract(under));
164 if (!holes.isEmpty()) {
165 clearWithOpenGL(renderArea, 0, 0, 0, 1);
166 }
167 return;
168 }
169
170 // Bind the current buffer to the GL texture, and wait for it to be
171 // ready for us to draw into.
Marissa Wallfd668622018-05-10 10:21:13 -0700172 status_t err = bindTextureImage();
David Sodman0c69cad2017-08-21 12:12:51 -0700173 if (err != NO_ERROR) {
174 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
175 // Go ahead and draw the buffer anyway; no matter what we do the screen
176 // is probably going to have something visibly wrong.
177 }
178
179 bool blackOutLayer = isProtected() || (isSecure() && !renderArea.isSecure());
180
Lloyd Pique144e1162017-12-20 16:44:52 -0800181 auto& engine(mFlinger->getRenderEngine());
David Sodman0c69cad2017-08-21 12:12:51 -0700182
183 if (!blackOutLayer) {
184 // TODO: we could be more subtle with isFixedSize()
185 const bool useFiltering = getFiltering() || needsFiltering(renderArea) || isFixedSize();
186
187 // Query the texture matrix given our current filtering mode.
188 float textureMatrix[16];
Marissa Wallfd668622018-05-10 10:21:13 -0700189 setFilteringEnabled(useFiltering);
190 getDrawingTransformMatrix(textureMatrix);
David Sodman0c69cad2017-08-21 12:12:51 -0700191
192 if (getTransformToDisplayInverse()) {
193 /*
194 * the code below applies the primary display's inverse transform to
195 * the texture transform
196 */
197 uint32_t transform = DisplayDevice::getPrimaryDisplayOrientationTransform();
198 mat4 tr = inverseOrientation(transform);
199
200 /**
201 * TODO(b/36727915): This is basically a hack.
202 *
203 * Ensure that regardless of the parent transformation,
204 * this buffer is always transformed from native display
205 * orientation to display orientation. For example, in the case
206 * of a camera where the buffer remains in native orientation,
207 * we want the pixels to always be upright.
208 */
209 sp<Layer> p = mDrawingParent.promote();
210 if (p != nullptr) {
211 const auto parentTransform = p->getTransform();
212 tr = tr * inverseOrientation(parentTransform.getOrientation());
213 }
214
215 // and finally apply it to the original texture matrix
216 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
217 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
218 }
219
220 // Set things up for texturing.
David Sodman0cf8f8d2017-12-20 18:19:45 -0800221 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
David Sodman0c69cad2017-08-21 12:12:51 -0700222 mTexture.setFiltering(useFiltering);
223 mTexture.setMatrix(textureMatrix);
David Sodmanca10ed22018-04-16 14:10:25 -0700224 compositionInfo.re.texture = mTexture;
David Sodman0c69cad2017-08-21 12:12:51 -0700225
226 engine.setupLayerTexturing(mTexture);
227 } else {
228 engine.setupLayerBlackedOut();
229 }
230 drawWithOpenGL(renderArea, useIdentityTransform);
231 engine.disableTexturing();
232}
233
Marissa Wall61c58622018-07-18 10:12:20 -0700234void BufferLayer::drawNow(const RenderArea& renderArea, bool useIdentityTransform) {
David Sodmanca10ed22018-04-16 14:10:25 -0700235 CompositionInfo& compositionInfo = getBE().compositionInfo;
236 auto& engine(mFlinger->getRenderEngine());
237
238 draw(renderArea, useIdentityTransform);
239
240 engine.setupLayerTexturing(compositionInfo.re.texture);
241 engine.setupLayerBlending(compositionInfo.re.preMultipliedAlpha, compositionInfo.re.opaque,
242 false, compositionInfo.re.color);
243 engine.setSourceDataSpace(compositionInfo.hwc.dataspace);
244 engine.setSourceY410BT2020(compositionInfo.re.Y410BT2020);
245 engine.drawMesh(getBE().getMesh());
246 engine.disableBlending();
247 engine.disableTexturing();
248 engine.setSourceY410BT2020(false);
249}
250
Marissa Wallfd668622018-05-10 10:21:13 -0700251bool BufferLayer::isHdrY410() const {
252 // pixel format is HDR Y410 masquerading as RGBA_1010102
253 return (mCurrentDataSpace == ui::Dataspace::BT2020_ITU_PQ &&
254 getDrawingApi() == NATIVE_WINDOW_API_MEDIA &&
255 getBE().compositionInfo.mBuffer->getPixelFormat() == HAL_PIXEL_FORMAT_RGBA_1010102);
David Sodmaneb085e02017-10-05 18:49:04 -0700256}
257
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700258void BufferLayer::setPerFrameData(const sp<const DisplayDevice>& display) {
David Sodman0c69cad2017-08-21 12:12:51 -0700259 // Apply this display's projection's viewport to the visible region
260 // before giving it to the HWC HAL.
Peiyong Linefefaac2018-08-17 12:27:51 -0700261 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700262 const auto& viewport = display->getViewport();
David Sodman0c69cad2017-08-21 12:12:51 -0700263 Region visible = tr.transform(visibleRegion.intersect(viewport));
Dominik Laskowski7e045462018-05-30 13:02:02 -0700264 const auto displayId = display->getId();
Lloyd Pique074e8122018-07-26 12:57:23 -0700265 if (!hasHwcLayer(displayId)) {
266 ALOGE("[%s] failed to setPerFrameData: no HWC layer found (%d)",
267 mName.string(), displayId);
268 return;
269 }
270 auto& hwcInfo = getBE().mHwcLayers[displayId];
271 auto& hwcLayer = hwcInfo.layer;
272 auto error = hwcLayer->setVisibleRegion(visible);
273 if (error != HWC2::Error::None) {
274 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
275 to_string(error).c_str(), static_cast<int32_t>(error));
276 visible.dump(LOG_TAG);
277 }
David Sodmanba340492018-08-05 21:51:33 -0700278 getBE().compositionInfo.hwc.visibleRegion = visible;
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 Sodmanba340492018-08-05 21:51:33 -0700286 getBE().compositionInfo.hwc.surfaceDamage = surfaceDamageRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700287
288 // Sideband layers
David Sodman0cc69182017-11-17 12:12:07 -0800289 if (getBE().compositionInfo.hwc.sidebandStream.get()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -0700290 setCompositionType(displayId, HWC2::Composition::Sideband);
Lloyd Pique074e8122018-07-26 12:57:23 -0700291 ALOGV("[%s] Requesting Sideband composition", mName.string());
292 error = hwcLayer->setSidebandStream(getBE().compositionInfo.hwc.sidebandStream->handle());
293 if (error != HWC2::Error::None) {
294 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", mName.string(),
295 getBE().compositionInfo.hwc.sidebandStream->handle(), to_string(error).c_str(),
296 static_cast<int32_t>(error));
297 }
David Sodmanba340492018-08-05 21:51:33 -0700298 getBE().compositionInfo.compositionType = HWC2::Composition::Sideband;
David Sodman0c69cad2017-08-21 12:12:51 -0700299 return;
300 }
301
David Sodman0c69cad2017-08-21 12:12:51 -0700302 // Device or Cursor layers
303 if (mPotentialCursor) {
304 ALOGV("[%s] Requesting Cursor composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700305 setCompositionType(displayId, HWC2::Composition::Cursor);
David Sodman0c69cad2017-08-21 12:12:51 -0700306 } else {
307 ALOGV("[%s] Requesting Device composition", mName.string());
Dominik Laskowski7e045462018-05-30 13:02:02 -0700308 setCompositionType(displayId, HWC2::Composition::Device);
David Sodman0c69cad2017-08-21 12:12:51 -0700309 }
310
Lloyd Pique074e8122018-07-26 12:57:23 -0700311 ALOGV("setPerFrameData: dataspace = %d", mCurrentDataSpace);
312 error = hwcLayer->setDataspace(mCurrentDataSpace);
313 if (error != HWC2::Error::None) {
314 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), mCurrentDataSpace,
315 to_string(error).c_str(), static_cast<int32_t>(error));
316 }
317
Marissa Wallfd668622018-05-10 10:21:13 -0700318 const HdrMetadata& metadata = getDrawingHdrMetadata();
Lloyd Pique074e8122018-07-26 12:57:23 -0700319 error = hwcLayer->setPerFrameMetadata(display->getSupportedPerFrameMetadata(), metadata);
320 if (error != HWC2::Error::None && error != HWC2::Error::Unsupported) {
321 ALOGE("[%s] Failed to set hdrMetadata: %s (%d)", mName.string(),
322 to_string(error).c_str(), static_cast<int32_t>(error));
323 }
David Sodmanba340492018-08-05 21:51:33 -0700324 getBE().compositionInfo.hwc.dataspace = mCurrentDataSpace;
325 getBE().compositionInfo.hwc.hdrMetadata = getDrawingHdrMetadata();
326 getBE().compositionInfo.hwc.supportedPerFrameMetadata = display->getSupportedPerFrameMetadata();
Lloyd Pique074e8122018-07-26 12:57:23 -0700327
Marissa Wallfd668622018-05-10 10:21:13 -0700328 setHwcLayerBuffer(display);
David Sodman0c69cad2017-08-21 12:12:51 -0700329}
330
Marissa Wallfd668622018-05-10 10:21:13 -0700331bool BufferLayer::onPreComposition(nsecs_t refreshStartTime) {
332 if (mBufferLatched) {
333 Mutex::Autolock lock(mFrameEventHistoryMutex);
334 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
David Sodman0c69cad2017-08-21 12:12:51 -0700335 }
Marissa Wallfd668622018-05-10 10:21:13 -0700336 mRefreshPending = false;
337 return hasReadyFrame();
David Sodman0c69cad2017-08-21 12:12:51 -0700338}
339
Marissa Wallfd668622018-05-10 10:21:13 -0700340bool BufferLayer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
341 const std::shared_ptr<FenceTime>& presentFence,
342 const CompositorTiming& compositorTiming) {
343 // mFrameLatencyNeeded is true when a new frame was latched for the
344 // composition.
345 if (!mFrameLatencyNeeded) return false;
346
347 // Update mFrameEventHistory.
Dan Stoza436ccf32018-06-21 12:10:12 -0700348 {
Marissa Wallfd668622018-05-10 10:21:13 -0700349 Mutex::Autolock lock(mFrameEventHistoryMutex);
350 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, glDoneFence, presentFence,
351 compositorTiming);
David Sodman0c69cad2017-08-21 12:12:51 -0700352 }
353
Marissa Wallfd668622018-05-10 10:21:13 -0700354 // Update mFrameTracker.
355 nsecs_t desiredPresentTime = getDesiredPresentTime();
356 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
357
358 const std::string layerName(getName().c_str());
359 mTimeStats.setDesiredTime(layerName, mCurrentFrameNumber, desiredPresentTime);
360
361 std::shared_ptr<FenceTime> frameReadyFence = getCurrentFenceTime();
362 if (frameReadyFence->isValid()) {
363 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
364 } else {
365 // There was no fence for this frame, so assume that it was ready
366 // to be presented at the desired present time.
367 mFrameTracker.setFrameReadyTime(desiredPresentTime);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700368 }
Marissa Wallfd668622018-05-10 10:21:13 -0700369
370 if (presentFence->isValid()) {
371 mTimeStats.setPresentFence(layerName, mCurrentFrameNumber, presentFence);
372 mFrameTracker.setActualPresentFence(std::shared_ptr<FenceTime>(presentFence));
373 } else if (mFlinger->getHwComposer().isConnected(HWC_DISPLAY_PRIMARY)) {
374 // The HWC doesn't support present fences, so use the refresh
375 // timestamp instead.
376 const nsecs_t actualPresentTime =
377 mFlinger->getHwComposer().getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
378 mTimeStats.setPresentTime(layerName, mCurrentFrameNumber, actualPresentTime);
379 mFrameTracker.setActualPresentTime(actualPresentTime);
380 }
381
382 mFrameTracker.advanceFrame();
383 mFrameLatencyNeeded = false;
384 return true;
David Sodman0c69cad2017-08-21 12:12:51 -0700385}
386
Marissa Wallfd668622018-05-10 10:21:13 -0700387Region BufferLayer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) {
388 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700389
Marissa Wallfd668622018-05-10 10:21:13 -0700390 std::optional<Region> sidebandStreamDirtyRegion = latchSidebandStream(recomputeVisibleRegions);
David Sodman0c69cad2017-08-21 12:12:51 -0700391
Marissa Wallfd668622018-05-10 10:21:13 -0700392 if (sidebandStreamDirtyRegion) {
393 return *sidebandStreamDirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700394 }
395
Marissa Wallfd668622018-05-10 10:21:13 -0700396 Region dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700397
Marissa Wallfd668622018-05-10 10:21:13 -0700398 if (!hasReadyFrame()) {
399 return dirtyRegion;
David Sodman0c69cad2017-08-21 12:12:51 -0700400 }
David Sodman0c69cad2017-08-21 12:12:51 -0700401
Marissa Wallfd668622018-05-10 10:21:13 -0700402 // if we've already called updateTexImage() without going through
403 // a composition step, we have to skip this layer at this point
404 // because we cannot call updateTeximage() without a corresponding
405 // compositionComplete() call.
406 // we'll trigger an update in onPreComposition().
407 if (mRefreshPending) {
408 return dirtyRegion;
409 }
410
411 // If the head buffer's acquire fence hasn't signaled yet, return and
412 // try again later
413 if (!fenceHasSignaled()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700414 mFlinger->signalLayerUpdate();
Marissa Wallfd668622018-05-10 10:21:13 -0700415 return dirtyRegion;
416 }
417
418 // Capture the old state of the layer for comparisons later
419 const State& s(getDrawingState());
420 const bool oldOpacity = isOpaque(s);
421 sp<GraphicBuffer> oldBuffer = mActiveBuffer;
422
423 if (!allTransactionsSignaled()) {
424 mFlinger->signalLayerUpdate();
425 return dirtyRegion;
426 }
427
428 status_t err = updateTexImage(recomputeVisibleRegions, latchTime);
429 if (err != NO_ERROR) {
430 return dirtyRegion;
431 }
432
433 err = updateActiveBuffer();
434 if (err != NO_ERROR) {
435 return dirtyRegion;
436 }
437
438 mBufferLatched = true;
439
440 err = updateFrameNumber(latchTime);
441 if (err != NO_ERROR) {
442 return dirtyRegion;
443 }
444
445 mRefreshPending = true;
446 mFrameLatencyNeeded = true;
447 if (oldBuffer == nullptr) {
448 // the first time we receive a buffer, we need to trigger a
449 // geometry invalidation.
450 recomputeVisibleRegions = true;
451 }
452
453 ui::Dataspace dataSpace = getDrawingDataSpace();
454 // treat modern dataspaces as legacy dataspaces whenever possible, until
455 // we can trust the buffer producers
456 switch (dataSpace) {
457 case ui::Dataspace::V0_SRGB:
458 dataSpace = ui::Dataspace::SRGB;
459 break;
460 case ui::Dataspace::V0_SRGB_LINEAR:
461 dataSpace = ui::Dataspace::SRGB_LINEAR;
462 break;
463 case ui::Dataspace::V0_JFIF:
464 dataSpace = ui::Dataspace::JFIF;
465 break;
466 case ui::Dataspace::V0_BT601_625:
467 dataSpace = ui::Dataspace::BT601_625;
468 break;
469 case ui::Dataspace::V0_BT601_525:
470 dataSpace = ui::Dataspace::BT601_525;
471 break;
472 case ui::Dataspace::V0_BT709:
473 dataSpace = ui::Dataspace::BT709;
474 break;
475 default:
476 break;
477 }
478 mCurrentDataSpace = dataSpace;
479
480 Rect crop(getDrawingCrop());
481 const uint32_t transform(getDrawingTransform());
482 const uint32_t scalingMode(getDrawingScalingMode());
483 if ((crop != mCurrentCrop) || (transform != mCurrentTransform) ||
484 (scalingMode != mCurrentScalingMode)) {
485 mCurrentCrop = crop;
486 mCurrentTransform = transform;
487 mCurrentScalingMode = scalingMode;
488 recomputeVisibleRegions = true;
489 }
490
491 if (oldBuffer != nullptr) {
492 uint32_t bufWidth = mActiveBuffer->getWidth();
493 uint32_t bufHeight = mActiveBuffer->getHeight();
494 if (bufWidth != uint32_t(oldBuffer->width) || bufHeight != uint32_t(oldBuffer->height)) {
495 recomputeVisibleRegions = true;
496 }
497 }
498
499 if (oldOpacity != isOpaque(s)) {
500 recomputeVisibleRegions = true;
501 }
502
503 // Remove any sync points corresponding to the buffer which was just
504 // latched
505 {
506 Mutex::Autolock lock(mLocalSyncPointMutex);
507 auto point = mLocalSyncPoints.begin();
508 while (point != mLocalSyncPoints.end()) {
509 if (!(*point)->frameIsAvailable() || !(*point)->transactionIsApplied()) {
510 // This sync point must have been added since we started
511 // latching. Don't drop it yet.
512 ++point;
513 continue;
514 }
515
516 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
517 point = mLocalSyncPoints.erase(point);
518 } else {
519 ++point;
520 }
521 }
522 }
523
524 // FIXME: postedRegion should be dirty & bounds
525 // transform the dirty region to window-manager space
Marissa Wall61c58622018-07-18 10:12:20 -0700526 return getTransform().transform(Region(Rect(getActiveWidth(s), getActiveHeight(s))));
Marissa Wallfd668622018-05-10 10:21:13 -0700527}
528
529// transaction
530void BufferLayer::notifyAvailableFrames() {
531 auto headFrameNumber = getHeadFrameNumber();
532 bool headFenceSignaled = fenceHasSignaled();
533 Mutex::Autolock lock(mLocalSyncPointMutex);
534 for (auto& point : mLocalSyncPoints) {
535 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
536 point->setFrameAvailable();
537 }
David Sodman0c69cad2017-08-21 12:12:51 -0700538 }
539}
540
Marissa Wallfd668622018-05-10 10:21:13 -0700541bool BufferLayer::hasReadyFrame() const {
542 return hasDrawingBuffer() || getSidebandStreamChanged() || getAutoRefresh();
543}
544
545uint32_t BufferLayer::getEffectiveScalingMode() const {
546 if (mOverrideScalingMode >= 0) {
547 return mOverrideScalingMode;
548 }
549
550 return mCurrentScalingMode;
551}
552
553bool BufferLayer::isProtected() const {
554 const sp<GraphicBuffer>& buffer(mActiveBuffer);
555 return (buffer != 0) && (buffer->getUsage() & GRALLOC_USAGE_PROTECTED);
556}
557
558bool BufferLayer::latchUnsignaledBuffers() {
559 static bool propertyLoaded = false;
560 static bool latch = false;
561 static std::mutex mutex;
562 std::lock_guard<std::mutex> lock(mutex);
563 if (!propertyLoaded) {
564 char value[PROPERTY_VALUE_MAX] = {};
565 property_get("debug.sf.latch_unsignaled", value, "0");
566 latch = atoi(value);
567 propertyLoaded = true;
568 }
569 return latch;
570}
571
572// h/w composer set-up
573bool BufferLayer::allTransactionsSignaled() {
574 auto headFrameNumber = getHeadFrameNumber();
575 bool matchingFramesFound = false;
576 bool allTransactionsApplied = true;
577 Mutex::Autolock lock(mLocalSyncPointMutex);
578
579 for (auto& point : mLocalSyncPoints) {
580 if (point->getFrameNumber() > headFrameNumber) {
581 break;
582 }
583 matchingFramesFound = true;
584
585 if (!point->frameIsAvailable()) {
586 // We haven't notified the remote layer that the frame for
587 // this point is available yet. Notify it now, and then
588 // abort this attempt to latch.
589 point->setFrameAvailable();
590 allTransactionsApplied = false;
591 break;
592 }
593
594 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
595 }
596 return !matchingFramesFound || allTransactionsApplied;
David Sodman0c69cad2017-08-21 12:12:51 -0700597}
598
599// As documented in libhardware header, formats in the range
600// 0x100 - 0x1FF are specific to the HAL implementation, and
601// are known to have no alpha channel
602// TODO: move definition for device-specific range into
603// hardware.h, instead of using hard-coded values here.
604#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
605
606bool BufferLayer::getOpacityForFormat(uint32_t format) {
607 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
608 return true;
609 }
610 switch (format) {
611 case HAL_PIXEL_FORMAT_RGBA_8888:
612 case HAL_PIXEL_FORMAT_BGRA_8888:
613 case HAL_PIXEL_FORMAT_RGBA_FP16:
614 case HAL_PIXEL_FORMAT_RGBA_1010102:
615 return false;
616 }
617 // in all other case, we have no blending (also for unknown formats)
618 return true;
619}
620
Marissa Wallfd668622018-05-10 10:21:13 -0700621bool BufferLayer::needsFiltering(const RenderArea& renderArea) const {
622 return mNeedsFiltering || renderArea.needsFiltering();
Chia-I Wu692e0832018-06-05 15:46:58 -0700623}
624
David Sodman41fdfc92017-11-06 16:09:56 -0800625void BufferLayer::drawWithOpenGL(const RenderArea& renderArea, bool useIdentityTransform) const {
Dan Stoza84d619e2018-03-28 17:07:36 -0700626 ATRACE_CALL();
David Sodman0c69cad2017-08-21 12:12:51 -0700627 const State& s(getDrawingState());
628
David Sodman9eeae692017-11-02 10:53:32 -0700629 computeGeometry(renderArea, getBE().mMesh, useIdentityTransform);
David Sodman0c69cad2017-08-21 12:12:51 -0700630
631 /*
632 * NOTE: the way we compute the texture coordinates here produces
633 * different results than when we take the HWC path -- in the later case
634 * the "source crop" is rounded to texel boundaries.
635 * This can produce significantly different results when the texture
636 * is scaled by a large amount.
637 *
638 * The GL code below is more logical (imho), and the difference with
639 * HWC is due to a limitation of the HWC API to integers -- a question
640 * is suspend is whether we should ignore this problem or revert to
641 * GL composition when a buffer scaling is applied (maybe with some
642 * minimal value)? Or, we could make GL behave like HWC -- but this feel
643 * like more of a hack.
644 */
Dan Stoza80d61162017-12-20 15:57:52 -0800645 const Rect bounds{computeBounds()}; // Rounds from FloatRect
David Sodman0c69cad2017-08-21 12:12:51 -0700646
Peiyong Linefefaac2018-08-17 12:27:51 -0700647 ui::Transform t = getTransform();
Dan Stoza80d61162017-12-20 15:57:52 -0800648 Rect win = bounds;
Marissa Wall61c58622018-07-18 10:12:20 -0700649 Rect finalCrop = getFinalCrop(s);
650 if (!finalCrop.isEmpty()) {
David Sodman0c69cad2017-08-21 12:12:51 -0700651 win = t.transform(win);
Marissa Wall61c58622018-07-18 10:12:20 -0700652 if (!win.intersect(finalCrop, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700653 win.clear();
654 }
655 win = t.inverse().transform(win);
Dan Stoza80d61162017-12-20 15:57:52 -0800656 if (!win.intersect(bounds, &win)) {
David Sodman0c69cad2017-08-21 12:12:51 -0700657 win.clear();
658 }
659 }
660
Marissa Wall61c58622018-07-18 10:12:20 -0700661 float left = float(win.left) / float(getActiveWidth(s));
662 float top = float(win.top) / float(getActiveHeight(s));
663 float right = float(win.right) / float(getActiveWidth(s));
664 float bottom = float(win.bottom) / float(getActiveHeight(s));
David Sodman0c69cad2017-08-21 12:12:51 -0700665
666 // TODO: we probably want to generate the texture coords with the mesh
667 // here we assume that we only have 4 vertices
David Sodman9eeae692017-11-02 10:53:32 -0700668 Mesh::VertexArray<vec2> texCoords(getBE().mMesh.getTexCoordArray<vec2>());
David Sodman0c69cad2017-08-21 12:12:51 -0700669 texCoords[0] = vec2(left, 1.0f - top);
670 texCoords[1] = vec2(left, 1.0f - bottom);
671 texCoords[2] = vec2(right, 1.0f - bottom);
672 texCoords[3] = vec2(right, 1.0f - top);
673
bohu21566132018-03-27 14:36:34 -0700674 auto& engine(mFlinger->getRenderEngine());
675 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), false /* disableTexture */,
676 getColor());
Chia-I Wu01591c92018-05-22 12:03:00 -0700677 engine.setSourceDataSpace(mCurrentDataSpace);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800678
Chia-I Wu692e0832018-06-05 15:46:58 -0700679 if (isHdrY410()) {
bohu21566132018-03-27 14:36:34 -0700680 engine.setSourceY410BT2020(true);
Chia-I Wu5c6e4632018-01-11 08:54:38 -0800681 }
bohu21566132018-03-27 14:36:34 -0700682
683 engine.drawMesh(getBE().mMesh);
684 engine.disableBlending();
685
686 engine.setSourceY410BT2020(false);
David Sodman0c69cad2017-08-21 12:12:51 -0700687}
688
David Sodman0c69cad2017-08-21 12:12:51 -0700689uint64_t BufferLayer::getHeadFrameNumber() const {
Marissa Wallfd668622018-05-10 10:21:13 -0700690 if (hasDrawingBuffer()) {
691 return getFrameNumber();
David Sodman0c69cad2017-08-21 12:12:51 -0700692 } else {
693 return mCurrentFrameNumber;
694 }
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