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.blur = 0xFF;
139 mCurrentState.layerStack = 0;
140 mCurrentState.flags = layerFlags;
141 mCurrentState.sequence = 0;
142 mCurrentState.requested = mCurrentState.active;
143 mCurrentState.color = 0;
145 // drawing state & current state are identical
146 mDrawingState = mCurrentState;
149 const auto& hwc = flinger->getHwComposer();
150 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
151 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
153 nsecs_t displayPeriod =
154 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
156 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
159 void Layer::onFirstRef() {
160 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
161 sp<IGraphicBufferProducer> producer;
162 sp<IGraphicBufferConsumer> consumer;
163 BufferQueue::createBufferQueue(&producer, &consumer);
164 mProducer = new MonitoredProducer(producer, mFlinger);
165 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
166 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
167 mSurfaceFlingerConsumer->setContentsChangedListener(this);
168 mSurfaceFlingerConsumer->setName(mName);
170 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
171 #warning "disabling triple buffering"
173 mProducer->setMaxDequeuedBufferCount(2);
176 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
177 updateTransformHint(hw);
181 sp<Client> c(mClientRef.promote());
183 c->detachLayer(this);
186 for (auto& point : mRemoteSyncPoints) {
187 point->setTransactionApplied();
189 for (auto& point : mLocalSyncPoints) {
190 point->setFrameAvailable();
192 mFlinger->deleteTextureAsync(mTextureName);
193 mFrameTracker.logAndResetStats(mName);
196 // ---------------------------------------------------------------------------
198 // ---------------------------------------------------------------------------
201 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
202 if (mHwcLayers.empty()) {
205 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
208 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
209 HWComposer::HWCLayerInterface* layer) {
211 layer->onDisplayed();
212 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
217 void Layer::onFrameAvailable(const BufferItem& item) {
218 // Add this buffer from our internal queue tracker
220 Mutex::Autolock lock(mQueueItemLock);
222 // Reset the frame number tracker when we receive the first buffer after
223 // a frame number reset
224 if (item.mFrameNumber == 1) {
225 mLastFrameNumberReceived = 0;
228 // Ensure that callbacks are handled in order
229 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
230 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
232 if (result != NO_ERROR) {
233 ALOGE("[%s] Timed out waiting on callback", mName.string());
237 mQueueItems.push_back(item);
238 android_atomic_inc(&mQueuedFrames);
240 // Wake up any pending callbacks
241 mLastFrameNumberReceived = item.mFrameNumber;
242 mQueueItemCondition.broadcast();
245 mFlinger->signalLayerUpdate();
248 void Layer::onFrameReplaced(const BufferItem& item) {
250 Mutex::Autolock lock(mQueueItemLock);
252 // Ensure that callbacks are handled in order
253 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
254 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
256 if (result != NO_ERROR) {
257 ALOGE("[%s] Timed out waiting on callback", mName.string());
261 if (mQueueItems.empty()) {
262 ALOGE("Can't replace a frame on an empty queue");
265 mQueueItems.editItemAt(mQueueItems.size() - 1) = item;
267 // Wake up any pending callbacks
268 mLastFrameNumberReceived = item.mFrameNumber;
269 mQueueItemCondition.broadcast();
273 void Layer::onSidebandStreamChanged() {
274 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
275 // mSidebandStreamChanged was false
276 mFlinger->signalLayerUpdate();
280 // called with SurfaceFlinger::mStateLock from the drawing thread after
281 // the layer has been remove from the current state list (and just before
282 // it's removed from the drawing state list)
283 void Layer::onRemoved() {
284 mSurfaceFlingerConsumer->abandon();
287 // ---------------------------------------------------------------------------
289 // ---------------------------------------------------------------------------
291 const String8& Layer::getName() const {
295 status_t Layer::setBuffers( uint32_t w, uint32_t h,
296 PixelFormat format, uint32_t flags)
298 uint32_t const maxSurfaceDims = min(
299 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
301 // never allow a surface larger than what our underlying GL implementation
303 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
304 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
310 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
311 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
312 mCurrentOpacity = getOpacityForFormat(format);
314 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
315 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
316 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
322 * The layer handle is just a BBinder object passed to the client
323 * (remote process) -- we don't keep any reference on our side such that
324 * the dtor is called when the remote side let go of its reference.
326 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
327 * this layer when the handle is destroyed.
329 class Layer::Handle : public BBinder, public LayerCleaner {
331 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
332 : LayerCleaner(flinger, layer), owner(layer) {}
337 sp<IBinder> Layer::getHandle() {
338 Mutex::Autolock _l(mLock);
340 LOG_ALWAYS_FATAL_IF(mHasSurface,
341 "Layer::getHandle() has already been called");
345 return new Handle(mFlinger, this);
348 sp<IGraphicBufferProducer> Layer::getProducer() const {
352 // ---------------------------------------------------------------------------
353 // h/w composer set-up
354 // ---------------------------------------------------------------------------
356 Rect Layer::getContentCrop() const {
357 // this is the crop rectangle that applies to the buffer
358 // itself (as opposed to the window)
360 if (!mCurrentCrop.isEmpty()) {
361 // if the buffer crop is defined, we use that
363 } else if (mActiveBuffer != NULL) {
364 // otherwise we use the whole buffer
365 crop = mActiveBuffer->getBounds();
367 // if we don't have a buffer yet, we use an empty/invalid crop
373 Rect Layer::reduce(const Rect& win, const Region& exclude) const{
374 if (CC_LIKELY(exclude.isEmpty())) {
377 if (exclude.isRect()) {
378 return win.reduce(exclude.getBounds());
380 return Region(win).subtract(exclude).getBounds();
383 Rect Layer::computeBounds() const {
384 const Layer::State& s(getDrawingState());
385 return computeBounds(s.activeTransparentRegion);
388 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
389 const Layer::State& s(getDrawingState());
390 Rect win(s.active.w, s.active.h);
392 if (!s.crop.isEmpty()) {
393 win.intersect(s.crop, &win);
395 // subtract the transparent region and snap to the bounds
396 return reduce(win, activeTransparentRegion);
399 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
400 // the content crop is the area of the content that gets scaled to the
402 FloatRect crop(getContentCrop());
404 // the crop is the area of the window that gets cropped, but not
405 // scaled in any ways.
406 const State& s(getDrawingState());
408 // apply the projection's clipping to the window crop in
409 // layerstack space, and convert-back to layer space.
410 // if there are no window scaling involved, this operation will map to full
411 // pixels in the buffer.
412 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
413 // a viewport clipping and a window transform. we should use floating point to fix this.
415 Rect activeCrop(s.active.w, s.active.h);
416 if (!s.crop.isEmpty()) {
420 activeCrop = s.active.transform.transform(activeCrop);
421 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
424 if (!s.finalCrop.isEmpty()) {
425 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
429 activeCrop = s.active.transform.inverse().transform(activeCrop);
431 // This needs to be here as transform.transform(Rect) computes the
432 // transformed rect and then takes the bounding box of the result before
433 // returning. This means
434 // transform.inverse().transform(transform.transform(Rect)) != Rect
435 // in which case we need to make sure the final rect is clipped to the
437 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
441 // subtract the transparent region and snap to the bounds
442 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
444 // Transform the window crop to match the buffer coordinate system,
445 // which means using the inverse of the current transform set on the
446 // SurfaceFlingerConsumer.
447 uint32_t invTransform = mCurrentTransform;
448 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
450 * the code below applies the primary display's inverse transform to the
453 uint32_t invTransformOrient =
454 DisplayDevice::getPrimaryDisplayOrientationTransform();
455 // calculate the inverse transform
456 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
457 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
458 NATIVE_WINDOW_TRANSFORM_FLIP_H;
460 // and apply to the current transform
461 invTransform = (Transform(invTransformOrient) * Transform(invTransform))
465 int winWidth = s.active.w;
466 int winHeight = s.active.h;
467 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
468 // If the activeCrop has been rotate the ends are rotated but not
469 // the space itself so when transforming ends back we can't rely on
470 // a modification of the axes of rotation. To account for this we
471 // need to reorient the inverse rotation in terms of the current
473 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
474 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
475 if (is_h_flipped == is_v_flipped) {
476 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
477 NATIVE_WINDOW_TRANSFORM_FLIP_H;
479 winWidth = s.active.h;
480 winHeight = s.active.w;
482 const Rect winCrop = activeCrop.transform(
483 invTransform, s.active.w, s.active.h);
485 // below, crop is intersected with winCrop expressed in crop's coordinate space
486 float xScale = crop.getWidth() / float(winWidth);
487 float yScale = crop.getHeight() / float(winHeight);
489 float insetL = winCrop.left * xScale;
490 float insetT = winCrop.top * yScale;
491 float insetR = (winWidth - winCrop.right ) * xScale;
492 float insetB = (winHeight - winCrop.bottom) * yScale;
496 crop.right -= insetR;
497 crop.bottom -= insetB;
503 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
505 void Layer::setGeometry(
506 const sp<const DisplayDevice>& hw,
507 HWComposer::HWCLayerInterface& layer)
511 const auto hwcId = displayDevice->getHwcDisplayId();
512 auto& hwcInfo = mHwcLayers[hwcId];
514 layer.setDefaultState();
519 hwcInfo.forceClientComposition = false;
521 if (isSecure() && !displayDevice->isSecure()) {
522 hwcInfo.forceClientComposition = true;
525 auto& hwcLayer = hwcInfo.layer;
527 layer.setSkip(false);
529 if (isSecure() && !hw->isSecure()) {
534 // this gives us only the "orientation" component of the transform
535 const State& s(getDrawingState());
537 if (!isOpaque(s) || s.alpha != 1.0f) {
538 auto blendMode = mPremultipliedAlpha ?
539 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
540 auto error = hwcLayer->setBlendMode(blendMode);
541 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
542 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
543 to_string(error).c_str(), static_cast<int32_t>(error));
546 #if defined(QTI_BSP) && !defined(QCOM_BSP_LEGACY)
549 if (!isOpaque(s) || s.alpha != 0xFF) {
551 layer.setBlending(mPremultipliedAlpha ?
552 HWC_BLENDING_PREMULT :
553 HWC_BLENDING_COVERAGE);
557 // apply the layer's transform, followed by the display's global transform
558 // here we're guaranteed that the layer's transform preserves rects
559 Region activeTransparentRegion(s.activeTransparentRegion);
560 if (!s.crop.isEmpty()) {
561 Rect activeCrop(s.crop);
562 activeCrop = s.active.transform.transform(activeCrop);
564 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
566 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
570 activeCrop = s.active.transform.inverse().transform(activeCrop);
571 // This needs to be here as transform.transform(Rect) computes the
572 // transformed rect and then takes the bounding box of the result before
573 // returning. This means
574 // transform.inverse().transform(transform.transform(Rect)) != Rect
575 // in which case we need to make sure the final rect is clipped to the
577 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
580 // mark regions outside the crop as transparent
581 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
582 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
583 s.active.w, s.active.h));
584 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
585 activeCrop.left, activeCrop.bottom));
586 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
587 s.active.w, activeCrop.bottom));
589 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
590 if (!s.finalCrop.isEmpty()) {
591 if(!frame.intersect(s.finalCrop, &frame)) {
596 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
599 const Transform& tr(displayDevice->getTransform());
600 Rect transformedFrame = tr.transform(frame);
601 auto error = hwcLayer->setDisplayFrame(transformedFrame);
602 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
603 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
604 transformedFrame.top, transformedFrame.right,
605 transformedFrame.bottom, to_string(error).c_str(),
606 static_cast<int32_t>(error));
608 FloatRect sourceCrop = computeCrop(displayDevice);
609 error = hwcLayer->setSourceCrop(sourceCrop);
610 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
611 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
612 sourceCrop.left, sourceCrop.top, sourceCrop.right,
613 sourceCrop.bottom, to_string(error).c_str(),
614 static_cast<int32_t>(error));
616 error = hwcLayer->setPlaneAlpha(s.alpha);
617 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
618 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
619 static_cast<int32_t>(error));
621 error = hwcLayer->setZOrder(s.z);
622 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
623 mName.string(), s.z, to_string(error).c_str(),
624 static_cast<int32_t>(error));
626 if (!frame.intersect(hw->getViewport(), &frame)) {
629 const Transform& tr(hw->getTransform());
630 layer.setFrame(tr.transform(frame));
631 setPosition(hw, layer, s);
632 layer.setCrop(computeCrop(hw));
633 layer.setPlaneAlpha(s.alpha);
637 * Transformations are applied in this order:
638 * 1) buffer orientation/flip/mirror
639 * 2) state transformation (window manager)
640 * 3) layer orientation (screen orientation)
641 * (NOTE: the matrices are multiplied in reverse order)
644 const Transform bufferOrientation(mCurrentTransform);
645 Transform transform(tr * s.active.transform * bufferOrientation);
647 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
649 * the code below applies the primary display's inverse transform to the
652 uint32_t invTransform =
653 DisplayDevice::getPrimaryDisplayOrientationTransform();
654 // calculate the inverse transform
655 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
656 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
657 NATIVE_WINDOW_TRANSFORM_FLIP_H;
659 // and apply to the current transform
660 transform = Transform(invTransform) * transform;
663 // this gives us only the "orientation" component of the transform
664 const uint32_t orientation = transform.getOrientation();
666 if (orientation & Transform::ROT_INVALID) {
667 // we can only handle simple transformation
668 hwcInfo.forceClientComposition = true;
670 auto transform = static_cast<HWC2::Transform>(orientation);
671 auto error = hwcLayer->setTransform(transform);
672 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
673 "%s (%d)", mName.string(), to_string(transform).c_str(),
674 to_string(error).c_str(), static_cast<int32_t>(error));
677 if (orientation & Transform::ROT_INVALID) {
678 // we can only handle simple transformation
681 layer.setTransform(orientation);
687 void Layer::forceClientComposition(int32_t hwcId) {
688 if (mHwcLayers.count(hwcId) == 0) {
689 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
693 mHwcLayers[hwcId].forceClientComposition = true;
698 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
699 // Apply this display's projection's viewport to the visible region
700 // before giving it to the HWC HAL.
701 const Transform& tr = displayDevice->getTransform();
702 const auto& viewport = displayDevice->getViewport();
703 Region visible = tr.transform(visibleRegion.intersect(viewport));
704 auto hwcId = displayDevice->getHwcDisplayId();
705 auto& hwcLayer = mHwcLayers[hwcId].layer;
706 auto error = hwcLayer->setVisibleRegion(visible);
707 if (error != HWC2::Error::None) {
708 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
709 to_string(error).c_str(), static_cast<int32_t>(error));
710 visible.dump(LOG_TAG);
713 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
714 if (error != HWC2::Error::None) {
715 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
716 to_string(error).c_str(), static_cast<int32_t>(error));
717 surfaceDamageRegion.dump(LOG_TAG);
721 if (mSidebandStream.get()) {
722 setCompositionType(hwcId, HWC2::Composition::Sideband);
723 ALOGV("[%s] Requesting Sideband composition", mName.string());
724 error = hwcLayer->setSidebandStream(mSidebandStream->handle());
725 if (error != HWC2::Error::None) {
726 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
727 mName.string(), mSidebandStream->handle(),
728 to_string(error).c_str(), static_cast<int32_t>(error));
733 // Client or SolidColor layers
734 if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr ||
735 mHwcLayers[hwcId].forceClientComposition) {
736 // TODO: This also includes solid color layers, but no API exists to
737 // setup a solid color layer yet
738 ALOGV("[%s] Requesting Client composition", mName.string());
739 setCompositionType(hwcId, HWC2::Composition::Client);
740 error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
741 if (error != HWC2::Error::None) {
742 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
743 to_string(error).c_str(), static_cast<int32_t>(error));
748 // Device or Cursor layers
749 if (mPotentialCursor) {
750 ALOGV("[%s] Requesting Cursor composition", mName.string());
751 setCompositionType(hwcId, HWC2::Composition::Cursor);
753 ALOGV("[%s] Requesting Device composition", mName.string());
754 setCompositionType(hwcId, HWC2::Composition::Device);
757 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
758 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence);
759 if (error != HWC2::Error::None) {
760 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
761 mActiveBuffer->handle, to_string(error).c_str(),
762 static_cast<int32_t>(error));
766 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
767 HWComposer::HWCLayerInterface& layer) {
768 // we have to set the visible region on every frame because
769 // we currently free it during onLayerDisplayed(), which is called
770 // after HWComposer::commit() -- every frame.
771 // Apply this display's projection's viewport to the visible region
772 // before giving it to the HWC HAL.
773 const Transform& tr = hw->getTransform();
774 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
775 layer.setVisibleRegionScreen(visible);
776 layer.setSurfaceDamage(surfaceDamageRegion);
777 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
779 if (mSidebandStream.get()) {
780 layer.setSidebandStream(mSidebandStream);
782 // NOTE: buffer can be NULL if the client never drew into this
783 // layer yet, or if we ran out of memory
784 layer.setBuffer(mActiveBuffer);
790 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
791 auto hwcId = displayDevice->getHwcDisplayId();
792 if (mHwcLayers.count(hwcId) == 0 ||
793 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
797 // This gives us only the "orientation" component of the transform
798 const State& s(getCurrentState());
800 // Apply the layer's transform, followed by the display's global transform
801 // Here we're guaranteed that the layer's transform preserves rects
802 Rect win(s.active.w, s.active.h);
803 if (!s.crop.isEmpty()) {
804 win.intersect(s.crop, &win);
806 // Subtract the transparent region and snap to the bounds
807 Rect bounds = reduce(win, s.activeTransparentRegion);
808 Rect frame(s.active.transform.transform(bounds));
809 frame.intersect(displayDevice->getViewport(), &frame);
810 if (!s.finalCrop.isEmpty()) {
811 frame.intersect(s.finalCrop, &frame);
813 auto& displayTransform(displayDevice->getTransform());
814 auto position = displayTransform.transform(frame);
816 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
818 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
819 "to (%d, %d): %s (%d)", mName.string(), position.left,
820 position.top, to_string(error).c_str(),
821 static_cast<int32_t>(error));
824 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
825 HWComposer::HWCLayerInterface& layer) {
828 // TODO: there is a possible optimization here: we only need to set the
829 // acquire fence the first time a new buffer is acquired on EACH display.
831 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
832 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
833 if (fence->isValid()) {
834 fenceFd = fence->dup();
836 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
840 setAcquiredFenceIfBlit(fenceFd, layer);
841 layer.setAcquireFenceFd(fenceFd);
844 Rect Layer::getPosition(
845 const sp<const DisplayDevice>& hw)
847 // this gives us only the "orientation" component of the transform
848 const State& s(getCurrentState());
850 // apply the layer's transform, followed by the display's global transform
851 // here we're guaranteed that the layer's transform preserves rects
852 Rect win(s.active.w, s.active.h);
853 if (!s.crop.isEmpty()) {
854 win.intersect(s.crop, &win);
856 // subtract the transparent region and snap to the bounds
857 Rect bounds = reduce(win, s.activeTransparentRegion);
858 Rect frame(s.active.transform.transform(bounds));
859 frame.intersect(hw->getViewport(), &frame);
860 if (!s.finalCrop.isEmpty()) {
861 frame.intersect(s.finalCrop, &frame);
863 const Transform& tr(hw->getTransform());
864 return Rect(tr.transform(frame));
868 // ---------------------------------------------------------------------------
870 // ---------------------------------------------------------------------------
872 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) {
873 onDraw(hw, clip, false);
876 void Layer::draw(const sp<const DisplayDevice>& hw,
877 bool useIdentityTransform) {
878 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
881 void Layer::draw(const sp<const DisplayDevice>& hw) {
882 onDraw(hw, Region(hw->bounds()), false);
885 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
886 bool useIdentityTransform)
890 if (CC_UNLIKELY(mActiveBuffer == 0)) {
891 // the texture has not been created yet, this Layer has
892 // in fact never been drawn into. This happens frequently with
893 // SurfaceView because the WindowManager can't know when the client
894 // has drawn the first time.
896 // If there is nothing under us, we paint the screen in black, otherwise
897 // we just skip this update.
899 // figure out if there is something below us
901 const SurfaceFlinger::LayerVector& drawingLayers(
902 mFlinger->mDrawingState.layersSortedByZ);
903 const size_t count = drawingLayers.size();
904 for (size_t i=0 ; i<count ; ++i) {
905 const sp<Layer>& layer(drawingLayers[i]);
906 if (layer.get() == static_cast<Layer const*>(this))
908 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
910 // if not everything below us is covered, we plug the holes!
911 Region holes(clip.subtract(under));
912 if (!holes.isEmpty()) {
913 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
918 // Bind the current buffer to the GL texture, and wait for it to be
919 // ready for us to draw into.
920 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
921 if (err != NO_ERROR) {
922 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
923 // Go ahead and draw the buffer anyway; no matter what we do the screen
924 // is probably going to have something visibly wrong.
927 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
929 RenderEngine& engine(mFlinger->getRenderEngine());
931 if (!blackOutLayer ||
932 ((hw->getDisplayType() == HWC_DISPLAY_PRIMARY) && canAllowGPUForProtected())) {
933 // TODO: we could be more subtle with isFixedSize()
934 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
936 // Query the texture matrix given our current filtering mode.
937 float textureMatrix[16];
938 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
939 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
941 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
944 * the code below applies the primary display's inverse transform to
945 * the texture transform
948 // create a 4x4 transform matrix from the display transform flags
949 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
950 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
951 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
955 DisplayDevice::getPrimaryDisplayOrientationTransform();
956 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
958 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
960 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
963 // calculate the inverse
966 // and finally apply it to the original texture matrix
967 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
968 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
971 // Set things up for texturing.
972 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
973 mTexture.setFiltering(useFiltering);
974 mTexture.setMatrix(textureMatrix);
976 engine.setupLayerTexturing(mTexture);
978 engine.setupLayerBlackedOut();
980 drawWithOpenGL(hw, clip, useIdentityTransform);
981 engine.disableTexturing();
985 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
986 const Region& /* clip */, float red, float green, float blue,
989 RenderEngine& engine(mFlinger->getRenderEngine());
990 computeGeometry(hw, mMesh, false);
991 engine.setupFillWithColor(red, green, blue, alpha);
992 engine.drawMesh(mMesh);
995 void Layer::clearWithOpenGL(
996 const sp<const DisplayDevice>& hw, const Region& clip) const {
997 clearWithOpenGL(hw, clip, 0,0,0,0);
1000 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1001 const Region& /* clip */, bool useIdentityTransform) const {
1002 const State& s(getDrawingState());
1004 computeGeometry(hw, mMesh, useIdentityTransform);
1007 * NOTE: the way we compute the texture coordinates here produces
1008 * different results than when we take the HWC path -- in the later case
1009 * the "source crop" is rounded to texel boundaries.
1010 * This can produce significantly different results when the texture
1011 * is scaled by a large amount.
1013 * The GL code below is more logical (imho), and the difference with
1014 * HWC is due to a limitation of the HWC API to integers -- a question
1015 * is suspend is whether we should ignore this problem or revert to
1016 * GL composition when a buffer scaling is applied (maybe with some
1017 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1018 * like more of a hack.
1021 Rect win(s.active.w, s.active.h);
1023 if (!s.crop.isEmpty()) {
1027 win = s.active.transform.transform(win);
1028 win.intersect(hw->getViewport(), &win);
1029 win = s.active.transform.inverse().transform(win);
1030 win.intersect(Rect(s.active.w, s.active.h), &win);
1031 win = reduce(win, s.activeTransparentRegion);
1033 Rect win(computeBounds());
1035 if (!s.finalCrop.isEmpty()) {
1036 win = s.active.transform.transform(win);
1037 if (!win.intersect(s.finalCrop, &win)) {
1040 win = s.active.transform.inverse().transform(win);
1041 if (!win.intersect(computeBounds(), &win)) {
1046 float left = float(win.left) / float(s.active.w);
1047 float top = float(win.top) / float(s.active.h);
1048 float right = float(win.right) / float(s.active.w);
1049 float bottom = float(win.bottom) / float(s.active.h);
1051 // TODO: we probably want to generate the texture coords with the mesh
1052 // here we assume that we only have 4 vertices
1053 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1054 texCoords[0] = vec2(left, 1.0f - top);
1055 texCoords[1] = vec2(left, 1.0f - bottom);
1056 texCoords[2] = vec2(right, 1.0f - bottom);
1057 texCoords[3] = vec2(right, 1.0f - top);
1059 RenderEngine& engine(mFlinger->getRenderEngine());
1060 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1061 engine.drawMesh(mMesh);
1062 engine.disableBlending();
1066 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1068 if (mHwcLayers.count(hwcId) == 0) {
1069 ALOGE("setCompositionType called without a valid HWC layer");
1072 auto& hwcInfo = mHwcLayers[hwcId];
1073 auto& hwcLayer = hwcInfo.layer;
1074 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1075 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1076 if (hwcInfo.compositionType != type) {
1077 ALOGV(" actually setting");
1078 hwcInfo.compositionType = type;
1080 auto error = hwcLayer->setCompositionType(type);
1081 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1082 "composition type %s: %s (%d)", mName.string(),
1083 to_string(type).c_str(), to_string(error).c_str(),
1084 static_cast<int32_t>(error));
1089 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1090 if (mHwcLayers.count(hwcId) == 0) {
1091 ALOGE("getCompositionType called without a valid HWC layer");
1092 return HWC2::Composition::Invalid;
1094 return mHwcLayers.at(hwcId).compositionType;
1097 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1098 if (mHwcLayers.count(hwcId) == 0) {
1099 ALOGE("setClearClientTarget called without a valid HWC layer");
1102 mHwcLayers[hwcId].clearClientTarget = clear;
1105 bool Layer::getClearClientTarget(int32_t hwcId) const {
1106 if (mHwcLayers.count(hwcId) == 0) {
1107 ALOGE("getClearClientTarget called without a valid HWC layer");
1110 return mHwcLayers.at(hwcId).clearClientTarget;
1114 uint32_t Layer::getProducerStickyTransform() const {
1115 int producerStickyTransform = 0;
1116 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1118 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1119 strerror(-ret), ret);
1122 return static_cast<uint32_t>(producerStickyTransform);
1125 uint64_t Layer::getHeadFrameNumber() const {
1126 Mutex::Autolock lock(mQueueItemLock);
1127 if (!mQueueItems.empty()) {
1128 return mQueueItems[0].mFrameNumber;
1130 return mCurrentFrameNumber;
1134 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1135 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1136 // Don't bother with a SyncPoint, since we've already latched the
1141 Mutex::Autolock lock(mLocalSyncPointMutex);
1142 mLocalSyncPoints.push_back(point);
1146 void Layer::setFiltering(bool filtering) {
1147 mFiltering = filtering;
1150 bool Layer::getFiltering() const {
1154 // As documented in libhardware header, formats in the range
1155 // 0x100 - 0x1FF are specific to the HAL implementation, and
1156 // are known to have no alpha channel
1157 // TODO: move definition for device-specific range into
1158 // hardware.h, instead of using hard-coded values here.
1159 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1161 bool Layer::getOpacityForFormat(uint32_t format) {
1162 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1166 case HAL_PIXEL_FORMAT_RGBA_8888:
1167 case HAL_PIXEL_FORMAT_BGRA_8888:
1170 // in all other case, we have no blending (also for unknown formats)
1174 // ----------------------------------------------------------------------------
1176 // ----------------------------------------------------------------------------
1178 static void boundPoint(vec2* point, const Rect& crop) {
1179 if (point->x < crop.left) {
1180 point->x = crop.left;
1182 if (point->x > crop.right) {
1183 point->x = crop.right;
1185 if (point->y < crop.top) {
1186 point->y = crop.top;
1188 if (point->y > crop.bottom) {
1189 point->y = crop.bottom;
1193 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1194 bool useIdentityTransform) const
1196 const Layer::State& s(getDrawingState());
1197 const Transform tr(hw->getTransform());
1198 const uint32_t hw_h = hw->getHeight();
1199 Rect win(s.active.w, s.active.h);
1200 if (!s.crop.isEmpty()) {
1201 win.intersect(s.crop, &win);
1204 win = s.active.transform.transform(win);
1205 win.intersect(hw->getViewport(), &win);
1206 win = s.active.transform.inverse().transform(win);
1207 win.intersect(Rect(s.active.w, s.active.h), &win);
1208 win = reduce(win, s.activeTransparentRegion);
1210 const Transform bufferOrientation(mCurrentTransform);
1211 Transform transform(tr * s.active.transform * bufferOrientation);
1212 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
1213 uint32_t invTransform = DisplayDevice::getPrimaryDisplayOrientationTransform();
1214 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
1215 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
1216 NATIVE_WINDOW_TRANSFORM_FLIP_H;
1218 transform = Transform(invTransform) * transform;
1220 const uint32_t orientation = transform.getOrientation();
1221 if (!(orientation | mCurrentTransform | mTransformHint)) {
1222 if (!useIdentityTransform) {
1223 win = s.active.transform.transform(win);
1224 win.intersect(hw->getViewport(), &win);
1228 win = reduce(win, s.activeTransparentRegion);
1233 // subtract the transparent region and snap to the bounds
1235 vec2 lt = vec2(win.left, win.top);
1236 vec2 lb = vec2(win.left, win.bottom);
1237 vec2 rb = vec2(win.right, win.bottom);
1238 vec2 rt = vec2(win.right, win.top);
1240 if (!useIdentityTransform) {
1242 if (orientation | mCurrentTransform | mTransformHint) {
1243 lt = s.active.transform.transform(lt);
1244 lb = s.active.transform.transform(lb);
1245 rb = s.active.transform.transform(rb);
1246 rt = s.active.transform.transform(rt);
1249 lt = s.active.transform.transform(lt);
1250 lb = s.active.transform.transform(lb);
1251 rb = s.active.transform.transform(rb);
1252 rt = s.active.transform.transform(rt);
1255 if (!s.finalCrop.isEmpty()) {
1256 boundPoint(<, s.finalCrop);
1257 boundPoint(&lb, s.finalCrop);
1258 boundPoint(&rb, s.finalCrop);
1259 boundPoint(&rt, s.finalCrop);
1262 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1263 position[0] = tr.transform(lt);
1264 position[1] = tr.transform(lb);
1265 position[2] = tr.transform(rb);
1266 position[3] = tr.transform(rt);
1267 for (size_t i=0 ; i<4 ; i++) {
1268 position[i].y = hw_h - position[i].y;
1272 bool Layer::isOpaque(const Layer::State& s) const
1274 // if we don't have a buffer yet, we're translucent regardless of the
1275 // layer's opaque flag.
1276 if (mActiveBuffer == 0) {
1280 // if the layer has the opaque flag, then we're always opaque,
1281 // otherwise we use the current buffer's format.
1282 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1285 bool Layer::isSecure() const
1287 const Layer::State& s(mDrawingState);
1288 return (s.flags & layer_state_t::eLayerSecure);
1291 bool Layer::isProtected() const
1293 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1294 return (activeBuffer != 0) &&
1295 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1298 bool Layer::isFixedSize() const {
1299 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1302 bool Layer::isCropped() const {
1303 return !mCurrentCrop.isEmpty();
1306 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1307 return mNeedsFiltering || hw->needsFiltering();
1310 void Layer::setVisibleRegion(const Region& visibleRegion) {
1311 // always called from main thread
1312 this->visibleRegion = visibleRegion;
1315 void Layer::setCoveredRegion(const Region& coveredRegion) {
1316 // always called from main thread
1317 this->coveredRegion = coveredRegion;
1320 void Layer::setVisibleNonTransparentRegion(const Region&
1321 setVisibleNonTransparentRegion) {
1322 // always called from main thread
1323 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1326 // ----------------------------------------------------------------------------
1328 // ----------------------------------------------------------------------------
1330 void Layer::pushPendingState() {
1331 if (!mCurrentState.modified) {
1335 // If this transaction is waiting on the receipt of a frame, generate a sync
1336 // point and send it to the remote layer.
1337 if (mCurrentState.handle != nullptr) {
1338 sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1339 sp<Layer> handleLayer = handle->owner.promote();
1340 if (handleLayer == nullptr) {
1341 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1342 // If we can't promote the layer we are intended to wait on,
1343 // then it is expired or otherwise invalid. Allow this transaction
1344 // to be applied as per normal (no synchronization).
1345 mCurrentState.handle = nullptr;
1347 auto syncPoint = std::make_shared<SyncPoint>(
1348 mCurrentState.frameNumber);
1349 if (handleLayer->addSyncPoint(syncPoint)) {
1350 mRemoteSyncPoints.push_back(std::move(syncPoint));
1352 // We already missed the frame we're supposed to synchronize
1353 // on, so go ahead and apply the state update
1354 mCurrentState.handle = nullptr;
1358 // Wake us up to check if the frame has been received
1359 setTransactionFlags(eTransactionNeeded);
1361 mPendingStates.push_back(mCurrentState);
1364 void Layer::popPendingState(State* stateToCommit) {
1365 auto oldFlags = stateToCommit->flags;
1366 *stateToCommit = mPendingStates[0];
1367 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1368 (stateToCommit->flags & stateToCommit->mask);
1370 mPendingStates.removeAt(0);
1373 bool Layer::applyPendingStates(State* stateToCommit) {
1374 bool stateUpdateAvailable = false;
1375 while (!mPendingStates.empty()) {
1376 if (mPendingStates[0].handle != nullptr) {
1377 if (mRemoteSyncPoints.empty()) {
1378 // If we don't have a sync point for this, apply it anyway. It
1379 // will be visually wrong, but it should keep us from getting
1380 // into too much trouble.
1381 ALOGE("[%s] No local sync point found", mName.string());
1382 popPendingState(stateToCommit);
1383 stateUpdateAvailable = true;
1387 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1388 mPendingStates[0].frameNumber) {
1389 ALOGE("[%s] Unexpected sync point frame number found",
1392 // Signal our end of the sync point and then dispose of it
1393 mRemoteSyncPoints.front()->setTransactionApplied();
1394 mRemoteSyncPoints.pop_front();
1398 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1399 // Apply the state update
1400 popPendingState(stateToCommit);
1401 stateUpdateAvailable = true;
1403 // Signal our end of the sync point and then dispose of it
1404 mRemoteSyncPoints.front()->setTransactionApplied();
1405 mRemoteSyncPoints.pop_front();
1410 popPendingState(stateToCommit);
1411 stateUpdateAvailable = true;
1415 // If we still have pending updates, wake SurfaceFlinger back up and point
1416 // it at this layer so we can process them
1417 if (!mPendingStates.empty()) {
1418 setTransactionFlags(eTransactionNeeded);
1419 mFlinger->setTransactionFlags(eTraversalNeeded);
1422 mCurrentState.modified = false;
1423 return stateUpdateAvailable;
1426 void Layer::notifyAvailableFrames() {
1427 auto headFrameNumber = getHeadFrameNumber();
1428 Mutex::Autolock lock(mLocalSyncPointMutex);
1429 for (auto& point : mLocalSyncPoints) {
1430 if (headFrameNumber >= point->getFrameNumber()) {
1431 point->setFrameAvailable();
1436 uint32_t Layer::doTransaction(uint32_t flags) {
1440 Layer::State c = getCurrentState();
1441 if (!applyPendingStates(&c)) {
1445 const Layer::State& s(getDrawingState());
1447 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1448 (c.requested.h != s.requested.h);
1451 // the size changed, we need to ask our client to request a new buffer
1452 ALOGD_IF(DEBUG_RESIZE,
1453 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1454 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1455 " requested={ wh={%4u,%4u} }}\n"
1456 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1457 " requested={ wh={%4u,%4u} }}\n",
1458 this, getName().string(), mCurrentTransform,
1459 getEffectiveScalingMode(),
1460 c.active.w, c.active.h,
1467 c.requested.w, c.requested.h,
1468 s.active.w, s.active.h,
1475 s.requested.w, s.requested.h);
1477 // record the new size, form this point on, when the client request
1478 // a buffer, it'll get the new size.
1479 mSurfaceFlingerConsumer->setDefaultBufferSize(
1480 c.requested.w, c.requested.h);
1483 const bool resizePending = (c.requested.w != c.active.w) ||
1484 (c.requested.h != c.active.h);
1485 if (!isFixedSize()) {
1486 if (resizePending && mSidebandStream == NULL) {
1487 // don't let Layer::doTransaction update the drawing state
1488 // if we have a pending resize, unless we are in fixed-size mode.
1489 // the drawing state will be updated only once we receive a buffer
1490 // with the correct size.
1492 // in particular, we want to make sure the clip (which is part
1493 // of the geometry state) is latched together with the size but is
1494 // latched immediately when no resizing is involved.
1496 // If a sideband stream is attached, however, we want to skip this
1497 // optimization so that transactions aren't missed when a buffer
1500 flags |= eDontUpdateGeometryState;
1504 // always set active to requested, unless we're asked not to
1505 // this is used by Layer, which special cases resizes.
1506 if (flags & eDontUpdateGeometryState) {
1508 Layer::State& editCurrentState(getCurrentState());
1509 if (mFreezePositionUpdates) {
1510 float tx = c.active.transform.tx();
1511 float ty = c.active.transform.ty();
1512 c.active = c.requested;
1513 c.active.transform.set(tx, ty);
1514 editCurrentState.active = c.active;
1516 editCurrentState.active = editCurrentState.requested;
1517 c.active = c.requested;
1521 if (s.active != c.active) {
1522 // invalidate and recompute the visible regions if needed
1523 flags |= Layer::eVisibleRegion;
1526 if (c.sequence != s.sequence) {
1527 // invalidate and recompute the visible regions if needed
1528 flags |= eVisibleRegion;
1529 this->contentDirty = true;
1531 // we may use linear filtering, if the matrix scales us
1532 const uint8_t type = c.active.transform.getType();
1533 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1534 (type >= Transform::SCALE));
1537 // If the layer is hidden, signal and clear out all local sync points so
1538 // that transactions for layers depending on this layer's frames becoming
1539 // visible are not blocked
1540 if (c.flags & layer_state_t::eLayerHidden) {
1541 Mutex::Autolock lock(mLocalSyncPointMutex);
1542 for (auto& point : mLocalSyncPoints) {
1543 point->setFrameAvailable();
1545 mLocalSyncPoints.clear();
1548 // Commit the transaction
1549 commitTransaction(c);
1553 void Layer::commitTransaction(const State& stateToCommit) {
1554 mDrawingState = stateToCommit;
1557 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1558 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1561 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1562 return android_atomic_or(flags, &mTransactionFlags);
1565 bool Layer::setPosition(float x, float y, bool immediate) {
1566 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1568 mCurrentState.sequence++;
1570 // We update the requested and active position simultaneously because
1571 // we want to apply the position portion of the transform matrix immediately,
1572 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1573 mCurrentState.requested.transform.set(x, y);
1574 if (immediate && !mFreezePositionUpdates) {
1575 mCurrentState.active.transform.set(x, y);
1577 mFreezePositionUpdates = mFreezePositionUpdates || !immediate;
1579 mCurrentState.modified = true;
1580 setTransactionFlags(eTransactionNeeded);
1584 bool Layer::setLayer(uint32_t z) {
1585 if (mCurrentState.z == z)
1587 mCurrentState.sequence++;
1588 mCurrentState.z = z;
1589 mCurrentState.modified = true;
1590 setTransactionFlags(eTransactionNeeded);
1593 bool Layer::setBlur(uint8_t blur) {
1594 if (mCurrentState.blur == blur)
1596 mCurrentState.sequence++;
1597 mCurrentState.blur = blur;
1598 setTransactionFlags(eTransactionNeeded);
1601 bool Layer::setSize(uint32_t w, uint32_t h) {
1602 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1604 mCurrentState.requested.w = w;
1605 mCurrentState.requested.h = h;
1606 mCurrentState.modified = true;
1607 setTransactionFlags(eTransactionNeeded);
1611 bool Layer::setAlpha(float alpha) {
1613 bool Layer::setAlpha(uint8_t alpha) {
1615 if (mCurrentState.alpha == alpha)
1617 mCurrentState.sequence++;
1618 mCurrentState.alpha = alpha;
1619 mCurrentState.modified = true;
1620 setTransactionFlags(eTransactionNeeded);
1623 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1624 mCurrentState.sequence++;
1625 mCurrentState.requested.transform.set(
1626 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1627 mCurrentState.modified = true;
1628 setTransactionFlags(eTransactionNeeded);
1631 bool Layer::setTransparentRegionHint(const Region& transparent) {
1632 mCurrentState.requestedTransparentRegion = transparent;
1633 mCurrentState.modified = true;
1634 setTransactionFlags(eTransactionNeeded);
1637 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1638 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1639 if (mCurrentState.flags == newFlags)
1641 mCurrentState.sequence++;
1642 mCurrentState.flags = newFlags;
1643 mCurrentState.mask = mask;
1644 mCurrentState.modified = true;
1645 setTransactionFlags(eTransactionNeeded);
1648 bool Layer::setCrop(const Rect& crop) {
1649 if (mCurrentState.crop == crop)
1651 mCurrentState.sequence++;
1652 mCurrentState.crop = crop;
1653 mCurrentState.modified = true;
1654 setTransactionFlags(eTransactionNeeded);
1657 bool Layer::setFinalCrop(const Rect& crop) {
1658 if (mCurrentState.finalCrop == crop)
1660 mCurrentState.sequence++;
1661 mCurrentState.finalCrop = crop;
1662 mCurrentState.modified = true;
1663 setTransactionFlags(eTransactionNeeded);
1667 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1668 if (scalingMode == mOverrideScalingMode)
1670 mOverrideScalingMode = scalingMode;
1671 setTransactionFlags(eTransactionNeeded);
1675 bool Layer::setColor(uint32_t color) {
1676 if (mCurrentState.color == color)
1678 mCurrentState.sequence++;
1679 mCurrentState.color = color;
1680 mCurrentState.modified = true;
1681 setTransactionFlags(eTransactionNeeded);
1685 uint32_t Layer::getEffectiveScalingMode() const {
1686 if (mOverrideScalingMode >= 0) {
1687 return mOverrideScalingMode;
1689 return mCurrentScalingMode;
1692 bool Layer::setLayerStack(uint32_t layerStack) {
1693 if (mCurrentState.layerStack == layerStack)
1695 mCurrentState.sequence++;
1696 mCurrentState.layerStack = layerStack;
1697 mCurrentState.modified = true;
1698 setTransactionFlags(eTransactionNeeded);
1702 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1703 uint64_t frameNumber) {
1704 mCurrentState.handle = handle;
1705 mCurrentState.frameNumber = frameNumber;
1706 // We don't set eTransactionNeeded, because just receiving a deferral
1707 // request without any other state updates shouldn't actually induce a delay
1708 mCurrentState.modified = true;
1710 mCurrentState.handle = nullptr;
1711 mCurrentState.frameNumber = 0;
1712 mCurrentState.modified = false;
1715 void Layer::useSurfaceDamage() {
1716 if (mFlinger->mForceFullDamage) {
1717 surfaceDamageRegion = Region::INVALID_REGION;
1719 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1723 void Layer::useEmptyDamage() {
1724 surfaceDamageRegion.clear();
1727 // ----------------------------------------------------------------------------
1728 // pageflip handling...
1729 // ----------------------------------------------------------------------------
1731 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1732 if (mSidebandStreamChanged || mAutoRefresh) {
1736 Mutex::Autolock lock(mQueueItemLock);
1737 if (mQueueItems.empty()) {
1740 auto timestamp = mQueueItems[0].mTimestamp;
1741 nsecs_t expectedPresent =
1742 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1744 // Ignore timestamps more than a second in the future
1745 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1746 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1747 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1750 bool isDue = timestamp < expectedPresent;
1751 return isDue || !isPlausible;
1754 bool Layer::onPreComposition() {
1755 mRefreshPending = false;
1756 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1759 void Layer::onPostComposition() {
1760 if (mFrameLatencyNeeded) {
1761 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1762 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1764 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1765 if (frameReadyFence->isValid()) {
1766 mFrameTracker.setFrameReadyFence(frameReadyFence);
1768 // There was no fence for this frame, so assume that it was ready
1769 // to be presented at the desired present time.
1770 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1773 const HWComposer& hwc = mFlinger->getHwComposer();
1775 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1777 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1779 if (presentFence->isValid()) {
1780 mFrameTracker.setActualPresentFence(presentFence);
1782 // The HWC doesn't support present fences, so use the refresh
1783 // timestamp instead.
1784 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1785 mFrameTracker.setActualPresentTime(presentTime);
1788 mFrameTracker.advanceFrame();
1789 mFrameLatencyNeeded = false;
1794 void Layer::releasePendingBuffer() {
1795 mSurfaceFlingerConsumer->releasePendingBuffer();
1799 bool Layer::isVisible() const {
1800 const Layer::State& s(mDrawingState);
1802 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1803 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1805 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1806 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1810 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1814 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1815 // mSidebandStreamChanged was true
1816 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1817 if (mSidebandStream != NULL) {
1818 setTransactionFlags(eTransactionNeeded);
1819 mFlinger->setTransactionFlags(eTraversalNeeded);
1821 recomputeVisibleRegions = true;
1823 const State& s(getDrawingState());
1824 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1827 Region outDirtyRegion;
1828 if (mQueuedFrames > 0 || mAutoRefresh) {
1830 // if we've already called updateTexImage() without going through
1831 // a composition step, we have to skip this layer at this point
1832 // because we cannot call updateTeximage() without a corresponding
1833 // compositionComplete() call.
1834 // we'll trigger an update in onPreComposition().
1835 if (mRefreshPending) {
1836 return outDirtyRegion;
1839 // Capture the old state of the layer for comparisons later
1840 const State& s(getDrawingState());
1841 const bool oldOpacity = isOpaque(s);
1842 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1844 struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1845 Layer::State& front;
1846 Layer::State& current;
1847 bool& recomputeVisibleRegions;
1848 bool stickyTransformSet;
1850 int32_t overrideScalingMode;
1852 Reject(Layer::State& front, Layer::State& current,
1853 bool& recomputeVisibleRegions, bool stickySet,
1855 int32_t overrideScalingMode)
1856 : front(front), current(current),
1857 recomputeVisibleRegions(recomputeVisibleRegions),
1858 stickyTransformSet(stickySet),
1860 overrideScalingMode(overrideScalingMode) {
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;
1956 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1957 getProducerStickyTransform() != 0, mName.string(),
1958 mOverrideScalingMode);
1961 // Check all of our local sync points to ensure that all transactions
1962 // which need to have been applied prior to the frame which is about to
1963 // be latched have signaled
1965 auto headFrameNumber = getHeadFrameNumber();
1966 bool matchingFramesFound = false;
1967 bool allTransactionsApplied = true;
1969 Mutex::Autolock lock(mLocalSyncPointMutex);
1970 for (auto& point : mLocalSyncPoints) {
1971 if (point->getFrameNumber() > headFrameNumber) {
1975 matchingFramesFound = true;
1977 if (!point->frameIsAvailable()) {
1978 // We haven't notified the remote layer that the frame for
1979 // this point is available yet. Notify it now, and then
1980 // abort this attempt to latch.
1981 point->setFrameAvailable();
1982 allTransactionsApplied = false;
1986 allTransactionsApplied &= point->transactionIsApplied();
1990 if (matchingFramesFound && !allTransactionsApplied) {
1991 mFlinger->signalLayerUpdate();
1992 return outDirtyRegion;
1995 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1996 // of the buffer queue isn't modified when the buffer queue is returning
1997 // BufferItem's that weren't actually queued. This can happen in shared
1999 bool queuedBuffer = false;
2000 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
2001 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
2002 mLastFrameNumberReceived);
2003 if (updateResult == BufferQueue::PRESENT_LATER) {
2004 // Producer doesn't want buffer to be displayed yet. Signal a
2005 // layer update so we check again at the next opportunity.
2006 mFlinger->signalLayerUpdate();
2007 return outDirtyRegion;
2008 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
2009 // If the buffer has been rejected, remove it from the shadow queue
2012 Mutex::Autolock lock(mQueueItemLock);
2013 mQueueItems.removeAt(0);
2014 android_atomic_dec(&mQueuedFrames);
2016 return outDirtyRegion;
2017 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
2018 // This can occur if something goes wrong when trying to create the
2019 // EGLImage for this buffer. If this happens, the buffer has already
2020 // been released, so we need to clean up the queue and bug out
2023 Mutex::Autolock lock(mQueueItemLock);
2024 mQueueItems.clear();
2025 android_atomic_and(0, &mQueuedFrames);
2028 // Once we have hit this state, the shadow queue may no longer
2029 // correctly reflect the incoming BufferQueue's contents, so even if
2030 // updateTexImage starts working, the only safe course of action is
2031 // to continue to ignore updates.
2032 mUpdateTexImageFailed = true;
2034 return outDirtyRegion;
2039 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2041 Mutex::Autolock lock(mQueueItemLock);
2043 // Remove any stale buffers that have been dropped during
2045 while ((mQueuedFrames > 0) && (mQueueItems[0].mFrameNumber != currentFrameNumber)) {
2046 mQueueItems.removeAt(0);
2047 android_atomic_dec(&mQueuedFrames);
2050 if (mQueuedFrames == 0) {
2051 ALOGE("[%s] mQueuedFrames is zero !!", mName.string());
2052 return outDirtyRegion;
2055 mQueueItems.removeAt(0);
2059 // Decrement the queued-frames count. Signal another event if we
2060 // have more frames pending.
2061 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
2063 mFlinger->signalLayerUpdate();
2066 if (updateResult != NO_ERROR) {
2067 // something happened!
2068 recomputeVisibleRegions = true;
2069 return outDirtyRegion;
2072 // update the active buffer
2073 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
2074 if (mActiveBuffer == NULL) {
2075 // this can only happen if the very first buffer was rejected.
2076 return outDirtyRegion;
2079 mRefreshPending = true;
2080 mFrameLatencyNeeded = true;
2081 if (oldActiveBuffer == NULL) {
2082 // the first time we receive a buffer, we need to trigger a
2083 // geometry invalidation.
2084 recomputeVisibleRegions = true;
2087 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
2088 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
2089 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
2090 if ((crop != mCurrentCrop) ||
2091 (transform != mCurrentTransform) ||
2092 (scalingMode != mCurrentScalingMode))
2094 mCurrentCrop = crop;
2095 mCurrentTransform = transform;
2096 mCurrentScalingMode = scalingMode;
2097 recomputeVisibleRegions = true;
2100 if (oldActiveBuffer != NULL) {
2101 uint32_t bufWidth = mActiveBuffer->getWidth();
2102 uint32_t bufHeight = mActiveBuffer->getHeight();
2103 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2104 bufHeight != uint32_t(oldActiveBuffer->height)) {
2105 recomputeVisibleRegions = true;
2106 mFreezePositionUpdates = false;
2110 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2111 if (oldOpacity != isOpaque(s)) {
2112 recomputeVisibleRegions = true;
2115 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2117 // Remove any sync points corresponding to the buffer which was just
2120 Mutex::Autolock lock(mLocalSyncPointMutex);
2121 auto point = mLocalSyncPoints.begin();
2122 while (point != mLocalSyncPoints.end()) {
2123 if (!(*point)->frameIsAvailable() ||
2124 !(*point)->transactionIsApplied()) {
2125 // This sync point must have been added since we started
2126 // latching. Don't drop it yet.
2131 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2132 point = mLocalSyncPoints.erase(point);
2139 // FIXME: postedRegion should be dirty & bounds
2140 Region dirtyRegion(Rect(s.active.w, s.active.h));
2142 // transform the dirty region to window-manager space
2143 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2145 return outDirtyRegion;
2148 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2150 // TODO: should we do something special if mSecure is set?
2151 if (mProtectedByApp) {
2152 // need a hardware-protected path to external video sink
2153 usage |= GraphicBuffer::USAGE_PROTECTED;
2155 if (mPotentialCursor) {
2156 usage |= GraphicBuffer::USAGE_CURSOR;
2158 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2162 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) {
2163 uint32_t orientation = 0;
2164 if (!mFlinger->mDebugDisableTransformHint) {
2165 // The transform hint is used to improve performance, but we can
2166 // only have a single transform hint, it cannot
2167 // apply to all displays.
2168 const Transform& planeTransform(hw->getTransform());
2169 orientation = planeTransform.getOrientation();
2170 if (orientation & Transform::ROT_INVALID) {
2174 mSurfaceFlingerConsumer->setTransformHint(orientation);
2175 mTransformHint = 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, blur=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2204 "alpha=0x%02x, blur=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,
2213 s.alpha, s.blur, s.flags,
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();
2271 // ---------------------------------------------------------------------------
2273 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2274 const sp<Layer>& layer)
2275 : mFlinger(flinger), mLayer(layer) {
2278 Layer::LayerCleaner::~LayerCleaner() {
2279 // destroy client resources
2280 mFlinger->onLayerDestroyed(mLayer);
2283 // ---------------------------------------------------------------------------
2284 }; // namespace android
2286 #if defined(__gl_h_)
2287 #error "don't include gl/gl.h in this file"
2290 #if defined(__gl2_h_)
2291 #error "don't include gl2/gl2.h in this file"