2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 //#define LOG_NDEBUG 0
19 #define LOG_TAG "Layer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
24 #include <sys/types.h>
27 #include <cutils/compiler.h>
28 #include <cutils/native_handle.h>
29 #include <cutils/properties.h>
31 #include <utils/Errors.h>
32 #include <utils/Log.h>
33 #include <utils/NativeHandle.h>
34 #include <utils/StopWatch.h>
35 #include <utils/Trace.h>
37 #include <ui/DebugUtils.h>
38 #include <ui/GraphicBuffer.h>
39 #include <ui/PixelFormat.h>
41 #include <gui/BufferItem.h>
42 #include <gui/BufferQueue.h>
43 #include <gui/Surface.h>
46 #include "Colorizer.h"
47 #include "DisplayDevice.h"
49 #include "LayerRejecter.h"
50 #include "MonitoredProducer.h"
51 #include "SurfaceFlinger.h"
53 #include "DisplayHardware/HWComposer.h"
55 #include "RenderEngine/RenderEngine.h"
59 #define DEBUG_RESIZE 0
63 // ---------------------------------------------------------------------------
65 int32_t Layer::sSequence = 1;
67 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
68 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
69 : contentDirty(false),
70 sequence(uint32_t(android_atomic_inc(&sSequence))),
73 mPremultipliedAlpha(true),
75 mFormat(PIXEL_FORMAT_NONE),
80 mSidebandStreamChanged(false),
81 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT),
83 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
84 mOverrideScalingMode(-1),
85 mCurrentOpacity(true),
86 mBufferLatched(false),
87 mCurrentFrameNumber(0),
88 mPreviousFrameNumber(0),
89 mRefreshPending(false),
90 mFrameLatencyNeeded(false),
92 mNeedsFiltering(false),
93 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
95 mIsGlesComposition(false),
97 mProtectedByApp(false),
100 mPotentialCursor(false),
102 mQueueItemCondition(),
104 mLastFrameNumberReceived(0),
105 mUpdateTexImageFailed(false),
107 mFreezeGeometryUpdates(false)
110 ALOGV("Creating Layer %s", name.string());
113 mCurrentCrop.makeInvalid();
114 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
115 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
117 uint32_t layerFlags = 0;
118 if (flags & ISurfaceComposerClient::eHidden)
119 layerFlags |= layer_state_t::eLayerHidden;
120 if (flags & ISurfaceComposerClient::eOpaque)
121 layerFlags |= layer_state_t::eLayerOpaque;
122 if (flags & ISurfaceComposerClient::eSecure)
123 layerFlags |= layer_state_t::eLayerSecure;
125 if (flags & ISurfaceComposerClient::eNonPremultiplied)
126 mPremultipliedAlpha = false;
129 mTransactionName = String8("TX - ") + mName;
131 mCurrentState.active.w = w;
132 mCurrentState.active.h = h;
133 mCurrentState.active.transform.set(0, 0);
134 mCurrentState.crop.makeInvalid();
135 mCurrentState.finalCrop.makeInvalid();
136 mCurrentState.requestedFinalCrop = mCurrentState.finalCrop;
137 mCurrentState.requestedCrop = mCurrentState.crop;
140 mCurrentState.alpha = 1.0f;
142 mCurrentState.alpha = 0xFF;
144 mCurrentState.layerStack = 0;
145 mCurrentState.flags = layerFlags;
146 mCurrentState.sequence = 0;
147 mCurrentState.requested = mCurrentState.active;
148 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN;
149 mCurrentState.appId = 0;
150 mCurrentState.type = 0;
152 // drawing state & current state are identical
153 mDrawingState = mCurrentState;
156 const auto& hwc = flinger->getHwComposer();
157 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
158 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
160 nsecs_t displayPeriod =
161 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
163 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
165 CompositorTiming compositorTiming;
166 flinger->getCompositorTiming(&compositorTiming);
167 mFrameEventHistory.initializeCompositorTiming(compositorTiming);
170 void Layer::onFirstRef() {
171 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
172 sp<IGraphicBufferProducer> producer;
173 sp<IGraphicBufferConsumer> consumer;
174 BufferQueue::createBufferQueue(&producer, &consumer, true);
175 mProducer = new MonitoredProducer(producer, mFlinger, this);
176 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this);
177 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
178 mSurfaceFlingerConsumer->setContentsChangedListener(this);
179 mSurfaceFlingerConsumer->setName(mName);
181 if (mFlinger->isLayerTripleBufferingDisabled()) {
182 mProducer->setMaxDequeuedBufferCount(2);
185 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
186 updateTransformHint(hw);
190 sp<Client> c(mClientRef.promote());
192 c->detachLayer(this);
195 for (auto& point : mRemoteSyncPoints) {
196 point->setTransactionApplied();
198 for (auto& point : mLocalSyncPoints) {
199 point->setFrameAvailable();
201 mFlinger->deleteTextureAsync(mTextureName);
202 mFrameTracker.logAndResetStats(mName);
205 if (!mHwcLayers.empty()) {
206 ALOGE("Found stale hardware composer layers when destroying "
207 "surface flinger layer %s", mName.string());
208 destroyAllHwcLayers();
213 // ---------------------------------------------------------------------------
215 // ---------------------------------------------------------------------------
218 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
219 if (mHwcLayers.empty()) {
222 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
225 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
226 HWComposer::HWCLayerInterface* layer) {
228 layer->onDisplayed();
229 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
234 void Layer::onFrameAvailable(const BufferItem& item) {
235 // Add this buffer from our internal queue tracker
237 Mutex::Autolock lock(mQueueItemLock);
238 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
239 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
240 // Reset the frame number tracker when we receive the first buffer after
241 // a frame number reset
242 if (item.mFrameNumber == 1) {
243 mLastFrameNumberReceived = 0;
246 // Ensure that callbacks are handled in order
247 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
248 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
250 if (result != NO_ERROR) {
251 ALOGE("[%s] Timed out waiting on callback", mName.string());
255 mQueueItems.push_back(item);
256 android_atomic_inc(&mQueuedFrames);
258 // Wake up any pending callbacks
259 mLastFrameNumberReceived = item.mFrameNumber;
260 mQueueItemCondition.broadcast();
263 mFlinger->signalLayerUpdate();
266 void Layer::onFrameReplaced(const BufferItem& item) {
268 Mutex::Autolock lock(mQueueItemLock);
270 // Ensure that callbacks are handled in order
271 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
272 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
274 if (result != NO_ERROR) {
275 ALOGE("[%s] Timed out waiting on callback", mName.string());
279 if (mQueueItems.empty()) {
280 ALOGE("Can't replace a frame on an empty queue");
283 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
285 // Wake up any pending callbacks
286 mLastFrameNumberReceived = item.mFrameNumber;
287 mQueueItemCondition.broadcast();
291 void Layer::onSidebandStreamChanged() {
292 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
293 // mSidebandStreamChanged was false
294 mFlinger->signalLayerUpdate();
298 void Layer::onRemovedFromCurrentState() {
299 // the layer is removed from SF mCurrentState to mLayersPendingRemoval
301 if (mCurrentState.zOrderRelativeOf != nullptr) {
302 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
303 if (strongRelative != nullptr) {
304 strongRelative->removeZOrderRelative(this);
305 mFlinger->setTransactionFlags(eTraversalNeeded);
307 mCurrentState.zOrderRelativeOf = nullptr;
310 for (const auto& child : mCurrentChildren) {
311 child->onRemovedFromCurrentState();
315 void Layer::onRemoved() {
316 // the layer is removed from SF mLayersPendingRemoval
318 mSurfaceFlingerConsumer->abandon();
320 destroyAllHwcLayers();
323 for (const auto& child : mCurrentChildren) {
328 // ---------------------------------------------------------------------------
330 // ---------------------------------------------------------------------------
332 const String8& Layer::getName() const {
336 status_t Layer::setBuffers( uint32_t w, uint32_t h,
337 PixelFormat format, uint32_t flags)
339 uint32_t const maxSurfaceDims = min(
340 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
342 // never allow a surface larger than what our underlying GL implementation
344 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
345 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
351 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
352 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
353 mCurrentOpacity = getOpacityForFormat(format);
355 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
356 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
357 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
362 sp<IBinder> Layer::getHandle() {
363 Mutex::Autolock _l(mLock);
365 LOG_ALWAYS_FATAL_IF(mHasSurface,
366 "Layer::getHandle() has already been called");
370 return new Handle(mFlinger, this);
373 sp<IGraphicBufferProducer> Layer::getProducer() const {
377 // ---------------------------------------------------------------------------
378 // h/w composer set-up
379 // ---------------------------------------------------------------------------
382 bool Layer::createHwcLayer(HWComposer* hwc, int32_t hwcId) {
383 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
384 "Already have a layer for hwcId %d", hwcId);
385 HWC2::Layer* layer = hwc->createLayer(hwcId);
389 HWCInfo& hwcInfo = mHwcLayers[hwcId];
391 hwcInfo.layer = layer;
392 layer->setLayerDestroyedListener(
393 [this, hwcId] (HWC2::Layer* /*layer*/){mHwcLayers.erase(hwcId);});
397 void Layer::destroyHwcLayer(int32_t hwcId) {
398 if (mHwcLayers.count(hwcId) == 0) {
401 auto& hwcInfo = mHwcLayers[hwcId];
402 LOG_ALWAYS_FATAL_IF(hwcInfo.layer == nullptr,
403 "Attempt to destroy null layer");
404 LOG_ALWAYS_FATAL_IF(hwcInfo.hwc == nullptr, "Missing HWComposer");
405 hwcInfo.hwc->destroyLayer(hwcId, hwcInfo.layer);
406 // The layer destroyed listener should have cleared the entry from
407 // mHwcLayers. Verify that.
408 LOG_ALWAYS_FATAL_IF(mHwcLayers.count(hwcId) != 0,
409 "Stale layer entry in mHwcLayers");
412 void Layer::destroyAllHwcLayers() {
413 size_t numLayers = mHwcLayers.size();
414 for (size_t i = 0; i < numLayers; ++i) {
415 LOG_ALWAYS_FATAL_IF(mHwcLayers.empty(), "destroyAllHwcLayers failed");
416 destroyHwcLayer(mHwcLayers.begin()->first);
418 LOG_ALWAYS_FATAL_IF(!mHwcLayers.empty(),
419 "All hardware composer layers should have been destroyed");
423 Rect Layer::getContentCrop() const {
424 // this is the crop rectangle that applies to the buffer
425 // itself (as opposed to the window)
427 if (!mCurrentCrop.isEmpty()) {
428 // if the buffer crop is defined, we use that
430 } else if (mActiveBuffer != NULL) {
431 // otherwise we use the whole buffer
432 crop = mActiveBuffer->getBounds();
434 // if we don't have a buffer yet, we use an empty/invalid crop
440 static Rect reduce(const Rect& win, const Region& exclude) {
441 if (CC_LIKELY(exclude.isEmpty())) {
444 if (exclude.isRect()) {
445 return win.reduce(exclude.getBounds());
447 return Region(win).subtract(exclude).getBounds();
450 Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
451 const Layer::State& s(getDrawingState());
452 Rect win(s.active.w, s.active.h);
454 if (!s.crop.isEmpty()) {
455 win.intersect(s.crop, &win);
458 Transform t = getTransform();
459 win = t.transform(win);
461 if (!s.finalCrop.isEmpty()) {
462 win.intersect(s.finalCrop, &win);
465 const sp<Layer>& p = mDrawingParent.promote();
466 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
467 // When calculating the parent bounds for purposes of clipping,
468 // we don't need to constrain the parent to its transparent region.
469 // The transparent region is an optimization based on the
470 // buffer contents of the layer, but does not affect the space allocated to
471 // it by policy, and thus children should be allowed to extend into the
472 // parent's transparent region. In fact one of the main uses, is to reduce
473 // buffer allocation size in cases where a child window sits behind a main window
474 // (by marking the hole in the parent window as a transparent region)
476 Rect bounds = p->computeScreenBounds(false);
477 bounds.intersect(win, &win);
480 if (reduceTransparentRegion) {
481 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
482 win = reduce(win, screenTransparentRegion);
488 Rect Layer::computeBounds() const {
489 const Layer::State& s(getDrawingState());
490 return computeBounds(s.activeTransparentRegion);
493 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
494 const Layer::State& s(getDrawingState());
495 Rect win(s.active.w, s.active.h);
497 if (!s.crop.isEmpty()) {
498 win.intersect(s.crop, &win);
502 const auto& p = mDrawingParent.promote();
504 // Look in computeScreenBounds recursive call for explanation of
505 // why we pass false here.
506 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
509 Transform t = getTransform();
511 win = t.transform(win);
512 win.intersect(bounds, &win);
513 win = t.inverse().transform(win);
516 // subtract the transparent region and snap to the bounds
517 return reduce(win, activeTransparentRegion);
520 Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
521 // the crop is the area of the window that gets cropped, but not
522 // scaled in any ways.
523 const State& s(getDrawingState());
525 // apply the projection's clipping to the window crop in
526 // layerstack space, and convert-back to layer space.
527 // if there are no window scaling involved, this operation will map to full
528 // pixels in the buffer.
529 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
530 // a viewport clipping and a window transform. we should use floating point to fix this.
532 Rect activeCrop(s.active.w, s.active.h);
533 if (!s.crop.isEmpty()) {
534 activeCrop.intersect(s.crop, &activeCrop);
537 Transform t = getTransform();
538 activeCrop = t.transform(activeCrop);
539 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
542 if (!s.finalCrop.isEmpty()) {
543 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
550 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
551 // the content crop is the area of the content that gets scaled to the
552 // layer's size. This is in buffer space.
553 FloatRect crop = getContentCrop().toFloatRect();
555 // In addition there is a WM-specified crop we pull from our drawing state.
556 const State& s(getDrawingState());
558 // Screen space to make reduction to parent crop clearer.
559 Rect activeCrop = computeInitialCrop(hw);
560 const auto& p = mDrawingParent.promote();
562 auto parentCrop = p->computeInitialCrop(hw);
563 activeCrop.intersect(parentCrop, &activeCrop);
565 Transform t = getTransform();
566 // Back to layer space to work with the content crop.
567 activeCrop = t.inverse().transform(activeCrop);
569 // This needs to be here as transform.transform(Rect) computes the
570 // transformed rect and then takes the bounding box of the result before
571 // returning. This means
572 // transform.inverse().transform(transform.transform(Rect)) != Rect
573 // in which case we need to make sure the final rect is clipped to the
575 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
579 // subtract the transparent region and snap to the bounds
580 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
582 // Transform the window crop to match the buffer coordinate system,
583 // which means using the inverse of the current transform set on the
584 // SurfaceFlingerConsumer.
585 uint32_t invTransform = mCurrentTransform;
586 if (getTransformToDisplayInverse()) {
588 * the code below applies the primary display's inverse transform to the
591 uint32_t invTransformOrient =
592 DisplayDevice::getPrimaryDisplayOrientationTransform();
593 // calculate the inverse transform
594 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
595 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
596 NATIVE_WINDOW_TRANSFORM_FLIP_H;
598 // and apply to the current transform
599 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
603 int winWidth = s.active.w;
604 int winHeight = s.active.h;
605 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
606 // If the activeCrop has been rotate the ends are rotated but not
607 // the space itself so when transforming ends back we can't rely on
608 // a modification of the axes of rotation. To account for this we
609 // need to reorient the inverse rotation in terms of the current
611 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
612 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
613 if (is_h_flipped == is_v_flipped) {
614 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
615 NATIVE_WINDOW_TRANSFORM_FLIP_H;
617 winWidth = s.active.h;
618 winHeight = s.active.w;
620 const Rect winCrop = activeCrop.transform(
621 invTransform, s.active.w, s.active.h);
623 // below, crop is intersected with winCrop expressed in crop's coordinate space
624 float xScale = crop.getWidth() / float(winWidth);
625 float yScale = crop.getHeight() / float(winHeight);
627 float insetL = winCrop.left * xScale;
628 float insetT = winCrop.top * yScale;
629 float insetR = (winWidth - winCrop.right ) * xScale;
630 float insetB = (winHeight - winCrop.bottom) * yScale;
634 crop.right -= insetR;
635 crop.bottom -= insetB;
641 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
643 void Layer::setGeometry(
644 const sp<const DisplayDevice>& hw,
645 HWComposer::HWCLayerInterface& layer)
649 const auto hwcId = displayDevice->getHwcDisplayId();
650 auto& hwcInfo = mHwcLayers[hwcId];
652 layer.setDefaultState();
657 hwcInfo.forceClientComposition = false;
659 if (isSecure() && !displayDevice->isSecure()) {
660 hwcInfo.forceClientComposition = true;
663 auto& hwcLayer = hwcInfo.layer;
665 layer.setSkip(false);
667 if (isSecure() && !hw->isSecure()) {
672 // this gives us only the "orientation" component of the transform
673 const State& s(getDrawingState());
675 auto blendMode = HWC2::BlendMode::None;
676 if (!isOpaque(s) || getAlpha() != 1.0f) {
677 blendMode = mPremultipliedAlpha ?
678 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
680 auto error = hwcLayer->setBlendMode(blendMode);
681 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
682 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
683 to_string(error).c_str(), static_cast<int32_t>(error));
685 if (!isOpaque(s) || getAlpha() != 0xFF) {
686 layer.setBlending(mPremultipliedAlpha ?
687 HWC_BLENDING_PREMULT :
688 HWC_BLENDING_COVERAGE);
692 // apply the layer's transform, followed by the display's global transform
693 // here we're guaranteed that the layer's transform preserves rects
694 Region activeTransparentRegion(s.activeTransparentRegion);
695 Transform t = getTransform();
696 if (!s.crop.isEmpty()) {
697 Rect activeCrop(s.crop);
698 activeCrop = t.transform(activeCrop);
700 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
702 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
706 activeCrop = t.inverse().transform(activeCrop, true);
707 // This needs to be here as transform.transform(Rect) computes the
708 // transformed rect and then takes the bounding box of the result before
709 // returning. This means
710 // transform.inverse().transform(transform.transform(Rect)) != Rect
711 // in which case we need to make sure the final rect is clipped to the
713 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
716 // mark regions outside the crop as transparent
717 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
718 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
719 s.active.w, s.active.h));
720 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
721 activeCrop.left, activeCrop.bottom));
722 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
723 s.active.w, activeCrop.bottom));
726 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
727 if (!s.finalCrop.isEmpty()) {
728 if(!frame.intersect(s.finalCrop, &frame)) {
733 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
736 const Transform& tr(displayDevice->getTransform());
737 Rect transformedFrame = tr.transform(frame);
738 error = hwcLayer->setDisplayFrame(transformedFrame);
739 if (error != HWC2::Error::None) {
740 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
741 mName.string(), transformedFrame.left, transformedFrame.top,
742 transformedFrame.right, transformedFrame.bottom,
743 to_string(error).c_str(), static_cast<int32_t>(error));
745 hwcInfo.displayFrame = transformedFrame;
748 FloatRect sourceCrop = computeCrop(displayDevice);
749 error = hwcLayer->setSourceCrop(sourceCrop);
750 if (error != HWC2::Error::None) {
751 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
752 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
753 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
754 static_cast<int32_t>(error));
756 hwcInfo.sourceCrop = sourceCrop;
759 float alpha = getAlpha();
760 error = hwcLayer->setPlaneAlpha(alpha);
761 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
762 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
763 static_cast<int32_t>(error));
765 error = hwcLayer->setZOrder(z);
766 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
767 mName.string(), z, to_string(error).c_str(),
768 static_cast<int32_t>(error));
772 sp<Layer> parent = mDrawingParent.promote();
774 auto& parentState = parent->getDrawingState();
775 type = parentState.type;
776 appId = parentState.appId;
779 error = hwcLayer->setInfo(type, appId);
780 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
781 mName.string(), static_cast<int32_t>(error));
783 if (!frame.intersect(hw->getViewport(), &frame)) {
786 const Transform& tr(hw->getTransform());
787 layer.setFrame(tr.transform(frame));
788 layer.setCrop(computeCrop(hw));
789 layer.setPlaneAlpha(getAlpha());
793 * Transformations are applied in this order:
794 * 1) buffer orientation/flip/mirror
795 * 2) state transformation (window manager)
796 * 3) layer orientation (screen orientation)
797 * (NOTE: the matrices are multiplied in reverse order)
800 const Transform bufferOrientation(mCurrentTransform);
801 Transform transform(tr * t * bufferOrientation);
803 if (getTransformToDisplayInverse()) {
805 * the code below applies the primary display's inverse transform to the
808 uint32_t invTransform =
809 DisplayDevice::getPrimaryDisplayOrientationTransform();
810 // calculate the inverse transform
811 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
812 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
813 NATIVE_WINDOW_TRANSFORM_FLIP_H;
817 * Here we cancel out the orientation component of the WM transform.
818 * The scaling and translate components are already included in our bounds
819 * computation so it's enough to just omit it in the composition.
820 * See comment in onDraw with ref to b/36727915 for why.
822 transform = Transform(invTransform) * tr * bufferOrientation;
825 // this gives us only the "orientation" component of the transform
826 const uint32_t orientation = transform.getOrientation();
828 if (orientation & Transform::ROT_INVALID) {
829 // we can only handle simple transformation
830 hwcInfo.forceClientComposition = true;
832 auto transform = static_cast<HWC2::Transform>(orientation);
833 auto error = hwcLayer->setTransform(transform);
834 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
835 "%s (%d)", mName.string(), to_string(transform).c_str(),
836 to_string(error).c_str(), static_cast<int32_t>(error));
839 if (orientation & Transform::ROT_INVALID) {
840 // we can only handle simple transformation
843 layer.setTransform(orientation);
849 void Layer::forceClientComposition(int32_t hwcId) {
850 if (mHwcLayers.count(hwcId) == 0) {
851 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
855 mHwcLayers[hwcId].forceClientComposition = true;
858 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
859 // Apply this display's projection's viewport to the visible region
860 // before giving it to the HWC HAL.
861 const Transform& tr = displayDevice->getTransform();
862 const auto& viewport = displayDevice->getViewport();
863 Region visible = tr.transform(visibleRegion.intersect(viewport));
864 auto hwcId = displayDevice->getHwcDisplayId();
865 auto& hwcInfo = mHwcLayers[hwcId];
866 auto& hwcLayer = hwcInfo.layer;
867 auto error = hwcLayer->setVisibleRegion(visible);
868 if (error != HWC2::Error::None) {
869 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
870 to_string(error).c_str(), static_cast<int32_t>(error));
871 visible.dump(LOG_TAG);
874 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
875 if (error != HWC2::Error::None) {
876 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
877 to_string(error).c_str(), static_cast<int32_t>(error));
878 surfaceDamageRegion.dump(LOG_TAG);
882 if (mSidebandStream.get()) {
883 setCompositionType(hwcId, HWC2::Composition::Sideband);
884 ALOGV("[%s] Requesting Sideband composition", mName.string());
885 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
886 if (error != HWC2::Error::None) {
887 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
888 mName.string(), mSidebandStream->handle(),
889 to_string(error).c_str(), static_cast<int32_t>(error));
895 if (hwcInfo.forceClientComposition ||
896 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
897 ALOGV("[%s] Requesting Client composition", mName.string());
898 setCompositionType(hwcId, HWC2::Composition::Client);
903 if (mActiveBuffer == nullptr) {
904 setCompositionType(hwcId, HWC2::Composition::SolidColor);
906 // For now, we only support black for DimLayer
907 error = hwcLayer->setColor({0, 0, 0, 255});
908 if (error != HWC2::Error::None) {
909 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
910 to_string(error).c_str(), static_cast<int32_t>(error));
913 // Clear out the transform, because it doesn't make sense absent a
915 error = hwcLayer->setTransform(HWC2::Transform::None);
916 if (error != HWC2::Error::None) {
917 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
918 to_string(error).c_str(), static_cast<int32_t>(error));
924 // Device or Cursor layers
925 if (mPotentialCursor) {
926 ALOGV("[%s] Requesting Cursor composition", mName.string());
927 setCompositionType(hwcId, HWC2::Composition::Cursor);
929 ALOGV("[%s] Requesting Device composition", mName.string());
930 setCompositionType(hwcId, HWC2::Composition::Device);
933 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
934 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
935 if (error != HWC2::Error::None) {
936 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
937 mCurrentState.dataSpace, to_string(error).c_str(),
938 static_cast<int32_t>(error));
941 uint32_t hwcSlot = 0;
942 sp<GraphicBuffer> hwcBuffer;
943 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
944 &hwcSlot, &hwcBuffer);
946 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
947 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
948 if (error != HWC2::Error::None) {
949 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
950 mActiveBuffer->handle, to_string(error).c_str(),
951 static_cast<int32_t>(error));
956 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
957 HWComposer::HWCLayerInterface& layer) {
958 // we have to set the visible region on every frame because
959 // we currently free it during onLayerDisplayed(), which is called
960 // after HWComposer::commit() -- every frame.
961 // Apply this display's projection's viewport to the visible region
962 // before giving it to the HWC HAL.
963 const Transform& tr = hw->getTransform();
964 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
965 layer.setVisibleRegionScreen(visible);
966 layer.setSurfaceDamage(surfaceDamageRegion);
967 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
969 if (mSidebandStream.get()) {
970 layer.setSidebandStream(mSidebandStream);
972 // NOTE: buffer can be NULL if the client never drew into this
973 // layer yet, or if we ran out of memory
974 layer.setBuffer(mActiveBuffer);
980 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
981 auto hwcId = displayDevice->getHwcDisplayId();
982 if (mHwcLayers.count(hwcId) == 0 ||
983 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
987 // This gives us only the "orientation" component of the transform
988 const State& s(getCurrentState());
990 // Apply the layer's transform, followed by the display's global transform
991 // Here we're guaranteed that the layer's transform preserves rects
992 Rect win(s.active.w, s.active.h);
993 if (!s.crop.isEmpty()) {
994 win.intersect(s.crop, &win);
996 // Subtract the transparent region and snap to the bounds
997 Rect bounds = reduce(win, s.activeTransparentRegion);
998 Rect frame(getTransform().transform(bounds));
999 frame.intersect(displayDevice->getViewport(), &frame);
1000 if (!s.finalCrop.isEmpty()) {
1001 frame.intersect(s.finalCrop, &frame);
1003 auto& displayTransform(displayDevice->getTransform());
1004 auto position = displayTransform.transform(frame);
1006 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
1008 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
1009 "to (%d, %d): %s (%d)", mName.string(), position.left,
1010 position.top, to_string(error).c_str(),
1011 static_cast<int32_t>(error));
1014 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
1015 HWComposer::HWCLayerInterface& layer) {
1018 // TODO: there is a possible optimization here: we only need to set the
1019 // acquire fence the first time a new buffer is acquired on EACH display.
1021 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
1022 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
1023 if (fence->isValid()) {
1024 fenceFd = fence->dup();
1025 if (fenceFd == -1) {
1026 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
1030 layer.setAcquireFenceFd(fenceFd);
1033 Rect Layer::getPosition(
1034 const sp<const DisplayDevice>& hw)
1036 // this gives us only the "orientation" component of the transform
1037 const State& s(getCurrentState());
1039 // apply the layer's transform, followed by the display's global transform
1040 // here we're guaranteed that the layer's transform preserves rects
1041 Rect win(s.active.w, s.active.h);
1042 if (!s.crop.isEmpty()) {
1043 win.intersect(s.crop, &win);
1045 // subtract the transparent region and snap to the bounds
1046 Rect bounds = reduce(win, s.activeTransparentRegion);
1047 Rect frame(getTransform().transform(bounds));
1048 frame.intersect(hw->getViewport(), &frame);
1049 if (!s.finalCrop.isEmpty()) {
1050 frame.intersect(s.finalCrop, &frame);
1052 const Transform& tr(hw->getTransform());
1053 return Rect(tr.transform(frame));
1057 // ---------------------------------------------------------------------------
1059 // ---------------------------------------------------------------------------
1061 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
1062 onDraw(hw, clip, false);
1065 void Layer::draw(const sp<const DisplayDevice>& hw,
1066 bool useIdentityTransform) const {
1067 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
1070 void Layer::draw(const sp<const DisplayDevice>& hw) const {
1071 onDraw(hw, Region(hw->bounds()), false);
1074 static constexpr mat4 inverseOrientation(uint32_t transform) {
1075 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1076 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1077 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1080 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1083 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1086 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1093 * onDraw will draw the current layer onto the presentable buffer
1095 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1096 bool useIdentityTransform) const
1100 if (CC_UNLIKELY(mActiveBuffer == 0)) {
1101 // the texture has not been created yet, this Layer has
1102 // in fact never been drawn into. This happens frequently with
1103 // SurfaceView because the WindowManager can't know when the client
1104 // has drawn the first time.
1106 // If there is nothing under us, we paint the screen in black, otherwise
1107 // we just skip this update.
1109 // figure out if there is something below us
1111 bool finished = false;
1112 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
1113 if (finished || layer == static_cast<Layer const*>(this)) {
1117 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1119 // if not everything below us is covered, we plug the holes!
1120 Region holes(clip.subtract(under));
1121 if (!holes.isEmpty()) {
1122 clearWithOpenGL(hw, 0, 0, 0, 1);
1127 // Bind the current buffer to the GL texture, and wait for it to be
1128 // ready for us to draw into.
1129 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1130 if (err != NO_ERROR) {
1131 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1132 // Go ahead and draw the buffer anyway; no matter what we do the screen
1133 // is probably going to have something visibly wrong.
1136 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1138 RenderEngine& engine(mFlinger->getRenderEngine());
1140 if (!blackOutLayer) {
1141 // TODO: we could be more subtle with isFixedSize()
1142 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1144 // Query the texture matrix given our current filtering mode.
1145 float textureMatrix[16];
1146 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1147 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1149 if (getTransformToDisplayInverse()) {
1152 * the code below applies the primary display's inverse transform to
1153 * the texture transform
1155 uint32_t transform =
1156 DisplayDevice::getPrimaryDisplayOrientationTransform();
1157 mat4 tr = inverseOrientation(transform);
1160 * TODO(b/36727915): This is basically a hack.
1162 * Ensure that regardless of the parent transformation,
1163 * this buffer is always transformed from native display
1164 * orientation to display orientation. For example, in the case
1165 * of a camera where the buffer remains in native orientation,
1166 * we want the pixels to always be upright.
1168 sp<Layer> p = mDrawingParent.promote();
1170 const auto parentTransform = p->getTransform();
1171 tr = tr * inverseOrientation(parentTransform.getOrientation());
1174 // and finally apply it to the original texture matrix
1175 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1176 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1179 // Set things up for texturing.
1180 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1181 mTexture.setFiltering(useFiltering);
1182 mTexture.setMatrix(textureMatrix);
1184 engine.setupLayerTexturing(mTexture);
1186 engine.setupLayerBlackedOut();
1188 drawWithOpenGL(hw, useIdentityTransform);
1189 engine.disableTexturing();
1193 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1194 float red, float green, float blue,
1197 RenderEngine& engine(mFlinger->getRenderEngine());
1198 computeGeometry(hw, mMesh, false);
1199 engine.setupFillWithColor(red, green, blue, alpha);
1200 engine.drawMesh(mMesh);
1203 void Layer::clearWithOpenGL(
1204 const sp<const DisplayDevice>& hw) const {
1205 clearWithOpenGL(hw, 0,0,0,0);
1208 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1209 bool useIdentityTransform) const {
1210 const State& s(getDrawingState());
1212 computeGeometry(hw, mMesh, useIdentityTransform);
1215 * NOTE: the way we compute the texture coordinates here produces
1216 * different results than when we take the HWC path -- in the later case
1217 * the "source crop" is rounded to texel boundaries.
1218 * This can produce significantly different results when the texture
1219 * is scaled by a large amount.
1221 * The GL code below is more logical (imho), and the difference with
1222 * HWC is due to a limitation of the HWC API to integers -- a question
1223 * is suspend is whether we should ignore this problem or revert to
1224 * GL composition when a buffer scaling is applied (maybe with some
1225 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1226 * like more of a hack.
1228 Rect win(computeBounds());
1230 Transform t = getTransform();
1231 if (!s.finalCrop.isEmpty()) {
1232 win = t.transform(win);
1233 if (!win.intersect(s.finalCrop, &win)) {
1236 win = t.inverse().transform(win);
1237 if (!win.intersect(computeBounds(), &win)) {
1242 float left = float(win.left) / float(s.active.w);
1243 float top = float(win.top) / float(s.active.h);
1244 float right = float(win.right) / float(s.active.w);
1245 float bottom = float(win.bottom) / float(s.active.h);
1247 // TODO: we probably want to generate the texture coords with the mesh
1248 // here we assume that we only have 4 vertices
1249 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1250 texCoords[0] = vec2(left, 1.0f - top);
1251 texCoords[1] = vec2(left, 1.0f - bottom);
1252 texCoords[2] = vec2(right, 1.0f - bottom);
1253 texCoords[3] = vec2(right, 1.0f - top);
1255 RenderEngine& engine(mFlinger->getRenderEngine());
1256 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1258 engine.setSourceDataSpace(mCurrentState.dataSpace);
1260 engine.drawMesh(mMesh);
1261 engine.disableBlending();
1265 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1267 if (mHwcLayers.count(hwcId) == 0) {
1268 ALOGE("setCompositionType called without a valid HWC layer");
1271 auto& hwcInfo = mHwcLayers[hwcId];
1272 auto& hwcLayer = hwcInfo.layer;
1273 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1274 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1275 if (hwcInfo.compositionType != type) {
1276 ALOGV(" actually setting");
1277 hwcInfo.compositionType = type;
1279 auto error = hwcLayer->setCompositionType(type);
1280 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1281 "composition type %s: %s (%d)", mName.string(),
1282 to_string(type).c_str(), to_string(error).c_str(),
1283 static_cast<int32_t>(error));
1288 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1289 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1290 // If we're querying the composition type for a display that does not
1291 // have a HWC counterpart, then it will always be Client
1292 return HWC2::Composition::Client;
1294 if (mHwcLayers.count(hwcId) == 0) {
1295 ALOGE("getCompositionType called with an invalid HWC layer");
1296 return HWC2::Composition::Invalid;
1298 return mHwcLayers.at(hwcId).compositionType;
1301 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1302 if (mHwcLayers.count(hwcId) == 0) {
1303 ALOGE("setClearClientTarget called without a valid HWC layer");
1306 mHwcLayers[hwcId].clearClientTarget = clear;
1309 bool Layer::getClearClientTarget(int32_t hwcId) const {
1310 if (mHwcLayers.count(hwcId) == 0) {
1311 ALOGE("getClearClientTarget called without a valid HWC layer");
1314 return mHwcLayers.at(hwcId).clearClientTarget;
1318 uint32_t Layer::getProducerStickyTransform() const {
1319 int producerStickyTransform = 0;
1320 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1322 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1323 strerror(-ret), ret);
1326 return static_cast<uint32_t>(producerStickyTransform);
1329 bool Layer::latchUnsignaledBuffers() {
1330 static bool propertyLoaded = false;
1331 static bool latch = false;
1332 static std::mutex mutex;
1333 std::lock_guard<std::mutex> lock(mutex);
1334 if (!propertyLoaded) {
1335 char value[PROPERTY_VALUE_MAX] = {};
1336 property_get("debug.sf.latch_unsignaled", value, "0");
1337 latch = atoi(value);
1338 propertyLoaded = true;
1343 uint64_t Layer::getHeadFrameNumber() const {
1344 Mutex::Autolock lock(mQueueItemLock);
1345 if (!mQueueItems.empty()) {
1346 return mQueueItems[0].mFrameNumber;
1348 return mCurrentFrameNumber;
1352 bool Layer::headFenceHasSignaled() const {
1354 if (latchUnsignaledBuffers()) {
1358 Mutex::Autolock lock(mQueueItemLock);
1359 if (mQueueItems.empty()) {
1362 if (mQueueItems[0].mIsDroppable) {
1363 // Even though this buffer's fence may not have signaled yet, it could
1364 // be replaced by another buffer before it has a chance to, which means
1365 // that it's possible to get into a situation where a buffer is never
1366 // able to be latched. To avoid this, grab this buffer anyway.
1369 return mQueueItems[0].mFenceTime->getSignalTime() !=
1370 Fence::SIGNAL_TIME_PENDING;
1376 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1377 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1378 // Don't bother with a SyncPoint, since we've already latched the
1383 Mutex::Autolock lock(mLocalSyncPointMutex);
1384 mLocalSyncPoints.push_back(point);
1388 void Layer::setFiltering(bool filtering) {
1389 mFiltering = filtering;
1392 bool Layer::getFiltering() const {
1396 // As documented in libhardware header, formats in the range
1397 // 0x100 - 0x1FF are specific to the HAL implementation, and
1398 // are known to have no alpha channel
1399 // TODO: move definition for device-specific range into
1400 // hardware.h, instead of using hard-coded values here.
1401 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1403 bool Layer::getOpacityForFormat(uint32_t format) {
1404 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1408 case HAL_PIXEL_FORMAT_RGBA_8888:
1409 case HAL_PIXEL_FORMAT_BGRA_8888:
1410 case HAL_PIXEL_FORMAT_RGBA_FP16:
1411 case HAL_PIXEL_FORMAT_RGBA_1010102:
1414 // in all other case, we have no blending (also for unknown formats)
1418 // ----------------------------------------------------------------------------
1420 // ----------------------------------------------------------------------------
1422 static void boundPoint(vec2* point, const Rect& crop) {
1423 if (point->x < crop.left) {
1424 point->x = crop.left;
1426 if (point->x > crop.right) {
1427 point->x = crop.right;
1429 if (point->y < crop.top) {
1430 point->y = crop.top;
1432 if (point->y > crop.bottom) {
1433 point->y = crop.bottom;
1437 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1438 bool useIdentityTransform) const
1440 const Layer::State& s(getDrawingState());
1441 const Transform hwTransform(hw->getTransform());
1442 const uint32_t hw_h = hw->getHeight();
1443 Rect win = computeBounds();
1445 vec2 lt = vec2(win.left, win.top);
1446 vec2 lb = vec2(win.left, win.bottom);
1447 vec2 rb = vec2(win.right, win.bottom);
1448 vec2 rt = vec2(win.right, win.top);
1450 Transform layerTransform = getTransform();
1451 if (!useIdentityTransform) {
1452 lt = layerTransform.transform(lt);
1453 lb = layerTransform.transform(lb);
1454 rb = layerTransform.transform(rb);
1455 rt = layerTransform.transform(rt);
1458 if (!s.finalCrop.isEmpty()) {
1459 boundPoint(<, s.finalCrop);
1460 boundPoint(&lb, s.finalCrop);
1461 boundPoint(&rb, s.finalCrop);
1462 boundPoint(&rt, s.finalCrop);
1465 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1466 position[0] = hwTransform.transform(lt);
1467 position[1] = hwTransform.transform(lb);
1468 position[2] = hwTransform.transform(rb);
1469 position[3] = hwTransform.transform(rt);
1470 for (size_t i=0 ; i<4 ; i++) {
1471 position[i].y = hw_h - position[i].y;
1475 bool Layer::isOpaque(const Layer::State& s) const
1477 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
1478 // layer's opaque flag.
1479 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
1483 // if the layer has the opaque flag, then we're always opaque,
1484 // otherwise we use the current buffer's format.
1485 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1488 bool Layer::isSecure() const
1490 const Layer::State& s(mDrawingState);
1491 return (s.flags & layer_state_t::eLayerSecure);
1494 bool Layer::isProtected() const
1496 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1497 return (activeBuffer != 0) &&
1498 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1501 bool Layer::isFixedSize() const {
1502 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1505 bool Layer::isCropped() const {
1506 return !mCurrentCrop.isEmpty();
1509 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1510 return mNeedsFiltering || hw->needsFiltering();
1513 void Layer::setVisibleRegion(const Region& visibleRegion) {
1514 // always called from main thread
1515 this->visibleRegion = visibleRegion;
1518 void Layer::setCoveredRegion(const Region& coveredRegion) {
1519 // always called from main thread
1520 this->coveredRegion = coveredRegion;
1523 void Layer::setVisibleNonTransparentRegion(const Region&
1524 setVisibleNonTransparentRegion) {
1525 // always called from main thread
1526 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1529 // ----------------------------------------------------------------------------
1531 // ----------------------------------------------------------------------------
1533 void Layer::pushPendingState() {
1534 if (!mCurrentState.modified) {
1538 // If this transaction is waiting on the receipt of a frame, generate a sync
1539 // point and send it to the remote layer.
1540 if (mCurrentState.barrierLayer != nullptr) {
1541 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1542 if (barrierLayer == nullptr) {
1543 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1544 // If we can't promote the layer we are intended to wait on,
1545 // then it is expired or otherwise invalid. Allow this transaction
1546 // to be applied as per normal (no synchronization).
1547 mCurrentState.barrierLayer = nullptr;
1549 auto syncPoint = std::make_shared<SyncPoint>(
1550 mCurrentState.frameNumber);
1551 if (barrierLayer->addSyncPoint(syncPoint)) {
1552 mRemoteSyncPoints.push_back(std::move(syncPoint));
1554 // We already missed the frame we're supposed to synchronize
1555 // on, so go ahead and apply the state update
1556 mCurrentState.barrierLayer = nullptr;
1560 // Wake us up to check if the frame has been received
1561 setTransactionFlags(eTransactionNeeded);
1562 mFlinger->setTransactionFlags(eTraversalNeeded);
1564 mPendingStates.push_back(mCurrentState);
1565 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1568 void Layer::popPendingState(State* stateToCommit) {
1569 auto oldFlags = stateToCommit->flags;
1570 *stateToCommit = mPendingStates[0];
1571 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1572 (stateToCommit->flags & stateToCommit->mask);
1574 mPendingStates.removeAt(0);
1575 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1578 bool Layer::applyPendingStates(State* stateToCommit) {
1579 bool stateUpdateAvailable = false;
1580 while (!mPendingStates.empty()) {
1581 if (mPendingStates[0].barrierLayer != nullptr) {
1582 if (mRemoteSyncPoints.empty()) {
1583 // If we don't have a sync point for this, apply it anyway. It
1584 // will be visually wrong, but it should keep us from getting
1585 // into too much trouble.
1586 ALOGE("[%s] No local sync point found", mName.string());
1587 popPendingState(stateToCommit);
1588 stateUpdateAvailable = true;
1592 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1593 mPendingStates[0].frameNumber) {
1594 ALOGE("[%s] Unexpected sync point frame number found",
1597 // Signal our end of the sync point and then dispose of it
1598 mRemoteSyncPoints.front()->setTransactionApplied();
1599 mRemoteSyncPoints.pop_front();
1603 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1604 // Apply the state update
1605 popPendingState(stateToCommit);
1606 stateUpdateAvailable = true;
1608 // Signal our end of the sync point and then dispose of it
1609 mRemoteSyncPoints.front()->setTransactionApplied();
1610 mRemoteSyncPoints.pop_front();
1615 popPendingState(stateToCommit);
1616 stateUpdateAvailable = true;
1620 // If we still have pending updates, wake SurfaceFlinger back up and point
1621 // it at this layer so we can process them
1622 if (!mPendingStates.empty()) {
1623 setTransactionFlags(eTransactionNeeded);
1624 mFlinger->setTransactionFlags(eTraversalNeeded);
1627 mCurrentState.modified = false;
1628 return stateUpdateAvailable;
1631 void Layer::notifyAvailableFrames() {
1632 auto headFrameNumber = getHeadFrameNumber();
1633 bool headFenceSignaled = headFenceHasSignaled();
1634 Mutex::Autolock lock(mLocalSyncPointMutex);
1635 for (auto& point : mLocalSyncPoints) {
1636 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1637 point->setFrameAvailable();
1642 uint32_t Layer::doTransaction(uint32_t flags) {
1646 Layer::State c = getCurrentState();
1647 if (!applyPendingStates(&c)) {
1651 const Layer::State& s(getDrawingState());
1653 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1654 (c.requested.h != s.requested.h);
1657 // the size changed, we need to ask our client to request a new buffer
1658 ALOGD_IF(DEBUG_RESIZE,
1659 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1660 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1661 " requested={ wh={%4u,%4u} }}\n"
1662 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1663 " requested={ wh={%4u,%4u} }}\n",
1664 this, getName().string(), mCurrentTransform,
1665 getEffectiveScalingMode(),
1666 c.active.w, c.active.h,
1673 c.requested.w, c.requested.h,
1674 s.active.w, s.active.h,
1681 s.requested.w, s.requested.h);
1683 // record the new size, form this point on, when the client request
1684 // a buffer, it'll get the new size.
1685 mSurfaceFlingerConsumer->setDefaultBufferSize(
1686 c.requested.w, c.requested.h);
1689 const bool resizePending = (c.requested.w != c.active.w) ||
1690 (c.requested.h != c.active.h);
1691 if (!isFixedSize()) {
1692 if (resizePending && mSidebandStream == NULL) {
1693 // don't let Layer::doTransaction update the drawing state
1694 // if we have a pending resize, unless we are in fixed-size mode.
1695 // the drawing state will be updated only once we receive a buffer
1696 // with the correct size.
1698 // in particular, we want to make sure the clip (which is part
1699 // of the geometry state) is latched together with the size but is
1700 // latched immediately when no resizing is involved.
1702 // If a sideband stream is attached, however, we want to skip this
1703 // optimization so that transactions aren't missed when a buffer
1706 flags |= eDontUpdateGeometryState;
1710 // Here we apply various requested geometry states, depending on our
1711 // latching configuration. See Layer.h for a detailed discussion of
1712 // how geometry latching is controlled.
1713 if (!(flags & eDontUpdateGeometryState)) {
1714 Layer::State& editCurrentState(getCurrentState());
1716 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1717 // mode, which causes attributes which normally latch regardless of scaling mode,
1718 // to be delayed. We copy the requested state to the active state making sure
1719 // to respect these rules (again see Layer.h for a detailed discussion).
1721 // There is an awkward asymmetry in the handling of the crop states in the position
1722 // states, as can be seen below. Largely this arises from position and transform
1723 // being stored in the same data structure while having different latching rules.
1726 // Careful that "c" and editCurrentState may not begin as equivalent due to
1727 // applyPendingStates in the presence of deferred transactions.
1728 if (mFreezeGeometryUpdates) {
1729 float tx = c.active.transform.tx();
1730 float ty = c.active.transform.ty();
1731 c.active = c.requested;
1732 c.active.transform.set(tx, ty);
1733 editCurrentState.active = c.active;
1735 editCurrentState.active = editCurrentState.requested;
1736 c.active = c.requested;
1740 if (s.active != c.active) {
1741 // invalidate and recompute the visible regions if needed
1742 flags |= Layer::eVisibleRegion;
1745 if (c.sequence != s.sequence) {
1746 // invalidate and recompute the visible regions if needed
1747 flags |= eVisibleRegion;
1748 this->contentDirty = true;
1750 // we may use linear filtering, if the matrix scales us
1751 const uint8_t type = c.active.transform.getType();
1752 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1753 (type >= Transform::SCALE));
1756 // If the layer is hidden, signal and clear out all local sync points so
1757 // that transactions for layers depending on this layer's frames becoming
1758 // visible are not blocked
1759 if (c.flags & layer_state_t::eLayerHidden) {
1763 // Commit the transaction
1764 commitTransaction(c);
1768 void Layer::commitTransaction(const State& stateToCommit) {
1769 mDrawingState = stateToCommit;
1772 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1773 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1776 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1777 return android_atomic_or(flags, &mTransactionFlags);
1780 bool Layer::setPosition(float x, float y, bool immediate) {
1781 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1783 mCurrentState.sequence++;
1785 // We update the requested and active position simultaneously because
1786 // we want to apply the position portion of the transform matrix immediately,
1787 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1788 mCurrentState.requested.transform.set(x, y);
1789 if (immediate && !mFreezeGeometryUpdates) {
1790 // Here we directly update the active state
1791 // unlike other setters, because we store it within
1792 // the transform, but use different latching rules.
1794 mCurrentState.active.transform.set(x, y);
1796 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1798 mCurrentState.modified = true;
1799 setTransactionFlags(eTransactionNeeded);
1803 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1804 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1808 if (childLayer->setLayer(z)) {
1809 mCurrentChildren.removeAt(idx);
1810 mCurrentChildren.add(childLayer);
1815 bool Layer::setLayer(int32_t z) {
1816 if (mCurrentState.z == z)
1818 mCurrentState.sequence++;
1819 mCurrentState.z = z;
1820 mCurrentState.modified = true;
1822 // Discard all relative layering.
1823 if (mCurrentState.zOrderRelativeOf != nullptr) {
1824 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1825 if (strongRelative != nullptr) {
1826 strongRelative->removeZOrderRelative(this);
1828 mCurrentState.zOrderRelativeOf = nullptr;
1830 setTransactionFlags(eTransactionNeeded);
1834 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1835 mCurrentState.zOrderRelatives.remove(relative);
1836 mCurrentState.sequence++;
1837 mCurrentState.modified = true;
1838 setTransactionFlags(eTransactionNeeded);
1841 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1842 mCurrentState.zOrderRelatives.add(relative);
1843 mCurrentState.modified = true;
1844 mCurrentState.sequence++;
1845 setTransactionFlags(eTransactionNeeded);
1848 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1849 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1850 if (handle == nullptr) {
1853 sp<Layer> relative = handle->owner.promote();
1854 if (relative == nullptr) {
1858 mCurrentState.sequence++;
1859 mCurrentState.modified = true;
1860 mCurrentState.z = z;
1862 mCurrentState.zOrderRelativeOf = relative;
1863 relative->addZOrderRelative(this);
1865 setTransactionFlags(eTransactionNeeded);
1870 bool Layer::setSize(uint32_t w, uint32_t h) {
1871 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1873 mCurrentState.requested.w = w;
1874 mCurrentState.requested.h = h;
1875 mCurrentState.modified = true;
1876 setTransactionFlags(eTransactionNeeded);
1880 bool Layer::setAlpha(float alpha) {
1882 bool Layer::setAlpha(uint8_t alpha) {
1884 if (mCurrentState.alpha == alpha)
1886 mCurrentState.sequence++;
1887 mCurrentState.alpha = alpha;
1888 mCurrentState.modified = true;
1889 setTransactionFlags(eTransactionNeeded);
1892 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1893 mCurrentState.sequence++;
1894 mCurrentState.requested.transform.set(
1895 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1896 mCurrentState.modified = true;
1897 setTransactionFlags(eTransactionNeeded);
1900 bool Layer::setTransparentRegionHint(const Region& transparent) {
1901 mCurrentState.requestedTransparentRegion = transparent;
1902 mCurrentState.modified = true;
1903 setTransactionFlags(eTransactionNeeded);
1906 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1907 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1908 if (mCurrentState.flags == newFlags)
1910 mCurrentState.sequence++;
1911 mCurrentState.flags = newFlags;
1912 mCurrentState.mask = mask;
1913 mCurrentState.modified = true;
1914 setTransactionFlags(eTransactionNeeded);
1918 bool Layer::setCrop(const Rect& crop, bool immediate) {
1919 if (mCurrentState.requestedCrop == crop)
1921 mCurrentState.sequence++;
1922 mCurrentState.requestedCrop = crop;
1923 if (immediate && !mFreezeGeometryUpdates) {
1924 mCurrentState.crop = crop;
1926 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1928 mCurrentState.modified = true;
1929 setTransactionFlags(eTransactionNeeded);
1933 bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1934 if (mCurrentState.requestedFinalCrop == crop)
1936 mCurrentState.sequence++;
1937 mCurrentState.requestedFinalCrop = crop;
1938 if (immediate && !mFreezeGeometryUpdates) {
1939 mCurrentState.finalCrop = crop;
1941 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1943 mCurrentState.modified = true;
1944 setTransactionFlags(eTransactionNeeded);
1948 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1949 if (scalingMode == mOverrideScalingMode)
1951 mOverrideScalingMode = scalingMode;
1952 setTransactionFlags(eTransactionNeeded);
1956 void Layer::setInfo(uint32_t type, uint32_t appId) {
1957 mCurrentState.appId = appId;
1958 mCurrentState.type = type;
1959 mCurrentState.modified = true;
1960 setTransactionFlags(eTransactionNeeded);
1963 uint32_t Layer::getEffectiveScalingMode() const {
1964 if (mOverrideScalingMode >= 0) {
1965 return mOverrideScalingMode;
1967 return mCurrentScalingMode;
1970 bool Layer::setLayerStack(uint32_t layerStack) {
1971 if (mCurrentState.layerStack == layerStack)
1973 mCurrentState.sequence++;
1974 mCurrentState.layerStack = layerStack;
1975 mCurrentState.modified = true;
1976 setTransactionFlags(eTransactionNeeded);
1980 bool Layer::setDataSpace(android_dataspace dataSpace) {
1981 if (mCurrentState.dataSpace == dataSpace)
1983 mCurrentState.sequence++;
1984 mCurrentState.dataSpace = dataSpace;
1985 mCurrentState.modified = true;
1986 setTransactionFlags(eTransactionNeeded);
1990 android_dataspace Layer::getDataSpace() const {
1991 return mCurrentState.dataSpace;
1994 uint32_t Layer::getLayerStack() const {
1995 auto p = mDrawingParent.promote();
1997 return getDrawingState().layerStack;
1999 return p->getLayerStack();
2002 void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
2003 uint64_t frameNumber) {
2004 mCurrentState.barrierLayer = barrierLayer;
2005 mCurrentState.frameNumber = frameNumber;
2006 // We don't set eTransactionNeeded, because just receiving a deferral
2007 // request without any other state updates shouldn't actually induce a delay
2008 mCurrentState.modified = true;
2010 mCurrentState.barrierLayer = nullptr;
2011 mCurrentState.frameNumber = 0;
2012 mCurrentState.modified = false;
2015 void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
2016 uint64_t frameNumber) {
2017 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
2018 deferTransactionUntil(handle->owner.promote(), frameNumber);
2021 void Layer::useSurfaceDamage() {
2022 if (mFlinger->mForceFullDamage) {
2023 surfaceDamageRegion = Region::INVALID_REGION;
2025 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
2029 void Layer::useEmptyDamage() {
2030 surfaceDamageRegion.clear();
2033 // ----------------------------------------------------------------------------
2034 // pageflip handling...
2035 // ----------------------------------------------------------------------------
2037 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
2038 if (mSidebandStreamChanged || mAutoRefresh) {
2042 Mutex::Autolock lock(mQueueItemLock);
2043 if (mQueueItems.empty()) {
2046 auto timestamp = mQueueItems[0].mTimestamp;
2047 nsecs_t expectedPresent =
2048 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
2050 // Ignore timestamps more than a second in the future
2051 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
2052 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
2053 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
2056 bool isDue = timestamp < expectedPresent;
2057 return isDue || !isPlausible;
2060 bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2061 if (mBufferLatched) {
2062 Mutex::Autolock lock(mFrameEventHistoryMutex);
2063 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2065 mRefreshPending = false;
2066 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
2069 bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
2070 const std::shared_ptr<FenceTime>& presentFence,
2071 const CompositorTiming& compositorTiming) {
2072 // mFrameLatencyNeeded is true when a new frame was latched for the
2074 if (!mFrameLatencyNeeded)
2077 // Update mFrameEventHistory.
2079 Mutex::Autolock lock(mFrameEventHistoryMutex);
2080 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
2081 glDoneFence, presentFence, compositorTiming);
2084 // Update mFrameTracker.
2085 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2086 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2088 std::shared_ptr<FenceTime> frameReadyFence =
2089 mSurfaceFlingerConsumer->getCurrentFenceTime();
2090 if (frameReadyFence->isValid()) {
2091 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
2093 // There was no fence for this frame, so assume that it was ready
2094 // to be presented at the desired present time.
2095 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2098 if (presentFence->isValid()) {
2099 mFrameTracker.setActualPresentFence(
2100 std::shared_ptr<FenceTime>(presentFence));
2102 // The HWC doesn't support present fences, so use the refresh
2103 // timestamp instead.
2104 mFrameTracker.setActualPresentTime(
2105 mFlinger->getHwComposer().getRefreshTimestamp(
2106 HWC_DISPLAY_PRIMARY));
2109 mFrameTracker.advanceFrame();
2110 mFrameLatencyNeeded = false;
2115 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2116 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2120 auto releaseFenceTime = std::make_shared<FenceTime>(
2121 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2122 mReleaseTimeline.updateSignalTimes();
2123 mReleaseTimeline.push(releaseFenceTime);
2125 Mutex::Autolock lock(mFrameEventHistoryMutex);
2126 if (mPreviousFrameNumber != 0) {
2127 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2128 dequeueReadyTime, std::move(releaseFenceTime));
2133 bool Layer::isHiddenByPolicy() const {
2134 const Layer::State& s(mDrawingState);
2135 const auto& parent = mDrawingParent.promote();
2136 if (parent != nullptr && parent->isHiddenByPolicy()) {
2139 return s.flags & layer_state_t::eLayerHidden;
2142 bool Layer::isVisible() const {
2144 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2145 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2147 return !(isHiddenByPolicy()) && getAlpha()
2148 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2152 bool Layer::allTransactionsSignaled() {
2153 auto headFrameNumber = getHeadFrameNumber();
2154 bool matchingFramesFound = false;
2155 bool allTransactionsApplied = true;
2156 Mutex::Autolock lock(mLocalSyncPointMutex);
2158 for (auto& point : mLocalSyncPoints) {
2159 if (point->getFrameNumber() > headFrameNumber) {
2162 matchingFramesFound = true;
2164 if (!point->frameIsAvailable()) {
2165 // We haven't notified the remote layer that the frame for
2166 // this point is available yet. Notify it now, and then
2167 // abort this attempt to latch.
2168 point->setFrameAvailable();
2169 allTransactionsApplied = false;
2173 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2175 return !matchingFramesFound || allTransactionsApplied;
2178 Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2182 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2183 // mSidebandStreamChanged was true
2184 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2185 if (mSidebandStream != NULL) {
2186 setTransactionFlags(eTransactionNeeded);
2187 mFlinger->setTransactionFlags(eTraversalNeeded);
2189 recomputeVisibleRegions = true;
2191 const State& s(getDrawingState());
2192 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2195 Region outDirtyRegion;
2196 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2197 return outDirtyRegion;
2200 // if we've already called updateTexImage() without going through
2201 // a composition step, we have to skip this layer at this point
2202 // because we cannot call updateTeximage() without a corresponding
2203 // compositionComplete() call.
2204 // we'll trigger an update in onPreComposition().
2205 if (mRefreshPending) {
2206 return outDirtyRegion;
2209 // If the head buffer's acquire fence hasn't signaled yet, return and
2211 if (!headFenceHasSignaled()) {
2212 mFlinger->signalLayerUpdate();
2213 return outDirtyRegion;
2216 // Capture the old state of the layer for comparisons later
2217 const State& s(getDrawingState());
2218 const bool oldOpacity = isOpaque(s);
2219 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2221 if (!allTransactionsSignaled()) {
2222 mFlinger->signalLayerUpdate();
2223 return outDirtyRegion;
2226 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2227 // of the buffer queue isn't modified when the buffer queue is returning
2228 // BufferItem's that weren't actually queued. This can happen in shared
2230 bool queuedBuffer = false;
2231 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2232 getProducerStickyTransform() != 0, mName.string(),
2233 mOverrideScalingMode, mFreezeGeometryUpdates);
2234 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2235 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2236 mLastFrameNumberReceived);
2237 if (updateResult == BufferQueue::PRESENT_LATER) {
2238 // Producer doesn't want buffer to be displayed yet. Signal a
2239 // layer update so we check again at the next opportunity.
2240 mFlinger->signalLayerUpdate();
2241 return outDirtyRegion;
2242 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2243 // If the buffer has been rejected, remove it from the shadow queue
2246 Mutex::Autolock lock(mQueueItemLock);
2247 mQueueItems.removeAt(0);
2248 android_atomic_dec(&mQueuedFrames);
2250 return outDirtyRegion;
2251 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2252 // This can occur if something goes wrong when trying to create the
2253 // EGLImage for this buffer. If this happens, the buffer has already
2254 // been released, so we need to clean up the queue and bug out
2257 Mutex::Autolock lock(mQueueItemLock);
2258 mQueueItems.clear();
2259 android_atomic_and(0, &mQueuedFrames);
2262 // Once we have hit this state, the shadow queue may no longer
2263 // correctly reflect the incoming BufferQueue's contents, so even if
2264 // updateTexImage starts working, the only safe course of action is
2265 // to continue to ignore updates.
2266 mUpdateTexImageFailed = true;
2268 return outDirtyRegion;
2273 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2275 Mutex::Autolock lock(mQueueItemLock);
2277 // Remove any stale buffers that have been dropped during
2279 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2280 mQueueItems.removeAt(0);
2281 android_atomic_dec(&mQueuedFrames);
2284 mQueueItems.removeAt(0);
2288 // Decrement the queued-frames count. Signal another event if we
2289 // have more frames pending.
2290 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2292 mFlinger->signalLayerUpdate();
2295 // update the active buffer
2296 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2297 &mActiveBufferSlot);
2298 if (mActiveBuffer == NULL) {
2299 // this can only happen if the very first buffer was rejected.
2300 return outDirtyRegion;
2303 mBufferLatched = true;
2304 mPreviousFrameNumber = mCurrentFrameNumber;
2305 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2308 Mutex::Autolock lock(mFrameEventHistoryMutex);
2309 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2311 auto releaseFenceTime = std::make_shared<FenceTime>(
2312 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2313 mReleaseTimeline.updateSignalTimes();
2314 mReleaseTimeline.push(releaseFenceTime);
2315 if (mPreviousFrameNumber != 0) {
2316 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2317 latchTime, std::move(releaseFenceTime));
2322 mRefreshPending = true;
2323 mFrameLatencyNeeded = true;
2324 if (oldActiveBuffer == NULL) {
2325 // the first time we receive a buffer, we need to trigger a
2326 // geometry invalidation.
2327 recomputeVisibleRegions = true;
2330 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2332 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2333 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2334 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2335 if ((crop != mCurrentCrop) ||
2336 (transform != mCurrentTransform) ||
2337 (scalingMode != mCurrentScalingMode))
2339 mCurrentCrop = crop;
2340 mCurrentTransform = transform;
2341 mCurrentScalingMode = scalingMode;
2342 recomputeVisibleRegions = true;
2345 if (oldActiveBuffer != NULL) {
2346 uint32_t bufWidth = mActiveBuffer->getWidth();
2347 uint32_t bufHeight = mActiveBuffer->getHeight();
2348 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2349 bufHeight != uint32_t(oldActiveBuffer->height)) {
2350 recomputeVisibleRegions = true;
2354 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2355 if (oldOpacity != isOpaque(s)) {
2356 recomputeVisibleRegions = true;
2359 // Remove any sync points corresponding to the buffer which was just
2362 Mutex::Autolock lock(mLocalSyncPointMutex);
2363 auto point = mLocalSyncPoints.begin();
2364 while (point != mLocalSyncPoints.end()) {
2365 if (!(*point)->frameIsAvailable() ||
2366 !(*point)->transactionIsApplied()) {
2367 // This sync point must have been added since we started
2368 // latching. Don't drop it yet.
2373 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2374 point = mLocalSyncPoints.erase(point);
2381 // FIXME: postedRegion should be dirty & bounds
2382 Region dirtyRegion(Rect(s.active.w, s.active.h));
2384 // transform the dirty region to window-manager space
2385 outDirtyRegion = (getTransform().transform(dirtyRegion));
2387 return outDirtyRegion;
2390 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2392 // TODO: should we do something special if mSecure is set?
2393 if (mProtectedByApp) {
2394 // need a hardware-protected path to external video sink
2395 usage |= GraphicBuffer::USAGE_PROTECTED;
2397 if (mPotentialCursor) {
2398 usage |= GraphicBuffer::USAGE_CURSOR;
2400 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2404 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2405 uint32_t orientation = 0;
2406 if (!mFlinger->mDebugDisableTransformHint) {
2407 // The transform hint is used to improve performance, but we can
2408 // only have a single transform hint, it cannot
2409 // apply to all displays.
2410 const Transform& planeTransform(hw->getTransform());
2411 orientation = planeTransform.getOrientation();
2412 if (orientation & Transform::ROT_INVALID) {
2416 mSurfaceFlingerConsumer->setTransformHint(orientation);
2419 // ----------------------------------------------------------------------------
2421 // ----------------------------------------------------------------------------
2423 void Layer::dump(String8& result, Colorizer& colorizer) const
2425 const Layer::State& s(getDrawingState());
2427 colorizer.colorize(result, Colorizer::GREEN);
2428 result.appendFormat(
2430 getTypeId(), this, getName().string());
2431 colorizer.reset(result);
2433 s.activeTransparentRegion.dump(result, "transparentRegion");
2434 visibleRegion.dump(result, "visibleRegion");
2435 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2436 sp<Client> client(mClientRef.promote());
2437 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2438 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2439 if (buffer != NULL) {
2440 pf = buffer->getPixelFormat();
2443 result.appendFormat( " "
2444 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2445 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2446 "isOpaque=%1d, invalidate=%1d, "
2447 "dataspace=%s, pixelformat=%s "
2449 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2451 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2454 getLayerStack(), s.z,
2455 s.active.transform.tx(), s.active.transform.ty(),
2456 s.active.w, s.active.h,
2457 s.crop.left, s.crop.top,
2458 s.crop.right, s.crop.bottom,
2459 s.finalCrop.left, s.finalCrop.top,
2460 s.finalCrop.right, s.finalCrop.bottom,
2461 isOpaque(s), contentDirty,
2462 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
2464 s.active.transform[0][0], s.active.transform[0][1],
2465 s.active.transform[1][0], s.active.transform[1][1],
2468 sp<const GraphicBuffer> buf0(mActiveBuffer);
2469 uint32_t w0=0, h0=0, s0=0, f0=0;
2471 w0 = buf0->getWidth();
2472 h0 = buf0->getHeight();
2473 s0 = buf0->getStride();
2476 result.appendFormat(
2478 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2479 " queued-frames=%d, mRefreshPending=%d\n",
2480 mFormat, w0, h0, s0,f0,
2481 mQueuedFrames, mRefreshPending);
2483 if (mSurfaceFlingerConsumer != 0) {
2484 mSurfaceFlingerConsumer->dumpState(result, " ");
2489 void Layer::miniDumpHeader(String8& result) {
2490 result.append("----------------------------------------");
2491 result.append("---------------------------------------\n");
2492 result.append(" Layer name\n");
2493 result.append(" Z | ");
2494 result.append(" Comp Type | ");
2495 result.append(" Disp Frame (LTRB) | ");
2496 result.append(" Source Crop (LTRB)\n");
2497 result.append("----------------------------------------");
2498 result.append("---------------------------------------\n");
2501 void Layer::miniDump(String8& result, int32_t hwcId) const {
2502 if (mHwcLayers.count(hwcId) == 0) {
2507 if (mName.length() > 77) {
2508 std::string shortened;
2509 shortened.append(mName.string(), 36);
2510 shortened.append("[...]");
2511 shortened.append(mName.string() + (mName.length() - 36), 36);
2512 name = shortened.c_str();
2517 result.appendFormat(" %s\n", name.string());
2519 const Layer::State& layerState(getDrawingState());
2520 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2521 result.appendFormat(" %10u | ", layerState.z);
2522 result.appendFormat("%10s | ",
2523 to_string(getCompositionType(hwcId)).c_str());
2524 const Rect& frame = hwcInfo.displayFrame;
2525 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2526 frame.right, frame.bottom);
2527 const FloatRect& crop = hwcInfo.sourceCrop;
2528 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2529 crop.right, crop.bottom);
2531 result.append("- - - - - - - - - - - - - - - - - - - - ");
2532 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2536 void Layer::dumpFrameStats(String8& result) const {
2537 mFrameTracker.dumpStats(result);
2540 void Layer::clearFrameStats() {
2541 mFrameTracker.clearStats();
2544 void Layer::logFrameStats() {
2545 mFrameTracker.logAndResetStats(mName);
2548 void Layer::getFrameStats(FrameStats* outStats) const {
2549 mFrameTracker.getStats(outStats);
2552 void Layer::dumpFrameEvents(String8& result) {
2553 result.appendFormat("- Layer %s (%s, %p)\n",
2554 getName().string(), getTypeId(), this);
2555 Mutex::Autolock lock(mFrameEventHistoryMutex);
2556 mFrameEventHistory.checkFencesForCompletion();
2557 mFrameEventHistory.dump(result);
2560 void Layer::onDisconnect() {
2561 Mutex::Autolock lock(mFrameEventHistoryMutex);
2562 mFrameEventHistory.onDisconnect();
2565 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2566 FrameEventHistoryDelta *outDelta) {
2567 Mutex::Autolock lock(mFrameEventHistoryMutex);
2568 if (newTimestamps) {
2569 // If there are any unsignaled fences in the aquire timeline at this
2570 // point, the previously queued frame hasn't been latched yet. Go ahead
2571 // and try to get the signal time here so the syscall is taken out of
2572 // the main thread's critical path.
2573 mAcquireTimeline.updateSignalTimes();
2574 // Push the new fence after updating since it's likely still pending.
2575 mAcquireTimeline.push(newTimestamps->acquireFence);
2576 mFrameEventHistory.addQueue(*newTimestamps);
2580 mFrameEventHistory.getAndResetDelta(outDelta);
2584 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2586 std::vector<OccupancyTracker::Segment> history;
2587 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2589 if (result != NO_ERROR) {
2590 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2597 bool Layer::getTransformToDisplayInverse() const {
2598 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2601 size_t Layer::getChildrenCount() const {
2603 for (const sp<Layer>& child : mCurrentChildren) {
2604 count += 1 + child->getChildrenCount();
2609 void Layer::addChild(const sp<Layer>& layer) {
2610 mCurrentChildren.add(layer);
2611 layer->setParent(this);
2614 ssize_t Layer::removeChild(const sp<Layer>& layer) {
2615 layer->setParent(nullptr);
2616 return mCurrentChildren.remove(layer);
2619 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2620 sp<Handle> handle = nullptr;
2621 sp<Layer> newParent = nullptr;
2622 if (newParentHandle == nullptr) {
2625 handle = static_cast<Handle*>(newParentHandle.get());
2626 newParent = handle->owner.promote();
2627 if (newParent == nullptr) {
2628 ALOGE("Unable to promote Layer handle");
2632 for (const sp<Layer>& child : mCurrentChildren) {
2633 newParent->addChild(child);
2635 sp<Client> client(child->mClientRef.promote());
2636 if (client != nullptr) {
2637 client->setParentLayer(newParent);
2640 mCurrentChildren.clear();
2645 bool Layer::detachChildren() {
2646 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
2647 if (child == this) {
2651 sp<Client> client(child->mClientRef.promote());
2652 if (client != nullptr) {
2653 client->detachLayer(child);
2660 void Layer::setParent(const sp<Layer>& layer) {
2661 mCurrentParent = layer;
2664 void Layer::clearSyncPoints() {
2665 for (const auto& child : mCurrentChildren) {
2666 child->clearSyncPoints();
2669 Mutex::Autolock lock(mLocalSyncPointMutex);
2670 for (auto& point : mLocalSyncPoints) {
2671 point->setFrameAvailable();
2673 mLocalSyncPoints.clear();
2676 int32_t Layer::getZ() const {
2677 return mDrawingState.z;
2680 LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2681 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2682 "makeTraversalList received invalid stateSet");
2683 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2684 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2685 const State& state = useDrawing ? mDrawingState : mCurrentState;
2687 if (state.zOrderRelatives.size() == 0) {
2690 LayerVector traverse;
2692 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2693 sp<Layer> strongRelative = weakRelative.promote();
2694 if (strongRelative != nullptr) {
2695 traverse.add(strongRelative);
2699 for (const sp<Layer>& child : children) {
2700 traverse.add(child);
2707 * Negatively signed relatives are before 'this' in Z-order.
2709 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2710 LayerVector list = makeTraversalList(stateSet);
2713 for (; i < list.size(); i++) {
2714 const auto& relative = list[i];
2715 if (relative->getZ() >= 0) {
2718 relative->traverseInZOrder(stateSet, visitor);
2721 for (; i < list.size(); i++) {
2722 const auto& relative = list[i];
2723 relative->traverseInZOrder(stateSet, visitor);
2728 * Positively signed relatives are before 'this' in reverse Z-order.
2730 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2731 const LayerVector::Visitor& visitor) {
2732 LayerVector list = makeTraversalList(stateSet);
2735 for (i = list.size()-1; i>=0; i--) {
2736 const auto& relative = list[i];
2737 if (relative->getZ() < 0) {
2740 relative->traverseInReverseZOrder(stateSet, visitor);
2744 const auto& relative = list[i];
2745 relative->traverseInReverseZOrder(stateSet, visitor);
2749 Transform Layer::getTransform() const {
2751 const auto& p = mDrawingParent.promote();
2753 t = p->getTransform();
2755 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2756 // it isFixedSize) then there may be additional scaling not accounted
2757 // for in the transform. We need to mirror this scaling in child surfaces
2758 // or we will break the contract where WM can treat child surfaces as
2759 // pixels in the parent surface.
2760 if (p->isFixedSize() && p->mActiveBuffer != nullptr) {
2763 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2764 bufferWidth = p->mActiveBuffer->getWidth();
2765 bufferHeight = p->mActiveBuffer->getHeight();
2767 bufferHeight = p->mActiveBuffer->getWidth();
2768 bufferWidth = p->mActiveBuffer->getHeight();
2770 float sx = p->getDrawingState().active.w /
2771 static_cast<float>(bufferWidth);
2772 float sy = p->getDrawingState().active.h /
2773 static_cast<float>(bufferHeight);
2774 Transform extraParentScaling;
2775 extraParentScaling.set(sx, 0, 0, sy);
2776 t = t * extraParentScaling;
2779 return t * getDrawingState().active.transform;
2783 float Layer::getAlpha() const {
2784 const auto& p = mDrawingParent.promote();
2786 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2787 return parentAlpha * getDrawingState().alpha;
2790 uint8_t Layer::getAlpha() const {
2791 const auto& p = mDrawingParent.promote();
2793 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2794 float drawingAlpha = getDrawingState().alpha / 255.0f;
2795 drawingAlpha = drawingAlpha * parentAlpha;
2796 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2800 void Layer::commitChildList() {
2801 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2802 const auto& child = mCurrentChildren[i];
2803 child->commitChildList();
2805 mDrawingChildren = mCurrentChildren;
2806 mDrawingParent = mCurrentParent;
2809 // ---------------------------------------------------------------------------
2811 }; // namespace android
2813 #if defined(__gl_h_)
2814 #error "don't include gl/gl.h in this file"
2817 #if defined(__gl2_h_)
2818 #error "don't include gl2/gl2.h in this file"