2 * Copyright (C) 2007 The Android Open Source Project
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
17 //#define LOG_NDEBUG 0
19 #define LOG_TAG "Layer"
20 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
24 #include <sys/types.h>
27 #include <cutils/compiler.h>
28 #include <cutils/native_handle.h>
29 #include <cutils/properties.h>
31 #include <utils/Errors.h>
32 #include <utils/Log.h>
33 #include <utils/NativeHandle.h>
34 #include <utils/StopWatch.h>
35 #include <utils/Trace.h>
37 #include <ui/GraphicBuffer.h>
38 #include <ui/PixelFormat.h>
40 #include <gui/BufferItem.h>
41 #include <gui/Surface.h>
44 #include "Colorizer.h"
45 #include "DisplayDevice.h"
47 #include "MonitoredProducer.h"
48 #include "SurfaceFlinger.h"
50 #include "DisplayHardware/HWComposer.h"
52 #include "RenderEngine/RenderEngine.h"
54 #define DEBUG_RESIZE 0
58 // ---------------------------------------------------------------------------
60 int32_t Layer::sSequence = 1;
62 Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client,
63 const String8& name, uint32_t w, uint32_t h, uint32_t flags)
64 : contentDirty(false),
65 sequence(uint32_t(android_atomic_inc(&sSequence))),
68 mPremultipliedAlpha(true),
70 mFormat(PIXEL_FORMAT_NONE),
75 mSidebandStreamChanged(false),
77 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE),
78 mOverrideScalingMode(-1),
79 mCurrentOpacity(true),
80 mCurrentFrameNumber(0),
81 mRefreshPending(false),
82 mFrameLatencyNeeded(false),
84 mNeedsFiltering(false),
85 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2),
87 mIsGlesComposition(false),
89 mProtectedByApp(false),
92 mPotentialCursor(false),
94 mQueueItemCondition(),
96 mLastFrameNumberReceived(0),
97 mUpdateTexImageFailed(false),
101 ALOGV("Creating Layer %s", name.string());
104 mCurrentCrop.makeInvalid();
105 mFlinger->getRenderEngine().genTextures(1, &mTextureName);
106 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName);
108 uint32_t layerFlags = 0;
109 if (flags & ISurfaceComposerClient::eHidden)
110 layerFlags |= layer_state_t::eLayerHidden;
111 if (flags & ISurfaceComposerClient::eOpaque)
112 layerFlags |= layer_state_t::eLayerOpaque;
113 if (flags & ISurfaceComposerClient::eSecure)
114 layerFlags |= layer_state_t::eLayerSecure;
116 if (flags & ISurfaceComposerClient::eNonPremultiplied)
117 mPremultipliedAlpha = false;
121 mCurrentState.active.w = w;
122 mCurrentState.active.h = h;
123 mCurrentState.active.transform.set(0, 0);
124 mCurrentState.crop.makeInvalid();
125 mCurrentState.finalCrop.makeInvalid();
128 mCurrentState.alpha = 1.0f;
130 mCurrentState.alpha = 0xFF;
132 mCurrentState.layerStack = 0;
133 mCurrentState.flags = layerFlags;
134 mCurrentState.sequence = 0;
135 mCurrentState.requested = mCurrentState.active;
137 // drawing state & current state are identical
138 mDrawingState = mCurrentState;
141 const auto& hwc = flinger->getHwComposer();
142 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY);
143 nsecs_t displayPeriod = activeConfig->getVsyncPeriod();
145 nsecs_t displayPeriod =
146 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
148 mFrameTracker.setDisplayRefreshPeriod(displayPeriod);
151 void Layer::onFirstRef() {
152 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use
153 sp<IGraphicBufferProducer> producer;
154 sp<IGraphicBufferConsumer> consumer;
155 BufferQueue::createBufferQueue(&producer, &consumer);
156 mProducer = new MonitoredProducer(producer, mFlinger);
157 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName);
158 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
159 mSurfaceFlingerConsumer->setContentsChangedListener(this);
160 mSurfaceFlingerConsumer->setName(mName);
162 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
163 #warning "disabling triple buffering"
165 mProducer->setMaxDequeuedBufferCount(2);
168 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice());
169 updateTransformHint(hw);
173 sp<Client> c(mClientRef.promote());
175 c->detachLayer(this);
178 for (auto& point : mRemoteSyncPoints) {
179 point->setTransactionApplied();
181 mFlinger->deleteTextureAsync(mTextureName);
182 mFrameTracker.logAndResetStats(mName);
185 // ---------------------------------------------------------------------------
187 // ---------------------------------------------------------------------------
190 void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) {
191 if (mHwcLayers.empty()) {
194 mSurfaceFlingerConsumer->setReleaseFence(releaseFence);
197 void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */,
198 HWComposer::HWCLayerInterface* layer) {
200 layer->onDisplayed();
201 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence());
206 void Layer::onFrameAvailable(const BufferItem& item) {
207 // Add this buffer from our internal queue tracker
209 Mutex::Autolock lock(mQueueItemLock);
211 // Reset the frame number tracker when we receive the first buffer after
212 // a frame number reset
213 if (item.mFrameNumber == 1) {
214 mLastFrameNumberReceived = 0;
217 // Ensure that callbacks are handled in order
218 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
219 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
221 if (result != NO_ERROR) {
222 ALOGE("[%s] Timed out waiting on callback", mName.string());
226 mQueueItems.push_back(item);
227 android_atomic_inc(&mQueuedFrames);
229 // Wake up any pending callbacks
230 mLastFrameNumberReceived = item.mFrameNumber;
231 mQueueItemCondition.broadcast();
234 mFlinger->signalLayerUpdate();
237 void Layer::onFrameReplaced(const BufferItem& item) {
239 Mutex::Autolock lock(mQueueItemLock);
241 // Ensure that callbacks are handled in order
242 while (item.mFrameNumber != mLastFrameNumberReceived + 1) {
243 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock,
245 if (result != NO_ERROR) {
246 ALOGE("[%s] Timed out waiting on callback", mName.string());
250 if (mQueueItems.empty()) {
251 ALOGE("Can't replace a frame on an empty queue");
254 mQueueItems.editItemAt(0) = item;
256 // Wake up any pending callbacks
257 mLastFrameNumberReceived = item.mFrameNumber;
258 mQueueItemCondition.broadcast();
262 void Layer::onSidebandStreamChanged() {
263 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) {
264 // mSidebandStreamChanged was false
265 mFlinger->signalLayerUpdate();
269 // called with SurfaceFlinger::mStateLock from the drawing thread after
270 // the layer has been remove from the current state list (and just before
271 // it's removed from the drawing state list)
272 void Layer::onRemoved() {
273 mSurfaceFlingerConsumer->abandon();
276 // ---------------------------------------------------------------------------
278 // ---------------------------------------------------------------------------
280 const String8& Layer::getName() const {
284 status_t Layer::setBuffers( uint32_t w, uint32_t h,
285 PixelFormat format, uint32_t flags)
287 uint32_t const maxSurfaceDims = min(
288 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims());
290 // never allow a surface larger than what our underlying GL implementation
292 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) {
293 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h));
299 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false;
300 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false;
301 mCurrentOpacity = getOpacityForFormat(format);
303 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h);
304 mSurfaceFlingerConsumer->setDefaultBufferFormat(format);
305 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0));
311 * The layer handle is just a BBinder object passed to the client
312 * (remote process) -- we don't keep any reference on our side such that
313 * the dtor is called when the remote side let go of its reference.
315 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for
316 * this layer when the handle is destroyed.
318 class Layer::Handle : public BBinder, public LayerCleaner {
320 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer)
321 : LayerCleaner(flinger, layer), owner(layer) {}
326 sp<IBinder> Layer::getHandle() {
327 Mutex::Autolock _l(mLock);
329 LOG_ALWAYS_FATAL_IF(mHasSurface,
330 "Layer::getHandle() has already been called");
334 return new Handle(mFlinger, this);
337 sp<IGraphicBufferProducer> Layer::getProducer() const {
341 // ---------------------------------------------------------------------------
342 // h/w composer set-up
343 // ---------------------------------------------------------------------------
345 Rect Layer::getContentCrop() const {
346 // this is the crop rectangle that applies to the buffer
347 // itself (as opposed to the window)
349 if (!mCurrentCrop.isEmpty()) {
350 // if the buffer crop is defined, we use that
352 } else if (mActiveBuffer != NULL) {
353 // otherwise we use the whole buffer
354 crop = mActiveBuffer->getBounds();
356 // if we don't have a buffer yet, we use an empty/invalid crop
362 static Rect reduce(const Rect& win, const Region& exclude) {
363 if (CC_LIKELY(exclude.isEmpty())) {
366 if (exclude.isRect()) {
367 return win.reduce(exclude.getBounds());
369 return Region(win).subtract(exclude).getBounds();
372 Rect Layer::computeBounds() const {
373 const Layer::State& s(getDrawingState());
374 return computeBounds(s.activeTransparentRegion);
377 Rect Layer::computeBounds(const Region& activeTransparentRegion) const {
378 const Layer::State& s(getDrawingState());
379 Rect win(s.active.w, s.active.h);
381 if (!s.crop.isEmpty()) {
382 win.intersect(s.crop, &win);
384 // subtract the transparent region and snap to the bounds
385 return reduce(win, activeTransparentRegion);
388 FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const {
389 // the content crop is the area of the content that gets scaled to the
391 FloatRect crop(getContentCrop());
393 // the crop is the area of the window that gets cropped, but not
394 // scaled in any ways.
395 const State& s(getDrawingState());
397 // apply the projection's clipping to the window crop in
398 // layerstack space, and convert-back to layer space.
399 // if there are no window scaling involved, this operation will map to full
400 // pixels in the buffer.
401 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have
402 // a viewport clipping and a window transform. we should use floating point to fix this.
404 Rect activeCrop(s.active.w, s.active.h);
405 if (!s.crop.isEmpty()) {
409 activeCrop = s.active.transform.transform(activeCrop);
410 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
413 if (!s.finalCrop.isEmpty()) {
414 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) {
418 activeCrop = s.active.transform.inverse().transform(activeCrop);
420 // This needs to be here as transform.transform(Rect) computes the
421 // transformed rect and then takes the bounding box of the result before
422 // returning. This means
423 // transform.inverse().transform(transform.transform(Rect)) != Rect
424 // in which case we need to make sure the final rect is clipped to the
426 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
430 // subtract the transparent region and snap to the bounds
431 activeCrop = reduce(activeCrop, s.activeTransparentRegion);
433 // Transform the window crop to match the buffer coordinate system,
434 // which means using the inverse of the current transform set on the
435 // SurfaceFlingerConsumer.
436 uint32_t invTransform = mCurrentTransform;
437 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
439 * the code below applies the display's inverse transform to the buffer
441 uint32_t invTransformOrient = hw->getOrientationTransform();
442 // calculate the inverse transform
443 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
444 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
445 NATIVE_WINDOW_TRANSFORM_FLIP_H;
446 // If the transform has been rotated the axis of flip has been swapped
447 // so we need to swap which flip operations we are performing
448 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
449 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
450 if (is_h_flipped != is_v_flipped) {
451 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
452 NATIVE_WINDOW_TRANSFORM_FLIP_H;
455 // and apply to the current transform
456 invTransform = (Transform(invTransform) * Transform(invTransformOrient)).getOrientation();
459 int winWidth = s.active.w;
460 int winHeight = s.active.h;
461 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
462 // If the activeCrop has been rotate the ends are rotated but not
463 // the space itself so when transforming ends back we can't rely on
464 // a modification of the axes of rotation. To account for this we
465 // need to reorient the inverse rotation in terms of the current
467 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
468 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
469 if (is_h_flipped == is_v_flipped) {
470 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
471 NATIVE_WINDOW_TRANSFORM_FLIP_H;
473 winWidth = s.active.h;
474 winHeight = s.active.w;
476 const Rect winCrop = activeCrop.transform(
477 invTransform, s.active.w, s.active.h);
479 // below, crop is intersected with winCrop expressed in crop's coordinate space
480 float xScale = crop.getWidth() / float(winWidth);
481 float yScale = crop.getHeight() / float(winHeight);
483 float insetL = winCrop.left * xScale;
484 float insetT = winCrop.top * yScale;
485 float insetR = (winWidth - winCrop.right ) * xScale;
486 float insetB = (winHeight - winCrop.bottom) * yScale;
490 crop.right -= insetR;
491 crop.bottom -= insetB;
497 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
499 void Layer::setGeometry(
500 const sp<const DisplayDevice>& hw,
501 HWComposer::HWCLayerInterface& layer)
505 const auto hwcId = displayDevice->getHwcDisplayId();
506 auto& hwcInfo = mHwcLayers[hwcId];
508 layer.setDefaultState();
513 hwcInfo.forceClientComposition = false;
515 if (isSecure() && !displayDevice->isSecure()) {
516 hwcInfo.forceClientComposition = true;
519 auto& hwcLayer = hwcInfo.layer;
521 layer.setSkip(false);
523 if (isSecure() && !hw->isSecure()) {
528 // this gives us only the "orientation" component of the transform
529 const State& s(getDrawingState());
531 if (!isOpaque(s) || s.alpha != 1.0f) {
532 auto blendMode = mPremultipliedAlpha ?
533 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
534 auto error = hwcLayer->setBlendMode(blendMode);
535 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
536 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
537 to_string(error).c_str(), static_cast<int32_t>(error));
540 if (!isOpaque(s) || s.alpha != 0xFF) {
541 layer.setBlending(mPremultipliedAlpha ?
542 HWC_BLENDING_PREMULT :
543 HWC_BLENDING_COVERAGE);
547 // apply the layer's transform, followed by the display's global transform
548 // here we're guaranteed that the layer's transform preserves rects
549 Region activeTransparentRegion(s.activeTransparentRegion);
550 if (!s.crop.isEmpty()) {
551 Rect activeCrop(s.crop);
552 activeCrop = s.active.transform.transform(activeCrop);
554 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
556 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
560 activeCrop = s.active.transform.inverse().transform(activeCrop);
561 // This needs to be here as transform.transform(Rect) computes the
562 // transformed rect and then takes the bounding box of the result before
563 // returning. This means
564 // transform.inverse().transform(transform.transform(Rect)) != Rect
565 // in which case we need to make sure the final rect is clipped to the
567 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
570 // mark regions outside the crop as transparent
571 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
572 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
573 s.active.w, s.active.h));
574 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
575 activeCrop.left, activeCrop.bottom));
576 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
577 s.active.w, activeCrop.bottom));
579 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
580 if (!s.finalCrop.isEmpty()) {
581 if(!frame.intersect(s.finalCrop, &frame)) {
586 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
589 const Transform& tr(displayDevice->getTransform());
590 Rect transformedFrame = tr.transform(frame);
591 auto error = hwcLayer->setDisplayFrame(transformedFrame);
592 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
593 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
594 transformedFrame.top, transformedFrame.right,
595 transformedFrame.bottom, to_string(error).c_str(),
596 static_cast<int32_t>(error));
598 FloatRect sourceCrop = computeCrop(displayDevice);
599 error = hwcLayer->setSourceCrop(sourceCrop);
600 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
601 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
602 sourceCrop.left, sourceCrop.top, sourceCrop.right,
603 sourceCrop.bottom, to_string(error).c_str(),
604 static_cast<int32_t>(error));
606 error = hwcLayer->setPlaneAlpha(s.alpha);
607 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
608 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
609 static_cast<int32_t>(error));
611 error = hwcLayer->setZOrder(s.z);
612 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
613 mName.string(), s.z, to_string(error).c_str(),
614 static_cast<int32_t>(error));
616 if (!frame.intersect(hw->getViewport(), &frame)) {
619 const Transform& tr(hw->getTransform());
620 layer.setFrame(tr.transform(frame));
621 layer.setCrop(computeCrop(hw));
622 layer.setPlaneAlpha(s.alpha);
626 * Transformations are applied in this order:
627 * 1) buffer orientation/flip/mirror
628 * 2) state transformation (window manager)
629 * 3) layer orientation (screen orientation)
630 * (NOTE: the matrices are multiplied in reverse order)
633 const Transform bufferOrientation(mCurrentTransform);
634 Transform transform(tr * s.active.transform * bufferOrientation);
636 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
638 * the code below applies the display's inverse transform to the buffer
641 uint32_t invTransform = displayDevice->getOrientationTransform();
643 uint32_t invTransform = hw->getOrientationTransform();
645 uint32_t t_orientation = transform.getOrientation();
646 // calculate the inverse transform
647 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
648 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
649 NATIVE_WINDOW_TRANSFORM_FLIP_H;
650 // If the transform has been rotated the axis of flip has been swapped
651 // so we need to swap which flip operations we are performing
652 bool is_h_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
653 bool is_v_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
654 if (is_h_flipped != is_v_flipped) {
655 t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
656 NATIVE_WINDOW_TRANSFORM_FLIP_H;
659 // and apply to the current transform
660 transform = Transform(t_orientation) * Transform(invTransform);
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);
720 auto compositionType = HWC2::Composition::Invalid;
721 if (mSidebandStream.get()) {
722 compositionType = HWC2::Composition::Sideband;
723 auto error = hwcLayer->setSidebandStream(mSidebandStream->handle());
724 if (error != HWC2::Error::None) {
725 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)",
726 mName.string(), mSidebandStream->handle(),
727 to_string(error).c_str(), static_cast<int32_t>(error));
731 if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr) {
732 compositionType = HWC2::Composition::Client;
733 auto error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
734 if (error != HWC2::Error::None) {
735 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
736 to_string(error).c_str(), static_cast<int32_t>(error));
740 if (mPotentialCursor) {
741 compositionType = HWC2::Composition::Cursor;
743 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
744 auto error = hwcLayer->setBuffer(mActiveBuffer->handle,
746 if (error != HWC2::Error::None) {
747 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
748 mActiveBuffer->handle, to_string(error).c_str(),
749 static_cast<int32_t>(error));
752 // If it's not a cursor, default to device composition
756 if (mHwcLayers[hwcId].forceClientComposition) {
757 ALOGV("[%s] Forcing Client composition", mName.string());
758 setCompositionType(hwcId, HWC2::Composition::Client);
759 } else if (compositionType != HWC2::Composition::Invalid) {
760 ALOGV("[%s] Requesting %s composition", mName.string(),
761 to_string(compositionType).c_str());
762 setCompositionType(hwcId, compositionType);
764 ALOGV("[%s] Requesting Device composition", mName.string());
765 setCompositionType(hwcId, HWC2::Composition::Device);
769 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
770 HWComposer::HWCLayerInterface& layer) {
771 // we have to set the visible region on every frame because
772 // we currently free it during onLayerDisplayed(), which is called
773 // after HWComposer::commit() -- every frame.
774 // Apply this display's projection's viewport to the visible region
775 // before giving it to the HWC HAL.
776 const Transform& tr = hw->getTransform();
777 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
778 layer.setVisibleRegionScreen(visible);
779 layer.setSurfaceDamage(surfaceDamageRegion);
780 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
782 if (mSidebandStream.get()) {
783 layer.setSidebandStream(mSidebandStream);
785 // NOTE: buffer can be NULL if the client never drew into this
786 // layer yet, or if we ran out of memory
787 layer.setBuffer(mActiveBuffer);
793 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
794 auto hwcId = displayDevice->getHwcDisplayId();
795 if (mHwcLayers.count(hwcId) == 0 ||
796 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
800 // This gives us only the "orientation" component of the transform
801 const State& s(getCurrentState());
803 // Apply the layer's transform, followed by the display's global transform
804 // Here we're guaranteed that the layer's transform preserves rects
805 Rect win(s.active.w, s.active.h);
806 if (!s.crop.isEmpty()) {
807 win.intersect(s.crop, &win);
809 // Subtract the transparent region and snap to the bounds
810 Rect bounds = reduce(win, s.activeTransparentRegion);
811 Rect frame(s.active.transform.transform(bounds));
812 frame.intersect(displayDevice->getViewport(), &frame);
813 if (!s.finalCrop.isEmpty()) {
814 frame.intersect(s.finalCrop, &frame);
816 auto& displayTransform(displayDevice->getTransform());
817 auto position = displayTransform.transform(frame);
819 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
821 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
822 "to (%d, %d): %s (%d)", mName.string(), position.left,
823 position.top, to_string(error).c_str(),
824 static_cast<int32_t>(error));
827 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
828 HWComposer::HWCLayerInterface& layer) {
831 // TODO: there is a possible optimization here: we only need to set the
832 // acquire fence the first time a new buffer is acquired on EACH display.
834 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
835 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
836 if (fence->isValid()) {
837 fenceFd = fence->dup();
839 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
843 layer.setAcquireFenceFd(fenceFd);
846 Rect Layer::getPosition(
847 const sp<const DisplayDevice>& hw)
849 // this gives us only the "orientation" component of the transform
850 const State& s(getCurrentState());
852 // apply the layer's transform, followed by the display's global transform
853 // here we're guaranteed that the layer's transform preserves rects
854 Rect win(s.active.w, s.active.h);
855 if (!s.crop.isEmpty()) {
856 win.intersect(s.crop, &win);
858 // subtract the transparent region and snap to the bounds
859 Rect bounds = reduce(win, s.activeTransparentRegion);
860 Rect frame(s.active.transform.transform(bounds));
861 frame.intersect(hw->getViewport(), &frame);
862 if (!s.finalCrop.isEmpty()) {
863 frame.intersect(s.finalCrop, &frame);
865 const Transform& tr(hw->getTransform());
866 return Rect(tr.transform(frame));
870 // ---------------------------------------------------------------------------
872 // ---------------------------------------------------------------------------
874 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
875 onDraw(hw, clip, false);
878 void Layer::draw(const sp<const DisplayDevice>& hw,
879 bool useIdentityTransform) const {
880 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
883 void Layer::draw(const sp<const DisplayDevice>& hw) const {
884 onDraw(hw, Region(hw->bounds()), false);
887 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
888 bool useIdentityTransform) const
892 if (CC_UNLIKELY(mActiveBuffer == 0)) {
893 // the texture has not been created yet, this Layer has
894 // in fact never been drawn into. This happens frequently with
895 // SurfaceView because the WindowManager can't know when the client
896 // has drawn the first time.
898 // If there is nothing under us, we paint the screen in black, otherwise
899 // we just skip this update.
901 // figure out if there is something below us
903 const SurfaceFlinger::LayerVector& drawingLayers(
904 mFlinger->mDrawingState.layersSortedByZ);
905 const size_t count = drawingLayers.size();
906 for (size_t i=0 ; i<count ; ++i) {
907 const sp<Layer>& layer(drawingLayers[i]);
908 if (layer.get() == static_cast<Layer const*>(this))
910 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
912 // if not everything below us is covered, we plug the holes!
913 Region holes(clip.subtract(under));
914 if (!holes.isEmpty()) {
915 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
920 // Bind the current buffer to the GL texture, and wait for it to be
921 // ready for us to draw into.
922 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
923 if (err != NO_ERROR) {
924 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
925 // Go ahead and draw the buffer anyway; no matter what we do the screen
926 // is probably going to have something visibly wrong.
929 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
931 RenderEngine& engine(mFlinger->getRenderEngine());
933 if (!blackOutLayer) {
934 // TODO: we could be more subtle with isFixedSize()
935 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
937 // Query the texture matrix given our current filtering mode.
938 float textureMatrix[16];
939 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
940 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
942 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
945 * the code below applies the display's inverse transform to 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);
954 uint32_t transform = hw->getOrientationTransform();
955 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
957 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
959 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
962 // calculate the inverse
965 // and finally apply it to the original texture matrix
966 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
967 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
970 // Set things up for texturing.
971 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
972 mTexture.setFiltering(useFiltering);
973 mTexture.setMatrix(textureMatrix);
975 engine.setupLayerTexturing(mTexture);
977 engine.setupLayerBlackedOut();
979 drawWithOpenGL(hw, clip, useIdentityTransform);
980 engine.disableTexturing();
984 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
985 const Region& /* clip */, float red, float green, float blue,
988 RenderEngine& engine(mFlinger->getRenderEngine());
989 computeGeometry(hw, mMesh, false);
990 engine.setupFillWithColor(red, green, blue, alpha);
991 engine.drawMesh(mMesh);
994 void Layer::clearWithOpenGL(
995 const sp<const DisplayDevice>& hw, const Region& clip) const {
996 clearWithOpenGL(hw, clip, 0,0,0,0);
999 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1000 const Region& /* clip */, bool useIdentityTransform) const {
1001 const State& s(getDrawingState());
1003 computeGeometry(hw, mMesh, useIdentityTransform);
1006 * NOTE: the way we compute the texture coordinates here produces
1007 * different results than when we take the HWC path -- in the later case
1008 * the "source crop" is rounded to texel boundaries.
1009 * This can produce significantly different results when the texture
1010 * is scaled by a large amount.
1012 * The GL code below is more logical (imho), and the difference with
1013 * HWC is due to a limitation of the HWC API to integers -- a question
1014 * is suspend is whether we should ignore this problem or revert to
1015 * GL composition when a buffer scaling is applied (maybe with some
1016 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1017 * like more of a hack.
1019 Rect win(computeBounds());
1021 if (!s.finalCrop.isEmpty()) {
1022 win = s.active.transform.transform(win);
1023 if (!win.intersect(s.finalCrop, &win)) {
1026 win = s.active.transform.inverse().transform(win);
1027 if (!win.intersect(computeBounds(), &win)) {
1032 float left = float(win.left) / float(s.active.w);
1033 float top = float(win.top) / float(s.active.h);
1034 float right = float(win.right) / float(s.active.w);
1035 float bottom = float(win.bottom) / float(s.active.h);
1037 // TODO: we probably want to generate the texture coords with the mesh
1038 // here we assume that we only have 4 vertices
1039 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1040 texCoords[0] = vec2(left, 1.0f - top);
1041 texCoords[1] = vec2(left, 1.0f - bottom);
1042 texCoords[2] = vec2(right, 1.0f - bottom);
1043 texCoords[3] = vec2(right, 1.0f - top);
1045 RenderEngine& engine(mFlinger->getRenderEngine());
1046 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1047 engine.drawMesh(mMesh);
1048 engine.disableBlending();
1052 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1054 if (mHwcLayers.count(hwcId) == 0) {
1055 ALOGE("setCompositionType called without a valid HWC layer");
1058 auto& hwcInfo = mHwcLayers[hwcId];
1059 auto& hwcLayer = hwcInfo.layer;
1060 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1061 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1062 if (hwcInfo.compositionType != type) {
1063 ALOGV(" actually setting");
1064 hwcInfo.compositionType = type;
1066 auto error = hwcLayer->setCompositionType(type);
1067 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1068 "composition type %s: %s (%d)", mName.string(),
1069 to_string(type).c_str(), to_string(error).c_str(),
1070 static_cast<int32_t>(error));
1075 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1076 if (mHwcLayers.count(hwcId) == 0) {
1077 ALOGE("getCompositionType called without a valid HWC layer");
1078 return HWC2::Composition::Invalid;
1080 return mHwcLayers.at(hwcId).compositionType;
1083 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1084 if (mHwcLayers.count(hwcId) == 0) {
1085 ALOGE("setClearClientTarget called without a valid HWC layer");
1088 mHwcLayers[hwcId].clearClientTarget = clear;
1091 bool Layer::getClearClientTarget(int32_t hwcId) const {
1092 if (mHwcLayers.count(hwcId) == 0) {
1093 ALOGE("getClearClientTarget called without a valid HWC layer");
1096 return mHwcLayers.at(hwcId).clearClientTarget;
1100 uint32_t Layer::getProducerStickyTransform() const {
1101 int producerStickyTransform = 0;
1102 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1104 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1105 strerror(-ret), ret);
1108 return static_cast<uint32_t>(producerStickyTransform);
1111 uint64_t Layer::getHeadFrameNumber() const {
1112 Mutex::Autolock lock(mQueueItemLock);
1113 if (!mQueueItems.empty()) {
1114 return mQueueItems[0].mFrameNumber;
1116 return mCurrentFrameNumber;
1120 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1121 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1122 // Don't bother with a SyncPoint, since we've already latched the
1127 Mutex::Autolock lock(mLocalSyncPointMutex);
1128 mLocalSyncPoints.push_back(point);
1132 void Layer::setFiltering(bool filtering) {
1133 mFiltering = filtering;
1136 bool Layer::getFiltering() const {
1140 // As documented in libhardware header, formats in the range
1141 // 0x100 - 0x1FF are specific to the HAL implementation, and
1142 // are known to have no alpha channel
1143 // TODO: move definition for device-specific range into
1144 // hardware.h, instead of using hard-coded values here.
1145 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1147 bool Layer::getOpacityForFormat(uint32_t format) {
1148 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1152 case HAL_PIXEL_FORMAT_RGBA_8888:
1153 case HAL_PIXEL_FORMAT_BGRA_8888:
1156 // in all other case, we have no blending (also for unknown formats)
1160 // ----------------------------------------------------------------------------
1162 // ----------------------------------------------------------------------------
1164 static void boundPoint(vec2* point, const Rect& crop) {
1165 if (point->x < crop.left) {
1166 point->x = crop.left;
1168 if (point->x > crop.right) {
1169 point->x = crop.right;
1171 if (point->y < crop.top) {
1172 point->y = crop.top;
1174 if (point->y > crop.bottom) {
1175 point->y = crop.bottom;
1179 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1180 bool useIdentityTransform) const
1182 const Layer::State& s(getDrawingState());
1183 const Transform tr(hw->getTransform());
1184 const uint32_t hw_h = hw->getHeight();
1185 Rect win(s.active.w, s.active.h);
1186 if (!s.crop.isEmpty()) {
1187 win.intersect(s.crop, &win);
1189 // subtract the transparent region and snap to the bounds
1190 win = reduce(win, s.activeTransparentRegion);
1192 vec2 lt = vec2(win.left, win.top);
1193 vec2 lb = vec2(win.left, win.bottom);
1194 vec2 rb = vec2(win.right, win.bottom);
1195 vec2 rt = vec2(win.right, win.top);
1197 if (!useIdentityTransform) {
1198 lt = s.active.transform.transform(lt);
1199 lb = s.active.transform.transform(lb);
1200 rb = s.active.transform.transform(rb);
1201 rt = s.active.transform.transform(rt);
1204 if (!s.finalCrop.isEmpty()) {
1205 boundPoint(<, s.finalCrop);
1206 boundPoint(&lb, s.finalCrop);
1207 boundPoint(&rb, s.finalCrop);
1208 boundPoint(&rt, s.finalCrop);
1211 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1212 position[0] = tr.transform(lt);
1213 position[1] = tr.transform(lb);
1214 position[2] = tr.transform(rb);
1215 position[3] = tr.transform(rt);
1216 for (size_t i=0 ; i<4 ; i++) {
1217 position[i].y = hw_h - position[i].y;
1221 bool Layer::isOpaque(const Layer::State& s) const
1223 // if we don't have a buffer yet, we're translucent regardless of the
1224 // layer's opaque flag.
1225 if (mActiveBuffer == 0) {
1229 // if the layer has the opaque flag, then we're always opaque,
1230 // otherwise we use the current buffer's format.
1231 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1234 bool Layer::isSecure() const
1236 const Layer::State& s(mDrawingState);
1237 return (s.flags & layer_state_t::eLayerSecure);
1240 bool Layer::isProtected() const
1242 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1243 return (activeBuffer != 0) &&
1244 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1247 bool Layer::isFixedSize() const {
1248 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1251 bool Layer::isCropped() const {
1252 return !mCurrentCrop.isEmpty();
1255 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1256 return mNeedsFiltering || hw->needsFiltering();
1259 void Layer::setVisibleRegion(const Region& visibleRegion) {
1260 // always called from main thread
1261 this->visibleRegion = visibleRegion;
1264 void Layer::setCoveredRegion(const Region& coveredRegion) {
1265 // always called from main thread
1266 this->coveredRegion = coveredRegion;
1269 void Layer::setVisibleNonTransparentRegion(const Region&
1270 setVisibleNonTransparentRegion) {
1271 // always called from main thread
1272 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1275 // ----------------------------------------------------------------------------
1277 // ----------------------------------------------------------------------------
1279 void Layer::pushPendingState() {
1280 if (!mCurrentState.modified) {
1284 // If this transaction is waiting on the receipt of a frame, generate a sync
1285 // point and send it to the remote layer.
1286 if (mCurrentState.handle != nullptr) {
1287 sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1288 sp<Layer> handleLayer = handle->owner.promote();
1289 if (handleLayer == nullptr) {
1290 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1291 // If we can't promote the layer we are intended to wait on,
1292 // then it is expired or otherwise invalid. Allow this transaction
1293 // to be applied as per normal (no synchronization).
1294 mCurrentState.handle = nullptr;
1296 auto syncPoint = std::make_shared<SyncPoint>(
1297 mCurrentState.frameNumber);
1298 if (handleLayer->addSyncPoint(syncPoint)) {
1299 mRemoteSyncPoints.push_back(std::move(syncPoint));
1301 // We already missed the frame we're supposed to synchronize
1302 // on, so go ahead and apply the state update
1303 mCurrentState.handle = nullptr;
1307 // Wake us up to check if the frame has been received
1308 setTransactionFlags(eTransactionNeeded);
1310 mPendingStates.push_back(mCurrentState);
1313 void Layer::popPendingState(State* stateToCommit) {
1314 auto oldFlags = stateToCommit->flags;
1315 *stateToCommit = mPendingStates[0];
1316 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1317 (stateToCommit->flags & stateToCommit->mask);
1319 mPendingStates.removeAt(0);
1322 bool Layer::applyPendingStates(State* stateToCommit) {
1323 bool stateUpdateAvailable = false;
1324 while (!mPendingStates.empty()) {
1325 if (mPendingStates[0].handle != nullptr) {
1326 if (mRemoteSyncPoints.empty()) {
1327 // If we don't have a sync point for this, apply it anyway. It
1328 // will be visually wrong, but it should keep us from getting
1329 // into too much trouble.
1330 ALOGE("[%s] No local sync point found", mName.string());
1331 popPendingState(stateToCommit);
1332 stateUpdateAvailable = true;
1336 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1337 mPendingStates[0].frameNumber) {
1338 ALOGE("[%s] Unexpected sync point frame number found",
1341 // Signal our end of the sync point and then dispose of it
1342 mRemoteSyncPoints.front()->setTransactionApplied();
1343 mRemoteSyncPoints.pop_front();
1347 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1348 // Apply the state update
1349 popPendingState(stateToCommit);
1350 stateUpdateAvailable = true;
1352 // Signal our end of the sync point and then dispose of it
1353 mRemoteSyncPoints.front()->setTransactionApplied();
1354 mRemoteSyncPoints.pop_front();
1359 popPendingState(stateToCommit);
1360 stateUpdateAvailable = true;
1364 // If we still have pending updates, wake SurfaceFlinger back up and point
1365 // it at this layer so we can process them
1366 if (!mPendingStates.empty()) {
1367 setTransactionFlags(eTransactionNeeded);
1368 mFlinger->setTransactionFlags(eTraversalNeeded);
1371 mCurrentState.modified = false;
1372 return stateUpdateAvailable;
1375 void Layer::notifyAvailableFrames() {
1376 auto headFrameNumber = getHeadFrameNumber();
1377 Mutex::Autolock lock(mLocalSyncPointMutex);
1378 for (auto& point : mLocalSyncPoints) {
1379 if (headFrameNumber >= point->getFrameNumber()) {
1380 point->setFrameAvailable();
1385 uint32_t Layer::doTransaction(uint32_t flags) {
1389 Layer::State c = getCurrentState();
1390 if (!applyPendingStates(&c)) {
1394 const Layer::State& s(getDrawingState());
1396 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1397 (c.requested.h != s.requested.h);
1400 // the size changed, we need to ask our client to request a new buffer
1401 ALOGD_IF(DEBUG_RESIZE,
1402 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1403 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1404 " requested={ wh={%4u,%4u} }}\n"
1405 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1406 " requested={ wh={%4u,%4u} }}\n",
1407 this, getName().string(), mCurrentTransform,
1408 getEffectiveScalingMode(),
1409 c.active.w, c.active.h,
1416 c.requested.w, c.requested.h,
1417 s.active.w, s.active.h,
1424 s.requested.w, s.requested.h);
1426 // record the new size, form this point on, when the client request
1427 // a buffer, it'll get the new size.
1428 mSurfaceFlingerConsumer->setDefaultBufferSize(
1429 c.requested.w, c.requested.h);
1432 if (!isFixedSize()) {
1434 const bool resizePending = (c.requested.w != c.active.w) ||
1435 (c.requested.h != c.active.h);
1437 if (resizePending && mSidebandStream == NULL) {
1438 // don't let Layer::doTransaction update the drawing state
1439 // if we have a pending resize, unless we are in fixed-size mode.
1440 // the drawing state will be updated only once we receive a buffer
1441 // with the correct size.
1443 // in particular, we want to make sure the clip (which is part
1444 // of the geometry state) is latched together with the size but is
1445 // latched immediately when no resizing is involved.
1447 // If a sideband stream is attached, however, we want to skip this
1448 // optimization so that transactions aren't missed when a buffer
1451 flags |= eDontUpdateGeometryState;
1455 // always set active to requested, unless we're asked not to
1456 // this is used by Layer, which special cases resizes.
1457 if (flags & eDontUpdateGeometryState) {
1459 c.active = c.requested;
1462 if (s.active != c.active) {
1463 // invalidate and recompute the visible regions if needed
1464 flags |= Layer::eVisibleRegion;
1467 if (c.sequence != s.sequence) {
1468 // invalidate and recompute the visible regions if needed
1469 flags |= eVisibleRegion;
1470 this->contentDirty = true;
1472 // we may use linear filtering, if the matrix scales us
1473 const uint8_t type = c.active.transform.getType();
1474 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1475 (type >= Transform::SCALE));
1478 // Commit the transaction
1479 commitTransaction(c);
1483 void Layer::commitTransaction(const State& stateToCommit) {
1484 mDrawingState = stateToCommit;
1487 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1488 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1491 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1492 return android_atomic_or(flags, &mTransactionFlags);
1495 bool Layer::setPosition(float x, float y) {
1496 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1498 mCurrentState.sequence++;
1500 // We update the requested and active position simultaneously because
1501 // we want to apply the position portion of the transform matrix immediately,
1502 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1503 mCurrentState.requested.transform.set(x, y);
1504 mCurrentState.active.transform.set(x, y);
1506 mCurrentState.modified = true;
1507 setTransactionFlags(eTransactionNeeded);
1510 bool Layer::setLayer(uint32_t z) {
1511 if (mCurrentState.z == z)
1513 mCurrentState.sequence++;
1514 mCurrentState.z = z;
1515 mCurrentState.modified = true;
1516 setTransactionFlags(eTransactionNeeded);
1519 bool Layer::setSize(uint32_t w, uint32_t h) {
1520 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1522 mCurrentState.requested.w = w;
1523 mCurrentState.requested.h = h;
1524 mCurrentState.modified = true;
1525 setTransactionFlags(eTransactionNeeded);
1529 bool Layer::setAlpha(float alpha) {
1531 bool Layer::setAlpha(uint8_t alpha) {
1533 if (mCurrentState.alpha == alpha)
1535 mCurrentState.sequence++;
1536 mCurrentState.alpha = alpha;
1537 mCurrentState.modified = true;
1538 setTransactionFlags(eTransactionNeeded);
1541 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1542 mCurrentState.sequence++;
1543 mCurrentState.requested.transform.set(
1544 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1545 mCurrentState.modified = true;
1546 setTransactionFlags(eTransactionNeeded);
1549 bool Layer::setTransparentRegionHint(const Region& transparent) {
1550 mCurrentState.requestedTransparentRegion = transparent;
1551 mCurrentState.modified = true;
1552 setTransactionFlags(eTransactionNeeded);
1555 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1556 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1557 if (mCurrentState.flags == newFlags)
1559 mCurrentState.sequence++;
1560 mCurrentState.flags = newFlags;
1561 mCurrentState.mask = mask;
1562 mCurrentState.modified = true;
1563 setTransactionFlags(eTransactionNeeded);
1566 bool Layer::setCrop(const Rect& crop) {
1567 if (mCurrentState.crop == crop)
1569 mCurrentState.sequence++;
1570 mCurrentState.crop = crop;
1571 mCurrentState.modified = true;
1572 setTransactionFlags(eTransactionNeeded);
1575 bool Layer::setFinalCrop(const Rect& crop) {
1576 if (mCurrentState.finalCrop == crop)
1578 mCurrentState.sequence++;
1579 mCurrentState.finalCrop = crop;
1580 mCurrentState.modified = true;
1581 setTransactionFlags(eTransactionNeeded);
1585 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1586 if (scalingMode == mOverrideScalingMode)
1588 mOverrideScalingMode = scalingMode;
1592 uint32_t Layer::getEffectiveScalingMode() const {
1593 if (mOverrideScalingMode >= 0) {
1594 return mOverrideScalingMode;
1596 return mCurrentScalingMode;
1599 bool Layer::setLayerStack(uint32_t layerStack) {
1600 if (mCurrentState.layerStack == layerStack)
1602 mCurrentState.sequence++;
1603 mCurrentState.layerStack = layerStack;
1604 mCurrentState.modified = true;
1605 setTransactionFlags(eTransactionNeeded);
1609 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1610 uint64_t frameNumber) {
1611 mCurrentState.handle = handle;
1612 mCurrentState.frameNumber = frameNumber;
1613 // We don't set eTransactionNeeded, because just receiving a deferral
1614 // request without any other state updates shouldn't actually induce a delay
1615 mCurrentState.modified = true;
1617 mCurrentState.handle = nullptr;
1618 mCurrentState.frameNumber = 0;
1619 mCurrentState.modified = false;
1622 void Layer::useSurfaceDamage() {
1623 if (mFlinger->mForceFullDamage) {
1624 surfaceDamageRegion = Region::INVALID_REGION;
1626 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1630 void Layer::useEmptyDamage() {
1631 surfaceDamageRegion.clear();
1634 // ----------------------------------------------------------------------------
1635 // pageflip handling...
1636 // ----------------------------------------------------------------------------
1638 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1639 if (mSidebandStreamChanged || mAutoRefresh) {
1643 Mutex::Autolock lock(mQueueItemLock);
1644 if (mQueueItems.empty()) {
1647 auto timestamp = mQueueItems[0].mTimestamp;
1648 nsecs_t expectedPresent =
1649 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1651 // Ignore timestamps more than a second in the future
1652 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1653 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1654 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1657 bool isDue = timestamp < expectedPresent;
1658 return isDue || !isPlausible;
1661 bool Layer::onPreComposition() {
1662 mRefreshPending = false;
1663 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1666 void Layer::onPostComposition() {
1667 if (mFrameLatencyNeeded) {
1668 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1669 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1671 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1672 if (frameReadyFence->isValid()) {
1673 mFrameTracker.setFrameReadyFence(frameReadyFence);
1675 // There was no fence for this frame, so assume that it was ready
1676 // to be presented at the desired present time.
1677 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1680 const HWComposer& hwc = mFlinger->getHwComposer();
1682 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1684 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1686 if (presentFence->isValid()) {
1687 mFrameTracker.setActualPresentFence(presentFence);
1689 // The HWC doesn't support present fences, so use the refresh
1690 // timestamp instead.
1691 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1692 mFrameTracker.setActualPresentTime(presentTime);
1695 mFrameTracker.advanceFrame();
1696 mFrameLatencyNeeded = false;
1701 void Layer::releasePendingBuffer() {
1702 mSurfaceFlingerConsumer->releasePendingBuffer();
1706 bool Layer::isVisible() const {
1707 const Layer::State& s(mDrawingState);
1709 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1710 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1712 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1713 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1717 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1721 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1722 // mSidebandStreamChanged was true
1723 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1724 if (mSidebandStream != NULL) {
1725 setTransactionFlags(eTransactionNeeded);
1726 mFlinger->setTransactionFlags(eTraversalNeeded);
1728 recomputeVisibleRegions = true;
1730 const State& s(getDrawingState());
1731 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1734 Region outDirtyRegion;
1735 if (mQueuedFrames > 0 || mAutoRefresh) {
1737 // if we've already called updateTexImage() without going through
1738 // a composition step, we have to skip this layer at this point
1739 // because we cannot call updateTeximage() without a corresponding
1740 // compositionComplete() call.
1741 // we'll trigger an update in onPreComposition().
1742 if (mRefreshPending) {
1743 return outDirtyRegion;
1746 // Capture the old state of the layer for comparisons later
1747 const State& s(getDrawingState());
1748 const bool oldOpacity = isOpaque(s);
1749 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1751 struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1752 Layer::State& front;
1753 Layer::State& current;
1754 bool& recomputeVisibleRegions;
1755 bool stickyTransformSet;
1757 int32_t overrideScalingMode;
1759 Reject(Layer::State& front, Layer::State& current,
1760 bool& recomputeVisibleRegions, bool stickySet,
1762 int32_t overrideScalingMode)
1763 : front(front), current(current),
1764 recomputeVisibleRegions(recomputeVisibleRegions),
1765 stickyTransformSet(stickySet),
1767 overrideScalingMode(overrideScalingMode) {
1770 virtual bool reject(const sp<GraphicBuffer>& buf,
1771 const BufferItem& item) {
1776 uint32_t bufWidth = buf->getWidth();
1777 uint32_t bufHeight = buf->getHeight();
1779 // check that we received a buffer of the right size
1780 // (Take the buffer's orientation into account)
1781 if (item.mTransform & Transform::ROT_90) {
1782 swap(bufWidth, bufHeight);
1785 int actualScalingMode = overrideScalingMode >= 0 ?
1786 overrideScalingMode : item.mScalingMode;
1787 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1788 if (front.active != front.requested) {
1791 (bufWidth == front.requested.w &&
1792 bufHeight == front.requested.h))
1794 // Here we pretend the transaction happened by updating the
1795 // current and drawing states. Drawing state is only accessed
1796 // in this thread, no need to have it locked
1797 front.active = front.requested;
1799 // We also need to update the current state so that
1800 // we don't end-up overwriting the drawing state with
1801 // this stale current state during the next transaction
1803 // NOTE: We don't need to hold the transaction lock here
1804 // because State::active is only accessed from this thread.
1805 current.active = front.active;
1807 // recompute visible region
1808 recomputeVisibleRegions = true;
1811 ALOGD_IF(DEBUG_RESIZE,
1812 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1813 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1814 " requested={ wh={%4u,%4u} }}\n",
1816 bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1817 front.active.w, front.active.h,
1822 front.crop.getWidth(),
1823 front.crop.getHeight(),
1824 front.requested.w, front.requested.h);
1827 if (!isFixedSize && !stickyTransformSet) {
1828 if (front.active.w != bufWidth ||
1829 front.active.h != bufHeight) {
1830 // reject this buffer
1831 ALOGE("[%s] rejecting buffer: "
1832 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1833 name, bufWidth, bufHeight, front.active.w, front.active.h);
1838 // if the transparent region has changed (this test is
1839 // conservative, but that's fine, worst case we're doing
1840 // a bit of extra work), we latch the new one and we
1841 // trigger a visible-region recompute.
1842 if (!front.activeTransparentRegion.isTriviallyEqual(
1843 front.requestedTransparentRegion)) {
1844 front.activeTransparentRegion = front.requestedTransparentRegion;
1846 // We also need to update the current state so that
1847 // we don't end-up overwriting the drawing state with
1848 // this stale current state during the next transaction
1850 // NOTE: We don't need to hold the transaction lock here
1851 // because State::active is only accessed from this thread.
1852 current.activeTransparentRegion = front.activeTransparentRegion;
1854 // recompute visible region
1855 recomputeVisibleRegions = true;
1862 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1863 getProducerStickyTransform() != 0, mName.string(),
1864 mOverrideScalingMode);
1867 // Check all of our local sync points to ensure that all transactions
1868 // which need to have been applied prior to the frame which is about to
1869 // be latched have signaled
1871 auto headFrameNumber = getHeadFrameNumber();
1872 bool matchingFramesFound = false;
1873 bool allTransactionsApplied = true;
1875 Mutex::Autolock lock(mLocalSyncPointMutex);
1876 for (auto& point : mLocalSyncPoints) {
1877 if (point->getFrameNumber() > headFrameNumber) {
1881 matchingFramesFound = true;
1883 if (!point->frameIsAvailable()) {
1884 // We haven't notified the remote layer that the frame for
1885 // this point is available yet. Notify it now, and then
1886 // abort this attempt to latch.
1887 point->setFrameAvailable();
1888 allTransactionsApplied = false;
1892 allTransactionsApplied &= point->transactionIsApplied();
1896 if (matchingFramesFound && !allTransactionsApplied) {
1897 mFlinger->signalLayerUpdate();
1898 return outDirtyRegion;
1901 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1902 // of the buffer queue isn't modified when the buffer queue is returning
1903 // BufferItem's that weren't actually queued. This can happen in shared
1905 bool queuedBuffer = false;
1906 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1907 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1908 mLastFrameNumberReceived);
1909 if (updateResult == BufferQueue::PRESENT_LATER) {
1910 // Producer doesn't want buffer to be displayed yet. Signal a
1911 // layer update so we check again at the next opportunity.
1912 mFlinger->signalLayerUpdate();
1913 return outDirtyRegion;
1914 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1915 // If the buffer has been rejected, remove it from the shadow queue
1918 Mutex::Autolock lock(mQueueItemLock);
1919 mQueueItems.removeAt(0);
1920 android_atomic_dec(&mQueuedFrames);
1922 return outDirtyRegion;
1923 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1924 // This can occur if something goes wrong when trying to create the
1925 // EGLImage for this buffer. If this happens, the buffer has already
1926 // been released, so we need to clean up the queue and bug out
1929 Mutex::Autolock lock(mQueueItemLock);
1930 mQueueItems.clear();
1931 android_atomic_and(0, &mQueuedFrames);
1934 // Once we have hit this state, the shadow queue may no longer
1935 // correctly reflect the incoming BufferQueue's contents, so even if
1936 // updateTexImage starts working, the only safe course of action is
1937 // to continue to ignore updates.
1938 mUpdateTexImageFailed = true;
1940 return outDirtyRegion;
1945 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1947 Mutex::Autolock lock(mQueueItemLock);
1949 // Remove any stale buffers that have been dropped during
1951 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1952 mQueueItems.removeAt(0);
1953 android_atomic_dec(&mQueuedFrames);
1956 mQueueItems.removeAt(0);
1960 // Decrement the queued-frames count. Signal another event if we
1961 // have more frames pending.
1962 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1964 mFlinger->signalLayerUpdate();
1967 if (updateResult != NO_ERROR) {
1968 // something happened!
1969 recomputeVisibleRegions = true;
1970 return outDirtyRegion;
1973 // update the active buffer
1974 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1975 if (mActiveBuffer == NULL) {
1976 // this can only happen if the very first buffer was rejected.
1977 return outDirtyRegion;
1980 mRefreshPending = true;
1981 mFrameLatencyNeeded = true;
1982 if (oldActiveBuffer == NULL) {
1983 // the first time we receive a buffer, we need to trigger a
1984 // geometry invalidation.
1985 recomputeVisibleRegions = true;
1988 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1989 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1990 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1991 if ((crop != mCurrentCrop) ||
1992 (transform != mCurrentTransform) ||
1993 (scalingMode != mCurrentScalingMode))
1995 mCurrentCrop = crop;
1996 mCurrentTransform = transform;
1997 mCurrentScalingMode = scalingMode;
1998 recomputeVisibleRegions = true;
2001 if (oldActiveBuffer != NULL) {
2002 uint32_t bufWidth = mActiveBuffer->getWidth();
2003 uint32_t bufHeight = mActiveBuffer->getHeight();
2004 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2005 bufHeight != uint32_t(oldActiveBuffer->height)) {
2006 recomputeVisibleRegions = true;
2010 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2011 if (oldOpacity != isOpaque(s)) {
2012 recomputeVisibleRegions = true;
2015 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2017 // Remove any sync points corresponding to the buffer which was just
2020 Mutex::Autolock lock(mLocalSyncPointMutex);
2021 auto point = mLocalSyncPoints.begin();
2022 while (point != mLocalSyncPoints.end()) {
2023 if (!(*point)->frameIsAvailable() ||
2024 !(*point)->transactionIsApplied()) {
2025 // This sync point must have been added since we started
2026 // latching. Don't drop it yet.
2031 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2032 point = mLocalSyncPoints.erase(point);
2039 // FIXME: postedRegion should be dirty & bounds
2040 Region dirtyRegion(Rect(s.active.w, s.active.h));
2042 // transform the dirty region to window-manager space
2043 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2045 return outDirtyRegion;
2048 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2050 // TODO: should we do something special if mSecure is set?
2051 if (mProtectedByApp) {
2052 // need a hardware-protected path to external video sink
2053 usage |= GraphicBuffer::USAGE_PROTECTED;
2055 if (mPotentialCursor) {
2056 usage |= GraphicBuffer::USAGE_CURSOR;
2058 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2062 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2063 uint32_t orientation = 0;
2064 if (!mFlinger->mDebugDisableTransformHint) {
2065 // The transform hint is used to improve performance, but we can
2066 // only have a single transform hint, it cannot
2067 // apply to all displays.
2068 const Transform& planeTransform(hw->getTransform());
2069 orientation = planeTransform.getOrientation();
2070 if (orientation & Transform::ROT_INVALID) {
2074 mSurfaceFlingerConsumer->setTransformHint(orientation);
2077 // ----------------------------------------------------------------------------
2079 // ----------------------------------------------------------------------------
2081 void Layer::dump(String8& result, Colorizer& colorizer) const
2083 const Layer::State& s(getDrawingState());
2085 colorizer.colorize(result, Colorizer::GREEN);
2086 result.appendFormat(
2088 getTypeId(), this, getName().string());
2089 colorizer.reset(result);
2091 s.activeTransparentRegion.dump(result, "transparentRegion");
2092 visibleRegion.dump(result, "visibleRegion");
2093 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2094 sp<Client> client(mClientRef.promote());
2096 result.appendFormat( " "
2097 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2098 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2099 "isOpaque=%1d, invalidate=%1d, "
2101 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2103 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2106 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2107 s.crop.left, s.crop.top,
2108 s.crop.right, s.crop.bottom,
2109 s.finalCrop.left, s.finalCrop.top,
2110 s.finalCrop.right, s.finalCrop.bottom,
2111 isOpaque(s), contentDirty,
2113 s.active.transform[0][0], s.active.transform[0][1],
2114 s.active.transform[1][0], s.active.transform[1][1],
2117 sp<const GraphicBuffer> buf0(mActiveBuffer);
2118 uint32_t w0=0, h0=0, s0=0, f0=0;
2120 w0 = buf0->getWidth();
2121 h0 = buf0->getHeight();
2122 s0 = buf0->getStride();
2125 result.appendFormat(
2127 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2128 " queued-frames=%d, mRefreshPending=%d\n",
2129 mFormat, w0, h0, s0,f0,
2130 mQueuedFrames, mRefreshPending);
2132 if (mSurfaceFlingerConsumer != 0) {
2133 mSurfaceFlingerConsumer->dump(result, " ");
2137 void Layer::dumpFrameStats(String8& result) const {
2138 mFrameTracker.dumpStats(result);
2141 void Layer::clearFrameStats() {
2142 mFrameTracker.clearStats();
2145 void Layer::logFrameStats() {
2146 mFrameTracker.logAndResetStats(mName);
2149 void Layer::getFrameStats(FrameStats* outStats) const {
2150 mFrameTracker.getStats(outStats);
2153 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2154 bool* outIsGlesComposition, nsecs_t* outPostedTime,
2155 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2157 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2160 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2161 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2162 HWC2::Composition::Client : true;
2164 *outIsGlesComposition = mIsGlesComposition;
2166 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2167 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2168 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2170 // ---------------------------------------------------------------------------
2172 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2173 const sp<Layer>& layer)
2174 : mFlinger(flinger), mLayer(layer) {
2177 Layer::LayerCleaner::~LayerCleaner() {
2178 // destroy client resources
2179 mFlinger->onLayerDestroyed(mLayer);
2182 // ---------------------------------------------------------------------------
2183 }; // namespace android
2185 #if defined(__gl_h_)
2186 #error "don't include gl/gl.h in this file"
2189 #if defined(__gl2_h_)
2190 #error "don't include gl2/gl2.h in this file"