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 // ---------------------------------------------------------------------------
207 // ---------------------------------------------------------------------------
210 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
211 if (mHwcLayers.empty()) {
214 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
217 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
218 HWComposer::HWCLayerInterface* layer) {
220 layer->onDisplayed();
221 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
226 void Layer::onFrameAvailable(const BufferItem& item) {
227 // Add this buffer from our internal queue tracker
229 Mutex::Autolock lock(mQueueItemLock);
230 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(),
231 item.mGraphicBuffer->getHeight(), item.mFrameNumber);
232 // Reset the frame number tracker when we receive the first buffer after
233 // a frame number reset
234 if (item.mFrameNumber == 1) {
235 mLastFrameNumberReceived = 0;
238 // Ensure that callbacks are handled in order
239 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
240 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
242 if (result != NO_ERROR) {
243 ALOGE("[%s] Timed out waiting on callback", mName.string());
247 mQueueItems.push_back(item);
248 android_atomic_inc(&mQueuedFrames);
250 // Wake up any pending callbacks
251 mLastFrameNumberReceived = item.mFrameNumber;
252 mQueueItemCondition.broadcast();
255 mFlinger->signalLayerUpdate();
258 void Layer::onFrameReplaced(const BufferItem& item) {
260 Mutex::Autolock lock(mQueueItemLock);
262 // Ensure that callbacks are handled in order
263 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
264 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
266 if (result != NO_ERROR) {
267 ALOGE("[%s] Timed out waiting on callback", mName.string());
271 if (mQueueItems.empty()) {
272 ALOGE("Can't replace a frame on an empty queue");
275 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
277 // Wake up any pending callbacks
278 mLastFrameNumberReceived = item.mFrameNumber;
279 mQueueItemCondition.broadcast();
283 void Layer::onSidebandStreamChanged() {
284 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
285 // mSidebandStreamChanged was false
286 mFlinger->signalLayerUpdate();
290 // called with SurfaceFlinger::mStateLock from the drawing thread after
291 // the layer has been remove from the current state list (and just before
292 // it's removed from the drawing state list)
293 void Layer::onRemoved() {
294 if (mCurrentState.zOrderRelativeOf != nullptr) {
295 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
296 if (strongRelative != nullptr) {
297 strongRelative->removeZOrderRelative(this);
299 mCurrentState.zOrderRelativeOf = nullptr;
302 mSurfaceFlingerConsumer->abandon();
308 for (const auto& child : mCurrentChildren) {
313 // ---------------------------------------------------------------------------
315 // ---------------------------------------------------------------------------
317 const String8& Layer::getName() const {
321 status_t Layer::setBuffers( uint32_t w, uint32_t h,
322 PixelFormat format, uint32_t flags)
324 uint32_t const maxSurfaceDims = min(
325 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
327 // never allow a surface larger than what our underlying GL implementation
329 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
330 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
336 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
337 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
338 mCurrentOpacity = getOpacityForFormat(format);
340 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
341 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
342 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
347 sp<IBinder> Layer::getHandle() {
348 Mutex::Autolock _l(mLock);
350 LOG_ALWAYS_FATAL_IF(mHasSurface,
351 "Layer::getHandle() has already been called");
355 return new Handle(mFlinger, this);
358 sp<IGraphicBufferProducer> Layer::getProducer() const {
362 // ---------------------------------------------------------------------------
363 // h/w composer set-up
364 // ---------------------------------------------------------------------------
366 Rect Layer::getContentCrop() const {
367 // this is the crop rectangle that applies to the buffer
368 // itself (as opposed to the window)
370 if (!mCurrentCrop.isEmpty()) {
371 // if the buffer crop is defined, we use that
373 } else if (mActiveBuffer != NULL) {
374 // otherwise we use the whole buffer
375 crop = mActiveBuffer->getBounds();
377 // if we don't have a buffer yet, we use an empty/invalid crop
383 static Rect reduce(const Rect& win, const Region& exclude) {
384 if (CC_LIKELY(exclude.isEmpty())) {
387 if (exclude.isRect()) {
388 return win.reduce(exclude.getBounds());
390 return Region(win).subtract(exclude).getBounds();
393 Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const {
394 const Layer::State& s(getDrawingState());
395 Rect win(s.active.w, s.active.h);
397 if (!s.crop.isEmpty()) {
398 win.intersect(s.crop, &win);
401 Transform t = getTransform();
402 win = t.transform(win);
404 if (!s.finalCrop.isEmpty()) {
405 win.intersect(s.finalCrop, &win);
408 const sp<Layer>& p = mDrawingParent.promote();
409 // Now we need to calculate the parent bounds, so we can clip ourselves to those.
410 // When calculating the parent bounds for purposes of clipping,
411 // we don't need to constrain the parent to its transparent region.
412 // The transparent region is an optimization based on the
413 // buffer contents of the layer, but does not affect the space allocated to
414 // it by policy, and thus children should be allowed to extend into the
415 // parent's transparent region. In fact one of the main uses, is to reduce
416 // buffer allocation size in cases where a child window sits behind a main window
417 // (by marking the hole in the parent window as a transparent region)
419 Rect bounds = p->computeScreenBounds(false);
420 bounds.intersect(win, &win);
423 if (reduceTransparentRegion) {
424 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion);
425 win = reduce(win, screenTransparentRegion);
431 Rect Layer::computeBounds() const {
432 const Layer::State& s(getDrawingState());
433 return computeBounds(s.activeTransparentRegion);
436 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
437 const Layer::State& s(getDrawingState());
438 Rect win(s.active.w, s.active.h);
440 if (!s.crop.isEmpty()) {
441 win.intersect(s.crop, &win);
445 const auto& p = mDrawingParent.promote();
447 // Look in computeScreenBounds recursive call for explanation of
448 // why we pass false here.
449 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */);
452 Transform t = getTransform();
454 win = t.transform(win);
455 win.intersect(bounds, &win);
456 win = t.inverse().transform(win);
459 // subtract the transparent region and snap to the bounds
460 return reduce(win, activeTransparentRegion);
463 Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const {
464 // the crop is the area of the window that gets cropped, but not
465 // scaled in any ways.
466 const State& s(getDrawingState());
468 // apply the projection's clipping to the window crop in
469 // layerstack space, and convert-back to layer space.
470 // if there are no window scaling involved, this operation will map to full
471 // pixels in the buffer.
472 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
473 // a viewport clipping and a window transform. we should use floating point to fix this.
475 Rect activeCrop(s.active.w, s.active.h);
476 if (!s.crop.isEmpty()) {
480 Transform t = getTransform();
481 activeCrop = t.transform(activeCrop);
482 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
485 if (!s.finalCrop.isEmpty()) {
486 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
493 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
494 // the content crop is the area of the content that gets scaled to the
495 // layer's size. This is in buffer space.
496 FloatRect crop = getContentCrop().toFloatRect();
498 // In addition there is a WM-specified crop we pull from our drawing state.
499 const State& s(getDrawingState());
501 // Screen space to make reduction to parent crop clearer.
502 Rect activeCrop = computeInitialCrop(hw);
503 const auto& p = mDrawingParent.promote();
505 auto parentCrop = p->computeInitialCrop(hw);
506 activeCrop.intersect(parentCrop, &activeCrop);
508 Transform t = getTransform();
509 // Back to layer space to work with the content crop.
510 activeCrop = t.inverse().transform(activeCrop);
512 // This needs to be here as transform.transform(Rect) computes the
513 // transformed rect and then takes the bounding box of the result before
514 // returning. This means
515 // transform.inverse().transform(transform.transform(Rect)) != Rect
516 // in which case we need to make sure the final rect is clipped to the
518 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
522 // subtract the transparent region and snap to the bounds
523 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
525 // Transform the window crop to match the buffer coordinate system,
526 // which means using the inverse of the current transform set on the
527 // SurfaceFlingerConsumer.
528 uint32_t invTransform = mCurrentTransform;
529 if (getTransformToDisplayInverse()) {
531 * the code below applies the primary display's inverse transform to the
534 uint32_t invTransformOrient =
535 DisplayDevice::getPrimaryDisplayOrientationTransform();
536 // calculate the inverse transform
537 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
538 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
539 NATIVE_WINDOW_TRANSFORM_FLIP_H;
541 // and apply to the current transform
542 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
546 int winWidth = s.active.w;
547 int winHeight = s.active.h;
548 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
549 // If the activeCrop has been rotate the ends are rotated but not
550 // the space itself so when transforming ends back we can't rely on
551 // a modification of the axes of rotation. To account for this we
552 // need to reorient the inverse rotation in terms of the current
554 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
555 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
556 if (is_h_flipped == is_v_flipped) {
557 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
558 NATIVE_WINDOW_TRANSFORM_FLIP_H;
560 winWidth = s.active.h;
561 winHeight = s.active.w;
563 const Rect winCrop = activeCrop.transform(
564 invTransform, s.active.w, s.active.h);
566 // below, crop is intersected with winCrop expressed in crop's coordinate space
567 float xScale = crop.getWidth() / float(winWidth);
568 float yScale = crop.getHeight() / float(winHeight);
570 float insetL = winCrop.left * xScale;
571 float insetT = winCrop.top * yScale;
572 float insetR = (winWidth - winCrop.right ) * xScale;
573 float insetB = (winHeight - winCrop.bottom) * yScale;
577 crop.right -= insetR;
578 crop.bottom -= insetB;
584 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z)
586 void Layer::setGeometry(
587 const sp<const DisplayDevice>& hw,
588 HWComposer::HWCLayerInterface& layer)
592 const auto hwcId = displayDevice->getHwcDisplayId();
593 auto& hwcInfo = mHwcLayers[hwcId];
595 layer.setDefaultState();
600 hwcInfo.forceClientComposition = false;
602 if (isSecure() && !displayDevice->isSecure()) {
603 hwcInfo.forceClientComposition = true;
606 auto& hwcLayer = hwcInfo.layer;
608 layer.setSkip(false);
610 if (isSecure() && !hw->isSecure()) {
615 // this gives us only the "orientation" component of the transform
616 const State& s(getDrawingState());
618 auto blendMode = HWC2::BlendMode::None;
619 if (!isOpaque(s) || getAlpha() != 1.0f) {
620 blendMode = mPremultipliedAlpha ?
621 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
623 auto error = hwcLayer->setBlendMode(blendMode);
624 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
625 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
626 to_string(error).c_str(), static_cast<int32_t>(error));
628 if (!isOpaque(s) || getAlpha() != 0xFF) {
629 layer.setBlending(mPremultipliedAlpha ?
630 HWC_BLENDING_PREMULT :
631 HWC_BLENDING_COVERAGE);
635 // apply the layer's transform, followed by the display's global transform
636 // here we're guaranteed that the layer's transform preserves rects
637 Region activeTransparentRegion(s.activeTransparentRegion);
638 Transform t = getTransform();
639 if (!s.crop.isEmpty()) {
640 Rect activeCrop(s.crop);
641 activeCrop = t.transform(activeCrop);
643 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
645 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
649 activeCrop = t.inverse().transform(activeCrop, true);
650 // This needs to be here as transform.transform(Rect) computes the
651 // transformed rect and then takes the bounding box of the result before
652 // returning. This means
653 // transform.inverse().transform(transform.transform(Rect)) != Rect
654 // in which case we need to make sure the final rect is clipped to the
656 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
659 // mark regions outside the crop as transparent
660 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
661 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
662 s.active.w, s.active.h));
663 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
664 activeCrop.left, activeCrop.bottom));
665 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
666 s.active.w, activeCrop.bottom));
669 Rect frame(t.transform(computeBounds(activeTransparentRegion)));
670 if (!s.finalCrop.isEmpty()) {
671 if(!frame.intersect(s.finalCrop, &frame)) {
676 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
679 const Transform& tr(displayDevice->getTransform());
680 Rect transformedFrame = tr.transform(frame);
681 error = hwcLayer->setDisplayFrame(transformedFrame);
682 if (error != HWC2::Error::None) {
683 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)",
684 mName.string(), transformedFrame.left, transformedFrame.top,
685 transformedFrame.right, transformedFrame.bottom,
686 to_string(error).c_str(), static_cast<int32_t>(error));
688 hwcInfo.displayFrame = transformedFrame;
691 FloatRect sourceCrop = computeCrop(displayDevice);
692 error = hwcLayer->setSourceCrop(sourceCrop);
693 if (error != HWC2::Error::None) {
694 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: "
695 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top,
696 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(),
697 static_cast<int32_t>(error));
699 hwcInfo.sourceCrop = sourceCrop;
702 float alpha = getAlpha();
703 error = hwcLayer->setPlaneAlpha(alpha);
704 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
705 "%s (%d)", mName.string(), alpha, to_string(error).c_str(),
706 static_cast<int32_t>(error));
708 error = hwcLayer->setZOrder(z);
709 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
710 mName.string(), z, to_string(error).c_str(),
711 static_cast<int32_t>(error));
715 sp<Layer> parent = mDrawingParent.promote();
717 auto& parentState = parent->getDrawingState();
718 type = parentState.type;
719 appId = parentState.appId;
722 error = hwcLayer->setInfo(type, appId);
723 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)",
724 mName.string(), static_cast<int32_t>(error));
726 if (!frame.intersect(hw->getViewport(), &frame)) {
729 const Transform& tr(hw->getTransform());
730 layer.setFrame(tr.transform(frame));
731 layer.setCrop(computeCrop(hw));
732 layer.setPlaneAlpha(getAlpha());
736 * Transformations are applied in this order:
737 * 1) buffer orientation/flip/mirror
738 * 2) state transformation (window manager)
739 * 3) layer orientation (screen orientation)
740 * (NOTE: the matrices are multiplied in reverse order)
743 const Transform bufferOrientation(mCurrentTransform);
744 Transform transform(tr * t * bufferOrientation);
746 if (getTransformToDisplayInverse()) {
748 * the code below applies the primary display's inverse transform to the
751 uint32_t invTransform =
752 DisplayDevice::getPrimaryDisplayOrientationTransform();
753 // calculate the inverse transform
754 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
755 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
756 NATIVE_WINDOW_TRANSFORM_FLIP_H;
760 * Here we cancel out the orientation component of the WM transform.
761 * The scaling and translate components are already included in our bounds
762 * computation so it's enough to just omit it in the composition.
763 * See comment in onDraw with ref to b/36727915 for why.
765 transform = Transform(invTransform) * tr * bufferOrientation;
768 // this gives us only the "orientation" component of the transform
769 const uint32_t orientation = transform.getOrientation();
771 if (orientation & Transform::ROT_INVALID) {
772 // we can only handle simple transformation
773 hwcInfo.forceClientComposition = true;
775 auto transform = static_cast<HWC2::Transform>(orientation);
776 auto error = hwcLayer->setTransform(transform);
777 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
778 "%s (%d)", mName.string(), to_string(transform).c_str(),
779 to_string(error).c_str(), static_cast<int32_t>(error));
782 if (orientation & Transform::ROT_INVALID) {
783 // we can only handle simple transformation
786 layer.setTransform(orientation);
792 void Layer::forceClientComposition(int32_t hwcId) {
793 if (mHwcLayers.count(hwcId) == 0) {
794 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
798 mHwcLayers[hwcId].forceClientComposition = true;
801 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
802 // Apply this display's projection's viewport to the visible region
803 // before giving it to the HWC HAL.
804 const Transform& tr = displayDevice->getTransform();
805 const auto& viewport = displayDevice->getViewport();
806 Region visible = tr.transform(visibleRegion.intersect(viewport));
807 auto hwcId = displayDevice->getHwcDisplayId();
808 auto& hwcInfo = mHwcLayers[hwcId];
809 auto& hwcLayer = hwcInfo.layer;
810 auto error = hwcLayer->setVisibleRegion(visible);
811 if (error != HWC2::Error::None) {
812 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
813 to_string(error).c_str(), static_cast<int32_t>(error));
814 visible.dump(LOG_TAG);
817 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
818 if (error != HWC2::Error::None) {
819 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
820 to_string(error).c_str(), static_cast<int32_t>(error));
821 surfaceDamageRegion.dump(LOG_TAG);
825 if (mSidebandStream.get()) {
826 setCompositionType(hwcId, HWC2::Composition::Sideband);
827 ALOGV("[%s] Requesting Sideband composition", mName.string());
828 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
829 if (error != HWC2::Error::None) {
830 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
831 mName.string(), mSidebandStream->handle(),
832 to_string(error).c_str(), static_cast<int32_t>(error));
838 if (hwcInfo.forceClientComposition ||
839 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
840 ALOGV("[%s] Requesting Client composition", mName.string());
841 setCompositionType(hwcId, HWC2::Composition::Client);
846 if (mActiveBuffer == nullptr) {
847 setCompositionType(hwcId, HWC2::Composition::SolidColor);
849 // For now, we only support black for DimLayer
850 error = hwcLayer->setColor({0, 0, 0, 255});
851 if (error != HWC2::Error::None) {
852 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
853 to_string(error).c_str(), static_cast<int32_t>(error));
856 // Clear out the transform, because it doesn't make sense absent a
858 error = hwcLayer->setTransform(HWC2::Transform::None);
859 if (error != HWC2::Error::None) {
860 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
861 to_string(error).c_str(), static_cast<int32_t>(error));
867 // Device or Cursor layers
868 if (mPotentialCursor) {
869 ALOGV("[%s] Requesting Cursor composition", mName.string());
870 setCompositionType(hwcId, HWC2::Composition::Cursor);
872 ALOGV("[%s] Requesting Device composition", mName.string());
873 setCompositionType(hwcId, HWC2::Composition::Device);
876 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace);
877 error = hwcLayer->setDataspace(mCurrentState.dataSpace);
878 if (error != HWC2::Error::None) {
879 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(),
880 mCurrentState.dataSpace, to_string(error).c_str(),
881 static_cast<int32_t>(error));
884 uint32_t hwcSlot = 0;
885 sp<GraphicBuffer> hwcBuffer;
886 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer,
887 &hwcSlot, &hwcBuffer);
889 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
890 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence);
891 if (error != HWC2::Error::None) {
892 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
893 mActiveBuffer->handle, to_string(error).c_str(),
894 static_cast<int32_t>(error));
899 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
900 HWComposer::HWCLayerInterface& layer) {
901 // we have to set the visible region on every frame because
902 // we currently free it during onLayerDisplayed(), which is called
903 // after HWComposer::commit() -- every frame.
904 // Apply this display's projection's viewport to the visible region
905 // before giving it to the HWC HAL.
906 const Transform& tr = hw->getTransform();
907 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
908 layer.setVisibleRegionScreen(visible);
909 layer.setSurfaceDamage(surfaceDamageRegion);
910 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
912 if (mSidebandStream.get()) {
913 layer.setSidebandStream(mSidebandStream);
915 // NOTE: buffer can be NULL if the client never drew into this
916 // layer yet, or if we ran out of memory
917 layer.setBuffer(mActiveBuffer);
923 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
924 auto hwcId = displayDevice->getHwcDisplayId();
925 if (mHwcLayers.count(hwcId) == 0 ||
926 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
930 // This gives us only the "orientation" component of the transform
931 const State& s(getCurrentState());
933 // Apply the layer's transform, followed by the display's global transform
934 // Here we're guaranteed that the layer's transform preserves rects
935 Rect win(s.active.w, s.active.h);
936 if (!s.crop.isEmpty()) {
937 win.intersect(s.crop, &win);
939 // Subtract the transparent region and snap to the bounds
940 Rect bounds = reduce(win, s.activeTransparentRegion);
941 Rect frame(getTransform().transform(bounds));
942 frame.intersect(displayDevice->getViewport(), &frame);
943 if (!s.finalCrop.isEmpty()) {
944 frame.intersect(s.finalCrop, &frame);
946 auto& displayTransform(displayDevice->getTransform());
947 auto position = displayTransform.transform(frame);
949 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
951 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
952 "to (%d, %d): %s (%d)", mName.string(), position.left,
953 position.top, to_string(error).c_str(),
954 static_cast<int32_t>(error));
957 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
958 HWComposer::HWCLayerInterface& layer) {
961 // TODO: there is a possible optimization here: we only need to set the
962 // acquire fence the first time a new buffer is acquired on EACH display.
964 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
965 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
966 if (fence->isValid()) {
967 fenceFd = fence->dup();
969 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
973 layer.setAcquireFenceFd(fenceFd);
976 Rect Layer::getPosition(
977 const sp<const DisplayDevice>& hw)
979 // this gives us only the "orientation" component of the transform
980 const State& s(getCurrentState());
982 // apply the layer's transform, followed by the display's global transform
983 // here we're guaranteed that the layer's transform preserves rects
984 Rect win(s.active.w, s.active.h);
985 if (!s.crop.isEmpty()) {
986 win.intersect(s.crop, &win);
988 // subtract the transparent region and snap to the bounds
989 Rect bounds = reduce(win, s.activeTransparentRegion);
990 Rect frame(getTransform().transform(bounds));
991 frame.intersect(hw->getViewport(), &frame);
992 if (!s.finalCrop.isEmpty()) {
993 frame.intersect(s.finalCrop, &frame);
995 const Transform& tr(hw->getTransform());
996 return Rect(tr.transform(frame));
1000 // ---------------------------------------------------------------------------
1002 // ---------------------------------------------------------------------------
1004 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
1005 onDraw(hw, clip, false);
1008 void Layer::draw(const sp<const DisplayDevice>& hw,
1009 bool useIdentityTransform) const {
1010 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
1013 void Layer::draw(const sp<const DisplayDevice>& hw) const {
1014 onDraw(hw, Region(hw->bounds()), false);
1017 static constexpr mat4 inverseOrientation(uint32_t transform) {
1018 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
1019 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
1020 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
1023 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1026 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) {
1029 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) {
1036 * onDraw will draw the current layer onto the presentable buffer
1038 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
1039 bool useIdentityTransform) const
1043 if (CC_UNLIKELY(mActiveBuffer == 0)) {
1044 // the texture has not been created yet, this Layer has
1045 // in fact never been drawn into. This happens frequently with
1046 // SurfaceView because the WindowManager can't know when the client
1047 // has drawn the first time.
1049 // If there is nothing under us, we paint the screen in black, otherwise
1050 // we just skip this update.
1052 // figure out if there is something below us
1054 bool finished = false;
1055 mFlinger->mDrawingState.traverseInZOrder([&](Layer* layer) {
1056 if (finished || layer == static_cast<Layer const*>(this)) {
1060 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
1062 // if not everything below us is covered, we plug the holes!
1063 Region holes(clip.subtract(under));
1064 if (!holes.isEmpty()) {
1065 clearWithOpenGL(hw, 0, 0, 0, 1);
1070 // Bind the current buffer to the GL texture, and wait for it to be
1071 // ready for us to draw into.
1072 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
1073 if (err != NO_ERROR) {
1074 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
1075 // Go ahead and draw the buffer anyway; no matter what we do the screen
1076 // is probably going to have something visibly wrong.
1079 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
1081 RenderEngine& engine(mFlinger->getRenderEngine());
1083 if (!blackOutLayer) {
1084 // TODO: we could be more subtle with isFixedSize()
1085 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
1087 // Query the texture matrix given our current filtering mode.
1088 float textureMatrix[16];
1089 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
1090 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
1092 if (getTransformToDisplayInverse()) {
1095 * the code below applies the primary display's inverse transform to
1096 * the texture transform
1098 uint32_t transform =
1099 DisplayDevice::getPrimaryDisplayOrientationTransform();
1100 mat4 tr = inverseOrientation(transform);
1103 * TODO(b/36727915): This is basically a hack.
1105 * Ensure that regardless of the parent transformation,
1106 * this buffer is always transformed from native display
1107 * orientation to display orientation. For example, in the case
1108 * of a camera where the buffer remains in native orientation,
1109 * we want the pixels to always be upright.
1111 sp<Layer> p = mDrawingParent.promote();
1113 const auto parentTransform = p->getTransform();
1114 tr = tr * inverseOrientation(parentTransform.getOrientation());
1117 // and finally apply it to the original texture matrix
1118 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
1119 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
1122 // Set things up for texturing.
1123 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
1124 mTexture.setFiltering(useFiltering);
1125 mTexture.setMatrix(textureMatrix);
1127 engine.setupLayerTexturing(mTexture);
1129 engine.setupLayerBlackedOut();
1131 drawWithOpenGL(hw, useIdentityTransform);
1132 engine.disableTexturing();
1136 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
1137 float red, float green, float blue,
1140 RenderEngine& engine(mFlinger->getRenderEngine());
1141 computeGeometry(hw, mMesh, false);
1142 engine.setupFillWithColor(red, green, blue, alpha);
1143 engine.drawMesh(mMesh);
1146 void Layer::clearWithOpenGL(
1147 const sp<const DisplayDevice>& hw) const {
1148 clearWithOpenGL(hw, 0,0,0,0);
1151 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1152 bool useIdentityTransform) const {
1153 const State& s(getDrawingState());
1155 computeGeometry(hw, mMesh, useIdentityTransform);
1158 * NOTE: the way we compute the texture coordinates here produces
1159 * different results than when we take the HWC path -- in the later case
1160 * the "source crop" is rounded to texel boundaries.
1161 * This can produce significantly different results when the texture
1162 * is scaled by a large amount.
1164 * The GL code below is more logical (imho), and the difference with
1165 * HWC is due to a limitation of the HWC API to integers -- a question
1166 * is suspend is whether we should ignore this problem or revert to
1167 * GL composition when a buffer scaling is applied (maybe with some
1168 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1169 * like more of a hack.
1171 Rect win(computeBounds());
1173 Transform t = getTransform();
1174 if (!s.finalCrop.isEmpty()) {
1175 win = t.transform(win);
1176 if (!win.intersect(s.finalCrop, &win)) {
1179 win = t.inverse().transform(win);
1180 if (!win.intersect(computeBounds(), &win)) {
1185 float left = float(win.left) / float(s.active.w);
1186 float top = float(win.top) / float(s.active.h);
1187 float right = float(win.right) / float(s.active.w);
1188 float bottom = float(win.bottom) / float(s.active.h);
1190 // TODO: we probably want to generate the texture coords with the mesh
1191 // here we assume that we only have 4 vertices
1192 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1193 texCoords[0] = vec2(left, 1.0f - top);
1194 texCoords[1] = vec2(left, 1.0f - bottom);
1195 texCoords[2] = vec2(right, 1.0f - bottom);
1196 texCoords[3] = vec2(right, 1.0f - top);
1198 RenderEngine& engine(mFlinger->getRenderEngine());
1199 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha());
1201 engine.setSourceDataSpace(mCurrentState.dataSpace);
1203 engine.drawMesh(mMesh);
1204 engine.disableBlending();
1208 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1210 if (mHwcLayers.count(hwcId) == 0) {
1211 ALOGE("setCompositionType called without a valid HWC layer");
1214 auto& hwcInfo = mHwcLayers[hwcId];
1215 auto& hwcLayer = hwcInfo.layer;
1216 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1217 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1218 if (hwcInfo.compositionType != type) {
1219 ALOGV(" actually setting");
1220 hwcInfo.compositionType = type;
1222 auto error = hwcLayer->setCompositionType(type);
1223 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1224 "composition type %s: %s (%d)", mName.string(),
1225 to_string(type).c_str(), to_string(error).c_str(),
1226 static_cast<int32_t>(error));
1231 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1232 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1233 // If we're querying the composition type for a display that does not
1234 // have a HWC counterpart, then it will always be Client
1235 return HWC2::Composition::Client;
1237 if (mHwcLayers.count(hwcId) == 0) {
1238 ALOGE("getCompositionType called with an invalid HWC layer");
1239 return HWC2::Composition::Invalid;
1241 return mHwcLayers.at(hwcId).compositionType;
1244 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1245 if (mHwcLayers.count(hwcId) == 0) {
1246 ALOGE("setClearClientTarget called without a valid HWC layer");
1249 mHwcLayers[hwcId].clearClientTarget = clear;
1252 bool Layer::getClearClientTarget(int32_t hwcId) const {
1253 if (mHwcLayers.count(hwcId) == 0) {
1254 ALOGE("getClearClientTarget called without a valid HWC layer");
1257 return mHwcLayers.at(hwcId).clearClientTarget;
1261 uint32_t Layer::getProducerStickyTransform() const {
1262 int producerStickyTransform = 0;
1263 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1265 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1266 strerror(-ret), ret);
1269 return static_cast<uint32_t>(producerStickyTransform);
1272 bool Layer::latchUnsignaledBuffers() {
1273 static bool propertyLoaded = false;
1274 static bool latch = false;
1275 static std::mutex mutex;
1276 std::lock_guard<std::mutex> lock(mutex);
1277 if (!propertyLoaded) {
1278 char value[PROPERTY_VALUE_MAX] = {};
1279 property_get("debug.sf.latch_unsignaled", value, "0");
1280 latch = atoi(value);
1281 propertyLoaded = true;
1286 uint64_t Layer::getHeadFrameNumber() const {
1287 Mutex::Autolock lock(mQueueItemLock);
1288 if (!mQueueItems.empty()) {
1289 return mQueueItems[0].mFrameNumber;
1291 return mCurrentFrameNumber;
1295 bool Layer::headFenceHasSignaled() const {
1297 if (latchUnsignaledBuffers()) {
1301 Mutex::Autolock lock(mQueueItemLock);
1302 if (mQueueItems.empty()) {
1305 if (mQueueItems[0].mIsDroppable) {
1306 // Even though this buffer's fence may not have signaled yet, it could
1307 // be replaced by another buffer before it has a chance to, which means
1308 // that it's possible to get into a situation where a buffer is never
1309 // able to be latched. To avoid this, grab this buffer anyway.
1312 return mQueueItems[0].mFenceTime->getSignalTime() !=
1313 Fence::SIGNAL_TIME_PENDING;
1319 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1320 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1321 // Don't bother with a SyncPoint, since we've already latched the
1326 Mutex::Autolock lock(mLocalSyncPointMutex);
1327 mLocalSyncPoints.push_back(point);
1331 void Layer::setFiltering(bool filtering) {
1332 mFiltering = filtering;
1335 bool Layer::getFiltering() const {
1339 // As documented in libhardware header, formats in the range
1340 // 0x100 - 0x1FF are specific to the HAL implementation, and
1341 // are known to have no alpha channel
1342 // TODO: move definition for device-specific range into
1343 // hardware.h, instead of using hard-coded values here.
1344 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1346 bool Layer::getOpacityForFormat(uint32_t format) {
1347 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1351 case HAL_PIXEL_FORMAT_RGBA_8888:
1352 case HAL_PIXEL_FORMAT_BGRA_8888:
1353 case HAL_PIXEL_FORMAT_RGBA_FP16:
1354 case HAL_PIXEL_FORMAT_RGBA_1010102:
1357 // in all other case, we have no blending (also for unknown formats)
1361 // ----------------------------------------------------------------------------
1363 // ----------------------------------------------------------------------------
1365 static void boundPoint(vec2* point, const Rect& crop) {
1366 if (point->x < crop.left) {
1367 point->x = crop.left;
1369 if (point->x > crop.right) {
1370 point->x = crop.right;
1372 if (point->y < crop.top) {
1373 point->y = crop.top;
1375 if (point->y > crop.bottom) {
1376 point->y = crop.bottom;
1380 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1381 bool useIdentityTransform) const
1383 const Layer::State& s(getDrawingState());
1384 const Transform hwTransform(hw->getTransform());
1385 const uint32_t hw_h = hw->getHeight();
1386 Rect win = computeBounds();
1388 vec2 lt = vec2(win.left, win.top);
1389 vec2 lb = vec2(win.left, win.bottom);
1390 vec2 rb = vec2(win.right, win.bottom);
1391 vec2 rt = vec2(win.right, win.top);
1393 Transform layerTransform = getTransform();
1394 if (!useIdentityTransform) {
1395 lt = layerTransform.transform(lt);
1396 lb = layerTransform.transform(lb);
1397 rb = layerTransform.transform(rb);
1398 rt = layerTransform.transform(rt);
1401 if (!s.finalCrop.isEmpty()) {
1402 boundPoint(<, s.finalCrop);
1403 boundPoint(&lb, s.finalCrop);
1404 boundPoint(&rb, s.finalCrop);
1405 boundPoint(&rt, s.finalCrop);
1408 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1409 position[0] = hwTransform.transform(lt);
1410 position[1] = hwTransform.transform(lb);
1411 position[2] = hwTransform.transform(rb);
1412 position[3] = hwTransform.transform(rt);
1413 for (size_t i=0 ; i<4 ; i++) {
1414 position[i].y = hw_h - position[i].y;
1418 bool Layer::isOpaque(const Layer::State& s) const
1420 // if we don't have a buffer or sidebandStream yet, we're translucent regardless of the
1421 // layer's opaque flag.
1422 if ((mSidebandStream == nullptr) && (mActiveBuffer == nullptr)) {
1426 // if the layer has the opaque flag, then we're always opaque,
1427 // otherwise we use the current buffer's format.
1428 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1431 bool Layer::isSecure() const
1433 const Layer::State& s(mDrawingState);
1434 return (s.flags & layer_state_t::eLayerSecure);
1437 bool Layer::isProtected() const
1439 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1440 return (activeBuffer != 0) &&
1441 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1444 bool Layer::isFixedSize() const {
1445 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1448 bool Layer::isCropped() const {
1449 return !mCurrentCrop.isEmpty();
1452 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1453 return mNeedsFiltering || hw->needsFiltering();
1456 void Layer::setVisibleRegion(const Region& visibleRegion) {
1457 // always called from main thread
1458 this->visibleRegion = visibleRegion;
1461 void Layer::setCoveredRegion(const Region& coveredRegion) {
1462 // always called from main thread
1463 this->coveredRegion = coveredRegion;
1466 void Layer::setVisibleNonTransparentRegion(const Region&
1467 setVisibleNonTransparentRegion) {
1468 // always called from main thread
1469 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1472 // ----------------------------------------------------------------------------
1474 // ----------------------------------------------------------------------------
1476 void Layer::pushPendingState() {
1477 if (!mCurrentState.modified) {
1481 // If this transaction is waiting on the receipt of a frame, generate a sync
1482 // point and send it to the remote layer.
1483 if (mCurrentState.barrierLayer != nullptr) {
1484 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote();
1485 if (barrierLayer == nullptr) {
1486 ALOGE("[%s] Unable to promote barrier Layer.", mName.string());
1487 // If we can't promote the layer we are intended to wait on,
1488 // then it is expired or otherwise invalid. Allow this transaction
1489 // to be applied as per normal (no synchronization).
1490 mCurrentState.barrierLayer = nullptr;
1492 auto syncPoint = std::make_shared<SyncPoint>(
1493 mCurrentState.frameNumber);
1494 if (barrierLayer->addSyncPoint(syncPoint)) {
1495 mRemoteSyncPoints.push_back(std::move(syncPoint));
1497 // We already missed the frame we're supposed to synchronize
1498 // on, so go ahead and apply the state update
1499 mCurrentState.barrierLayer = nullptr;
1503 // Wake us up to check if the frame has been received
1504 setTransactionFlags(eTransactionNeeded);
1505 mFlinger->setTransactionFlags(eTraversalNeeded);
1507 mPendingStates.push_back(mCurrentState);
1508 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1511 void Layer::popPendingState(State* stateToCommit) {
1512 auto oldFlags = stateToCommit->flags;
1513 *stateToCommit = mPendingStates[0];
1514 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1515 (stateToCommit->flags & stateToCommit->mask);
1517 mPendingStates.removeAt(0);
1518 ATRACE_INT(mTransactionName.string(), mPendingStates.size());
1521 bool Layer::applyPendingStates(State* stateToCommit) {
1522 bool stateUpdateAvailable = false;
1523 while (!mPendingStates.empty()) {
1524 if (mPendingStates[0].barrierLayer != nullptr) {
1525 if (mRemoteSyncPoints.empty()) {
1526 // If we don't have a sync point for this, apply it anyway. It
1527 // will be visually wrong, but it should keep us from getting
1528 // into too much trouble.
1529 ALOGE("[%s] No local sync point found", mName.string());
1530 popPendingState(stateToCommit);
1531 stateUpdateAvailable = true;
1535 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1536 mPendingStates[0].frameNumber) {
1537 ALOGE("[%s] Unexpected sync point frame number found",
1540 // Signal our end of the sync point and then dispose of it
1541 mRemoteSyncPoints.front()->setTransactionApplied();
1542 mRemoteSyncPoints.pop_front();
1546 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1547 // Apply the state update
1548 popPendingState(stateToCommit);
1549 stateUpdateAvailable = true;
1551 // Signal our end of the sync point and then dispose of it
1552 mRemoteSyncPoints.front()->setTransactionApplied();
1553 mRemoteSyncPoints.pop_front();
1558 popPendingState(stateToCommit);
1559 stateUpdateAvailable = true;
1563 // If we still have pending updates, wake SurfaceFlinger back up and point
1564 // it at this layer so we can process them
1565 if (!mPendingStates.empty()) {
1566 setTransactionFlags(eTransactionNeeded);
1567 mFlinger->setTransactionFlags(eTraversalNeeded);
1570 mCurrentState.modified = false;
1571 return stateUpdateAvailable;
1574 void Layer::notifyAvailableFrames() {
1575 auto headFrameNumber = getHeadFrameNumber();
1576 bool headFenceSignaled = headFenceHasSignaled();
1577 Mutex::Autolock lock(mLocalSyncPointMutex);
1578 for (auto& point : mLocalSyncPoints) {
1579 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1580 point->setFrameAvailable();
1585 uint32_t Layer::doTransaction(uint32_t flags) {
1589 Layer::State c = getCurrentState();
1590 if (!applyPendingStates(&c)) {
1594 const Layer::State& s(getDrawingState());
1596 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1597 (c.requested.h != s.requested.h);
1600 // the size changed, we need to ask our client to request a new buffer
1601 ALOGD_IF(DEBUG_RESIZE,
1602 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1603 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1604 " requested={ wh={%4u,%4u} }}\n"
1605 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1606 " requested={ wh={%4u,%4u} }}\n",
1607 this, getName().string(), mCurrentTransform,
1608 getEffectiveScalingMode(),
1609 c.active.w, c.active.h,
1616 c.requested.w, c.requested.h,
1617 s.active.w, s.active.h,
1624 s.requested.w, s.requested.h);
1626 // record the new size, form this point on, when the client request
1627 // a buffer, it'll get the new size.
1628 mSurfaceFlingerConsumer->setDefaultBufferSize(
1629 c.requested.w, c.requested.h);
1632 const bool resizePending = (c.requested.w != c.active.w) ||
1633 (c.requested.h != c.active.h);
1634 if (!isFixedSize()) {
1635 if (resizePending && mSidebandStream == NULL) {
1636 // don't let Layer::doTransaction update the drawing state
1637 // if we have a pending resize, unless we are in fixed-size mode.
1638 // the drawing state will be updated only once we receive a buffer
1639 // with the correct size.
1641 // in particular, we want to make sure the clip (which is part
1642 // of the geometry state) is latched together with the size but is
1643 // latched immediately when no resizing is involved.
1645 // If a sideband stream is attached, however, we want to skip this
1646 // optimization so that transactions aren't missed when a buffer
1649 flags |= eDontUpdateGeometryState;
1653 // Here we apply various requested geometry states, depending on our
1654 // latching configuration. See Layer.h for a detailed discussion of
1655 // how geometry latching is controlled.
1656 if (!(flags & eDontUpdateGeometryState)) {
1657 Layer::State& editCurrentState(getCurrentState());
1659 // If mFreezeGeometryUpdates is true we are in the setGeometryAppliesWithResize
1660 // mode, which causes attributes which normally latch regardless of scaling mode,
1661 // to be delayed. We copy the requested state to the active state making sure
1662 // to respect these rules (again see Layer.h for a detailed discussion).
1664 // There is an awkward asymmetry in the handling of the crop states in the position
1665 // states, as can be seen below. Largely this arises from position and transform
1666 // being stored in the same data structure while having different latching rules.
1669 // Careful that "c" and editCurrentState may not begin as equivalent due to
1670 // applyPendingStates in the presence of deferred transactions.
1671 if (mFreezeGeometryUpdates) {
1672 float tx = c.active.transform.tx();
1673 float ty = c.active.transform.ty();
1674 c.active = c.requested;
1675 c.active.transform.set(tx, ty);
1676 editCurrentState.active = c.active;
1678 editCurrentState.active = editCurrentState.requested;
1679 c.active = c.requested;
1683 if (s.active != c.active) {
1684 // invalidate and recompute the visible regions if needed
1685 flags |= Layer::eVisibleRegion;
1688 if (c.sequence != s.sequence) {
1689 // invalidate and recompute the visible regions if needed
1690 flags |= eVisibleRegion;
1691 this->contentDirty = true;
1693 // we may use linear filtering, if the matrix scales us
1694 const uint8_t type = c.active.transform.getType();
1695 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1696 (type >= Transform::SCALE));
1699 // If the layer is hidden, signal and clear out all local sync points so
1700 // that transactions for layers depending on this layer's frames becoming
1701 // visible are not blocked
1702 if (c.flags & layer_state_t::eLayerHidden) {
1706 // Commit the transaction
1707 commitTransaction(c);
1711 void Layer::commitTransaction(const State& stateToCommit) {
1712 mDrawingState = stateToCommit;
1715 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1716 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1719 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1720 return android_atomic_or(flags, &mTransactionFlags);
1723 bool Layer::setPosition(float x, float y, bool immediate) {
1724 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1726 mCurrentState.sequence++;
1728 // We update the requested and active position simultaneously because
1729 // we want to apply the position portion of the transform matrix immediately,
1730 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1731 mCurrentState.requested.transform.set(x, y);
1732 if (immediate && !mFreezeGeometryUpdates) {
1733 // Here we directly update the active state
1734 // unlike other setters, because we store it within
1735 // the transform, but use different latching rules.
1737 mCurrentState.active.transform.set(x, y);
1739 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1741 mCurrentState.modified = true;
1742 setTransactionFlags(eTransactionNeeded);
1746 bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) {
1747 ssize_t idx = mCurrentChildren.indexOf(childLayer);
1751 if (childLayer->setLayer(z)) {
1752 mCurrentChildren.removeAt(idx);
1753 mCurrentChildren.add(childLayer);
1758 bool Layer::setLayer(int32_t z) {
1759 if (mCurrentState.z == z)
1761 mCurrentState.sequence++;
1762 mCurrentState.z = z;
1763 mCurrentState.modified = true;
1765 // Discard all relative layering.
1766 if (mCurrentState.zOrderRelativeOf != nullptr) {
1767 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote();
1768 if (strongRelative != nullptr) {
1769 strongRelative->removeZOrderRelative(this);
1771 mCurrentState.zOrderRelativeOf = nullptr;
1773 setTransactionFlags(eTransactionNeeded);
1777 void Layer::removeZOrderRelative(const wp<Layer>& relative) {
1778 mCurrentState.zOrderRelatives.remove(relative);
1779 mCurrentState.sequence++;
1780 mCurrentState.modified = true;
1781 setTransactionFlags(eTransactionNeeded);
1784 void Layer::addZOrderRelative(const wp<Layer>& relative) {
1785 mCurrentState.zOrderRelatives.add(relative);
1786 mCurrentState.modified = true;
1787 mCurrentState.sequence++;
1788 setTransactionFlags(eTransactionNeeded);
1791 bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) {
1792 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get());
1793 if (handle == nullptr) {
1796 sp<Layer> relative = handle->owner.promote();
1797 if (relative == nullptr) {
1801 mCurrentState.sequence++;
1802 mCurrentState.modified = true;
1803 mCurrentState.z = z;
1805 mCurrentState.zOrderRelativeOf = relative;
1806 relative->addZOrderRelative(this);
1808 setTransactionFlags(eTransactionNeeded);
1813 bool Layer::setSize(uint32_t w, uint32_t h) {
1814 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1816 mCurrentState.requested.w = w;
1817 mCurrentState.requested.h = h;
1818 mCurrentState.modified = true;
1819 setTransactionFlags(eTransactionNeeded);
1823 bool Layer::setAlpha(float alpha) {
1825 bool Layer::setAlpha(uint8_t alpha) {
1827 if (mCurrentState.alpha == alpha)
1829 mCurrentState.sequence++;
1830 mCurrentState.alpha = alpha;
1831 mCurrentState.modified = true;
1832 setTransactionFlags(eTransactionNeeded);
1835 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1836 mCurrentState.sequence++;
1837 mCurrentState.requested.transform.set(
1838 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy);
1839 mCurrentState.modified = true;
1840 setTransactionFlags(eTransactionNeeded);
1843 bool Layer::setTransparentRegionHint(const Region& transparent) {
1844 mCurrentState.requestedTransparentRegion = transparent;
1845 mCurrentState.modified = true;
1846 setTransactionFlags(eTransactionNeeded);
1849 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1850 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1851 if (mCurrentState.flags == newFlags)
1853 mCurrentState.sequence++;
1854 mCurrentState.flags = newFlags;
1855 mCurrentState.mask = mask;
1856 mCurrentState.modified = true;
1857 setTransactionFlags(eTransactionNeeded);
1861 bool Layer::setCrop(const Rect& crop, bool immediate) {
1862 if (mCurrentState.requestedCrop == crop)
1864 mCurrentState.sequence++;
1865 mCurrentState.requestedCrop = crop;
1866 if (immediate && !mFreezeGeometryUpdates) {
1867 mCurrentState.crop = crop;
1869 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1871 mCurrentState.modified = true;
1872 setTransactionFlags(eTransactionNeeded);
1876 bool Layer::setFinalCrop(const Rect& crop, bool immediate) {
1877 if (mCurrentState.requestedFinalCrop == crop)
1879 mCurrentState.sequence++;
1880 mCurrentState.requestedFinalCrop = crop;
1881 if (immediate && !mFreezeGeometryUpdates) {
1882 mCurrentState.finalCrop = crop;
1884 mFreezeGeometryUpdates = mFreezeGeometryUpdates || !immediate;
1886 mCurrentState.modified = true;
1887 setTransactionFlags(eTransactionNeeded);
1891 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1892 if (scalingMode == mOverrideScalingMode)
1894 mOverrideScalingMode = scalingMode;
1895 setTransactionFlags(eTransactionNeeded);
1899 void Layer::setInfo(uint32_t type, uint32_t appId) {
1900 mCurrentState.appId = appId;
1901 mCurrentState.type = type;
1902 mCurrentState.modified = true;
1903 setTransactionFlags(eTransactionNeeded);
1906 uint32_t Layer::getEffectiveScalingMode() const {
1907 if (mOverrideScalingMode >= 0) {
1908 return mOverrideScalingMode;
1910 return mCurrentScalingMode;
1913 bool Layer::setLayerStack(uint32_t layerStack) {
1914 if (mCurrentState.layerStack == layerStack)
1916 mCurrentState.sequence++;
1917 mCurrentState.layerStack = layerStack;
1918 mCurrentState.modified = true;
1919 setTransactionFlags(eTransactionNeeded);
1923 bool Layer::setDataSpace(android_dataspace dataSpace) {
1924 if (mCurrentState.dataSpace == dataSpace)
1926 mCurrentState.sequence++;
1927 mCurrentState.dataSpace = dataSpace;
1928 mCurrentState.modified = true;
1929 setTransactionFlags(eTransactionNeeded);
1933 android_dataspace Layer::getDataSpace() const {
1934 return mCurrentState.dataSpace;
1937 uint32_t Layer::getLayerStack() const {
1938 auto p = mDrawingParent.promote();
1940 return getDrawingState().layerStack;
1942 return p->getLayerStack();
1945 void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer,
1946 uint64_t frameNumber) {
1947 mCurrentState.barrierLayer = barrierLayer;
1948 mCurrentState.frameNumber = frameNumber;
1949 // We don't set eTransactionNeeded, because just receiving a deferral
1950 // request without any other state updates shouldn't actually induce a delay
1951 mCurrentState.modified = true;
1953 mCurrentState.barrierLayer = nullptr;
1954 mCurrentState.frameNumber = 0;
1955 mCurrentState.modified = false;
1958 void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle,
1959 uint64_t frameNumber) {
1960 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get());
1961 deferTransactionUntil(handle->owner.promote(), frameNumber);
1964 void Layer::useSurfaceDamage() {
1965 if (mFlinger->mForceFullDamage) {
1966 surfaceDamageRegion = Region::INVALID_REGION;
1968 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1972 void Layer::useEmptyDamage() {
1973 surfaceDamageRegion.clear();
1976 // ----------------------------------------------------------------------------
1977 // pageflip handling...
1978 // ----------------------------------------------------------------------------
1980 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1981 if (mSidebandStreamChanged || mAutoRefresh) {
1985 Mutex::Autolock lock(mQueueItemLock);
1986 if (mQueueItems.empty()) {
1989 auto timestamp = mQueueItems[0].mTimestamp;
1990 nsecs_t expectedPresent =
1991 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1993 // Ignore timestamps more than a second in the future
1994 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1995 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1996 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1999 bool isDue = timestamp < expectedPresent;
2000 return isDue || !isPlausible;
2003 bool Layer::onPreComposition(nsecs_t refreshStartTime) {
2004 if (mBufferLatched) {
2005 Mutex::Autolock lock(mFrameEventHistoryMutex);
2006 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime);
2008 mRefreshPending = false;
2009 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
2012 bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence,
2013 const std::shared_ptr<FenceTime>& presentFence,
2014 const CompositorTiming& compositorTiming) {
2015 // mFrameLatencyNeeded is true when a new frame was latched for the
2017 if (!mFrameLatencyNeeded)
2020 // Update mFrameEventHistory.
2022 Mutex::Autolock lock(mFrameEventHistoryMutex);
2023 mFrameEventHistory.addPostComposition(mCurrentFrameNumber,
2024 glDoneFence, presentFence, compositorTiming);
2027 // Update mFrameTracker.
2028 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
2029 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
2031 std::shared_ptr<FenceTime> frameReadyFence =
2032 mSurfaceFlingerConsumer->getCurrentFenceTime();
2033 if (frameReadyFence->isValid()) {
2034 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence));
2036 // There was no fence for this frame, so assume that it was ready
2037 // to be presented at the desired present time.
2038 mFrameTracker.setFrameReadyTime(desiredPresentTime);
2041 if (presentFence->isValid()) {
2042 mFrameTracker.setActualPresentFence(
2043 std::shared_ptr<FenceTime>(presentFence));
2045 // The HWC doesn't support present fences, so use the refresh
2046 // timestamp instead.
2047 mFrameTracker.setActualPresentTime(
2048 mFlinger->getHwComposer().getRefreshTimestamp(
2049 HWC_DISPLAY_PRIMARY));
2052 mFrameTracker.advanceFrame();
2053 mFrameLatencyNeeded = false;
2058 void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) {
2059 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) {
2063 auto releaseFenceTime = std::make_shared<FenceTime>(
2064 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2065 mReleaseTimeline.updateSignalTimes();
2066 mReleaseTimeline.push(releaseFenceTime);
2068 Mutex::Autolock lock(mFrameEventHistoryMutex);
2069 if (mPreviousFrameNumber != 0) {
2070 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2071 dequeueReadyTime, std::move(releaseFenceTime));
2076 bool Layer::isHiddenByPolicy() const {
2077 const Layer::State& s(mDrawingState);
2078 const auto& parent = mDrawingParent.promote();
2079 if (parent != nullptr && parent->isHiddenByPolicy()) {
2082 return s.flags & layer_state_t::eLayerHidden;
2085 bool Layer::isVisible() const {
2087 return !(isHiddenByPolicy()) && getAlpha() > 0.0f
2088 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2090 return !(isHiddenByPolicy()) && getAlpha()
2091 && (mActiveBuffer != NULL || mSidebandStream != NULL);
2095 bool Layer::allTransactionsSignaled() {
2096 auto headFrameNumber = getHeadFrameNumber();
2097 bool matchingFramesFound = false;
2098 bool allTransactionsApplied = true;
2099 Mutex::Autolock lock(mLocalSyncPointMutex);
2101 for (auto& point : mLocalSyncPoints) {
2102 if (point->getFrameNumber() > headFrameNumber) {
2105 matchingFramesFound = true;
2107 if (!point->frameIsAvailable()) {
2108 // We haven't notified the remote layer that the frame for
2109 // this point is available yet. Notify it now, and then
2110 // abort this attempt to latch.
2111 point->setFrameAvailable();
2112 allTransactionsApplied = false;
2116 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied();
2118 return !matchingFramesFound || allTransactionsApplied;
2121 Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime)
2125 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
2126 // mSidebandStreamChanged was true
2127 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
2128 if (mSidebandStream != NULL) {
2129 setTransactionFlags(eTransactionNeeded);
2130 mFlinger->setTransactionFlags(eTraversalNeeded);
2132 recomputeVisibleRegions = true;
2134 const State& s(getDrawingState());
2135 return getTransform().transform(Region(Rect(s.active.w, s.active.h)));
2138 Region outDirtyRegion;
2139 if (mQueuedFrames <= 0 && !mAutoRefresh) {
2140 return outDirtyRegion;
2143 // if we've already called updateTexImage() without going through
2144 // a composition step, we have to skip this layer at this point
2145 // because we cannot call updateTeximage() without a corresponding
2146 // compositionComplete() call.
2147 // we'll trigger an update in onPreComposition().
2148 if (mRefreshPending) {
2149 return outDirtyRegion;
2152 // If the head buffer's acquire fence hasn't signaled yet, return and
2154 if (!headFenceHasSignaled()) {
2155 mFlinger->signalLayerUpdate();
2156 return outDirtyRegion;
2159 // Capture the old state of the layer for comparisons later
2160 const State& s(getDrawingState());
2161 const bool oldOpacity = isOpaque(s);
2162 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
2164 if (!allTransactionsSignaled()) {
2165 mFlinger->signalLayerUpdate();
2166 return outDirtyRegion;
2169 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2170 // of the buffer queue isn't modified when the buffer queue is returning
2171 // BufferItem's that weren't actually queued. This can happen in shared
2173 bool queuedBuffer = false;
2174 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
2175 getProducerStickyTransform() != 0, mName.string(),
2176 mOverrideScalingMode, mFreezeGeometryUpdates);
2177 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2178 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2179 mLastFrameNumberReceived);
2180 if (updateResult == BufferQueue::PRESENT_LATER) {
2181 // Producer doesn't want buffer to be displayed yet. Signal a
2182 // layer update so we check again at the next opportunity.
2183 mFlinger->signalLayerUpdate();
2184 return outDirtyRegion;
2185 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2186 // If the buffer has been rejected, remove it from the shadow queue
2189 Mutex::Autolock lock(mQueueItemLock);
2190 mQueueItems.removeAt(0);
2191 android_atomic_dec(&mQueuedFrames);
2193 return outDirtyRegion;
2194 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2195 // This can occur if something goes wrong when trying to create the
2196 // EGLImage for this buffer. If this happens, the buffer has already
2197 // been released, so we need to clean up the queue and bug out
2200 Mutex::Autolock lock(mQueueItemLock);
2201 mQueueItems.clear();
2202 android_atomic_and(0, &mQueuedFrames);
2205 // Once we have hit this state, the shadow queue may no longer
2206 // correctly reflect the incoming BufferQueue's contents, so even if
2207 // updateTexImage starts working, the only safe course of action is
2208 // to continue to ignore updates.
2209 mUpdateTexImageFailed = true;
2211 return outDirtyRegion;
2216 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2218 Mutex::Autolock lock(mQueueItemLock);
2220 // Remove any stale buffers that have been dropped during
2222 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2223 mQueueItems.removeAt(0);
2224 android_atomic_dec(&mQueuedFrames);
2227 mQueueItems.removeAt(0);
2231 // Decrement the queued-frames count. Signal another event if we
2232 // have more frames pending.
2233 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2235 mFlinger->signalLayerUpdate();
2238 // update the active buffer
2239 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(
2240 &mActiveBufferSlot);
2241 if (mActiveBuffer == NULL) {
2242 // this can only happen if the very first buffer was rejected.
2243 return outDirtyRegion;
2246 mBufferLatched = true;
2247 mPreviousFrameNumber = mCurrentFrameNumber;
2248 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2251 Mutex::Autolock lock(mFrameEventHistoryMutex);
2252 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime);
2254 auto releaseFenceTime = std::make_shared<FenceTime>(
2255 mSurfaceFlingerConsumer->getPrevFinalReleaseFence());
2256 mReleaseTimeline.updateSignalTimes();
2257 mReleaseTimeline.push(releaseFenceTime);
2258 if (mPreviousFrameNumber != 0) {
2259 mFrameEventHistory.addRelease(mPreviousFrameNumber,
2260 latchTime, std::move(releaseFenceTime));
2265 mRefreshPending = true;
2266 mFrameLatencyNeeded = true;
2267 if (oldActiveBuffer == NULL) {
2268 // the first time we receive a buffer, we need to trigger a
2269 // geometry invalidation.
2270 recomputeVisibleRegions = true;
2273 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace());
2275 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2276 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2277 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2278 if ((crop != mCurrentCrop) ||
2279 (transform != mCurrentTransform) ||
2280 (scalingMode != mCurrentScalingMode))
2282 mCurrentCrop = crop;
2283 mCurrentTransform = transform;
2284 mCurrentScalingMode = scalingMode;
2285 recomputeVisibleRegions = true;
2288 if (oldActiveBuffer != NULL) {
2289 uint32_t bufWidth = mActiveBuffer->getWidth();
2290 uint32_t bufHeight = mActiveBuffer->getHeight();
2291 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2292 bufHeight != uint32_t(oldActiveBuffer->height)) {
2293 recomputeVisibleRegions = true;
2297 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2298 if (oldOpacity != isOpaque(s)) {
2299 recomputeVisibleRegions = true;
2302 // Remove any sync points corresponding to the buffer which was just
2305 Mutex::Autolock lock(mLocalSyncPointMutex);
2306 auto point = mLocalSyncPoints.begin();
2307 while (point != mLocalSyncPoints.end()) {
2308 if (!(*point)->frameIsAvailable() ||
2309 !(*point)->transactionIsApplied()) {
2310 // This sync point must have been added since we started
2311 // latching. Don't drop it yet.
2316 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2317 point = mLocalSyncPoints.erase(point);
2324 // FIXME: postedRegion should be dirty & bounds
2325 Region dirtyRegion(Rect(s.active.w, s.active.h));
2327 // transform the dirty region to window-manager space
2328 outDirtyRegion = (getTransform().transform(dirtyRegion));
2330 return outDirtyRegion;
2333 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2335 // TODO: should we do something special if mSecure is set?
2336 if (mProtectedByApp) {
2337 // need a hardware-protected path to external video sink
2338 usage |= GraphicBuffer::USAGE_PROTECTED;
2340 if (mPotentialCursor) {
2341 usage |= GraphicBuffer::USAGE_CURSOR;
2343 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2347 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2348 uint32_t orientation = 0;
2349 if (!mFlinger->mDebugDisableTransformHint) {
2350 // The transform hint is used to improve performance, but we can
2351 // only have a single transform hint, it cannot
2352 // apply to all displays.
2353 const Transform& planeTransform(hw->getTransform());
2354 orientation = planeTransform.getOrientation();
2355 if (orientation & Transform::ROT_INVALID) {
2359 mSurfaceFlingerConsumer->setTransformHint(orientation);
2362 // ----------------------------------------------------------------------------
2364 // ----------------------------------------------------------------------------
2366 void Layer::dump(String8& result, Colorizer& colorizer) const
2368 const Layer::State& s(getDrawingState());
2370 colorizer.colorize(result, Colorizer::GREEN);
2371 result.appendFormat(
2373 getTypeId(), this, getName().string());
2374 colorizer.reset(result);
2376 s.activeTransparentRegion.dump(result, "transparentRegion");
2377 visibleRegion.dump(result, "visibleRegion");
2378 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2379 sp<Client> client(mClientRef.promote());
2380 PixelFormat pf = PIXEL_FORMAT_UNKNOWN;
2381 const sp<GraphicBuffer>& buffer(getActiveBuffer());
2382 if (buffer != NULL) {
2383 pf = buffer->getPixelFormat();
2386 result.appendFormat( " "
2387 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2388 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2389 "isOpaque=%1d, invalidate=%1d, "
2390 "dataspace=%s, pixelformat=%s "
2392 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2394 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2397 getLayerStack(), s.z,
2398 s.active.transform.tx(), s.active.transform.ty(),
2399 s.active.w, s.active.h,
2400 s.crop.left, s.crop.top,
2401 s.crop.right, s.crop.bottom,
2402 s.finalCrop.left, s.finalCrop.top,
2403 s.finalCrop.right, s.finalCrop.bottom,
2404 isOpaque(s), contentDirty,
2405 dataspaceDetails(getDataSpace()).c_str(), decodePixelFormat(pf).c_str(),
2407 s.active.transform[0][0], s.active.transform[0][1],
2408 s.active.transform[1][0], s.active.transform[1][1],
2411 sp<const GraphicBuffer> buf0(mActiveBuffer);
2412 uint32_t w0=0, h0=0, s0=0, f0=0;
2414 w0 = buf0->getWidth();
2415 h0 = buf0->getHeight();
2416 s0 = buf0->getStride();
2419 result.appendFormat(
2421 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2422 " queued-frames=%d, mRefreshPending=%d\n",
2423 mFormat, w0, h0, s0,f0,
2424 mQueuedFrames, mRefreshPending);
2426 if (mSurfaceFlingerConsumer != 0) {
2427 mSurfaceFlingerConsumer->dumpState(result, " ");
2432 void Layer::miniDumpHeader(String8& result) {
2433 result.append("----------------------------------------");
2434 result.append("---------------------------------------\n");
2435 result.append(" Layer name\n");
2436 result.append(" Z | ");
2437 result.append(" Comp Type | ");
2438 result.append(" Disp Frame (LTRB) | ");
2439 result.append(" Source Crop (LTRB)\n");
2440 result.append("----------------------------------------");
2441 result.append("---------------------------------------\n");
2444 void Layer::miniDump(String8& result, int32_t hwcId) const {
2445 if (mHwcLayers.count(hwcId) == 0) {
2450 if (mName.length() > 77) {
2451 std::string shortened;
2452 shortened.append(mName.string(), 36);
2453 shortened.append("[...]");
2454 shortened.append(mName.string() + (mName.length() - 36), 36);
2455 name = shortened.c_str();
2460 result.appendFormat(" %s\n", name.string());
2462 const Layer::State& layerState(getDrawingState());
2463 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId);
2464 result.appendFormat(" %10u | ", layerState.z);
2465 result.appendFormat("%10s | ",
2466 to_string(getCompositionType(hwcId)).c_str());
2467 const Rect& frame = hwcInfo.displayFrame;
2468 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top,
2469 frame.right, frame.bottom);
2470 const FloatRect& crop = hwcInfo.sourceCrop;
2471 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top,
2472 crop.right, crop.bottom);
2474 result.append("- - - - - - - - - - - - - - - - - - - - ");
2475 result.append("- - - - - - - - - - - - - - - - - - - -\n");
2479 void Layer::dumpFrameStats(String8& result) const {
2480 mFrameTracker.dumpStats(result);
2483 void Layer::clearFrameStats() {
2484 mFrameTracker.clearStats();
2487 void Layer::logFrameStats() {
2488 mFrameTracker.logAndResetStats(mName);
2491 void Layer::getFrameStats(FrameStats* outStats) const {
2492 mFrameTracker.getStats(outStats);
2495 void Layer::dumpFrameEvents(String8& result) {
2496 result.appendFormat("- Layer %s (%s, %p)\n",
2497 getName().string(), getTypeId(), this);
2498 Mutex::Autolock lock(mFrameEventHistoryMutex);
2499 mFrameEventHistory.checkFencesForCompletion();
2500 mFrameEventHistory.dump(result);
2503 void Layer::onDisconnect() {
2504 Mutex::Autolock lock(mFrameEventHistoryMutex);
2505 mFrameEventHistory.onDisconnect();
2508 void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps,
2509 FrameEventHistoryDelta *outDelta) {
2510 Mutex::Autolock lock(mFrameEventHistoryMutex);
2511 if (newTimestamps) {
2512 // If there are any unsignaled fences in the aquire timeline at this
2513 // point, the previously queued frame hasn't been latched yet. Go ahead
2514 // and try to get the signal time here so the syscall is taken out of
2515 // the main thread's critical path.
2516 mAcquireTimeline.updateSignalTimes();
2517 // Push the new fence after updating since it's likely still pending.
2518 mAcquireTimeline.push(newTimestamps->acquireFence);
2519 mFrameEventHistory.addQueue(*newTimestamps);
2523 mFrameEventHistory.getAndResetDelta(outDelta);
2527 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2529 std::vector<OccupancyTracker::Segment> history;
2530 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2532 if (result != NO_ERROR) {
2533 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2540 bool Layer::getTransformToDisplayInverse() const {
2541 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2544 size_t Layer::getChildrenCount() const {
2546 for (const sp<Layer>& child : mCurrentChildren) {
2547 count += 1 + child->getChildrenCount();
2552 void Layer::addChild(const sp<Layer>& layer) {
2553 mCurrentChildren.add(layer);
2554 layer->setParent(this);
2557 ssize_t Layer::removeChild(const sp<Layer>& layer) {
2558 layer->setParent(nullptr);
2559 return mCurrentChildren.remove(layer);
2562 bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) {
2563 sp<Handle> handle = nullptr;
2564 sp<Layer> newParent = nullptr;
2565 if (newParentHandle == nullptr) {
2568 handle = static_cast<Handle*>(newParentHandle.get());
2569 newParent = handle->owner.promote();
2570 if (newParent == nullptr) {
2571 ALOGE("Unable to promote Layer handle");
2575 for (const sp<Layer>& child : mCurrentChildren) {
2576 newParent->addChild(child);
2578 sp<Client> client(child->mClientRef.promote());
2579 if (client != nullptr) {
2580 client->setParentLayer(newParent);
2583 mCurrentChildren.clear();
2588 bool Layer::detachChildren() {
2589 traverseInZOrder(LayerVector::StateSet::Drawing, [this](Layer* child) {
2590 if (child == this) {
2594 sp<Client> client(child->mClientRef.promote());
2595 if (client != nullptr) {
2596 client->detachLayer(child);
2603 void Layer::setParent(const sp<Layer>& layer) {
2604 mCurrentParent = layer;
2607 void Layer::clearSyncPoints() {
2608 for (const auto& child : mCurrentChildren) {
2609 child->clearSyncPoints();
2612 Mutex::Autolock lock(mLocalSyncPointMutex);
2613 for (auto& point : mLocalSyncPoints) {
2614 point->setFrameAvailable();
2616 mLocalSyncPoints.clear();
2619 int32_t Layer::getZ() const {
2620 return mDrawingState.z;
2623 LayerVector Layer::makeTraversalList(LayerVector::StateSet stateSet) {
2624 LOG_ALWAYS_FATAL_IF(stateSet == LayerVector::StateSet::Invalid,
2625 "makeTraversalList received invalid stateSet");
2626 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
2627 const LayerVector& children = useDrawing ? mDrawingChildren : mCurrentChildren;
2628 const State& state = useDrawing ? mDrawingState : mCurrentState;
2630 if (state.zOrderRelatives.size() == 0) {
2633 LayerVector traverse;
2635 for (const wp<Layer>& weakRelative : state.zOrderRelatives) {
2636 sp<Layer> strongRelative = weakRelative.promote();
2637 if (strongRelative != nullptr) {
2638 traverse.add(strongRelative);
2642 for (const sp<Layer>& child : children) {
2643 traverse.add(child);
2650 * Negatively signed relatives are before 'this' in Z-order.
2652 void Layer::traverseInZOrder(LayerVector::StateSet stateSet, const LayerVector::Visitor& visitor) {
2653 LayerVector list = makeTraversalList(stateSet);
2656 for (; i < list.size(); i++) {
2657 const auto& relative = list[i];
2658 if (relative->getZ() >= 0) {
2661 relative->traverseInZOrder(stateSet, visitor);
2664 for (; i < list.size(); i++) {
2665 const auto& relative = list[i];
2666 relative->traverseInZOrder(stateSet, visitor);
2671 * Positively signed relatives are before 'this' in reverse Z-order.
2673 void Layer::traverseInReverseZOrder(LayerVector::StateSet stateSet,
2674 const LayerVector::Visitor& visitor) {
2675 LayerVector list = makeTraversalList(stateSet);
2678 for (i = list.size()-1; i>=0; i--) {
2679 const auto& relative = list[i];
2680 if (relative->getZ() < 0) {
2683 relative->traverseInReverseZOrder(stateSet, visitor);
2687 const auto& relative = list[i];
2688 relative->traverseInReverseZOrder(stateSet, visitor);
2692 Transform Layer::getTransform() const {
2694 const auto& p = mDrawingParent.promote();
2696 t = p->getTransform();
2698 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g.
2699 // it isFixedSize) then there may be additional scaling not accounted
2700 // for in the transform. We need to mirror this scaling in child surfaces
2701 // or we will break the contract where WM can treat child surfaces as
2702 // pixels in the parent surface.
2703 if (p->isFixedSize()) {
2706 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) {
2707 bufferWidth = p->mActiveBuffer->getWidth();
2708 bufferHeight = p->mActiveBuffer->getHeight();
2710 bufferHeight = p->mActiveBuffer->getWidth();
2711 bufferWidth = p->mActiveBuffer->getHeight();
2713 float sx = p->getDrawingState().active.w /
2714 static_cast<float>(bufferWidth);
2715 float sy = p->getDrawingState().active.h /
2716 static_cast<float>(bufferHeight);
2717 Transform extraParentScaling;
2718 extraParentScaling.set(sx, 0, 0, sy);
2719 t = t * extraParentScaling;
2722 return t * getDrawingState().active.transform;
2726 float Layer::getAlpha() const {
2727 const auto& p = mDrawingParent.promote();
2729 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0;
2730 return parentAlpha * getDrawingState().alpha;
2733 uint8_t Layer::getAlpha() const {
2734 const auto& p = mDrawingParent.promote();
2736 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0;
2737 float drawingAlpha = getDrawingState().alpha / 255.0f;
2738 drawingAlpha = drawingAlpha * parentAlpha;
2739 return static_cast<uint8_t>(std::round(drawingAlpha * 255));
2743 void Layer::commitChildList() {
2744 for (size_t i = 0; i < mCurrentChildren.size(); i++) {
2745 const auto& child = mCurrentChildren[i];
2746 child->commitChildList();
2748 mDrawingChildren = mCurrentChildren;
2749 mDrawingParent = mCurrentParent;
2752 // ---------------------------------------------------------------------------
2754 }; // namespace android
2756 #if defined(__gl_h_)
2757 #error "don't include gl/gl.h in this file"
2760 #if defined(__gl2_h_)
2761 #error "don't include gl2/gl2.h in this file"