2 * Copyright (c) 2016, The Linux Foundation. All rights reserved.
6 * Copyright (C) 2007 The Android Open Source Project
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
21 //#define LOG_NDEBUG 0
23 #define LOG_TAG "Layer"
24 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
28 #include <sys/types.h>
31 #include <cutils/compiler.h>
32 #include <cutils/native_handle.h>
33 #include <cutils/properties.h>
35 #include <utils/Errors.h>
36 #include <utils/Log.h>
37 #include <utils/NativeHandle.h>
38 #include <utils/StopWatch.h>
39 #include <utils/Trace.h>
41 #include <ui/GraphicBuffer.h>
42 #include <ui/PixelFormat.h>
44 #include <gui/BufferItem.h>
45 #include <gui/Surface.h>
48 #include "Colorizer.h"
49 #include "DisplayDevice.h"
51 #include "MonitoredProducer.h"
52 #include "SurfaceFlinger.h"
54 #include "DisplayHardware/HWComposer.h"
56 #include "RenderEngine/RenderEngine.h"
58 #define DEBUG_RESIZE 0
62 // ---------------------------------------------------------------------------
64 int32_t Layer::sSequence = 1;
66 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
67 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
68 : contentDirty(false),
69 sequence(uint32_t(android_atomic_inc(&sSequence))),
72 mPremultipliedAlpha(true),
74 mFormat(PIXEL_FORMAT_NONE),
79 mSidebandStreamChanged(false),
81 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
82 mOverrideScalingMode(-1),
83 mCurrentOpacity(true),
84 mCurrentFrameNumber(0),
85 mRefreshPending(false),
86 mFrameLatencyNeeded(false),
88 mNeedsFiltering(false),
89 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
91 mIsGlesComposition(false),
93 mProtectedByApp(false),
96 mPotentialCursor(false),
98 mQueueItemCondition(),
100 mLastFrameNumberReceived(0),
101 mUpdateTexImageFailed(false),
103 mFreezePositionUpdates(false),
107 ALOGV("Creating Layer %s", name.string());
110 mCurrentCrop.makeInvalid();
111 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
112 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
114 uint32_t layerFlags = 0;
115 if (flags & ISurfaceComposerClient::eHidden)
116 layerFlags |= layer_state_t::eLayerHidden;
117 if (flags & ISurfaceComposerClient::eOpaque)
118 layerFlags |= layer_state_t::eLayerOpaque;
119 if (flags & ISurfaceComposerClient::eSecure)
120 layerFlags |= layer_state_t::eLayerSecure;
122 if (flags & ISurfaceComposerClient::eNonPremultiplied)
123 mPremultipliedAlpha = false;
127 mCurrentState.active.w = w;
128 mCurrentState.active.h = h;
129 mCurrentState.active.transform.set(0, 0);
130 mCurrentState.crop.makeInvalid();
131 mCurrentState.finalCrop.makeInvalid();
134 mCurrentState.alpha = 1.0f;
136 mCurrentState.alpha = 0xFF;
138 mCurrentState.layerStack = 0;
139 mCurrentState.flags = layerFlags;
140 mCurrentState.sequence = 0;
141 mCurrentState.requested = mCurrentState.active;
142 mCurrentState.color = 0;
144 // drawing state & current state are identical
145 mDrawingState = mCurrentState;
148 const auto& hwc = flinger->getHwComposer();
149 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
150 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
152 nsecs_t displayPeriod =
153 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
155 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
158 void Layer::onFirstRef() {
159 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
160 sp<IGraphicBufferProducer> producer;
161 sp<IGraphicBufferConsumer> consumer;
162 BufferQueue::createBufferQueue(&producer, &consumer);
163 mProducer = new MonitoredProducer(producer, mFlinger);
164 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
165 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
166 mSurfaceFlingerConsumer->setContentsChangedListener(this);
167 mSurfaceFlingerConsumer->setName(mName);
169 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
170 #warning "disabling triple buffering"
172 mProducer->setMaxDequeuedBufferCount(2);
175 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
176 updateTransformHint(hw);
180 sp<Client> c(mClientRef.promote());
182 c->detachLayer(this);
185 for (auto& point : mRemoteSyncPoints) {
186 point->setTransactionApplied();
188 for (auto& point : mLocalSyncPoints) {
189 point->setFrameAvailable();
191 mFlinger->deleteTextureAsync(mTextureName);
192 mFrameTracker.logAndResetStats(mName);
195 // ---------------------------------------------------------------------------
197 // ---------------------------------------------------------------------------
200 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
201 if (mHwcLayers.empty()) {
204 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
207 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
208 HWComposer::HWCLayerInterface* layer) {
210 layer->onDisplayed();
211 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
216 void Layer::onFrameAvailable(const BufferItem& item) {
217 // Add this buffer from our internal queue tracker
219 Mutex::Autolock lock(mQueueItemLock);
221 // Reset the frame number tracker when we receive the first buffer after
222 // a frame number reset
223 if (item.mFrameNumber == 1) {
224 mLastFrameNumberReceived = 0;
227 // Ensure that callbacks are handled in order
228 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
229 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
231 if (result != NO_ERROR) {
232 ALOGE("[%s] Timed out waiting on callback", mName.string());
236 mQueueItems.push_back(item);
237 android_atomic_inc(&mQueuedFrames);
239 // Wake up any pending callbacks
240 mLastFrameNumberReceived = item.mFrameNumber;
241 mQueueItemCondition.broadcast();
244 mFlinger->signalLayerUpdate();
247 void Layer::onFrameReplaced(const BufferItem& item) {
249 Mutex::Autolock lock(mQueueItemLock);
251 // Ensure that callbacks are handled in order
252 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
253 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
255 if (result != NO_ERROR) {
256 ALOGE("[%s] Timed out waiting on callback", mName.string());
260 if (mQueueItems.empty()) {
261 ALOGE("Can't replace a frame on an empty queue");
264 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
266 // Wake up any pending callbacks
267 mLastFrameNumberReceived = item.mFrameNumber;
268 mQueueItemCondition.broadcast();
272 void Layer::onSidebandStreamChanged() {
273 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
274 // mSidebandStreamChanged was false
275 mFlinger->signalLayerUpdate();
279 // called with SurfaceFlinger::mStateLock from the drawing thread after
280 // the layer has been remove from the current state list (and just before
281 // it's removed from the drawing state list)
282 void Layer::onRemoved() {
283 mSurfaceFlingerConsumer->abandon();
286 // ---------------------------------------------------------------------------
288 // ---------------------------------------------------------------------------
290 const String8& Layer::getName() const {
294 status_t Layer::setBuffers( uint32_t w, uint32_t h,
295 PixelFormat format, uint32_t flags)
297 uint32_t const maxSurfaceDims = min(
298 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
300 // never allow a surface larger than what our underlying GL implementation
302 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
303 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
309 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
310 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
311 mCurrentOpacity = getOpacityForFormat(format);
313 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
314 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
315 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
321 * The layer handle is just a BBinder object passed to the client
322 * (remote process) -- we don't keep any reference on our side such that
323 * the dtor is called when the remote side let go of its reference.
325 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
326 * this layer when the handle is destroyed.
328 class Layer::Handle : public BBinder, public LayerCleaner {
330 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
331 : LayerCleaner(flinger, layer), owner(layer) {}
336 sp<IBinder> Layer::getHandle() {
337 Mutex::Autolock _l(mLock);
339 LOG_ALWAYS_FATAL_IF(mHasSurface,
340 "Layer::getHandle() has already been called");
344 return new Handle(mFlinger, this);
347 sp<IGraphicBufferProducer> Layer::getProducer() const {
351 // ---------------------------------------------------------------------------
352 // h/w composer set-up
353 // ---------------------------------------------------------------------------
355 Rect Layer::getContentCrop() const {
356 // this is the crop rectangle that applies to the buffer
357 // itself (as opposed to the window)
359 if (!mCurrentCrop.isEmpty()) {
360 // if the buffer crop is defined, we use that
362 } else if (mActiveBuffer != NULL) {
363 // otherwise we use the whole buffer
364 crop = mActiveBuffer->getBounds();
366 // if we don't have a buffer yet, we use an empty/invalid crop
372 Rect Layer::reduce(const Rect& win, const Region& exclude) const{
373 if (CC_LIKELY(exclude.isEmpty())) {
376 if (exclude.isRect()) {
377 return win.reduce(exclude.getBounds());
379 return Region(win).subtract(exclude).getBounds();
382 Rect Layer::computeBounds() const {
383 const Layer::State& s(getDrawingState());
384 return computeBounds(s.activeTransparentRegion);
387 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
388 const Layer::State& s(getDrawingState());
389 Rect win(s.active.w, s.active.h);
391 if (!s.crop.isEmpty()) {
392 win.intersect(s.crop, &win);
394 // subtract the transparent region and snap to the bounds
395 return reduce(win, activeTransparentRegion);
398 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
399 // the content crop is the area of the content that gets scaled to the
401 FloatRect crop(getContentCrop());
403 // the crop is the area of the window that gets cropped, but not
404 // scaled in any ways.
405 const State& s(getDrawingState());
407 // apply the projection's clipping to the window crop in
408 // layerstack space, and convert-back to layer space.
409 // if there are no window scaling involved, this operation will map to full
410 // pixels in the buffer.
411 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
412 // a viewport clipping and a window transform. we should use floating point to fix this.
414 Rect activeCrop(s.active.w, s.active.h);
415 if (!s.crop.isEmpty()) {
419 activeCrop = s.active.transform.transform(activeCrop);
420 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
423 if (!s.finalCrop.isEmpty()) {
424 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
428 activeCrop = s.active.transform.inverse().transform(activeCrop);
430 // This needs to be here as transform.transform(Rect) computes the
431 // transformed rect and then takes the bounding box of the result before
432 // returning. This means
433 // transform.inverse().transform(transform.transform(Rect)) != Rect
434 // in which case we need to make sure the final rect is clipped to the
436 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
440 // subtract the transparent region and snap to the bounds
441 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
443 // Transform the window crop to match the buffer coordinate system,
444 // which means using the inverse of the current transform set on the
445 // SurfaceFlingerConsumer.
446 uint32_t invTransform = mCurrentTransform;
447 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
449 * the code below applies the primary display's inverse transform to the
452 uint32_t invTransformOrient =
453 DisplayDevice::getPrimaryDisplayOrientationTransform();
454 // calculate the inverse transform
455 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
456 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
457 NATIVE_WINDOW_TRANSFORM_FLIP_H;
459 // and apply to the current transform
460 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
464 int winWidth = s.active.w;
465 int winHeight = s.active.h;
466 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
467 // If the activeCrop has been rotate the ends are rotated but not
468 // the space itself so when transforming ends back we can't rely on
469 // a modification of the axes of rotation. To account for this we
470 // need to reorient the inverse rotation in terms of the current
472 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
473 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
474 if (is_h_flipped == is_v_flipped) {
475 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
476 NATIVE_WINDOW_TRANSFORM_FLIP_H;
478 winWidth = s.active.h;
479 winHeight = s.active.w;
481 const Rect winCrop = activeCrop.transform(
482 invTransform, s.active.w, s.active.h);
484 // below, crop is intersected with winCrop expressed in crop's coordinate space
485 float xScale = crop.getWidth() / float(winWidth);
486 float yScale = crop.getHeight() / float(winHeight);
488 float insetL = winCrop.left * xScale;
489 float insetT = winCrop.top * yScale;
490 float insetR = (winWidth - winCrop.right ) * xScale;
491 float insetB = (winHeight - winCrop.bottom) * yScale;
495 crop.right -= insetR;
496 crop.bottom -= insetB;
502 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
504 void Layer::setGeometry(
505 const sp<const DisplayDevice>& hw,
506 HWComposer::HWCLayerInterface& layer)
510 const auto hwcId = displayDevice->getHwcDisplayId();
511 auto& hwcInfo = mHwcLayers[hwcId];
513 layer.setDefaultState();
518 hwcInfo.forceClientComposition = false;
520 if (isSecure() && !displayDevice->isSecure()) {
521 hwcInfo.forceClientComposition = true;
524 auto& hwcLayer = hwcInfo.layer;
526 layer.setSkip(false);
528 if (isSecure() && !hw->isSecure()) {
533 // this gives us only the "orientation" component of the transform
534 const State& s(getDrawingState());
536 if (!isOpaque(s) || s.alpha != 1.0f) {
537 auto blendMode = mPremultipliedAlpha ?
538 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
539 auto error = hwcLayer->setBlendMode(blendMode);
540 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
541 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
542 to_string(error).c_str(), static_cast<int32_t>(error));
546 layer.setBlending(mPremultipliedAlpha ?
547 HWC_BLENDING_PREMULT :
548 HWC_BLENDING_COVERAGE);
552 // apply the layer's transform, followed by the display's global transform
553 // here we're guaranteed that the layer's transform preserves rects
554 Region activeTransparentRegion(s.activeTransparentRegion);
555 if (!s.crop.isEmpty()) {
556 Rect activeCrop(s.crop);
557 activeCrop = s.active.transform.transform(activeCrop);
559 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
561 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
565 activeCrop = s.active.transform.inverse().transform(activeCrop);
566 // This needs to be here as transform.transform(Rect) computes the
567 // transformed rect and then takes the bounding box of the result before
568 // returning. This means
569 // transform.inverse().transform(transform.transform(Rect)) != Rect
570 // in which case we need to make sure the final rect is clipped to the
572 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
575 // mark regions outside the crop as transparent
576 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
577 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
578 s.active.w, s.active.h));
579 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
580 activeCrop.left, activeCrop.bottom));
581 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
582 s.active.w, activeCrop.bottom));
584 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
585 if (!s.finalCrop.isEmpty()) {
586 if(!frame.intersect(s.finalCrop, &frame)) {
591 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
594 const Transform& tr(displayDevice->getTransform());
595 Rect transformedFrame = tr.transform(frame);
596 auto error = hwcLayer->setDisplayFrame(transformedFrame);
597 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
598 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
599 transformedFrame.top, transformedFrame.right,
600 transformedFrame.bottom, to_string(error).c_str(),
601 static_cast<int32_t>(error));
603 FloatRect sourceCrop = computeCrop(displayDevice);
604 error = hwcLayer->setSourceCrop(sourceCrop);
605 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
606 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
607 sourceCrop.left, sourceCrop.top, sourceCrop.right,
608 sourceCrop.bottom, to_string(error).c_str(),
609 static_cast<int32_t>(error));
611 error = hwcLayer->setPlaneAlpha(s.alpha);
612 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
613 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
614 static_cast<int32_t>(error));
616 error = hwcLayer->setZOrder(s.z);
617 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
618 mName.string(), s.z, to_string(error).c_str(),
619 static_cast<int32_t>(error));
621 if (!frame.intersect(hw->getViewport(), &frame)) {
624 const Transform& tr(hw->getTransform());
625 layer.setFrame(tr.transform(frame));
626 setPosition(hw, layer, s);
627 layer.setCrop(computeCrop(hw));
628 layer.setPlaneAlpha(s.alpha);
632 * Transformations are applied in this order:
633 * 1) buffer orientation/flip/mirror
634 * 2) state transformation (window manager)
635 * 3) layer orientation (screen orientation)
636 * (NOTE: the matrices are multiplied in reverse order)
639 const Transform bufferOrientation(mCurrentTransform);
640 Transform transform(tr * s.active.transform * bufferOrientation);
642 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
644 * the code below applies the primary display's inverse transform to the
647 uint32_t invTransform =
648 DisplayDevice::getPrimaryDisplayOrientationTransform();
649 // calculate the inverse transform
650 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
651 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
652 NATIVE_WINDOW_TRANSFORM_FLIP_H;
654 // and apply to the current transform
655 transform = Transform(invTransform) * transform;
658 // this gives us only the "orientation" component of the transform
659 const uint32_t orientation = transform.getOrientation();
661 if (orientation & Transform::ROT_INVALID) {
662 // we can only handle simple transformation
663 hwcInfo.forceClientComposition = true;
665 auto transform = static_cast<HWC2::Transform>(orientation);
666 auto error = hwcLayer->setTransform(transform);
667 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
668 "%s (%d)", mName.string(), to_string(transform).c_str(),
669 to_string(error).c_str(), static_cast<int32_t>(error));
672 if (orientation & Transform::ROT_INVALID) {
673 // we can only handle simple transformation
676 layer.setTransform(orientation);
682 void Layer::forceClientComposition(int32_t hwcId) {
683 if (mHwcLayers.count(hwcId) == 0) {
684 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
688 mHwcLayers[hwcId].forceClientComposition = true;
693 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
694 // Apply this display's projection's viewport to the visible region
695 // before giving it to the HWC HAL.
696 const Transform& tr = displayDevice->getTransform();
697 const auto& viewport = displayDevice->getViewport();
698 Region visible = tr.transform(visibleRegion.intersect(viewport));
699 auto hwcId = displayDevice->getHwcDisplayId();
700 auto& hwcLayer = mHwcLayers[hwcId].layer;
701 auto error = hwcLayer->setVisibleRegion(visible);
702 if (error != HWC2::Error::None) {
703 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
704 to_string(error).c_str(), static_cast<int32_t>(error));
705 visible.dump(LOG_TAG);
708 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
709 if (error != HWC2::Error::None) {
710 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
711 to_string(error).c_str(), static_cast<int32_t>(error));
712 surfaceDamageRegion.dump(LOG_TAG);
716 if (mSidebandStream.get()) {
717 setCompositionType(hwcId, HWC2::Composition::Sideband);
718 ALOGV("[%s] Requesting Sideband composition", mName.string());
719 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
720 if (error != HWC2::Error::None) {
721 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
722 mName.string(), mSidebandStream->handle(),
723 to_string(error).c_str(), static_cast<int32_t>(error));
728 // Client or SolidColor layers
729 if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr ||
730 mHwcLayers[hwcId].forceClientComposition) {
731 // TODO: This also includes solid color layers, but no API exists to
732 // setup a solid color layer yet
733 ALOGV("[%s] Requesting Client composition", mName.string());
734 setCompositionType(hwcId, HWC2::Composition::Client);
735 error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
736 if (error != HWC2::Error::None) {
737 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
738 to_string(error).c_str(), static_cast<int32_t>(error));
743 // Device or Cursor layers
744 if (mPotentialCursor) {
745 ALOGV("[%s] Requesting Cursor composition", mName.string());
746 setCompositionType(hwcId, HWC2::Composition::Cursor);
748 ALOGV("[%s] Requesting Device composition", mName.string());
749 setCompositionType(hwcId, HWC2::Composition::Device);
752 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
753 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
754 if (error != HWC2::Error::None) {
755 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
756 mActiveBuffer->handle, to_string(error).c_str(),
757 static_cast<int32_t>(error));
761 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
762 HWComposer::HWCLayerInterface& layer) {
763 // we have to set the visible region on every frame because
764 // we currently free it during onLayerDisplayed(), which is called
765 // after HWComposer::commit() -- every frame.
766 // Apply this display's projection's viewport to the visible region
767 // before giving it to the HWC HAL.
768 const Transform& tr = hw->getTransform();
769 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
770 layer.setVisibleRegionScreen(visible);
771 layer.setSurfaceDamage(surfaceDamageRegion);
772 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
774 if (mSidebandStream.get()) {
775 layer.setSidebandStream(mSidebandStream);
777 // NOTE: buffer can be NULL if the client never drew into this
778 // layer yet, or if we ran out of memory
779 layer.setBuffer(mActiveBuffer);
785 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
786 auto hwcId = displayDevice->getHwcDisplayId();
787 if (mHwcLayers.count(hwcId) == 0 ||
788 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
792 // This gives us only the "orientation" component of the transform
793 const State& s(getCurrentState());
795 // Apply the layer's transform, followed by the display's global transform
796 // Here we're guaranteed that the layer's transform preserves rects
797 Rect win(s.active.w, s.active.h);
798 if (!s.crop.isEmpty()) {
799 win.intersect(s.crop, &win);
801 // Subtract the transparent region and snap to the bounds
802 Rect bounds = reduce(win, s.activeTransparentRegion);
803 Rect frame(s.active.transform.transform(bounds));
804 frame.intersect(displayDevice->getViewport(), &frame);
805 if (!s.finalCrop.isEmpty()) {
806 frame.intersect(s.finalCrop, &frame);
808 auto& displayTransform(displayDevice->getTransform());
809 auto position = displayTransform.transform(frame);
811 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
813 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
814 "to (%d, %d): %s (%d)", mName.string(), position.left,
815 position.top, to_string(error).c_str(),
816 static_cast<int32_t>(error));
819 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
820 HWComposer::HWCLayerInterface& layer) {
823 // TODO: there is a possible optimization here: we only need to set the
824 // acquire fence the first time a new buffer is acquired on EACH display.
826 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
827 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
828 if (fence->isValid()) {
829 fenceFd = fence->dup();
831 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
835 setAcquiredFenceIfBlit(fenceFd, layer);
836 layer.setAcquireFenceFd(fenceFd);
839 Rect Layer::getPosition(
840 const sp<const DisplayDevice>& hw)
842 // this gives us only the "orientation" component of the transform
843 const State& s(getCurrentState());
845 // apply the layer's transform, followed by the display's global transform
846 // here we're guaranteed that the layer's transform preserves rects
847 Rect win(s.active.w, s.active.h);
848 if (!s.crop.isEmpty()) {
849 win.intersect(s.crop, &win);
851 // subtract the transparent region and snap to the bounds
852 Rect bounds = reduce(win, s.activeTransparentRegion);
853 Rect frame(s.active.transform.transform(bounds));
854 frame.intersect(hw->getViewport(), &frame);
855 if (!s.finalCrop.isEmpty()) {
856 frame.intersect(s.finalCrop, &frame);
858 const Transform& tr(hw->getTransform());
859 return Rect(tr.transform(frame));
863 // ---------------------------------------------------------------------------
865 // ---------------------------------------------------------------------------
867 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
868 onDraw(hw, clip, false);
871 void Layer::draw(const sp<const DisplayDevice>& hw,
872 bool useIdentityTransform) const {
873 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
876 void Layer::draw(const sp<const DisplayDevice>& hw) const {
877 onDraw(hw, Region(hw->bounds()), false);
880 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
881 bool useIdentityTransform) const
885 if (CC_UNLIKELY(mActiveBuffer == 0)) {
886 // the texture has not been created yet, this Layer has
887 // in fact never been drawn into. This happens frequently with
888 // SurfaceView because the WindowManager can't know when the client
889 // has drawn the first time.
891 // If there is nothing under us, we paint the screen in black, otherwise
892 // we just skip this update.
894 // figure out if there is something below us
896 const SurfaceFlinger::LayerVector& drawingLayers(
897 mFlinger->mDrawingState.layersSortedByZ);
898 const size_t count = drawingLayers.size();
899 for (size_t i=0 ; i<count ; ++i) {
900 const sp<Layer>& layer(drawingLayers[i]);
901 if (layer.get() == static_cast<Layer const*>(this))
903 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
905 // if not everything below us is covered, we plug the holes!
906 Region holes(clip.subtract(under));
907 if (!holes.isEmpty()) {
908 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
913 // Bind the current buffer to the GL texture, and wait for it to be
914 // ready for us to draw into.
915 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
916 if (err != NO_ERROR) {
917 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
918 // Go ahead and draw the buffer anyway; no matter what we do the screen
919 // is probably going to have something visibly wrong.
922 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
924 RenderEngine& engine(mFlinger->getRenderEngine());
926 if (!blackOutLayer ||
927 ((hw->getDisplayType() == HWC_DISPLAY_PRIMARY) && canAllowGPUForProtected())) {
928 // TODO: we could be more subtle with isFixedSize()
929 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
931 // Query the texture matrix given our current filtering mode.
932 float textureMatrix[16];
933 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
934 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
936 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
939 * the code below applies the primary display's inverse transform to
940 * the texture transform
943 // create a 4x4 transform matrix from the display transform flags
944 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
945 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
946 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
950 DisplayDevice::getPrimaryDisplayOrientationTransform();
951 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
953 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
955 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
958 // calculate the inverse
961 // and finally apply it to the original texture matrix
962 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
963 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
966 // Set things up for texturing.
967 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
968 mTexture.setFiltering(useFiltering);
969 mTexture.setMatrix(textureMatrix);
971 engine.setupLayerTexturing(mTexture);
973 engine.setupLayerBlackedOut();
975 drawWithOpenGL(hw, clip, useIdentityTransform);
976 engine.disableTexturing();
980 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
981 const Region& /* clip */, float red, float green, float blue,
984 RenderEngine& engine(mFlinger->getRenderEngine());
985 computeGeometry(hw, mMesh, false);
986 engine.setupFillWithColor(red, green, blue, alpha);
987 engine.drawMesh(mMesh);
990 void Layer::clearWithOpenGL(
991 const sp<const DisplayDevice>& hw, const Region& clip) const {
992 clearWithOpenGL(hw, clip, 0,0,0,0);
995 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
996 const Region& /* clip */, bool useIdentityTransform) const {
997 const State& s(getDrawingState());
999 computeGeometry(hw, mMesh, useIdentityTransform);
1002 * NOTE: the way we compute the texture coordinates here produces
1003 * different results than when we take the HWC path -- in the later case
1004 * the "source crop" is rounded to texel boundaries.
1005 * This can produce significantly different results when the texture
1006 * is scaled by a large amount.
1008 * The GL code below is more logical (imho), and the difference with
1009 * HWC is due to a limitation of the HWC API to integers -- a question
1010 * is suspend is whether we should ignore this problem or revert to
1011 * GL composition when a buffer scaling is applied (maybe with some
1012 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1013 * like more of a hack.
1016 Rect win(s.active.w, s.active.h);
1018 if (!s.crop.isEmpty()) {
1022 win = s.active.transform.transform(win);
1023 win.intersect(hw->getViewport(), &win);
1024 win = s.active.transform.inverse().transform(win);
1025 win.intersect(Rect(s.active.w, s.active.h), &win);
1026 win = reduce(win, s.activeTransparentRegion);
1028 Rect win(computeBounds());
1030 if (!s.finalCrop.isEmpty()) {
1031 win = s.active.transform.transform(win);
1032 if (!win.intersect(s.finalCrop, &win)) {
1035 win = s.active.transform.inverse().transform(win);
1036 if (!win.intersect(computeBounds(), &win)) {
1041 float left = float(win.left) / float(s.active.w);
1042 float top = float(win.top) / float(s.active.h);
1043 float right = float(win.right) / float(s.active.w);
1044 float bottom = float(win.bottom) / float(s.active.h);
1046 // TODO: we probably want to generate the texture coords with the mesh
1047 // here we assume that we only have 4 vertices
1048 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1049 texCoords[0] = vec2(left, 1.0f - top);
1050 texCoords[1] = vec2(left, 1.0f - bottom);
1051 texCoords[2] = vec2(right, 1.0f - bottom);
1052 texCoords[3] = vec2(right, 1.0f - top);
1054 RenderEngine& engine(mFlinger->getRenderEngine());
1055 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1056 engine.drawMesh(mMesh);
1057 engine.disableBlending();
1061 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1063 if (mHwcLayers.count(hwcId) == 0) {
1064 ALOGE("setCompositionType called without a valid HWC layer");
1067 auto& hwcInfo = mHwcLayers[hwcId];
1068 auto& hwcLayer = hwcInfo.layer;
1069 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1070 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1071 if (hwcInfo.compositionType != type) {
1072 ALOGV(" actually setting");
1073 hwcInfo.compositionType = type;
1075 auto error = hwcLayer->setCompositionType(type);
1076 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1077 "composition type %s: %s (%d)", mName.string(),
1078 to_string(type).c_str(), to_string(error).c_str(),
1079 static_cast<int32_t>(error));
1084 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1085 if (mHwcLayers.count(hwcId) == 0) {
1086 ALOGE("getCompositionType called without a valid HWC layer");
1087 return HWC2::Composition::Invalid;
1089 return mHwcLayers.at(hwcId).compositionType;
1092 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1093 if (mHwcLayers.count(hwcId) == 0) {
1094 ALOGE("setClearClientTarget called without a valid HWC layer");
1097 mHwcLayers[hwcId].clearClientTarget = clear;
1100 bool Layer::getClearClientTarget(int32_t hwcId) const {
1101 if (mHwcLayers.count(hwcId) == 0) {
1102 ALOGE("getClearClientTarget called without a valid HWC layer");
1105 return mHwcLayers.at(hwcId).clearClientTarget;
1109 uint32_t Layer::getProducerStickyTransform() const {
1110 int producerStickyTransform = 0;
1111 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1113 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1114 strerror(-ret), ret);
1117 return static_cast<uint32_t>(producerStickyTransform);
1120 uint64_t Layer::getHeadFrameNumber() const {
1121 Mutex::Autolock lock(mQueueItemLock);
1122 if (!mQueueItems.empty()) {
1123 return mQueueItems[0].mFrameNumber;
1125 return mCurrentFrameNumber;
1129 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1130 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1131 // Don't bother with a SyncPoint, since we've already latched the
1136 Mutex::Autolock lock(mLocalSyncPointMutex);
1137 mLocalSyncPoints.push_back(point);
1141 void Layer::setFiltering(bool filtering) {
1142 mFiltering = filtering;
1145 bool Layer::getFiltering() const {
1149 // As documented in libhardware header, formats in the range
1150 // 0x100 - 0x1FF are specific to the HAL implementation, and
1151 // are known to have no alpha channel
1152 // TODO: move definition for device-specific range into
1153 // hardware.h, instead of using hard-coded values here.
1154 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1156 bool Layer::getOpacityForFormat(uint32_t format) {
1157 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1161 case HAL_PIXEL_FORMAT_RGBA_8888:
1162 case HAL_PIXEL_FORMAT_BGRA_8888:
1165 // in all other case, we have no blending (also for unknown formats)
1169 // ----------------------------------------------------------------------------
1171 // ----------------------------------------------------------------------------
1173 static void boundPoint(vec2* point, const Rect& crop) {
1174 if (point->x < crop.left) {
1175 point->x = crop.left;
1177 if (point->x > crop.right) {
1178 point->x = crop.right;
1180 if (point->y < crop.top) {
1181 point->y = crop.top;
1183 if (point->y > crop.bottom) {
1184 point->y = crop.bottom;
1188 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1189 bool useIdentityTransform) const
1191 const Layer::State& s(getDrawingState());
1192 const Transform tr(hw->getTransform());
1193 const uint32_t hw_h = hw->getHeight();
1194 Rect win(s.active.w, s.active.h);
1195 if (!s.crop.isEmpty()) {
1196 win.intersect(s.crop, &win);
1199 win = s.active.transform.transform(win);
1200 win.intersect(hw->getViewport(), &win);
1201 win = s.active.transform.inverse().transform(win);
1202 win.intersect(Rect(s.active.w, s.active.h), &win);
1203 win = reduce(win, s.activeTransparentRegion);
1205 const Transform bufferOrientation(mCurrentTransform);
1206 Transform transform(tr * s.active.transform * bufferOrientation);
1207 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1208 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
1209 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1210 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
1211 NATIVE_WINDOW_TRANSFORM_FLIP_H;
1213 transform = Transform(invTransform) * transform;
1215 const uint32_t orientation = transform.getOrientation();
1216 if (!(orientation | mCurrentTransform | mTransformHint)) {
1217 if (!useIdentityTransform) {
1218 win = s.active.transform.transform(win);
1219 win.intersect(hw->getViewport(), &win);
1223 win = reduce(win, s.activeTransparentRegion);
1228 // subtract the transparent region and snap to the bounds
1230 vec2 lt = vec2(win.left, win.top);
1231 vec2 lb = vec2(win.left, win.bottom);
1232 vec2 rb = vec2(win.right, win.bottom);
1233 vec2 rt = vec2(win.right, win.top);
1235 if (!useIdentityTransform) {
1237 if (orientation | mCurrentTransform | mTransformHint) {
1238 lt = s.active.transform.transform(lt);
1239 lb = s.active.transform.transform(lb);
1240 rb = s.active.transform.transform(rb);
1241 rt = s.active.transform.transform(rt);
1244 lt = s.active.transform.transform(lt);
1245 lb = s.active.transform.transform(lb);
1246 rb = s.active.transform.transform(rb);
1247 rt = s.active.transform.transform(rt);
1250 if (!s.finalCrop.isEmpty()) {
1251 boundPoint(<, s.finalCrop);
1252 boundPoint(&lb, s.finalCrop);
1253 boundPoint(&rb, s.finalCrop);
1254 boundPoint(&rt, s.finalCrop);
1257 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1258 position[0] = tr.transform(lt);
1259 position[1] = tr.transform(lb);
1260 position[2] = tr.transform(rb);
1261 position[3] = tr.transform(rt);
1262 for (size_t i=0 ; i<4 ; i++) {
1263 position[i].y = hw_h - position[i].y;
1267 bool Layer::isOpaque(const Layer::State& s) const
1269 // if we don't have a buffer yet, we're translucent regardless of the
1270 // layer's opaque flag.
1271 if (mActiveBuffer == 0) {
1275 // if the layer has the opaque flag, then we're always opaque,
1276 // otherwise we use the current buffer's format.
1277 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1280 bool Layer::isSecure() const
1282 const Layer::State& s(mDrawingState);
1283 return (s.flags & layer_state_t::eLayerSecure);
1286 bool Layer::isProtected() const
1288 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1289 return (activeBuffer != 0) &&
1290 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1293 bool Layer::isFixedSize() const {
1294 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1297 bool Layer::isCropped() const {
1298 return !mCurrentCrop.isEmpty();
1301 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1302 return mNeedsFiltering || hw->needsFiltering();
1305 void Layer::setVisibleRegion(const Region& visibleRegion) {
1306 // always called from main thread
1307 this->visibleRegion = visibleRegion;
1310 void Layer::setCoveredRegion(const Region& coveredRegion) {
1311 // always called from main thread
1312 this->coveredRegion = coveredRegion;
1315 void Layer::setVisibleNonTransparentRegion(const Region&
1316 setVisibleNonTransparentRegion) {
1317 // always called from main thread
1318 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1321 // ----------------------------------------------------------------------------
1323 // ----------------------------------------------------------------------------
1325 void Layer::pushPendingState() {
1326 if (!mCurrentState.modified) {
1330 // If this transaction is waiting on the receipt of a frame, generate a sync
1331 // point and send it to the remote layer.
1332 if (mCurrentState.handle != nullptr) {
1333 sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1334 sp<Layer> handleLayer = handle->owner.promote();
1335 if (handleLayer == nullptr) {
1336 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1337 // If we can't promote the layer we are intended to wait on,
1338 // then it is expired or otherwise invalid. Allow this transaction
1339 // to be applied as per normal (no synchronization).
1340 mCurrentState.handle = nullptr;
1342 auto syncPoint = std::make_shared<SyncPoint>(
1343 mCurrentState.frameNumber);
1344 if (handleLayer->addSyncPoint(syncPoint)) {
1345 mRemoteSyncPoints.push_back(std::move(syncPoint));
1347 // We already missed the frame we're supposed to synchronize
1348 // on, so go ahead and apply the state update
1349 mCurrentState.handle = nullptr;
1353 // Wake us up to check if the frame has been received
1354 setTransactionFlags(eTransactionNeeded);
1356 mPendingStates.push_back(mCurrentState);
1359 void Layer::popPendingState(State* stateToCommit) {
1360 auto oldFlags = stateToCommit->flags;
1361 *stateToCommit = mPendingStates[0];
1362 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1363 (stateToCommit->flags & stateToCommit->mask);
1365 mPendingStates.removeAt(0);
1368 bool Layer::applyPendingStates(State* stateToCommit) {
1369 bool stateUpdateAvailable = false;
1370 while (!mPendingStates.empty()) {
1371 if (mPendingStates[0].handle != nullptr) {
1372 if (mRemoteSyncPoints.empty()) {
1373 // If we don't have a sync point for this, apply it anyway. It
1374 // will be visually wrong, but it should keep us from getting
1375 // into too much trouble.
1376 ALOGE("[%s] No local sync point found", mName.string());
1377 popPendingState(stateToCommit);
1378 stateUpdateAvailable = true;
1382 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1383 mPendingStates[0].frameNumber) {
1384 ALOGE("[%s] Unexpected sync point frame number found",
1387 // Signal our end of the sync point and then dispose of it
1388 mRemoteSyncPoints.front()->setTransactionApplied();
1389 mRemoteSyncPoints.pop_front();
1393 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1394 // Apply the state update
1395 popPendingState(stateToCommit);
1396 stateUpdateAvailable = true;
1398 // Signal our end of the sync point and then dispose of it
1399 mRemoteSyncPoints.front()->setTransactionApplied();
1400 mRemoteSyncPoints.pop_front();
1405 popPendingState(stateToCommit);
1406 stateUpdateAvailable = true;
1410 // If we still have pending updates, wake SurfaceFlinger back up and point
1411 // it at this layer so we can process them
1412 if (!mPendingStates.empty()) {
1413 setTransactionFlags(eTransactionNeeded);
1414 mFlinger->setTransactionFlags(eTraversalNeeded);
1417 mCurrentState.modified = false;
1418 return stateUpdateAvailable;
1421 void Layer::notifyAvailableFrames() {
1422 auto headFrameNumber = getHeadFrameNumber();
1423 Mutex::Autolock lock(mLocalSyncPointMutex);
1424 for (auto& point : mLocalSyncPoints) {
1425 if (headFrameNumber >= point->getFrameNumber()) {
1426 point->setFrameAvailable();
1431 uint32_t Layer::doTransaction(uint32_t flags) {
1435 Layer::State c = getCurrentState();
1436 if (!applyPendingStates(&c)) {
1440 const Layer::State& s(getDrawingState());
1442 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1443 (c.requested.h != s.requested.h);
1446 // the size changed, we need to ask our client to request a new buffer
1447 ALOGD_IF(DEBUG_RESIZE,
1448 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1449 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1450 " requested={ wh={%4u,%4u} }}\n"
1451 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1452 " requested={ wh={%4u,%4u} }}\n",
1453 this, getName().string(), mCurrentTransform,
1454 getEffectiveScalingMode(),
1455 c.active.w, c.active.h,
1462 c.requested.w, c.requested.h,
1463 s.active.w, s.active.h,
1470 s.requested.w, s.requested.h);
1472 // record the new size, form this point on, when the client request
1473 // a buffer, it'll get the new size.
1474 mSurfaceFlingerConsumer->setDefaultBufferSize(
1475 c.requested.w, c.requested.h);
1478 const bool resizePending = (c.requested.w != c.active.w) ||
1479 (c.requested.h != c.active.h);
1480 if (!isFixedSize()) {
1481 if (resizePending && mSidebandStream == NULL) {
1482 // don't let Layer::doTransaction update the drawing state
1483 // if we have a pending resize, unless we are in fixed-size mode.
1484 // the drawing state will be updated only once we receive a buffer
1485 // with the correct size.
1487 // in particular, we want to make sure the clip (which is part
1488 // of the geometry state) is latched together with the size but is
1489 // latched immediately when no resizing is involved.
1491 // If a sideband stream is attached, however, we want to skip this
1492 // optimization so that transactions aren't missed when a buffer
1495 flags |= eDontUpdateGeometryState;
1499 // always set active to requested, unless we're asked not to
1500 // this is used by Layer, which special cases resizes.
1501 if (flags & eDontUpdateGeometryState) {
1503 Layer::State& editCurrentState(getCurrentState());
1504 if (mFreezePositionUpdates) {
1505 float tx = c.active.transform.tx();
1506 float ty = c.active.transform.ty();
1507 c.active = c.requested;
1508 c.active.transform.set(tx, ty);
1509 editCurrentState.active = c.active;
1511 editCurrentState.active = editCurrentState.requested;
1512 c.active = c.requested;
1516 if (s.active != c.active) {
1517 // invalidate and recompute the visible regions if needed
1518 flags |= Layer::eVisibleRegion;
1521 if (c.sequence != s.sequence) {
1522 // invalidate and recompute the visible regions if needed
1523 flags |= eVisibleRegion;
1524 this->contentDirty = true;
1526 // we may use linear filtering, if the matrix scales us
1527 const uint8_t type = c.active.transform.getType();
1528 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1529 (type >= Transform::SCALE));
1532 // If the layer is hidden, signal and clear out all local sync points so
1533 // that transactions for layers depending on this layer's frames becoming
1534 // visible are not blocked
1535 if (c.flags & layer_state_t::eLayerHidden) {
1536 Mutex::Autolock lock(mLocalSyncPointMutex);
1537 for (auto& point : mLocalSyncPoints) {
1538 point->setFrameAvailable();
1540 mLocalSyncPoints.clear();
1543 // Commit the transaction
1544 commitTransaction(c);
1548 void Layer::commitTransaction(const State& stateToCommit) {
1549 mDrawingState = stateToCommit;
1552 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1553 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1556 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1557 return android_atomic_or(flags, &mTransactionFlags);
1560 bool Layer::setPosition(float x, float y, bool immediate) {
1561 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1563 mCurrentState.sequence++;
1565 // We update the requested and active position simultaneously because
1566 // we want to apply the position portion of the transform matrix immediately,
1567 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1568 mCurrentState.requested.transform.set(x, y);
1569 if (immediate && !mFreezePositionUpdates) {
1570 mCurrentState.active.transform.set(x, y);
1572 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1574 mCurrentState.modified = true;
1575 setTransactionFlags(eTransactionNeeded);
1579 bool Layer::setLayer(uint32_t z) {
1580 if (mCurrentState.z == z)
1582 mCurrentState.sequence++;
1583 mCurrentState.z = z;
1584 mCurrentState.modified = true;
1585 setTransactionFlags(eTransactionNeeded);
1588 bool Layer::setSize(uint32_t w, uint32_t h) {
1589 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1591 mCurrentState.requested.w = w;
1592 mCurrentState.requested.h = h;
1593 mCurrentState.modified = true;
1594 setTransactionFlags(eTransactionNeeded);
1598 bool Layer::setAlpha(float alpha) {
1600 bool Layer::setAlpha(uint8_t alpha) {
1602 if (mCurrentState.alpha == alpha)
1604 mCurrentState.sequence++;
1605 mCurrentState.alpha = alpha;
1606 mCurrentState.modified = true;
1607 setTransactionFlags(eTransactionNeeded);
1610 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1611 mCurrentState.sequence++;
1612 mCurrentState.requested.transform.set(
1613 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1614 mCurrentState.modified = true;
1615 setTransactionFlags(eTransactionNeeded);
1618 bool Layer::setTransparentRegionHint(const Region& transparent) {
1619 mCurrentState.requestedTransparentRegion = transparent;
1620 mCurrentState.modified = true;
1621 setTransactionFlags(eTransactionNeeded);
1624 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1625 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1626 if (mCurrentState.flags == newFlags)
1628 mCurrentState.sequence++;
1629 mCurrentState.flags = newFlags;
1630 mCurrentState.mask = mask;
1631 mCurrentState.modified = true;
1632 setTransactionFlags(eTransactionNeeded);
1635 bool Layer::setCrop(const Rect& crop) {
1636 if (mCurrentState.crop == crop)
1638 mCurrentState.sequence++;
1639 mCurrentState.crop = crop;
1640 mCurrentState.modified = true;
1641 setTransactionFlags(eTransactionNeeded);
1644 bool Layer::setFinalCrop(const Rect& crop) {
1645 if (mCurrentState.finalCrop == crop)
1647 mCurrentState.sequence++;
1648 mCurrentState.finalCrop = crop;
1649 mCurrentState.modified = true;
1650 setTransactionFlags(eTransactionNeeded);
1654 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1655 if (scalingMode == mOverrideScalingMode)
1657 mOverrideScalingMode = scalingMode;
1658 setTransactionFlags(eTransactionNeeded);
1662 bool Layer::setColor(uint32_t color) {
1663 if (mCurrentState.color == color)
1665 mCurrentState.sequence++;
1666 mCurrentState.color = color;
1667 mCurrentState.modified = true;
1668 setTransactionFlags(eTransactionNeeded);
1672 uint32_t Layer::getEffectiveScalingMode() const {
1673 if (mOverrideScalingMode >= 0) {
1674 return mOverrideScalingMode;
1676 return mCurrentScalingMode;
1679 bool Layer::setLayerStack(uint32_t layerStack) {
1680 if (mCurrentState.layerStack == layerStack)
1682 mCurrentState.sequence++;
1683 mCurrentState.layerStack = layerStack;
1684 mCurrentState.modified = true;
1685 setTransactionFlags(eTransactionNeeded);
1689 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1690 uint64_t frameNumber) {
1691 mCurrentState.handle = handle;
1692 mCurrentState.frameNumber = frameNumber;
1693 // We don't set eTransactionNeeded, because just receiving a deferral
1694 // request without any other state updates shouldn't actually induce a delay
1695 mCurrentState.modified = true;
1697 mCurrentState.handle = nullptr;
1698 mCurrentState.frameNumber = 0;
1699 mCurrentState.modified = false;
1702 void Layer::useSurfaceDamage() {
1703 if (mFlinger->mForceFullDamage) {
1704 surfaceDamageRegion = Region::INVALID_REGION;
1706 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1710 void Layer::useEmptyDamage() {
1711 surfaceDamageRegion.clear();
1714 // ----------------------------------------------------------------------------
1715 // pageflip handling...
1716 // ----------------------------------------------------------------------------
1718 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1719 if (mSidebandStreamChanged || mAutoRefresh) {
1723 Mutex::Autolock lock(mQueueItemLock);
1724 if (mQueueItems.empty()) {
1727 auto timestamp = mQueueItems[0].mTimestamp;
1728 nsecs_t expectedPresent =
1729 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1731 // Ignore timestamps more than a second in the future
1732 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1733 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1734 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1737 bool isDue = timestamp < expectedPresent;
1738 return isDue || !isPlausible;
1741 bool Layer::onPreComposition() {
1742 mRefreshPending = false;
1743 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1746 void Layer::onPostComposition() {
1747 if (mFrameLatencyNeeded) {
1748 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1749 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1751 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1752 if (frameReadyFence->isValid()) {
1753 mFrameTracker.setFrameReadyFence(frameReadyFence);
1755 // There was no fence for this frame, so assume that it was ready
1756 // to be presented at the desired present time.
1757 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1760 const HWComposer& hwc = mFlinger->getHwComposer();
1762 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1764 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1766 if (presentFence->isValid()) {
1767 mFrameTracker.setActualPresentFence(presentFence);
1769 // The HWC doesn't support present fences, so use the refresh
1770 // timestamp instead.
1771 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1772 mFrameTracker.setActualPresentTime(presentTime);
1775 mFrameTracker.advanceFrame();
1776 mFrameLatencyNeeded = false;
1781 void Layer::releasePendingBuffer() {
1782 mSurfaceFlingerConsumer->releasePendingBuffer();
1786 bool Layer::isVisible() const {
1787 const Layer::State& s(mDrawingState);
1789 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1790 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1792 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1793 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1797 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1801 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1802 // mSidebandStreamChanged was true
1803 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1804 if (mSidebandStream != NULL) {
1805 setTransactionFlags(eTransactionNeeded);
1806 mFlinger->setTransactionFlags(eTraversalNeeded);
1808 recomputeVisibleRegions = true;
1810 const State& s(getDrawingState());
1811 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1814 Region outDirtyRegion;
1815 if (mQueuedFrames > 0 || mAutoRefresh) {
1817 // if we've already called updateTexImage() without going through
1818 // a composition step, we have to skip this layer at this point
1819 // because we cannot call updateTeximage() without a corresponding
1820 // compositionComplete() call.
1821 // we'll trigger an update in onPreComposition().
1822 if (mRefreshPending) {
1823 return outDirtyRegion;
1826 // Capture the old state of the layer for comparisons later
1827 const State& s(getDrawingState());
1828 const bool oldOpacity = isOpaque(s);
1829 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1831 struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1832 Layer::State& front;
1833 Layer::State& current;
1834 bool& recomputeVisibleRegions;
1835 bool stickyTransformSet;
1837 int32_t overrideScalingMode;
1839 Reject(Layer::State& front, Layer::State& current,
1840 bool& recomputeVisibleRegions, bool stickySet,
1842 int32_t overrideScalingMode)
1843 : front(front), current(current),
1844 recomputeVisibleRegions(recomputeVisibleRegions),
1845 stickyTransformSet(stickySet),
1847 overrideScalingMode(overrideScalingMode) {
1850 virtual bool reject(const sp<GraphicBuffer>& buf,
1851 const BufferItem& item) {
1856 uint32_t bufWidth = buf->getWidth();
1857 uint32_t bufHeight = buf->getHeight();
1859 // check that we received a buffer of the right size
1860 // (Take the buffer's orientation into account)
1861 if (item.mTransform & Transform::ROT_90) {
1862 swap(bufWidth, bufHeight);
1865 int actualScalingMode = overrideScalingMode >= 0 ?
1866 overrideScalingMode : item.mScalingMode;
1867 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1868 if (front.active != front.requested) {
1871 (bufWidth == front.requested.w &&
1872 bufHeight == front.requested.h))
1874 // Here we pretend the transaction happened by updating the
1875 // current and drawing states. Drawing state is only accessed
1876 // in this thread, no need to have it locked
1877 front.active = front.requested;
1879 // We also need to update the current state so that
1880 // we don't end-up overwriting the drawing state with
1881 // this stale current state during the next transaction
1883 // NOTE: We don't need to hold the transaction lock here
1884 // because State::active is only accessed from this thread.
1885 current.active = front.active;
1886 current.modified = true;
1888 // recompute visible region
1889 recomputeVisibleRegions = true;
1892 ALOGD_IF(DEBUG_RESIZE,
1893 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1894 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1895 " requested={ wh={%4u,%4u} }}\n",
1897 bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1898 front.active.w, front.active.h,
1903 front.crop.getWidth(),
1904 front.crop.getHeight(),
1905 front.requested.w, front.requested.h);
1908 if (!isFixedSize && !stickyTransformSet) {
1909 if (front.active.w != bufWidth ||
1910 front.active.h != bufHeight) {
1911 // reject this buffer
1912 ALOGE("[%s] rejecting buffer: "
1913 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1914 name, bufWidth, bufHeight, front.active.w, front.active.h);
1919 // if the transparent region has changed (this test is
1920 // conservative, but that's fine, worst case we're doing
1921 // a bit of extra work), we latch the new one and we
1922 // trigger a visible-region recompute.
1923 if (!front.activeTransparentRegion.isTriviallyEqual(
1924 front.requestedTransparentRegion)) {
1925 front.activeTransparentRegion = front.requestedTransparentRegion;
1927 // We also need to update the current state so that
1928 // we don't end-up overwriting the drawing state with
1929 // this stale current state during the next transaction
1931 // NOTE: We don't need to hold the transaction lock here
1932 // because State::active is only accessed from this thread.
1933 current.activeTransparentRegion = front.activeTransparentRegion;
1935 // recompute visible region
1936 recomputeVisibleRegions = true;
1943 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1944 getProducerStickyTransform() != 0, mName.string(),
1945 mOverrideScalingMode);
1948 // Check all of our local sync points to ensure that all transactions
1949 // which need to have been applied prior to the frame which is about to
1950 // be latched have signaled
1952 auto headFrameNumber = getHeadFrameNumber();
1953 bool matchingFramesFound = false;
1954 bool allTransactionsApplied = true;
1956 Mutex::Autolock lock(mLocalSyncPointMutex);
1957 for (auto& point : mLocalSyncPoints) {
1958 if (point->getFrameNumber() > headFrameNumber) {
1962 matchingFramesFound = true;
1964 if (!point->frameIsAvailable()) {
1965 // We haven't notified the remote layer that the frame for
1966 // this point is available yet. Notify it now, and then
1967 // abort this attempt to latch.
1968 point->setFrameAvailable();
1969 allTransactionsApplied = false;
1973 allTransactionsApplied &= point->transactionIsApplied();
1977 if (matchingFramesFound && !allTransactionsApplied) {
1978 mFlinger->signalLayerUpdate();
1979 return outDirtyRegion;
1982 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1983 // of the buffer queue isn't modified when the buffer queue is returning
1984 // BufferItem's that weren't actually queued. This can happen in shared
1986 bool queuedBuffer = false;
1987 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1988 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1989 mLastFrameNumberReceived);
1990 if (updateResult == BufferQueue::PRESENT_LATER) {
1991 // Producer doesn't want buffer to be displayed yet. Signal a
1992 // layer update so we check again at the next opportunity.
1993 mFlinger->signalLayerUpdate();
1994 return outDirtyRegion;
1995 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1996 // If the buffer has been rejected, remove it from the shadow queue
1999 Mutex::Autolock lock(mQueueItemLock);
2000 mQueueItems.removeAt(0);
2001 android_atomic_dec(&mQueuedFrames);
2003 return outDirtyRegion;
2004 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2005 // This can occur if something goes wrong when trying to create the
2006 // EGLImage for this buffer. If this happens, the buffer has already
2007 // been released, so we need to clean up the queue and bug out
2010 Mutex::Autolock lock(mQueueItemLock);
2011 mQueueItems.clear();
2012 android_atomic_and(0, &mQueuedFrames);
2015 // Once we have hit this state, the shadow queue may no longer
2016 // correctly reflect the incoming BufferQueue's contents, so even if
2017 // updateTexImage starts working, the only safe course of action is
2018 // to continue to ignore updates.
2019 mUpdateTexImageFailed = true;
2021 return outDirtyRegion;
2026 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2028 Mutex::Autolock lock(mQueueItemLock);
2030 // Remove any stale buffers that have been dropped during
2032 while ((mQueuedFrames > 0) && (mQueueItems[0].mFrameNumber != currentFrameNumber)) {
2033 mQueueItems.removeAt(0);
2034 android_atomic_dec(&mQueuedFrames);
2037 if (mQueuedFrames == 0) {
2038 ALOGE("[%s] mQueuedFrames is zero !!", mName.string());
2039 return outDirtyRegion;
2042 mQueueItems.removeAt(0);
2046 // Decrement the queued-frames count. Signal another event if we
2047 // have more frames pending.
2048 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2050 mFlinger->signalLayerUpdate();
2053 if (updateResult != NO_ERROR) {
2054 // something happened!
2055 recomputeVisibleRegions = true;
2056 return outDirtyRegion;
2059 // update the active buffer
2060 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2061 if (mActiveBuffer == NULL) {
2062 // this can only happen if the very first buffer was rejected.
2063 return outDirtyRegion;
2066 mRefreshPending = true;
2067 mFrameLatencyNeeded = true;
2068 if (oldActiveBuffer == NULL) {
2069 // the first time we receive a buffer, we need to trigger a
2070 // geometry invalidation.
2071 recomputeVisibleRegions = true;
2074 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2075 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2076 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2077 if ((crop != mCurrentCrop) ||
2078 (transform != mCurrentTransform) ||
2079 (scalingMode != mCurrentScalingMode))
2081 mCurrentCrop = crop;
2082 mCurrentTransform = transform;
2083 mCurrentScalingMode = scalingMode;
2084 recomputeVisibleRegions = true;
2087 if (oldActiveBuffer != NULL) {
2088 uint32_t bufWidth = mActiveBuffer->getWidth();
2089 uint32_t bufHeight = mActiveBuffer->getHeight();
2090 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2091 bufHeight != uint32_t(oldActiveBuffer->height)) {
2092 recomputeVisibleRegions = true;
2093 mFreezePositionUpdates = false;
2097 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2098 if (oldOpacity != isOpaque(s)) {
2099 recomputeVisibleRegions = true;
2102 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2104 // Remove any sync points corresponding to the buffer which was just
2107 Mutex::Autolock lock(mLocalSyncPointMutex);
2108 auto point = mLocalSyncPoints.begin();
2109 while (point != mLocalSyncPoints.end()) {
2110 if (!(*point)->frameIsAvailable() ||
2111 !(*point)->transactionIsApplied()) {
2112 // This sync point must have been added since we started
2113 // latching. Don't drop it yet.
2118 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2119 point = mLocalSyncPoints.erase(point);
2126 // FIXME: postedRegion should be dirty & bounds
2127 Region dirtyRegion(Rect(s.active.w, s.active.h));
2129 // transform the dirty region to window-manager space
2130 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2132 return outDirtyRegion;
2135 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2137 // TODO: should we do something special if mSecure is set?
2138 if (mProtectedByApp) {
2139 // need a hardware-protected path to external video sink
2140 usage |= GraphicBuffer::USAGE_PROTECTED;
2142 if (mPotentialCursor) {
2143 usage |= GraphicBuffer::USAGE_CURSOR;
2145 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2149 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) {
2150 uint32_t orientation = 0;
2151 if (!mFlinger->mDebugDisableTransformHint) {
2152 // The transform hint is used to improve performance, but we can
2153 // only have a single transform hint, it cannot
2154 // apply to all displays.
2155 const Transform& planeTransform(hw->getTransform());
2156 orientation = planeTransform.getOrientation();
2157 if (orientation & Transform::ROT_INVALID) {
2161 mSurfaceFlingerConsumer->setTransformHint(orientation);
2162 mTransformHint = orientation;
2165 // ----------------------------------------------------------------------------
2167 // ----------------------------------------------------------------------------
2169 void Layer::dump(String8& result, Colorizer& colorizer) const
2171 const Layer::State& s(getDrawingState());
2173 colorizer.colorize(result, Colorizer::GREEN);
2174 result.appendFormat(
2176 getTypeId(), this, getName().string());
2177 colorizer.reset(result);
2179 s.activeTransparentRegion.dump(result, "transparentRegion");
2180 visibleRegion.dump(result, "visibleRegion");
2181 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2182 sp<Client> client(mClientRef.promote());
2184 result.appendFormat( " "
2185 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2186 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2187 "isOpaque=%1d, invalidate=%1d, "
2189 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2191 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2194 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2195 s.crop.left, s.crop.top,
2196 s.crop.right, s.crop.bottom,
2197 s.finalCrop.left, s.finalCrop.top,
2198 s.finalCrop.right, s.finalCrop.bottom,
2199 isOpaque(s), contentDirty,
2201 s.active.transform[0][0], s.active.transform[0][1],
2202 s.active.transform[1][0], s.active.transform[1][1],
2205 sp<const GraphicBuffer> buf0(mActiveBuffer);
2206 uint32_t w0=0, h0=0, s0=0, f0=0;
2208 w0 = buf0->getWidth();
2209 h0 = buf0->getHeight();
2210 s0 = buf0->getStride();
2213 result.appendFormat(
2215 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2216 " queued-frames=%d, mRefreshPending=%d\n",
2217 mFormat, w0, h0, s0,f0,
2218 mQueuedFrames, mRefreshPending);
2220 if (mSurfaceFlingerConsumer != 0) {
2221 mSurfaceFlingerConsumer->dump(result, " ");
2225 void Layer::dumpFrameStats(String8& result) const {
2226 mFrameTracker.dumpStats(result);
2229 void Layer::clearFrameStats() {
2230 mFrameTracker.clearStats();
2233 void Layer::logFrameStats() {
2234 mFrameTracker.logAndResetStats(mName);
2237 void Layer::getFrameStats(FrameStats* outStats) const {
2238 mFrameTracker.getStats(outStats);
2241 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2242 bool* outIsGlesComposition, nsecs_t* outPostedTime,
2243 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2245 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2248 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2249 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2250 HWC2::Composition::Client : true;
2252 *outIsGlesComposition = mIsGlesComposition;
2254 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2255 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2256 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2258 // ---------------------------------------------------------------------------
2260 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2261 const sp<Layer>& layer)
2262 : mFlinger(flinger), mLayer(layer) {
2265 Layer::LayerCleaner::~LayerCleaner() {
2266 // destroy client resources
2267 mFlinger->onLayerDestroyed(mLayer);
2270 // ---------------------------------------------------------------------------
2271 }; // namespace android
2273 #if defined(__gl_h_)
2274 #error "don't include gl/gl.h in this file"
2277 #if defined(__gl2_h_)
2278 #error "don't include gl2/gl2.h in this file"