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/GraphicBuffer.h>
38 #include <ui/PixelFormat.h>
40 #include <gui/BufferItem.h>
41 #include <gui/Surface.h>
44 #include "Colorizer.h"
45 #include "DisplayDevice.h"
47 #include "MonitoredProducer.h"
48 #include "SurfaceFlinger.h"
50 #include "DisplayHardware/HWComposer.h"
52 #include "RenderEngine/RenderEngine.h"
56 #define DEBUG_RESIZE 0
60 // ---------------------------------------------------------------------------
62 int32_t Layer::sSequence = 1;
64 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
65 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
66 : contentDirty(false),
67 sequence(uint32_t(android_atomic_inc(&sSequence))),
70 mPremultipliedAlpha(true),
72 mFormat(PIXEL_FORMAT_NONE),
77 mSidebandStreamChanged(false),
79 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
80 mOverrideScalingMode(-1),
81 mCurrentOpacity(true),
82 mCurrentFrameNumber(0),
83 mRefreshPending(false),
84 mFrameLatencyNeeded(false),
86 mNeedsFiltering(false),
87 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
89 mIsGlesComposition(false),
91 mProtectedByApp(false),
94 mPotentialCursor(false),
96 mQueueItemCondition(),
98 mLastFrameNumberReceived(0),
99 mUpdateTexImageFailed(false),
101 mFreezePositionUpdates(false)
104 ALOGV("Creating Layer %s", name.string());
107 mCurrentCrop.makeInvalid();
108 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
109 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
111 uint32_t layerFlags = 0;
112 if (flags & ISurfaceComposerClient::eHidden)
113 layerFlags |= layer_state_t::eLayerHidden;
114 if (flags & ISurfaceComposerClient::eOpaque)
115 layerFlags |= layer_state_t::eLayerOpaque;
116 if (flags & ISurfaceComposerClient::eSecure)
117 layerFlags |= layer_state_t::eLayerSecure;
119 if (flags & ISurfaceComposerClient::eNonPremultiplied)
120 mPremultipliedAlpha = false;
124 mCurrentState.active.w = w;
125 mCurrentState.active.h = h;
126 mCurrentState.active.transform.set(0, 0);
127 mCurrentState.crop.makeInvalid();
128 mCurrentState.finalCrop.makeInvalid();
131 mCurrentState.alpha = 1.0f;
133 mCurrentState.alpha = 0xFF;
135 mCurrentState.layerStack = 0;
136 mCurrentState.flags = layerFlags;
137 mCurrentState.sequence = 0;
138 mCurrentState.requested = mCurrentState.active;
140 // drawing state & current state are identical
141 mDrawingState = mCurrentState;
144 const auto& hwc = flinger->getHwComposer();
145 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
146 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
148 nsecs_t displayPeriod =
149 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
151 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
154 void Layer::onFirstRef() {
155 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
156 sp<IGraphicBufferProducer> producer;
157 sp<IGraphicBufferConsumer> consumer;
158 BufferQueue::createBufferQueue(&producer, &consumer);
159 mProducer = new MonitoredProducer(producer, mFlinger);
160 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName,
162 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
163 mSurfaceFlingerConsumer->setContentsChangedListener(this);
164 mSurfaceFlingerConsumer->setName(mName);
166 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
167 #warning "disabling triple buffering"
169 mProducer->setMaxDequeuedBufferCount(2);
172 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
173 updateTransformHint(hw);
177 sp<Client> c(mClientRef.promote());
179 c->detachLayer(this);
182 for (auto& point : mRemoteSyncPoints) {
183 point->setTransactionApplied();
185 for (auto& point : mLocalSyncPoints) {
186 point->setFrameAvailable();
188 mFlinger->deleteTextureAsync(mTextureName);
189 mFrameTracker.logAndResetStats(mName);
192 // ---------------------------------------------------------------------------
194 // ---------------------------------------------------------------------------
197 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
198 if (mHwcLayers.empty()) {
201 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
204 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
205 HWComposer::HWCLayerInterface* layer) {
207 layer->onDisplayed();
208 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
213 void Layer::onFrameAvailable(const BufferItem& item) {
214 // Add this buffer from our internal queue tracker
216 Mutex::Autolock lock(mQueueItemLock);
218 // Reset the frame number tracker when we receive the first buffer after
219 // a frame number reset
220 if (item.mFrameNumber == 1) {
221 mLastFrameNumberReceived = 0;
224 // Ensure that callbacks are handled in order
225 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
226 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
228 if (result != NO_ERROR) {
229 ALOGE("[%s] Timed out waiting on callback", mName.string());
233 mQueueItems.push_back(item);
234 android_atomic_inc(&mQueuedFrames);
236 // Wake up any pending callbacks
237 mLastFrameNumberReceived = item.mFrameNumber;
238 mQueueItemCondition.broadcast();
241 mFlinger->signalLayerUpdate();
244 void Layer::onFrameReplaced(const BufferItem& item) {
246 Mutex::Autolock lock(mQueueItemLock);
248 // Ensure that callbacks are handled in order
249 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
250 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
252 if (result != NO_ERROR) {
253 ALOGE("[%s] Timed out waiting on callback", mName.string());
257 if (mQueueItems.empty()) {
258 ALOGE("Can't replace a frame on an empty queue");
261 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
263 // Wake up any pending callbacks
264 mLastFrameNumberReceived = item.mFrameNumber;
265 mQueueItemCondition.broadcast();
269 void Layer::onSidebandStreamChanged() {
270 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
271 // mSidebandStreamChanged was false
272 mFlinger->signalLayerUpdate();
276 // called with SurfaceFlinger::mStateLock from the drawing thread after
277 // the layer has been remove from the current state list (and just before
278 // it's removed from the drawing state list)
279 void Layer::onRemoved() {
280 mSurfaceFlingerConsumer->abandon();
283 // ---------------------------------------------------------------------------
285 // ---------------------------------------------------------------------------
287 const String8& Layer::getName() const {
291 status_t Layer::setBuffers( uint32_t w, uint32_t h,
292 PixelFormat format, uint32_t flags)
294 uint32_t const maxSurfaceDims = min(
295 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
297 // never allow a surface larger than what our underlying GL implementation
299 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
300 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
306 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
307 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
308 mCurrentOpacity = getOpacityForFormat(format);
310 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
311 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
312 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
318 * The layer handle is just a BBinder object passed to the client
319 * (remote process) -- we don't keep any reference on our side such that
320 * the dtor is called when the remote side let go of its reference.
322 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
323 * this layer when the handle is destroyed.
325 class Layer::Handle : public BBinder, public LayerCleaner {
327 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
328 : LayerCleaner(flinger, layer), owner(layer) {}
333 sp<IBinder> Layer::getHandle() {
334 Mutex::Autolock _l(mLock);
336 LOG_ALWAYS_FATAL_IF(mHasSurface,
337 "Layer::getHandle() has already been called");
341 return new Handle(mFlinger, this);
344 sp<IGraphicBufferProducer> Layer::getProducer() const {
348 // ---------------------------------------------------------------------------
349 // h/w composer set-up
350 // ---------------------------------------------------------------------------
352 Rect Layer::getContentCrop() const {
353 // this is the crop rectangle that applies to the buffer
354 // itself (as opposed to the window)
356 if (!mCurrentCrop.isEmpty()) {
357 // if the buffer crop is defined, we use that
359 } else if (mActiveBuffer != NULL) {
360 // otherwise we use the whole buffer
361 crop = mActiveBuffer->getBounds();
363 // if we don't have a buffer yet, we use an empty/invalid crop
369 static Rect reduce(const Rect& win, const Region& exclude) {
370 if (CC_LIKELY(exclude.isEmpty())) {
373 if (exclude.isRect()) {
374 return win.reduce(exclude.getBounds());
376 return Region(win).subtract(exclude).getBounds();
379 Rect Layer::computeBounds() const {
380 const Layer::State& s(getDrawingState());
381 return computeBounds(s.activeTransparentRegion);
384 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
385 const Layer::State& s(getDrawingState());
386 Rect win(s.active.w, s.active.h);
388 if (!s.crop.isEmpty()) {
389 win.intersect(s.crop, &win);
391 // subtract the transparent region and snap to the bounds
392 return reduce(win, activeTransparentRegion);
395 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
396 // the content crop is the area of the content that gets scaled to the
398 FloatRect crop(getContentCrop());
400 // the crop is the area of the window that gets cropped, but not
401 // scaled in any ways.
402 const State& s(getDrawingState());
404 // apply the projection's clipping to the window crop in
405 // layerstack space, and convert-back to layer space.
406 // if there are no window scaling involved, this operation will map to full
407 // pixels in the buffer.
408 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
409 // a viewport clipping and a window transform. we should use floating point to fix this.
411 Rect activeCrop(s.active.w, s.active.h);
412 if (!s.crop.isEmpty()) {
416 activeCrop = s.active.transform.transform(activeCrop);
417 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
420 if (!s.finalCrop.isEmpty()) {
421 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
425 activeCrop = s.active.transform.inverse().transform(activeCrop);
427 // This needs to be here as transform.transform(Rect) computes the
428 // transformed rect and then takes the bounding box of the result before
429 // returning. This means
430 // transform.inverse().transform(transform.transform(Rect)) != Rect
431 // in which case we need to make sure the final rect is clipped to the
433 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
437 // subtract the transparent region and snap to the bounds
438 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
440 // Transform the window crop to match the buffer coordinate system,
441 // which means using the inverse of the current transform set on the
442 // SurfaceFlingerConsumer.
443 uint32_t invTransform = mCurrentTransform;
444 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
446 * the code below applies the primary display's inverse transform to the
449 uint32_t invTransformOrient =
450 DisplayDevice::getPrimaryDisplayOrientationTransform();
451 // calculate the inverse transform
452 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
453 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
454 NATIVE_WINDOW_TRANSFORM_FLIP_H;
456 // and apply to the current transform
457 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
461 int winWidth = s.active.w;
462 int winHeight = s.active.h;
463 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
464 // If the activeCrop has been rotate the ends are rotated but not
465 // the space itself so when transforming ends back we can't rely on
466 // a modification of the axes of rotation. To account for this we
467 // need to reorient the inverse rotation in terms of the current
469 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
470 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
471 if (is_h_flipped == is_v_flipped) {
472 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
473 NATIVE_WINDOW_TRANSFORM_FLIP_H;
475 winWidth = s.active.h;
476 winHeight = s.active.w;
478 const Rect winCrop = activeCrop.transform(
479 invTransform, s.active.w, s.active.h);
481 // below, crop is intersected with winCrop expressed in crop's coordinate space
482 float xScale = crop.getWidth() / float(winWidth);
483 float yScale = crop.getHeight() / float(winHeight);
485 float insetL = winCrop.left * xScale;
486 float insetT = winCrop.top * yScale;
487 float insetR = (winWidth - winCrop.right ) * xScale;
488 float insetB = (winHeight - winCrop.bottom) * yScale;
492 crop.right -= insetR;
493 crop.bottom -= insetB;
499 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
501 void Layer::setGeometry(
502 const sp<const DisplayDevice>& hw,
503 HWComposer::HWCLayerInterface& layer)
507 const auto hwcId = displayDevice->getHwcDisplayId();
508 auto& hwcInfo = mHwcLayers[hwcId];
510 layer.setDefaultState();
515 hwcInfo.forceClientComposition = false;
517 if (isSecure() && !displayDevice->isSecure()) {
518 hwcInfo.forceClientComposition = true;
521 auto& hwcLayer = hwcInfo.layer;
523 layer.setSkip(false);
525 if (isSecure() && !hw->isSecure()) {
530 // this gives us only the "orientation" component of the transform
531 const State& s(getDrawingState());
533 if (!isOpaque(s) || s.alpha != 1.0f) {
534 auto blendMode = mPremultipliedAlpha ?
535 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
536 auto error = hwcLayer->setBlendMode(blendMode);
537 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
538 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
539 to_string(error).c_str(), static_cast<int32_t>(error));
542 if (!isOpaque(s) || s.alpha != 0xFF) {
543 layer.setBlending(mPremultipliedAlpha ?
544 HWC_BLENDING_PREMULT :
545 HWC_BLENDING_COVERAGE);
549 // apply the layer's transform, followed by the display's global transform
550 // here we're guaranteed that the layer's transform preserves rects
551 Region activeTransparentRegion(s.activeTransparentRegion);
552 if (!s.crop.isEmpty()) {
553 Rect activeCrop(s.crop);
554 activeCrop = s.active.transform.transform(activeCrop);
556 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
558 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
562 activeCrop = s.active.transform.inverse().transform(activeCrop, true);
563 // This needs to be here as transform.transform(Rect) computes the
564 // transformed rect and then takes the bounding box of the result before
565 // returning. This means
566 // transform.inverse().transform(transform.transform(Rect)) != Rect
567 // in which case we need to make sure the final rect is clipped to the
569 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
572 // mark regions outside the crop as transparent
573 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
574 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
575 s.active.w, s.active.h));
576 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
577 activeCrop.left, activeCrop.bottom));
578 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
579 s.active.w, activeCrop.bottom));
581 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
582 if (!s.finalCrop.isEmpty()) {
583 if(!frame.intersect(s.finalCrop, &frame)) {
588 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
591 const Transform& tr(displayDevice->getTransform());
592 Rect transformedFrame = tr.transform(frame);
593 auto error = hwcLayer->setDisplayFrame(transformedFrame);
594 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
595 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
596 transformedFrame.top, transformedFrame.right,
597 transformedFrame.bottom, to_string(error).c_str(),
598 static_cast<int32_t>(error));
600 FloatRect sourceCrop = computeCrop(displayDevice);
601 error = hwcLayer->setSourceCrop(sourceCrop);
602 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
603 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
604 sourceCrop.left, sourceCrop.top, sourceCrop.right,
605 sourceCrop.bottom, to_string(error).c_str(),
606 static_cast<int32_t>(error));
608 error = hwcLayer->setPlaneAlpha(s.alpha);
609 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
610 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
611 static_cast<int32_t>(error));
613 error = hwcLayer->setZOrder(s.z);
614 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
615 mName.string(), s.z, to_string(error).c_str(),
616 static_cast<int32_t>(error));
618 if (!frame.intersect(hw->getViewport(), &frame)) {
621 const Transform& tr(hw->getTransform());
622 layer.setFrame(tr.transform(frame));
623 layer.setCrop(computeCrop(hw));
624 layer.setPlaneAlpha(s.alpha);
628 * Transformations are applied in this order:
629 * 1) buffer orientation/flip/mirror
630 * 2) state transformation (window manager)
631 * 3) layer orientation (screen orientation)
632 * (NOTE: the matrices are multiplied in reverse order)
635 const Transform bufferOrientation(mCurrentTransform);
636 Transform transform(tr * s.active.transform * bufferOrientation);
638 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
640 * the code below applies the primary display's inverse transform to the
643 uint32_t invTransform =
644 DisplayDevice::getPrimaryDisplayOrientationTransform();
645 // calculate the inverse transform
646 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
647 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
648 NATIVE_WINDOW_TRANSFORM_FLIP_H;
650 // and apply to the current transform
651 transform = Transform(invTransform) * transform;
654 // this gives us only the "orientation" component of the transform
655 const uint32_t orientation = transform.getOrientation();
657 if (orientation & Transform::ROT_INVALID) {
658 // we can only handle simple transformation
659 hwcInfo.forceClientComposition = true;
661 auto transform = static_cast<HWC2::Transform>(orientation);
662 auto error = hwcLayer->setTransform(transform);
663 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
664 "%s (%d)", mName.string(), to_string(transform).c_str(),
665 to_string(error).c_str(), static_cast<int32_t>(error));
668 if (orientation & Transform::ROT_INVALID) {
669 // we can only handle simple transformation
672 layer.setTransform(orientation);
678 void Layer::forceClientComposition(int32_t hwcId) {
679 if (mHwcLayers.count(hwcId) == 0) {
680 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
684 mHwcLayers[hwcId].forceClientComposition = true;
689 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
690 // Apply this display's projection's viewport to the visible region
691 // before giving it to the HWC HAL.
692 const Transform& tr = displayDevice->getTransform();
693 const auto& viewport = displayDevice->getViewport();
694 Region visible = tr.transform(visibleRegion.intersect(viewport));
695 auto hwcId = displayDevice->getHwcDisplayId();
696 auto& hwcLayer = mHwcLayers[hwcId].layer;
697 auto error = hwcLayer->setVisibleRegion(visible);
698 if (error != HWC2::Error::None) {
699 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
700 to_string(error).c_str(), static_cast<int32_t>(error));
701 visible.dump(LOG_TAG);
704 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
705 if (error != HWC2::Error::None) {
706 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
707 to_string(error).c_str(), static_cast<int32_t>(error));
708 surfaceDamageRegion.dump(LOG_TAG);
712 if (mSidebandStream.get()) {
713 setCompositionType(hwcId, HWC2::Composition::Sideband);
714 ALOGV("[%s] Requesting Sideband composition", mName.string());
715 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
716 if (error != HWC2::Error::None) {
717 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
718 mName.string(), mSidebandStream->handle(),
719 to_string(error).c_str(), static_cast<int32_t>(error));
725 if (mHwcLayers[hwcId].forceClientComposition ||
726 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) {
727 ALOGV("[%s] Requesting Client composition", mName.string());
728 setCompositionType(hwcId, HWC2::Composition::Client);
733 if (mActiveBuffer == nullptr) {
734 setCompositionType(hwcId, HWC2::Composition::SolidColor);
736 // For now, we only support black for DimLayer
737 error = hwcLayer->setColor({0, 0, 0, 255});
738 if (error != HWC2::Error::None) {
739 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(),
740 to_string(error).c_str(), static_cast<int32_t>(error));
743 // Clear out the transform, because it doesn't make sense absent a
745 error = hwcLayer->setTransform(HWC2::Transform::None);
746 if (error != HWC2::Error::None) {
747 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(),
748 to_string(error).c_str(), static_cast<int32_t>(error));
754 // Device or Cursor layers
755 if (mPotentialCursor) {
756 ALOGV("[%s] Requesting Cursor composition", mName.string());
757 setCompositionType(hwcId, HWC2::Composition::Cursor);
759 ALOGV("[%s] Requesting Device composition", mName.string());
760 setCompositionType(hwcId, HWC2::Composition::Device);
763 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
764 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
765 if (error != HWC2::Error::None) {
766 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
767 mActiveBuffer->handle, to_string(error).c_str(),
768 static_cast<int32_t>(error));
772 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
773 HWComposer::HWCLayerInterface& layer) {
774 // we have to set the visible region on every frame because
775 // we currently free it during onLayerDisplayed(), which is called
776 // after HWComposer::commit() -- every frame.
777 // Apply this display's projection's viewport to the visible region
778 // before giving it to the HWC HAL.
779 const Transform& tr = hw->getTransform();
780 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
781 layer.setVisibleRegionScreen(visible);
782 layer.setSurfaceDamage(surfaceDamageRegion);
783 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
785 if (mSidebandStream.get()) {
786 layer.setSidebandStream(mSidebandStream);
788 // NOTE: buffer can be NULL if the client never drew into this
789 // layer yet, or if we ran out of memory
790 layer.setBuffer(mActiveBuffer);
796 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
797 auto hwcId = displayDevice->getHwcDisplayId();
798 if (mHwcLayers.count(hwcId) == 0 ||
799 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
803 // This gives us only the "orientation" component of the transform
804 const State& s(getCurrentState());
806 // Apply the layer's transform, followed by the display's global transform
807 // Here we're guaranteed that the layer's transform preserves rects
808 Rect win(s.active.w, s.active.h);
809 if (!s.crop.isEmpty()) {
810 win.intersect(s.crop, &win);
812 // Subtract the transparent region and snap to the bounds
813 Rect bounds = reduce(win, s.activeTransparentRegion);
814 Rect frame(s.active.transform.transform(bounds));
815 frame.intersect(displayDevice->getViewport(), &frame);
816 if (!s.finalCrop.isEmpty()) {
817 frame.intersect(s.finalCrop, &frame);
819 auto& displayTransform(displayDevice->getTransform());
820 auto position = displayTransform.transform(frame);
822 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
824 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
825 "to (%d, %d): %s (%d)", mName.string(), position.left,
826 position.top, to_string(error).c_str(),
827 static_cast<int32_t>(error));
830 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
831 HWComposer::HWCLayerInterface& layer) {
834 // TODO: there is a possible optimization here: we only need to set the
835 // acquire fence the first time a new buffer is acquired on EACH display.
837 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
838 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
839 if (fence->isValid()) {
840 fenceFd = fence->dup();
842 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
846 layer.setAcquireFenceFd(fenceFd);
849 Rect Layer::getPosition(
850 const sp<const DisplayDevice>& hw)
852 // this gives us only the "orientation" component of the transform
853 const State& s(getCurrentState());
855 // apply the layer's transform, followed by the display's global transform
856 // here we're guaranteed that the layer's transform preserves rects
857 Rect win(s.active.w, s.active.h);
858 if (!s.crop.isEmpty()) {
859 win.intersect(s.crop, &win);
861 // subtract the transparent region and snap to the bounds
862 Rect bounds = reduce(win, s.activeTransparentRegion);
863 Rect frame(s.active.transform.transform(bounds));
864 frame.intersect(hw->getViewport(), &frame);
865 if (!s.finalCrop.isEmpty()) {
866 frame.intersect(s.finalCrop, &frame);
868 const Transform& tr(hw->getTransform());
869 return Rect(tr.transform(frame));
873 // ---------------------------------------------------------------------------
875 // ---------------------------------------------------------------------------
877 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
878 onDraw(hw, clip, false);
881 void Layer::draw(const sp<const DisplayDevice>& hw,
882 bool useIdentityTransform) const {
883 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
886 void Layer::draw(const sp<const DisplayDevice>& hw) const {
887 onDraw(hw, Region(hw->bounds()), false);
890 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
891 bool useIdentityTransform) const
895 if (CC_UNLIKELY(mActiveBuffer == 0)) {
896 // the texture has not been created yet, this Layer has
897 // in fact never been drawn into. This happens frequently with
898 // SurfaceView because the WindowManager can't know when the client
899 // has drawn the first time.
901 // If there is nothing under us, we paint the screen in black, otherwise
902 // we just skip this update.
904 // figure out if there is something below us
906 const SurfaceFlinger::LayerVector& drawingLayers(
907 mFlinger->mDrawingState.layersSortedByZ);
908 const size_t count = drawingLayers.size();
909 for (size_t i=0 ; i<count ; ++i) {
910 const sp<Layer>& layer(drawingLayers[i]);
911 if (layer.get() == static_cast<Layer const*>(this))
913 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
915 // if not everything below us is covered, we plug the holes!
916 Region holes(clip.subtract(under));
917 if (!holes.isEmpty()) {
918 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
923 // Bind the current buffer to the GL texture, and wait for it to be
924 // ready for us to draw into.
925 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
926 if (err != NO_ERROR) {
927 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
928 // Go ahead and draw the buffer anyway; no matter what we do the screen
929 // is probably going to have something visibly wrong.
932 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
934 RenderEngine& engine(mFlinger->getRenderEngine());
936 if (!blackOutLayer) {
937 // TODO: we could be more subtle with isFixedSize()
938 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
940 // Query the texture matrix given our current filtering mode.
941 float textureMatrix[16];
942 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
943 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
945 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
948 * the code below applies the primary display's inverse transform to
949 * the texture transform
952 // create a 4x4 transform matrix from the display transform flags
953 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
954 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
955 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
959 DisplayDevice::getPrimaryDisplayOrientationTransform();
960 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
962 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
964 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
967 // calculate the inverse
970 // and finally apply it to the original texture matrix
971 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
972 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
975 // Set things up for texturing.
976 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
977 mTexture.setFiltering(useFiltering);
978 mTexture.setMatrix(textureMatrix);
980 engine.setupLayerTexturing(mTexture);
982 engine.setupLayerBlackedOut();
984 drawWithOpenGL(hw, clip, useIdentityTransform);
985 engine.disableTexturing();
989 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
990 const Region& /* clip */, float red, float green, float blue,
993 RenderEngine& engine(mFlinger->getRenderEngine());
994 computeGeometry(hw, mMesh, false);
995 engine.setupFillWithColor(red, green, blue, alpha);
996 engine.drawMesh(mMesh);
999 void Layer::clearWithOpenGL(
1000 const sp<const DisplayDevice>& hw, const Region& clip) const {
1001 clearWithOpenGL(hw, clip, 0,0,0,0);
1004 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1005 const Region& /* clip */, bool useIdentityTransform) const {
1006 const State& s(getDrawingState());
1008 computeGeometry(hw, mMesh, useIdentityTransform);
1011 * NOTE: the way we compute the texture coordinates here produces
1012 * different results than when we take the HWC path -- in the later case
1013 * the "source crop" is rounded to texel boundaries.
1014 * This can produce significantly different results when the texture
1015 * is scaled by a large amount.
1017 * The GL code below is more logical (imho), and the difference with
1018 * HWC is due to a limitation of the HWC API to integers -- a question
1019 * is suspend is whether we should ignore this problem or revert to
1020 * GL composition when a buffer scaling is applied (maybe with some
1021 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1022 * like more of a hack.
1024 Rect win(computeBounds());
1026 if (!s.finalCrop.isEmpty()) {
1027 win = s.active.transform.transform(win);
1028 if (!win.intersect(s.finalCrop, &win)) {
1031 win = s.active.transform.inverse().transform(win);
1032 if (!win.intersect(computeBounds(), &win)) {
1037 float left = float(win.left) / float(s.active.w);
1038 float top = float(win.top) / float(s.active.h);
1039 float right = float(win.right) / float(s.active.w);
1040 float bottom = float(win.bottom) / float(s.active.h);
1042 // TODO: we probably want to generate the texture coords with the mesh
1043 // here we assume that we only have 4 vertices
1044 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1045 texCoords[0] = vec2(left, 1.0f - top);
1046 texCoords[1] = vec2(left, 1.0f - bottom);
1047 texCoords[2] = vec2(right, 1.0f - bottom);
1048 texCoords[3] = vec2(right, 1.0f - top);
1050 RenderEngine& engine(mFlinger->getRenderEngine());
1051 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1052 engine.drawMesh(mMesh);
1053 engine.disableBlending();
1057 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1059 if (mHwcLayers.count(hwcId) == 0) {
1060 ALOGE("setCompositionType called without a valid HWC layer");
1063 auto& hwcInfo = mHwcLayers[hwcId];
1064 auto& hwcLayer = hwcInfo.layer;
1065 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1066 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1067 if (hwcInfo.compositionType != type) {
1068 ALOGV(" actually setting");
1069 hwcInfo.compositionType = type;
1071 auto error = hwcLayer->setCompositionType(type);
1072 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1073 "composition type %s: %s (%d)", mName.string(),
1074 to_string(type).c_str(), to_string(error).c_str(),
1075 static_cast<int32_t>(error));
1080 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1081 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) {
1082 // If we're querying the composition type for a display that does not
1083 // have a HWC counterpart, then it will always be Client
1084 return HWC2::Composition::Client;
1086 if (mHwcLayers.count(hwcId) == 0) {
1087 ALOGE("getCompositionType called with an invalid HWC layer");
1088 return HWC2::Composition::Invalid;
1090 return mHwcLayers.at(hwcId).compositionType;
1093 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1094 if (mHwcLayers.count(hwcId) == 0) {
1095 ALOGE("setClearClientTarget called without a valid HWC layer");
1098 mHwcLayers[hwcId].clearClientTarget = clear;
1101 bool Layer::getClearClientTarget(int32_t hwcId) const {
1102 if (mHwcLayers.count(hwcId) == 0) {
1103 ALOGE("getClearClientTarget called without a valid HWC layer");
1106 return mHwcLayers.at(hwcId).clearClientTarget;
1110 uint32_t Layer::getProducerStickyTransform() const {
1111 int producerStickyTransform = 0;
1112 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1114 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1115 strerror(-ret), ret);
1118 return static_cast<uint32_t>(producerStickyTransform);
1121 bool Layer::latchUnsignaledBuffers() {
1122 static bool propertyLoaded = false;
1123 static bool latch = false;
1124 static std::mutex mutex;
1125 std::lock_guard<std::mutex> lock(mutex);
1126 if (!propertyLoaded) {
1127 char value[PROPERTY_VALUE_MAX] = {};
1128 property_get("debug.sf.latch_unsignaled", value, "0");
1129 latch = atoi(value);
1130 propertyLoaded = true;
1135 uint64_t Layer::getHeadFrameNumber() const {
1136 Mutex::Autolock lock(mQueueItemLock);
1137 if (!mQueueItems.empty()) {
1138 return mQueueItems[0].mFrameNumber;
1140 return mCurrentFrameNumber;
1144 bool Layer::headFenceHasSignaled() const {
1146 if (latchUnsignaledBuffers()) {
1150 Mutex::Autolock lock(mQueueItemLock);
1151 if (mQueueItems.empty()) {
1154 if (mQueueItems[0].mIsDroppable) {
1155 // Even though this buffer's fence may not have signaled yet, it could
1156 // be replaced by another buffer before it has a chance to, which means
1157 // that it's possible to get into a situation where a buffer is never
1158 // able to be latched. To avoid this, grab this buffer anyway.
1161 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX;
1167 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1168 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1169 // Don't bother with a SyncPoint, since we've already latched the
1174 Mutex::Autolock lock(mLocalSyncPointMutex);
1175 mLocalSyncPoints.push_back(point);
1179 void Layer::setFiltering(bool filtering) {
1180 mFiltering = filtering;
1183 bool Layer::getFiltering() const {
1187 // As documented in libhardware header, formats in the range
1188 // 0x100 - 0x1FF are specific to the HAL implementation, and
1189 // are known to have no alpha channel
1190 // TODO: move definition for device-specific range into
1191 // hardware.h, instead of using hard-coded values here.
1192 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1194 bool Layer::getOpacityForFormat(uint32_t format) {
1195 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1199 case HAL_PIXEL_FORMAT_RGBA_8888:
1200 case HAL_PIXEL_FORMAT_BGRA_8888:
1203 // in all other case, we have no blending (also for unknown formats)
1207 // ----------------------------------------------------------------------------
1209 // ----------------------------------------------------------------------------
1211 static void boundPoint(vec2* point, const Rect& crop) {
1212 if (point->x < crop.left) {
1213 point->x = crop.left;
1215 if (point->x > crop.right) {
1216 point->x = crop.right;
1218 if (point->y < crop.top) {
1219 point->y = crop.top;
1221 if (point->y > crop.bottom) {
1222 point->y = crop.bottom;
1226 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1227 bool useIdentityTransform) const
1229 const Layer::State& s(getDrawingState());
1230 const Transform tr(hw->getTransform());
1231 const uint32_t hw_h = hw->getHeight();
1232 Rect win(s.active.w, s.active.h);
1233 if (!s.crop.isEmpty()) {
1234 win.intersect(s.crop, &win);
1236 // subtract the transparent region and snap to the bounds
1237 win = reduce(win, s.activeTransparentRegion);
1239 vec2 lt = vec2(win.left, win.top);
1240 vec2 lb = vec2(win.left, win.bottom);
1241 vec2 rb = vec2(win.right, win.bottom);
1242 vec2 rt = vec2(win.right, win.top);
1244 if (!useIdentityTransform) {
1245 lt = s.active.transform.transform(lt);
1246 lb = s.active.transform.transform(lb);
1247 rb = s.active.transform.transform(rb);
1248 rt = s.active.transform.transform(rt);
1251 if (!s.finalCrop.isEmpty()) {
1252 boundPoint(<, s.finalCrop);
1253 boundPoint(&lb, s.finalCrop);
1254 boundPoint(&rb, s.finalCrop);
1255 boundPoint(&rt, s.finalCrop);
1258 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1259 position[0] = tr.transform(lt);
1260 position[1] = tr.transform(lb);
1261 position[2] = tr.transform(rb);
1262 position[3] = tr.transform(rt);
1263 for (size_t i=0 ; i<4 ; i++) {
1264 position[i].y = hw_h - position[i].y;
1268 bool Layer::isOpaque(const Layer::State& s) const
1270 // if we don't have a buffer yet, we're translucent regardless of the
1271 // layer's opaque flag.
1272 if (mActiveBuffer == 0) {
1276 // if the layer has the opaque flag, then we're always opaque,
1277 // otherwise we use the current buffer's format.
1278 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1281 bool Layer::isSecure() const
1283 const Layer::State& s(mDrawingState);
1284 return (s.flags & layer_state_t::eLayerSecure);
1287 bool Layer::isProtected() const
1289 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1290 return (activeBuffer != 0) &&
1291 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1294 bool Layer::isFixedSize() const {
1295 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1298 bool Layer::isCropped() const {
1299 return !mCurrentCrop.isEmpty();
1302 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1303 return mNeedsFiltering || hw->needsFiltering();
1306 void Layer::setVisibleRegion(const Region& visibleRegion) {
1307 // always called from main thread
1308 this->visibleRegion = visibleRegion;
1311 void Layer::setCoveredRegion(const Region& coveredRegion) {
1312 // always called from main thread
1313 this->coveredRegion = coveredRegion;
1316 void Layer::setVisibleNonTransparentRegion(const Region&
1317 setVisibleNonTransparentRegion) {
1318 // always called from main thread
1319 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1322 // ----------------------------------------------------------------------------
1324 // ----------------------------------------------------------------------------
1326 void Layer::pushPendingState() {
1327 if (!mCurrentState.modified) {
1331 // If this transaction is waiting on the receipt of a frame, generate a sync
1332 // point and send it to the remote layer.
1333 if (mCurrentState.handle != nullptr) {
1334 sp<IBinder> strongBinder = mCurrentState.handle.promote();
1335 sp<Handle> handle = nullptr;
1336 sp<Layer> handleLayer = nullptr;
1337 if (strongBinder != nullptr) {
1338 handle = static_cast<Handle*>(strongBinder.get());
1339 handleLayer = handle->owner.promote();
1341 if (strongBinder == nullptr || handleLayer == nullptr) {
1342 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1343 // If we can't promote the layer we are intended to wait on,
1344 // then it is expired or otherwise invalid. Allow this transaction
1345 // to be applied as per normal (no synchronization).
1346 mCurrentState.handle = nullptr;
1348 auto syncPoint = std::make_shared<SyncPoint>(
1349 mCurrentState.frameNumber);
1350 if (handleLayer->addSyncPoint(syncPoint)) {
1351 mRemoteSyncPoints.push_back(std::move(syncPoint));
1353 // We already missed the frame we're supposed to synchronize
1354 // on, so go ahead and apply the state update
1355 mCurrentState.handle = nullptr;
1359 // Wake us up to check if the frame has been received
1360 setTransactionFlags(eTransactionNeeded);
1362 mPendingStates.push_back(mCurrentState);
1365 void Layer::popPendingState(State* stateToCommit) {
1366 auto oldFlags = stateToCommit->flags;
1367 *stateToCommit = mPendingStates[0];
1368 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1369 (stateToCommit->flags & stateToCommit->mask);
1371 mPendingStates.removeAt(0);
1374 bool Layer::applyPendingStates(State* stateToCommit) {
1375 bool stateUpdateAvailable = false;
1376 while (!mPendingStates.empty()) {
1377 if (mPendingStates[0].handle != nullptr) {
1378 if (mRemoteSyncPoints.empty()) {
1379 // If we don't have a sync point for this, apply it anyway. It
1380 // will be visually wrong, but it should keep us from getting
1381 // into too much trouble.
1382 ALOGE("[%s] No local sync point found", mName.string());
1383 popPendingState(stateToCommit);
1384 stateUpdateAvailable = true;
1388 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1389 mPendingStates[0].frameNumber) {
1390 ALOGE("[%s] Unexpected sync point frame number found",
1393 // Signal our end of the sync point and then dispose of it
1394 mRemoteSyncPoints.front()->setTransactionApplied();
1395 mRemoteSyncPoints.pop_front();
1399 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1400 // Apply the state update
1401 popPendingState(stateToCommit);
1402 stateUpdateAvailable = true;
1404 // Signal our end of the sync point and then dispose of it
1405 mRemoteSyncPoints.front()->setTransactionApplied();
1406 mRemoteSyncPoints.pop_front();
1411 popPendingState(stateToCommit);
1412 stateUpdateAvailable = true;
1416 // If we still have pending updates, wake SurfaceFlinger back up and point
1417 // it at this layer so we can process them
1418 if (!mPendingStates.empty()) {
1419 setTransactionFlags(eTransactionNeeded);
1420 mFlinger->setTransactionFlags(eTraversalNeeded);
1423 mCurrentState.modified = false;
1424 return stateUpdateAvailable;
1427 void Layer::notifyAvailableFrames() {
1428 auto headFrameNumber = getHeadFrameNumber();
1429 bool headFenceSignaled = headFenceHasSignaled();
1430 Mutex::Autolock lock(mLocalSyncPointMutex);
1431 for (auto& point : mLocalSyncPoints) {
1432 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) {
1433 point->setFrameAvailable();
1438 uint32_t Layer::doTransaction(uint32_t flags) {
1442 Layer::State c = getCurrentState();
1443 if (!applyPendingStates(&c)) {
1447 const Layer::State& s(getDrawingState());
1449 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1450 (c.requested.h != s.requested.h);
1453 // the size changed, we need to ask our client to request a new buffer
1454 ALOGD_IF(DEBUG_RESIZE,
1455 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1456 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1457 " requested={ wh={%4u,%4u} }}\n"
1458 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1459 " requested={ wh={%4u,%4u} }}\n",
1460 this, getName().string(), mCurrentTransform,
1461 getEffectiveScalingMode(),
1462 c.active.w, c.active.h,
1469 c.requested.w, c.requested.h,
1470 s.active.w, s.active.h,
1477 s.requested.w, s.requested.h);
1479 // record the new size, form this point on, when the client request
1480 // a buffer, it'll get the new size.
1481 mSurfaceFlingerConsumer->setDefaultBufferSize(
1482 c.requested.w, c.requested.h);
1485 const bool resizePending = (c.requested.w != c.active.w) ||
1486 (c.requested.h != c.active.h);
1487 if (!isFixedSize()) {
1488 if (resizePending && mSidebandStream == NULL) {
1489 // don't let Layer::doTransaction update the drawing state
1490 // if we have a pending resize, unless we are in fixed-size mode.
1491 // the drawing state will be updated only once we receive a buffer
1492 // with the correct size.
1494 // in particular, we want to make sure the clip (which is part
1495 // of the geometry state) is latched together with the size but is
1496 // latched immediately when no resizing is involved.
1498 // If a sideband stream is attached, however, we want to skip this
1499 // optimization so that transactions aren't missed when a buffer
1502 flags |= eDontUpdateGeometryState;
1506 // always set active to requested, unless we're asked not to
1507 // this is used by Layer, which special cases resizes.
1508 if (flags & eDontUpdateGeometryState) {
1510 Layer::State& editCurrentState(getCurrentState());
1511 if (mFreezePositionUpdates) {
1512 float tx = c.active.transform.tx();
1513 float ty = c.active.transform.ty();
1514 c.active = c.requested;
1515 c.active.transform.set(tx, ty);
1516 editCurrentState.active = c.active;
1518 editCurrentState.active = editCurrentState.requested;
1519 c.active = c.requested;
1523 if (s.active != c.active) {
1524 // invalidate and recompute the visible regions if needed
1525 flags |= Layer::eVisibleRegion;
1528 if (c.sequence != s.sequence) {
1529 // invalidate and recompute the visible regions if needed
1530 flags |= eVisibleRegion;
1531 this->contentDirty = true;
1533 // we may use linear filtering, if the matrix scales us
1534 const uint8_t type = c.active.transform.getType();
1535 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1536 (type >= Transform::SCALE));
1539 // If the layer is hidden, signal and clear out all local sync points so
1540 // that transactions for layers depending on this layer's frames becoming
1541 // visible are not blocked
1542 if (c.flags & layer_state_t::eLayerHidden) {
1543 Mutex::Autolock lock(mLocalSyncPointMutex);
1544 for (auto& point : mLocalSyncPoints) {
1545 point->setFrameAvailable();
1547 mLocalSyncPoints.clear();
1550 // Commit the transaction
1551 commitTransaction(c);
1555 void Layer::commitTransaction(const State& stateToCommit) {
1556 mDrawingState = stateToCommit;
1559 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1560 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1563 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1564 return android_atomic_or(flags, &mTransactionFlags);
1567 bool Layer::setPosition(float x, float y, bool immediate) {
1568 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1570 mCurrentState.sequence++;
1572 // We update the requested and active position simultaneously because
1573 // we want to apply the position portion of the transform matrix immediately,
1574 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1575 mCurrentState.requested.transform.set(x, y);
1576 if (immediate && !mFreezePositionUpdates) {
1577 mCurrentState.active.transform.set(x, y);
1579 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1581 mCurrentState.modified = true;
1582 setTransactionFlags(eTransactionNeeded);
1586 bool Layer::setLayer(uint32_t z) {
1587 if (mCurrentState.z == z)
1589 mCurrentState.sequence++;
1590 mCurrentState.z = z;
1591 mCurrentState.modified = true;
1592 setTransactionFlags(eTransactionNeeded);
1595 bool Layer::setSize(uint32_t w, uint32_t h) {
1596 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1598 mCurrentState.requested.w = w;
1599 mCurrentState.requested.h = h;
1600 mCurrentState.modified = true;
1601 setTransactionFlags(eTransactionNeeded);
1605 bool Layer::setAlpha(float alpha) {
1607 bool Layer::setAlpha(uint8_t alpha) {
1609 if (mCurrentState.alpha == alpha)
1611 mCurrentState.sequence++;
1612 mCurrentState.alpha = alpha;
1613 mCurrentState.modified = true;
1614 setTransactionFlags(eTransactionNeeded);
1617 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1618 mCurrentState.sequence++;
1619 mCurrentState.requested.transform.set(
1620 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1621 mCurrentState.modified = true;
1622 setTransactionFlags(eTransactionNeeded);
1625 bool Layer::setTransparentRegionHint(const Region& transparent) {
1626 mCurrentState.requestedTransparentRegion = transparent;
1627 mCurrentState.modified = true;
1628 setTransactionFlags(eTransactionNeeded);
1631 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1632 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1633 if (mCurrentState.flags == newFlags)
1635 mCurrentState.sequence++;
1636 mCurrentState.flags = newFlags;
1637 mCurrentState.mask = mask;
1638 mCurrentState.modified = true;
1639 setTransactionFlags(eTransactionNeeded);
1643 bool Layer::setCrop(const Rect& crop, bool immediate) {
1644 if (mCurrentState.crop == crop)
1646 mCurrentState.sequence++;
1647 mCurrentState.requestedCrop = crop;
1649 mCurrentState.crop = crop;
1651 mCurrentState.modified = true;
1652 setTransactionFlags(eTransactionNeeded);
1655 bool Layer::setFinalCrop(const Rect& crop) {
1656 if (mCurrentState.finalCrop == crop)
1658 mCurrentState.sequence++;
1659 mCurrentState.finalCrop = crop;
1660 mCurrentState.modified = true;
1661 setTransactionFlags(eTransactionNeeded);
1665 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1666 if (scalingMode == mOverrideScalingMode)
1668 mOverrideScalingMode = scalingMode;
1669 setTransactionFlags(eTransactionNeeded);
1673 uint32_t Layer::getEffectiveScalingMode() const {
1674 if (mOverrideScalingMode >= 0) {
1675 return mOverrideScalingMode;
1677 return mCurrentScalingMode;
1680 bool Layer::setLayerStack(uint32_t layerStack) {
1681 if (mCurrentState.layerStack == layerStack)
1683 mCurrentState.sequence++;
1684 mCurrentState.layerStack = layerStack;
1685 mCurrentState.modified = true;
1686 setTransactionFlags(eTransactionNeeded);
1690 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1691 uint64_t frameNumber) {
1692 mCurrentState.handle = handle;
1693 mCurrentState.frameNumber = frameNumber;
1694 // We don't set eTransactionNeeded, because just receiving a deferral
1695 // request without any other state updates shouldn't actually induce a delay
1696 mCurrentState.modified = true;
1698 mCurrentState.handle = nullptr;
1699 mCurrentState.frameNumber = 0;
1700 mCurrentState.modified = false;
1703 void Layer::useSurfaceDamage() {
1704 if (mFlinger->mForceFullDamage) {
1705 surfaceDamageRegion = Region::INVALID_REGION;
1707 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1711 void Layer::useEmptyDamage() {
1712 surfaceDamageRegion.clear();
1715 // ----------------------------------------------------------------------------
1716 // pageflip handling...
1717 // ----------------------------------------------------------------------------
1719 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1720 if (mSidebandStreamChanged || mAutoRefresh) {
1724 Mutex::Autolock lock(mQueueItemLock);
1725 if (mQueueItems.empty()) {
1728 auto timestamp = mQueueItems[0].mTimestamp;
1729 nsecs_t expectedPresent =
1730 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1732 // Ignore timestamps more than a second in the future
1733 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1734 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1735 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1738 bool isDue = timestamp < expectedPresent;
1739 return isDue || !isPlausible;
1742 bool Layer::onPreComposition() {
1743 mRefreshPending = false;
1744 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1747 bool Layer::onPostComposition() {
1748 bool frameLatencyNeeded = mFrameLatencyNeeded;
1749 if (mFrameLatencyNeeded) {
1750 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1751 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1753 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1754 if (frameReadyFence->isValid()) {
1755 mFrameTracker.setFrameReadyFence(frameReadyFence);
1757 // There was no fence for this frame, so assume that it was ready
1758 // to be presented at the desired present time.
1759 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1762 const HWComposer& hwc = mFlinger->getHwComposer();
1764 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1766 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1768 if (presentFence->isValid()) {
1769 mFrameTracker.setActualPresentFence(presentFence);
1771 // The HWC doesn't support present fences, so use the refresh
1772 // timestamp instead.
1773 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1774 mFrameTracker.setActualPresentTime(presentTime);
1777 mFrameTracker.advanceFrame();
1778 mFrameLatencyNeeded = false;
1780 return frameLatencyNeeded;
1784 void Layer::releasePendingBuffer() {
1785 mSurfaceFlingerConsumer->releasePendingBuffer();
1789 bool Layer::isVisible() const {
1790 const Layer::State& s(mDrawingState);
1792 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1793 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1795 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1796 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1800 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1804 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1805 // mSidebandStreamChanged was true
1806 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1807 if (mSidebandStream != NULL) {
1808 setTransactionFlags(eTransactionNeeded);
1809 mFlinger->setTransactionFlags(eTraversalNeeded);
1811 recomputeVisibleRegions = true;
1813 const State& s(getDrawingState());
1814 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1817 Region outDirtyRegion;
1818 if (mQueuedFrames > 0 || mAutoRefresh) {
1820 // if we've already called updateTexImage() without going through
1821 // a composition step, we have to skip this layer at this point
1822 // because we cannot call updateTeximage() without a corresponding
1823 // compositionComplete() call.
1824 // we'll trigger an update in onPreComposition().
1825 if (mRefreshPending) {
1826 return outDirtyRegion;
1829 // If the head buffer's acquire fence hasn't signaled yet, return and
1831 if (!headFenceHasSignaled()) {
1832 mFlinger->signalLayerUpdate();
1833 return outDirtyRegion;
1836 // Capture the old state of the layer for comparisons later
1837 const State& s(getDrawingState());
1838 const bool oldOpacity = isOpaque(s);
1839 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1841 struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1842 Layer::State& front;
1843 Layer::State& current;
1844 bool& recomputeVisibleRegions;
1845 bool stickyTransformSet;
1847 int32_t overrideScalingMode;
1848 bool& freezePositionUpdates;
1850 Reject(Layer::State& front, Layer::State& current,
1851 bool& recomputeVisibleRegions, bool stickySet,
1853 int32_t overrideScalingMode,
1854 bool& freezePositionUpdates)
1855 : front(front), current(current),
1856 recomputeVisibleRegions(recomputeVisibleRegions),
1857 stickyTransformSet(stickySet),
1859 overrideScalingMode(overrideScalingMode),
1860 freezePositionUpdates(freezePositionUpdates) {
1863 virtual bool reject(const sp<GraphicBuffer>& buf,
1864 const BufferItem& item) {
1869 uint32_t bufWidth = buf->getWidth();
1870 uint32_t bufHeight = buf->getHeight();
1872 // check that we received a buffer of the right size
1873 // (Take the buffer's orientation into account)
1874 if (item.mTransform & Transform::ROT_90) {
1875 swap(bufWidth, bufHeight);
1878 int actualScalingMode = overrideScalingMode >= 0 ?
1879 overrideScalingMode : item.mScalingMode;
1880 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1881 if (front.active != front.requested) {
1884 (bufWidth == front.requested.w &&
1885 bufHeight == front.requested.h))
1887 // Here we pretend the transaction happened by updating the
1888 // current and drawing states. Drawing state is only accessed
1889 // in this thread, no need to have it locked
1890 front.active = front.requested;
1892 // We also need to update the current state so that
1893 // we don't end-up overwriting the drawing state with
1894 // this stale current state during the next transaction
1896 // NOTE: We don't need to hold the transaction lock here
1897 // because State::active is only accessed from this thread.
1898 current.active = front.active;
1899 current.modified = true;
1901 // recompute visible region
1902 recomputeVisibleRegions = true;
1905 ALOGD_IF(DEBUG_RESIZE,
1906 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1907 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1908 " requested={ wh={%4u,%4u} }}\n",
1910 bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1911 front.active.w, front.active.h,
1916 front.crop.getWidth(),
1917 front.crop.getHeight(),
1918 front.requested.w, front.requested.h);
1921 if (!isFixedSize && !stickyTransformSet) {
1922 if (front.active.w != bufWidth ||
1923 front.active.h != bufHeight) {
1924 // reject this buffer
1925 ALOGE("[%s] rejecting buffer: "
1926 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1927 name, bufWidth, bufHeight, front.active.w, front.active.h);
1932 // if the transparent region has changed (this test is
1933 // conservative, but that's fine, worst case we're doing
1934 // a bit of extra work), we latch the new one and we
1935 // trigger a visible-region recompute.
1936 if (!front.activeTransparentRegion.isTriviallyEqual(
1937 front.requestedTransparentRegion)) {
1938 front.activeTransparentRegion = front.requestedTransparentRegion;
1940 // We also need to update the current state so that
1941 // we don't end-up overwriting the drawing state with
1942 // this stale current state during the next transaction
1944 // NOTE: We don't need to hold the transaction lock here
1945 // because State::active is only accessed from this thread.
1946 current.activeTransparentRegion = front.activeTransparentRegion;
1948 // recompute visible region
1949 recomputeVisibleRegions = true;
1952 if (front.crop != front.requestedCrop) {
1953 front.crop = front.requestedCrop;
1954 current.crop = front.requestedCrop;
1955 recomputeVisibleRegions = true;
1957 freezePositionUpdates = false;
1963 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1964 getProducerStickyTransform() != 0, mName.string(),
1965 mOverrideScalingMode, mFreezePositionUpdates);
1968 // Check all of our local sync points to ensure that all transactions
1969 // which need to have been applied prior to the frame which is about to
1970 // be latched have signaled
1972 auto headFrameNumber = getHeadFrameNumber();
1973 bool matchingFramesFound = false;
1974 bool allTransactionsApplied = true;
1976 Mutex::Autolock lock(mLocalSyncPointMutex);
1977 for (auto& point : mLocalSyncPoints) {
1978 if (point->getFrameNumber() > headFrameNumber) {
1982 matchingFramesFound = true;
1984 if (!point->frameIsAvailable()) {
1985 // We haven't notified the remote layer that the frame for
1986 // this point is available yet. Notify it now, and then
1987 // abort this attempt to latch.
1988 point->setFrameAvailable();
1989 allTransactionsApplied = false;
1993 allTransactionsApplied &= point->transactionIsApplied();
1997 if (matchingFramesFound && !allTransactionsApplied) {
1998 mFlinger->signalLayerUpdate();
1999 return outDirtyRegion;
2002 // This boolean is used to make sure that SurfaceFlinger's shadow copy
2003 // of the buffer queue isn't modified when the buffer queue is returning
2004 // BufferItem's that weren't actually queued. This can happen in shared
2006 bool queuedBuffer = false;
2007 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2008 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2009 mLastFrameNumberReceived);
2010 if (updateResult == BufferQueue::PRESENT_LATER) {
2011 // Producer doesn't want buffer to be displayed yet. Signal a
2012 // layer update so we check again at the next opportunity.
2013 mFlinger->signalLayerUpdate();
2014 return outDirtyRegion;
2015 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2016 // If the buffer has been rejected, remove it from the shadow queue
2019 Mutex::Autolock lock(mQueueItemLock);
2020 mQueueItems.removeAt(0);
2021 android_atomic_dec(&mQueuedFrames);
2023 return outDirtyRegion;
2024 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2025 // This can occur if something goes wrong when trying to create the
2026 // EGLImage for this buffer. If this happens, the buffer has already
2027 // been released, so we need to clean up the queue and bug out
2030 Mutex::Autolock lock(mQueueItemLock);
2031 mQueueItems.clear();
2032 android_atomic_and(0, &mQueuedFrames);
2035 // Once we have hit this state, the shadow queue may no longer
2036 // correctly reflect the incoming BufferQueue's contents, so even if
2037 // updateTexImage starts working, the only safe course of action is
2038 // to continue to ignore updates.
2039 mUpdateTexImageFailed = true;
2041 return outDirtyRegion;
2046 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2048 Mutex::Autolock lock(mQueueItemLock);
2050 // Remove any stale buffers that have been dropped during
2052 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
2053 mQueueItems.removeAt(0);
2054 android_atomic_dec(&mQueuedFrames);
2057 mQueueItems.removeAt(0);
2061 // Decrement the queued-frames count. Signal another event if we
2062 // have more frames pending.
2063 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2065 mFlinger->signalLayerUpdate();
2068 if (updateResult != NO_ERROR) {
2069 // something happened!
2070 recomputeVisibleRegions = true;
2071 return outDirtyRegion;
2074 // update the active buffer
2075 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2076 if (mActiveBuffer == NULL) {
2077 // this can only happen if the very first buffer was rejected.
2078 return outDirtyRegion;
2081 mRefreshPending = true;
2082 mFrameLatencyNeeded = true;
2083 if (oldActiveBuffer == NULL) {
2084 // the first time we receive a buffer, we need to trigger a
2085 // geometry invalidation.
2086 recomputeVisibleRegions = true;
2089 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2090 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2091 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2092 if ((crop != mCurrentCrop) ||
2093 (transform != mCurrentTransform) ||
2094 (scalingMode != mCurrentScalingMode))
2096 mCurrentCrop = crop;
2097 mCurrentTransform = transform;
2098 mCurrentScalingMode = scalingMode;
2099 recomputeVisibleRegions = true;
2102 if (oldActiveBuffer != NULL) {
2103 uint32_t bufWidth = mActiveBuffer->getWidth();
2104 uint32_t bufHeight = mActiveBuffer->getHeight();
2105 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2106 bufHeight != uint32_t(oldActiveBuffer->height)) {
2107 recomputeVisibleRegions = true;
2111 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2112 if (oldOpacity != isOpaque(s)) {
2113 recomputeVisibleRegions = true;
2116 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2118 // Remove any sync points corresponding to the buffer which was just
2121 Mutex::Autolock lock(mLocalSyncPointMutex);
2122 auto point = mLocalSyncPoints.begin();
2123 while (point != mLocalSyncPoints.end()) {
2124 if (!(*point)->frameIsAvailable() ||
2125 !(*point)->transactionIsApplied()) {
2126 // This sync point must have been added since we started
2127 // latching. Don't drop it yet.
2132 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2133 point = mLocalSyncPoints.erase(point);
2140 // FIXME: postedRegion should be dirty & bounds
2141 Region dirtyRegion(Rect(s.active.w, s.active.h));
2143 // transform the dirty region to window-manager space
2144 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2146 return outDirtyRegion;
2149 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2151 // TODO: should we do something special if mSecure is set?
2152 if (mProtectedByApp) {
2153 // need a hardware-protected path to external video sink
2154 usage |= GraphicBuffer::USAGE_PROTECTED;
2156 if (mPotentialCursor) {
2157 usage |= GraphicBuffer::USAGE_CURSOR;
2159 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2163 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2164 uint32_t orientation = 0;
2165 if (!mFlinger->mDebugDisableTransformHint) {
2166 // The transform hint is used to improve performance, but we can
2167 // only have a single transform hint, it cannot
2168 // apply to all displays.
2169 const Transform& planeTransform(hw->getTransform());
2170 orientation = planeTransform.getOrientation();
2171 if (orientation & Transform::ROT_INVALID) {
2175 mSurfaceFlingerConsumer->setTransformHint(orientation);
2178 // ----------------------------------------------------------------------------
2180 // ----------------------------------------------------------------------------
2182 void Layer::dump(String8& result, Colorizer& colorizer) const
2184 const Layer::State& s(getDrawingState());
2186 colorizer.colorize(result, Colorizer::GREEN);
2187 result.appendFormat(
2189 getTypeId(), this, getName().string());
2190 colorizer.reset(result);
2192 s.activeTransparentRegion.dump(result, "transparentRegion");
2193 visibleRegion.dump(result, "visibleRegion");
2194 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2195 sp<Client> client(mClientRef.promote());
2197 result.appendFormat( " "
2198 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2199 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2200 "isOpaque=%1d, invalidate=%1d, "
2202 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2204 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2207 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2208 s.crop.left, s.crop.top,
2209 s.crop.right, s.crop.bottom,
2210 s.finalCrop.left, s.finalCrop.top,
2211 s.finalCrop.right, s.finalCrop.bottom,
2212 isOpaque(s), contentDirty,
2214 s.active.transform[0][0], s.active.transform[0][1],
2215 s.active.transform[1][0], s.active.transform[1][1],
2218 sp<const GraphicBuffer> buf0(mActiveBuffer);
2219 uint32_t w0=0, h0=0, s0=0, f0=0;
2221 w0 = buf0->getWidth();
2222 h0 = buf0->getHeight();
2223 s0 = buf0->getStride();
2226 result.appendFormat(
2228 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2229 " queued-frames=%d, mRefreshPending=%d\n",
2230 mFormat, w0, h0, s0,f0,
2231 mQueuedFrames, mRefreshPending);
2233 if (mSurfaceFlingerConsumer != 0) {
2234 mSurfaceFlingerConsumer->dump(result, " ");
2238 void Layer::dumpFrameStats(String8& result) const {
2239 mFrameTracker.dumpStats(result);
2242 void Layer::clearFrameStats() {
2243 mFrameTracker.clearStats();
2246 void Layer::logFrameStats() {
2247 mFrameTracker.logAndResetStats(mName);
2250 void Layer::getFrameStats(FrameStats* outStats) const {
2251 mFrameTracker.getStats(outStats);
2254 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2255 bool* outIsGlesComposition, nsecs_t* outPostedTime,
2256 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2258 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2261 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2262 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2263 HWC2::Composition::Client : true;
2265 *outIsGlesComposition = mIsGlesComposition;
2267 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2268 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2269 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2272 std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory(
2274 std::vector<OccupancyTracker::Segment> history;
2275 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush,
2277 if (result != NO_ERROR) {
2278 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(),
2285 bool Layer::getTransformToDisplayInverse() const {
2286 return mSurfaceFlingerConsumer->getTransformToDisplayInverse();
2289 // ---------------------------------------------------------------------------
2291 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2292 const sp<Layer>& layer)
2293 : mFlinger(flinger), mLayer(layer) {
2296 Layer::LayerCleaner::~LayerCleaner() {
2297 // destroy client resources
2298 mFlinger->onLayerDestroyed(mLayer);
2301 // ---------------------------------------------------------------------------
2302 }; // namespace android
2304 #if defined(__gl_h_)
2305 #error "don't include gl/gl.h in this file"
2308 #if defined(__gl2_h_)
2309 #error "don't include gl2/gl2.h in this file"