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(mQueueItems.size() - 1) = 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 primary display's inverse transform to the
442 uint32_t invTransformOrient =
443 DisplayDevice::getPrimaryDisplayOrientationTransform();
444 // calculate the inverse transform
445 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) {
446 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
447 NATIVE_WINDOW_TRANSFORM_FLIP_H;
448 // If the transform has been rotated the axis of flip has been swapped
449 // so we need to swap which flip operations we are performing
450 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
451 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
452 if (is_h_flipped != is_v_flipped) {
453 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
454 NATIVE_WINDOW_TRANSFORM_FLIP_H;
457 // and apply to the current transform
458 invTransform = (Transform(invTransform) * Transform(invTransformOrient)).getOrientation();
461 int winWidth = s.active.w;
462 int winHeight = s.active.h;
463 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
464 // If the activeCrop has been rotate the ends are rotated but not
465 // the space itself so when transforming ends back we can't rely on
466 // a modification of the axes of rotation. To account for this we
467 // need to reorient the inverse rotation in terms of the current
469 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
470 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
471 if (is_h_flipped == is_v_flipped) {
472 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
473 NATIVE_WINDOW_TRANSFORM_FLIP_H;
475 winWidth = s.active.h;
476 winHeight = s.active.w;
478 const Rect winCrop = activeCrop.transform(
479 invTransform, s.active.w, s.active.h);
481 // below, crop is intersected with winCrop expressed in crop's coordinate space
482 float xScale = crop.getWidth() / float(winWidth);
483 float yScale = crop.getHeight() / float(winHeight);
485 float insetL = winCrop.left * xScale;
486 float insetT = winCrop.top * yScale;
487 float insetR = (winWidth - winCrop.right ) * xScale;
488 float insetB = (winHeight - winCrop.bottom) * yScale;
492 crop.right -= insetR;
493 crop.bottom -= insetB;
499 void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice)
501 void Layer::setGeometry(
502 const sp<const DisplayDevice>& hw,
503 HWComposer::HWCLayerInterface& layer)
507 const auto hwcId = displayDevice->getHwcDisplayId();
508 auto& hwcInfo = mHwcLayers[hwcId];
510 layer.setDefaultState();
515 hwcInfo.forceClientComposition = false;
517 if (isSecure() && !displayDevice->isSecure()) {
518 hwcInfo.forceClientComposition = true;
521 auto& hwcLayer = hwcInfo.layer;
523 layer.setSkip(false);
525 if (isSecure() && !hw->isSecure()) {
530 // this gives us only the "orientation" component of the transform
531 const State& s(getDrawingState());
533 if (!isOpaque(s) || s.alpha != 1.0f) {
534 auto blendMode = mPremultipliedAlpha ?
535 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage;
536 auto error = hwcLayer->setBlendMode(blendMode);
537 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:"
538 " %s (%d)", mName.string(), to_string(blendMode).c_str(),
539 to_string(error).c_str(), static_cast<int32_t>(error));
542 if (!isOpaque(s) || s.alpha != 0xFF) {
543 layer.setBlending(mPremultipliedAlpha ?
544 HWC_BLENDING_PREMULT :
545 HWC_BLENDING_COVERAGE);
549 // apply the layer's transform, followed by the display's global transform
550 // here we're guaranteed that the layer's transform preserves rects
551 Region activeTransparentRegion(s.activeTransparentRegion);
552 if (!s.crop.isEmpty()) {
553 Rect activeCrop(s.crop);
554 activeCrop = s.active.transform.transform(activeCrop);
556 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) {
558 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) {
562 activeCrop = s.active.transform.inverse().transform(activeCrop);
563 // This needs to be here as transform.transform(Rect) computes the
564 // transformed rect and then takes the bounding box of the result before
565 // returning. This means
566 // transform.inverse().transform(transform.transform(Rect)) != Rect
567 // in which case we need to make sure the final rect is clipped to the
569 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) {
572 // mark regions outside the crop as transparent
573 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top));
574 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom,
575 s.active.w, s.active.h));
576 activeTransparentRegion.orSelf(Rect(0, activeCrop.top,
577 activeCrop.left, activeCrop.bottom));
578 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top,
579 s.active.w, activeCrop.bottom));
581 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion)));
582 if (!s.finalCrop.isEmpty()) {
583 if(!frame.intersect(s.finalCrop, &frame)) {
588 if (!frame.intersect(displayDevice->getViewport(), &frame)) {
591 const Transform& tr(displayDevice->getTransform());
592 Rect transformedFrame = tr.transform(frame);
593 auto error = hwcLayer->setDisplayFrame(transformedFrame);
594 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame "
595 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left,
596 transformedFrame.top, transformedFrame.right,
597 transformedFrame.bottom, to_string(error).c_str(),
598 static_cast<int32_t>(error));
600 FloatRect sourceCrop = computeCrop(displayDevice);
601 error = hwcLayer->setSourceCrop(sourceCrop);
602 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop "
603 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(),
604 sourceCrop.left, sourceCrop.top, sourceCrop.right,
605 sourceCrop.bottom, to_string(error).c_str(),
606 static_cast<int32_t>(error));
608 error = hwcLayer->setPlaneAlpha(s.alpha);
609 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: "
610 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(),
611 static_cast<int32_t>(error));
613 error = hwcLayer->setZOrder(s.z);
614 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)",
615 mName.string(), s.z, to_string(error).c_str(),
616 static_cast<int32_t>(error));
618 if (!frame.intersect(hw->getViewport(), &frame)) {
621 const Transform& tr(hw->getTransform());
622 layer.setFrame(tr.transform(frame));
623 layer.setCrop(computeCrop(hw));
624 layer.setPlaneAlpha(s.alpha);
628 * Transformations are applied in this order:
629 * 1) buffer orientation/flip/mirror
630 * 2) state transformation (window manager)
631 * 3) layer orientation (screen orientation)
632 * (NOTE: the matrices are multiplied in reverse order)
635 const Transform bufferOrientation(mCurrentTransform);
636 Transform transform(tr * s.active.transform * bufferOrientation);
638 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
640 * the code below applies the primary display's inverse transform to the
643 uint32_t invTransform =
644 DisplayDevice::getPrimaryDisplayOrientationTransform();
646 uint32_t t_orientation = transform.getOrientation();
647 // calculate the inverse transform
648 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) {
649 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
650 NATIVE_WINDOW_TRANSFORM_FLIP_H;
651 // If the transform has been rotated the axis of flip has been swapped
652 // so we need to swap which flip operations we are performing
653 bool is_h_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0;
654 bool is_v_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0;
655 if (is_h_flipped != is_v_flipped) {
656 t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V |
657 NATIVE_WINDOW_TRANSFORM_FLIP_H;
660 // and apply to the current transform
661 transform = Transform(t_orientation) * Transform(invTransform);
664 // this gives us only the "orientation" component of the transform
665 const uint32_t orientation = transform.getOrientation();
667 if (orientation & Transform::ROT_INVALID) {
668 // we can only handle simple transformation
669 hwcInfo.forceClientComposition = true;
671 auto transform = static_cast<HWC2::Transform>(orientation);
672 auto error = hwcLayer->setTransform(transform);
673 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: "
674 "%s (%d)", mName.string(), to_string(transform).c_str(),
675 to_string(error).c_str(), static_cast<int32_t>(error));
678 if (orientation & Transform::ROT_INVALID) {
679 // we can only handle simple transformation
682 layer.setTransform(orientation);
688 void Layer::forceClientComposition(int32_t hwcId) {
689 if (mHwcLayers.count(hwcId) == 0) {
690 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId);
694 mHwcLayers[hwcId].forceClientComposition = true;
699 void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) {
700 // Apply this display's projection's viewport to the visible region
701 // before giving it to the HWC HAL.
702 const Transform& tr = displayDevice->getTransform();
703 const auto& viewport = displayDevice->getViewport();
704 Region visible = tr.transform(visibleRegion.intersect(viewport));
705 auto hwcId = displayDevice->getHwcDisplayId();
706 auto& hwcLayer = mHwcLayers[hwcId].layer;
707 auto error = hwcLayer->setVisibleRegion(visible);
708 if (error != HWC2::Error::None) {
709 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(),
710 to_string(error).c_str(), static_cast<int32_t>(error));
711 visible.dump(LOG_TAG);
714 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion);
715 if (error != HWC2::Error::None) {
716 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(),
717 to_string(error).c_str(), static_cast<int32_t>(error));
718 surfaceDamageRegion.dump(LOG_TAG);
721 auto compositionType = HWC2::Composition::Invalid;
722 if (mSidebandStream.get()) {
723 compositionType = HWC2::Composition::Sideband;
724 auto 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));
732 if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr) {
733 compositionType = HWC2::Composition::Client;
734 auto error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE);
735 if (error != HWC2::Error::None) {
736 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(),
737 to_string(error).c_str(), static_cast<int32_t>(error));
741 if (mPotentialCursor) {
742 compositionType = HWC2::Composition::Cursor;
744 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence();
745 auto error = hwcLayer->setBuffer(mActiveBuffer->handle,
747 if (error != HWC2::Error::None) {
748 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(),
749 mActiveBuffer->handle, to_string(error).c_str(),
750 static_cast<int32_t>(error));
753 // If it's not a cursor, default to device composition
757 if (mHwcLayers[hwcId].forceClientComposition) {
758 ALOGV("[%s] Forcing Client composition", mName.string());
759 setCompositionType(hwcId, HWC2::Composition::Client);
760 } else if (compositionType != HWC2::Composition::Invalid) {
761 ALOGV("[%s] Requesting %s composition", mName.string(),
762 to_string(compositionType).c_str());
763 setCompositionType(hwcId, compositionType);
765 ALOGV("[%s] Requesting Device composition", mName.string());
766 setCompositionType(hwcId, HWC2::Composition::Device);
770 void Layer::setPerFrameData(const sp<const DisplayDevice>& hw,
771 HWComposer::HWCLayerInterface& layer) {
772 // we have to set the visible region on every frame because
773 // we currently free it during onLayerDisplayed(), which is called
774 // after HWComposer::commit() -- every frame.
775 // Apply this display's projection's viewport to the visible region
776 // before giving it to the HWC HAL.
777 const Transform& tr = hw->getTransform();
778 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport()));
779 layer.setVisibleRegionScreen(visible);
780 layer.setSurfaceDamage(surfaceDamageRegion);
781 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER);
783 if (mSidebandStream.get()) {
784 layer.setSidebandStream(mSidebandStream);
786 // NOTE: buffer can be NULL if the client never drew into this
787 // layer yet, or if we ran out of memory
788 layer.setBuffer(mActiveBuffer);
794 void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) {
795 auto hwcId = displayDevice->getHwcDisplayId();
796 if (mHwcLayers.count(hwcId) == 0 ||
797 getCompositionType(hwcId) != HWC2::Composition::Cursor) {
801 // This gives us only the "orientation" component of the transform
802 const State& s(getCurrentState());
804 // Apply the layer's transform, followed by the display's global transform
805 // Here we're guaranteed that the layer's transform preserves rects
806 Rect win(s.active.w, s.active.h);
807 if (!s.crop.isEmpty()) {
808 win.intersect(s.crop, &win);
810 // Subtract the transparent region and snap to the bounds
811 Rect bounds = reduce(win, s.activeTransparentRegion);
812 Rect frame(s.active.transform.transform(bounds));
813 frame.intersect(displayDevice->getViewport(), &frame);
814 if (!s.finalCrop.isEmpty()) {
815 frame.intersect(s.finalCrop, &frame);
817 auto& displayTransform(displayDevice->getTransform());
818 auto position = displayTransform.transform(frame);
820 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left,
822 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position "
823 "to (%d, %d): %s (%d)", mName.string(), position.left,
824 position.top, to_string(error).c_str(),
825 static_cast<int32_t>(error));
828 void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */,
829 HWComposer::HWCLayerInterface& layer) {
832 // TODO: there is a possible optimization here: we only need to set the
833 // acquire fence the first time a new buffer is acquired on EACH display.
835 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) {
836 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence();
837 if (fence->isValid()) {
838 fenceFd = fence->dup();
840 ALOGW("failed to dup layer fence, skipping sync: %d", errno);
844 layer.setAcquireFenceFd(fenceFd);
847 Rect Layer::getPosition(
848 const sp<const DisplayDevice>& hw)
850 // this gives us only the "orientation" component of the transform
851 const State& s(getCurrentState());
853 // apply the layer's transform, followed by the display's global transform
854 // here we're guaranteed that the layer's transform preserves rects
855 Rect win(s.active.w, s.active.h);
856 if (!s.crop.isEmpty()) {
857 win.intersect(s.crop, &win);
859 // subtract the transparent region and snap to the bounds
860 Rect bounds = reduce(win, s.activeTransparentRegion);
861 Rect frame(s.active.transform.transform(bounds));
862 frame.intersect(hw->getViewport(), &frame);
863 if (!s.finalCrop.isEmpty()) {
864 frame.intersect(s.finalCrop, &frame);
866 const Transform& tr(hw->getTransform());
867 return Rect(tr.transform(frame));
871 // ---------------------------------------------------------------------------
873 // ---------------------------------------------------------------------------
875 void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const {
876 onDraw(hw, clip, false);
879 void Layer::draw(const sp<const DisplayDevice>& hw,
880 bool useIdentityTransform) const {
881 onDraw(hw, Region(hw->bounds()), useIdentityTransform);
884 void Layer::draw(const sp<const DisplayDevice>& hw) const {
885 onDraw(hw, Region(hw->bounds()), false);
888 void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip,
889 bool useIdentityTransform) const
893 if (CC_UNLIKELY(mActiveBuffer == 0)) {
894 // the texture has not been created yet, this Layer has
895 // in fact never been drawn into. This happens frequently with
896 // SurfaceView because the WindowManager can't know when the client
897 // has drawn the first time.
899 // If there is nothing under us, we paint the screen in black, otherwise
900 // we just skip this update.
902 // figure out if there is something below us
904 const SurfaceFlinger::LayerVector& drawingLayers(
905 mFlinger->mDrawingState.layersSortedByZ);
906 const size_t count = drawingLayers.size();
907 for (size_t i=0 ; i<count ; ++i) {
908 const sp<Layer>& layer(drawingLayers[i]);
909 if (layer.get() == static_cast<Layer const*>(this))
911 under.orSelf( hw->getTransform().transform(layer->visibleRegion) );
913 // if not everything below us is covered, we plug the holes!
914 Region holes(clip.subtract(under));
915 if (!holes.isEmpty()) {
916 clearWithOpenGL(hw, holes, 0, 0, 0, 1);
921 // Bind the current buffer to the GL texture, and wait for it to be
922 // ready for us to draw into.
923 status_t err = mSurfaceFlingerConsumer->bindTextureImage();
924 if (err != NO_ERROR) {
925 ALOGW("onDraw: bindTextureImage failed (err=%d)", err);
926 // Go ahead and draw the buffer anyway; no matter what we do the screen
927 // is probably going to have something visibly wrong.
930 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure());
932 RenderEngine& engine(mFlinger->getRenderEngine());
934 if (!blackOutLayer) {
935 // TODO: we could be more subtle with isFixedSize()
936 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize();
938 // Query the texture matrix given our current filtering mode.
939 float textureMatrix[16];
940 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering);
941 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix);
943 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) {
946 * the code below applies the primary display's inverse transform to
947 * the texture transform
950 // create a 4x4 transform matrix from the display transform flags
951 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1);
952 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1);
953 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1);
957 DisplayDevice::getPrimaryDisplayOrientationTransform();
958 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90)
960 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H)
962 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V)
965 // calculate the inverse
968 // and finally apply it to the original texture matrix
969 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr);
970 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix));
973 // Set things up for texturing.
974 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight());
975 mTexture.setFiltering(useFiltering);
976 mTexture.setMatrix(textureMatrix);
978 engine.setupLayerTexturing(mTexture);
980 engine.setupLayerBlackedOut();
982 drawWithOpenGL(hw, clip, useIdentityTransform);
983 engine.disableTexturing();
987 void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw,
988 const Region& /* clip */, float red, float green, float blue,
991 RenderEngine& engine(mFlinger->getRenderEngine());
992 computeGeometry(hw, mMesh, false);
993 engine.setupFillWithColor(red, green, blue, alpha);
994 engine.drawMesh(mMesh);
997 void Layer::clearWithOpenGL(
998 const sp<const DisplayDevice>& hw, const Region& clip) const {
999 clearWithOpenGL(hw, clip, 0,0,0,0);
1002 void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw,
1003 const Region& /* clip */, bool useIdentityTransform) const {
1004 const State& s(getDrawingState());
1006 computeGeometry(hw, mMesh, useIdentityTransform);
1009 * NOTE: the way we compute the texture coordinates here produces
1010 * different results than when we take the HWC path -- in the later case
1011 * the "source crop" is rounded to texel boundaries.
1012 * This can produce significantly different results when the texture
1013 * is scaled by a large amount.
1015 * The GL code below is more logical (imho), and the difference with
1016 * HWC is due to a limitation of the HWC API to integers -- a question
1017 * is suspend is whether we should ignore this problem or revert to
1018 * GL composition when a buffer scaling is applied (maybe with some
1019 * minimal value)? Or, we could make GL behave like HWC -- but this feel
1020 * like more of a hack.
1022 Rect win(computeBounds());
1024 if (!s.finalCrop.isEmpty()) {
1025 win = s.active.transform.transform(win);
1026 if (!win.intersect(s.finalCrop, &win)) {
1029 win = s.active.transform.inverse().transform(win);
1030 if (!win.intersect(computeBounds(), &win)) {
1035 float left = float(win.left) / float(s.active.w);
1036 float top = float(win.top) / float(s.active.h);
1037 float right = float(win.right) / float(s.active.w);
1038 float bottom = float(win.bottom) / float(s.active.h);
1040 // TODO: we probably want to generate the texture coords with the mesh
1041 // here we assume that we only have 4 vertices
1042 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>());
1043 texCoords[0] = vec2(left, 1.0f - top);
1044 texCoords[1] = vec2(left, 1.0f - bottom);
1045 texCoords[2] = vec2(right, 1.0f - bottom);
1046 texCoords[3] = vec2(right, 1.0f - top);
1048 RenderEngine& engine(mFlinger->getRenderEngine());
1049 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha);
1050 engine.drawMesh(mMesh);
1051 engine.disableBlending();
1055 void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type,
1057 if (mHwcLayers.count(hwcId) == 0) {
1058 ALOGE("setCompositionType called without a valid HWC layer");
1061 auto& hwcInfo = mHwcLayers[hwcId];
1062 auto& hwcLayer = hwcInfo.layer;
1063 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(),
1064 to_string(type).c_str(), static_cast<int>(callIntoHwc));
1065 if (hwcInfo.compositionType != type) {
1066 ALOGV(" actually setting");
1067 hwcInfo.compositionType = type;
1069 auto error = hwcLayer->setCompositionType(type);
1070 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set "
1071 "composition type %s: %s (%d)", mName.string(),
1072 to_string(type).c_str(), to_string(error).c_str(),
1073 static_cast<int32_t>(error));
1078 HWC2::Composition Layer::getCompositionType(int32_t hwcId) const {
1079 if (mHwcLayers.count(hwcId) == 0) {
1080 ALOGE("getCompositionType called without a valid HWC layer");
1081 return HWC2::Composition::Invalid;
1083 return mHwcLayers.at(hwcId).compositionType;
1086 void Layer::setClearClientTarget(int32_t hwcId, bool clear) {
1087 if (mHwcLayers.count(hwcId) == 0) {
1088 ALOGE("setClearClientTarget called without a valid HWC layer");
1091 mHwcLayers[hwcId].clearClientTarget = clear;
1094 bool Layer::getClearClientTarget(int32_t hwcId) const {
1095 if (mHwcLayers.count(hwcId) == 0) {
1096 ALOGE("getClearClientTarget called without a valid HWC layer");
1099 return mHwcLayers.at(hwcId).clearClientTarget;
1103 uint32_t Layer::getProducerStickyTransform() const {
1104 int producerStickyTransform = 0;
1105 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform);
1107 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__,
1108 strerror(-ret), ret);
1111 return static_cast<uint32_t>(producerStickyTransform);
1114 uint64_t Layer::getHeadFrameNumber() const {
1115 Mutex::Autolock lock(mQueueItemLock);
1116 if (!mQueueItems.empty()) {
1117 return mQueueItems[0].mFrameNumber;
1119 return mCurrentFrameNumber;
1123 bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) {
1124 if (point->getFrameNumber() <= mCurrentFrameNumber) {
1125 // Don't bother with a SyncPoint, since we've already latched the
1130 Mutex::Autolock lock(mLocalSyncPointMutex);
1131 mLocalSyncPoints.push_back(point);
1135 void Layer::setFiltering(bool filtering) {
1136 mFiltering = filtering;
1139 bool Layer::getFiltering() const {
1143 // As documented in libhardware header, formats in the range
1144 // 0x100 - 0x1FF are specific to the HAL implementation, and
1145 // are known to have no alpha channel
1146 // TODO: move definition for device-specific range into
1147 // hardware.h, instead of using hard-coded values here.
1148 #define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF)
1150 bool Layer::getOpacityForFormat(uint32_t format) {
1151 if (HARDWARE_IS_DEVICE_FORMAT(format)) {
1155 case HAL_PIXEL_FORMAT_RGBA_8888:
1156 case HAL_PIXEL_FORMAT_BGRA_8888:
1159 // in all other case, we have no blending (also for unknown formats)
1163 // ----------------------------------------------------------------------------
1165 // ----------------------------------------------------------------------------
1167 static void boundPoint(vec2* point, const Rect& crop) {
1168 if (point->x < crop.left) {
1169 point->x = crop.left;
1171 if (point->x > crop.right) {
1172 point->x = crop.right;
1174 if (point->y < crop.top) {
1175 point->y = crop.top;
1177 if (point->y > crop.bottom) {
1178 point->y = crop.bottom;
1182 void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh,
1183 bool useIdentityTransform) const
1185 const Layer::State& s(getDrawingState());
1186 const Transform tr(hw->getTransform());
1187 const uint32_t hw_h = hw->getHeight();
1188 Rect win(s.active.w, s.active.h);
1189 if (!s.crop.isEmpty()) {
1190 win.intersect(s.crop, &win);
1192 // subtract the transparent region and snap to the bounds
1193 win = reduce(win, s.activeTransparentRegion);
1195 vec2 lt = vec2(win.left, win.top);
1196 vec2 lb = vec2(win.left, win.bottom);
1197 vec2 rb = vec2(win.right, win.bottom);
1198 vec2 rt = vec2(win.right, win.top);
1200 if (!useIdentityTransform) {
1201 lt = s.active.transform.transform(lt);
1202 lb = s.active.transform.transform(lb);
1203 rb = s.active.transform.transform(rb);
1204 rt = s.active.transform.transform(rt);
1207 if (!s.finalCrop.isEmpty()) {
1208 boundPoint(<, s.finalCrop);
1209 boundPoint(&lb, s.finalCrop);
1210 boundPoint(&rb, s.finalCrop);
1211 boundPoint(&rt, s.finalCrop);
1214 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>());
1215 position[0] = tr.transform(lt);
1216 position[1] = tr.transform(lb);
1217 position[2] = tr.transform(rb);
1218 position[3] = tr.transform(rt);
1219 for (size_t i=0 ; i<4 ; i++) {
1220 position[i].y = hw_h - position[i].y;
1224 bool Layer::isOpaque(const Layer::State& s) const
1226 // if we don't have a buffer yet, we're translucent regardless of the
1227 // layer's opaque flag.
1228 if (mActiveBuffer == 0) {
1232 // if the layer has the opaque flag, then we're always opaque,
1233 // otherwise we use the current buffer's format.
1234 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity;
1237 bool Layer::isSecure() const
1239 const Layer::State& s(mDrawingState);
1240 return (s.flags & layer_state_t::eLayerSecure);
1243 bool Layer::isProtected() const
1245 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer);
1246 return (activeBuffer != 0) &&
1247 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED);
1250 bool Layer::isFixedSize() const {
1251 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1254 bool Layer::isCropped() const {
1255 return !mCurrentCrop.isEmpty();
1258 bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const {
1259 return mNeedsFiltering || hw->needsFiltering();
1262 void Layer::setVisibleRegion(const Region& visibleRegion) {
1263 // always called from main thread
1264 this->visibleRegion = visibleRegion;
1267 void Layer::setCoveredRegion(const Region& coveredRegion) {
1268 // always called from main thread
1269 this->coveredRegion = coveredRegion;
1272 void Layer::setVisibleNonTransparentRegion(const Region&
1273 setVisibleNonTransparentRegion) {
1274 // always called from main thread
1275 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion;
1278 // ----------------------------------------------------------------------------
1280 // ----------------------------------------------------------------------------
1282 void Layer::pushPendingState() {
1283 if (!mCurrentState.modified) {
1287 // If this transaction is waiting on the receipt of a frame, generate a sync
1288 // point and send it to the remote layer.
1289 if (mCurrentState.handle != nullptr) {
1290 sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get());
1291 sp<Layer> handleLayer = handle->owner.promote();
1292 if (handleLayer == nullptr) {
1293 ALOGE("[%s] Unable to promote Layer handle", mName.string());
1294 // If we can't promote the layer we are intended to wait on,
1295 // then it is expired or otherwise invalid. Allow this transaction
1296 // to be applied as per normal (no synchronization).
1297 mCurrentState.handle = nullptr;
1299 auto syncPoint = std::make_shared<SyncPoint>(
1300 mCurrentState.frameNumber);
1301 if (handleLayer->addSyncPoint(syncPoint)) {
1302 mRemoteSyncPoints.push_back(std::move(syncPoint));
1304 // We already missed the frame we're supposed to synchronize
1305 // on, so go ahead and apply the state update
1306 mCurrentState.handle = nullptr;
1310 // Wake us up to check if the frame has been received
1311 setTransactionFlags(eTransactionNeeded);
1313 mPendingStates.push_back(mCurrentState);
1316 void Layer::popPendingState(State* stateToCommit) {
1317 auto oldFlags = stateToCommit->flags;
1318 *stateToCommit = mPendingStates[0];
1319 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) |
1320 (stateToCommit->flags & stateToCommit->mask);
1322 mPendingStates.removeAt(0);
1325 bool Layer::applyPendingStates(State* stateToCommit) {
1326 bool stateUpdateAvailable = false;
1327 while (!mPendingStates.empty()) {
1328 if (mPendingStates[0].handle != nullptr) {
1329 if (mRemoteSyncPoints.empty()) {
1330 // If we don't have a sync point for this, apply it anyway. It
1331 // will be visually wrong, but it should keep us from getting
1332 // into too much trouble.
1333 ALOGE("[%s] No local sync point found", mName.string());
1334 popPendingState(stateToCommit);
1335 stateUpdateAvailable = true;
1339 if (mRemoteSyncPoints.front()->getFrameNumber() !=
1340 mPendingStates[0].frameNumber) {
1341 ALOGE("[%s] Unexpected sync point frame number found",
1344 // Signal our end of the sync point and then dispose of it
1345 mRemoteSyncPoints.front()->setTransactionApplied();
1346 mRemoteSyncPoints.pop_front();
1350 if (mRemoteSyncPoints.front()->frameIsAvailable()) {
1351 // Apply the state update
1352 popPendingState(stateToCommit);
1353 stateUpdateAvailable = true;
1355 // Signal our end of the sync point and then dispose of it
1356 mRemoteSyncPoints.front()->setTransactionApplied();
1357 mRemoteSyncPoints.pop_front();
1362 popPendingState(stateToCommit);
1363 stateUpdateAvailable = true;
1367 // If we still have pending updates, wake SurfaceFlinger back up and point
1368 // it at this layer so we can process them
1369 if (!mPendingStates.empty()) {
1370 setTransactionFlags(eTransactionNeeded);
1371 mFlinger->setTransactionFlags(eTraversalNeeded);
1374 mCurrentState.modified = false;
1375 return stateUpdateAvailable;
1378 void Layer::notifyAvailableFrames() {
1379 auto headFrameNumber = getHeadFrameNumber();
1380 Mutex::Autolock lock(mLocalSyncPointMutex);
1381 for (auto& point : mLocalSyncPoints) {
1382 if (headFrameNumber >= point->getFrameNumber()) {
1383 point->setFrameAvailable();
1388 uint32_t Layer::doTransaction(uint32_t flags) {
1392 Layer::State c = getCurrentState();
1393 if (!applyPendingStates(&c)) {
1397 const Layer::State& s(getDrawingState());
1399 const bool sizeChanged = (c.requested.w != s.requested.w) ||
1400 (c.requested.h != s.requested.h);
1403 // the size changed, we need to ask our client to request a new buffer
1404 ALOGD_IF(DEBUG_RESIZE,
1405 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n"
1406 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1407 " requested={ wh={%4u,%4u} }}\n"
1408 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1409 " requested={ wh={%4u,%4u} }}\n",
1410 this, getName().string(), mCurrentTransform,
1411 getEffectiveScalingMode(),
1412 c.active.w, c.active.h,
1419 c.requested.w, c.requested.h,
1420 s.active.w, s.active.h,
1427 s.requested.w, s.requested.h);
1429 // record the new size, form this point on, when the client request
1430 // a buffer, it'll get the new size.
1431 mSurfaceFlingerConsumer->setDefaultBufferSize(
1432 c.requested.w, c.requested.h);
1435 if (!isFixedSize()) {
1437 const bool resizePending = (c.requested.w != c.active.w) ||
1438 (c.requested.h != c.active.h);
1440 if (resizePending && mSidebandStream == NULL) {
1441 // don't let Layer::doTransaction update the drawing state
1442 // if we have a pending resize, unless we are in fixed-size mode.
1443 // the drawing state will be updated only once we receive a buffer
1444 // with the correct size.
1446 // in particular, we want to make sure the clip (which is part
1447 // of the geometry state) is latched together with the size but is
1448 // latched immediately when no resizing is involved.
1450 // If a sideband stream is attached, however, we want to skip this
1451 // optimization so that transactions aren't missed when a buffer
1454 flags |= eDontUpdateGeometryState;
1458 // always set active to requested, unless we're asked not to
1459 // this is used by Layer, which special cases resizes.
1460 if (flags & eDontUpdateGeometryState) {
1462 c.active = c.requested;
1465 if (s.active != c.active) {
1466 // invalidate and recompute the visible regions if needed
1467 flags |= Layer::eVisibleRegion;
1470 if (c.sequence != s.sequence) {
1471 // invalidate and recompute the visible regions if needed
1472 flags |= eVisibleRegion;
1473 this->contentDirty = true;
1475 // we may use linear filtering, if the matrix scales us
1476 const uint8_t type = c.active.transform.getType();
1477 mNeedsFiltering = (!c.active.transform.preserveRects() ||
1478 (type >= Transform::SCALE));
1481 // Commit the transaction
1482 commitTransaction(c);
1486 void Layer::commitTransaction(const State& stateToCommit) {
1487 mDrawingState = stateToCommit;
1490 uint32_t Layer::getTransactionFlags(uint32_t flags) {
1491 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1494 uint32_t Layer::setTransactionFlags(uint32_t flags) {
1495 return android_atomic_or(flags, &mTransactionFlags);
1498 bool Layer::setPosition(float x, float y) {
1499 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y)
1501 mCurrentState.sequence++;
1503 // We update the requested and active position simultaneously because
1504 // we want to apply the position portion of the transform matrix immediately,
1505 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer.
1506 mCurrentState.requested.transform.set(x, y);
1507 mCurrentState.active.transform.set(x, y);
1509 mCurrentState.modified = true;
1510 setTransactionFlags(eTransactionNeeded);
1513 bool Layer::setLayer(uint32_t z) {
1514 if (mCurrentState.z == z)
1516 mCurrentState.sequence++;
1517 mCurrentState.z = z;
1518 mCurrentState.modified = true;
1519 setTransactionFlags(eTransactionNeeded);
1522 bool Layer::setSize(uint32_t w, uint32_t h) {
1523 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h)
1525 mCurrentState.requested.w = w;
1526 mCurrentState.requested.h = h;
1527 mCurrentState.modified = true;
1528 setTransactionFlags(eTransactionNeeded);
1532 bool Layer::setAlpha(float alpha) {
1534 bool Layer::setAlpha(uint8_t alpha) {
1536 if (mCurrentState.alpha == alpha)
1538 mCurrentState.sequence++;
1539 mCurrentState.alpha = alpha;
1540 mCurrentState.modified = true;
1541 setTransactionFlags(eTransactionNeeded);
1544 bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) {
1545 mCurrentState.sequence++;
1546 mCurrentState.requested.transform.set(
1547 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy);
1548 mCurrentState.modified = true;
1549 setTransactionFlags(eTransactionNeeded);
1552 bool Layer::setTransparentRegionHint(const Region& transparent) {
1553 mCurrentState.requestedTransparentRegion = transparent;
1554 mCurrentState.modified = true;
1555 setTransactionFlags(eTransactionNeeded);
1558 bool Layer::setFlags(uint8_t flags, uint8_t mask) {
1559 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask);
1560 if (mCurrentState.flags == newFlags)
1562 mCurrentState.sequence++;
1563 mCurrentState.flags = newFlags;
1564 mCurrentState.mask = mask;
1565 mCurrentState.modified = true;
1566 setTransactionFlags(eTransactionNeeded);
1569 bool Layer::setCrop(const Rect& crop) {
1570 if (mCurrentState.crop == crop)
1572 mCurrentState.sequence++;
1573 mCurrentState.crop = crop;
1574 mCurrentState.modified = true;
1575 setTransactionFlags(eTransactionNeeded);
1578 bool Layer::setFinalCrop(const Rect& crop) {
1579 if (mCurrentState.finalCrop == crop)
1581 mCurrentState.sequence++;
1582 mCurrentState.finalCrop = crop;
1583 mCurrentState.modified = true;
1584 setTransactionFlags(eTransactionNeeded);
1588 bool Layer::setOverrideScalingMode(int32_t scalingMode) {
1589 if (scalingMode == mOverrideScalingMode)
1591 mOverrideScalingMode = scalingMode;
1595 uint32_t Layer::getEffectiveScalingMode() const {
1596 if (mOverrideScalingMode >= 0) {
1597 return mOverrideScalingMode;
1599 return mCurrentScalingMode;
1602 bool Layer::setLayerStack(uint32_t layerStack) {
1603 if (mCurrentState.layerStack == layerStack)
1605 mCurrentState.sequence++;
1606 mCurrentState.layerStack = layerStack;
1607 mCurrentState.modified = true;
1608 setTransactionFlags(eTransactionNeeded);
1612 void Layer::deferTransactionUntil(const sp<IBinder>& handle,
1613 uint64_t frameNumber) {
1614 mCurrentState.handle = handle;
1615 mCurrentState.frameNumber = frameNumber;
1616 // We don't set eTransactionNeeded, because just receiving a deferral
1617 // request without any other state updates shouldn't actually induce a delay
1618 mCurrentState.modified = true;
1620 mCurrentState.handle = nullptr;
1621 mCurrentState.frameNumber = 0;
1622 mCurrentState.modified = false;
1625 void Layer::useSurfaceDamage() {
1626 if (mFlinger->mForceFullDamage) {
1627 surfaceDamageRegion = Region::INVALID_REGION;
1629 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage();
1633 void Layer::useEmptyDamage() {
1634 surfaceDamageRegion.clear();
1637 // ----------------------------------------------------------------------------
1638 // pageflip handling...
1639 // ----------------------------------------------------------------------------
1641 bool Layer::shouldPresentNow(const DispSync& dispSync) const {
1642 if (mSidebandStreamChanged || mAutoRefresh) {
1646 Mutex::Autolock lock(mQueueItemLock);
1647 if (mQueueItems.empty()) {
1650 auto timestamp = mQueueItems[0].mTimestamp;
1651 nsecs_t expectedPresent =
1652 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync);
1654 // Ignore timestamps more than a second in the future
1655 bool isPlausible = timestamp < (expectedPresent + s2ns(1));
1656 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible "
1657 "relative to expectedPresent %" PRId64, mName.string(), timestamp,
1660 bool isDue = timestamp < expectedPresent;
1661 return isDue || !isPlausible;
1664 bool Layer::onPreComposition() {
1665 mRefreshPending = false;
1666 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh;
1669 void Layer::onPostComposition() {
1670 if (mFrameLatencyNeeded) {
1671 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp();
1672 mFrameTracker.setDesiredPresentTime(desiredPresentTime);
1674 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence();
1675 if (frameReadyFence->isValid()) {
1676 mFrameTracker.setFrameReadyFence(frameReadyFence);
1678 // There was no fence for this frame, so assume that it was ready
1679 // to be presented at the desired present time.
1680 mFrameTracker.setFrameReadyTime(desiredPresentTime);
1683 const HWComposer& hwc = mFlinger->getHwComposer();
1685 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY);
1687 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1689 if (presentFence->isValid()) {
1690 mFrameTracker.setActualPresentFence(presentFence);
1692 // The HWC doesn't support present fences, so use the refresh
1693 // timestamp instead.
1694 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1695 mFrameTracker.setActualPresentTime(presentTime);
1698 mFrameTracker.advanceFrame();
1699 mFrameLatencyNeeded = false;
1704 void Layer::releasePendingBuffer() {
1705 mSurfaceFlingerConsumer->releasePendingBuffer();
1709 bool Layer::isVisible() const {
1710 const Layer::State& s(mDrawingState);
1712 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f
1713 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1715 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha
1716 && (mActiveBuffer != NULL || mSidebandStream != NULL);
1720 Region Layer::latchBuffer(bool& recomputeVisibleRegions)
1724 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) {
1725 // mSidebandStreamChanged was true
1726 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream();
1727 if (mSidebandStream != NULL) {
1728 setTransactionFlags(eTransactionNeeded);
1729 mFlinger->setTransactionFlags(eTraversalNeeded);
1731 recomputeVisibleRegions = true;
1733 const State& s(getDrawingState());
1734 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h)));
1737 Region outDirtyRegion;
1738 if (mQueuedFrames > 0 || mAutoRefresh) {
1740 // if we've already called updateTexImage() without going through
1741 // a composition step, we have to skip this layer at this point
1742 // because we cannot call updateTeximage() without a corresponding
1743 // compositionComplete() call.
1744 // we'll trigger an update in onPreComposition().
1745 if (mRefreshPending) {
1746 return outDirtyRegion;
1749 // Capture the old state of the layer for comparisons later
1750 const State& s(getDrawingState());
1751 const bool oldOpacity = isOpaque(s);
1752 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer;
1754 struct Reject : public SurfaceFlingerConsumer::BufferRejecter {
1755 Layer::State& front;
1756 Layer::State& current;
1757 bool& recomputeVisibleRegions;
1758 bool stickyTransformSet;
1760 int32_t overrideScalingMode;
1762 Reject(Layer::State& front, Layer::State& current,
1763 bool& recomputeVisibleRegions, bool stickySet,
1765 int32_t overrideScalingMode)
1766 : front(front), current(current),
1767 recomputeVisibleRegions(recomputeVisibleRegions),
1768 stickyTransformSet(stickySet),
1770 overrideScalingMode(overrideScalingMode) {
1773 virtual bool reject(const sp<GraphicBuffer>& buf,
1774 const BufferItem& item) {
1779 uint32_t bufWidth = buf->getWidth();
1780 uint32_t bufHeight = buf->getHeight();
1782 // check that we received a buffer of the right size
1783 // (Take the buffer's orientation into account)
1784 if (item.mTransform & Transform::ROT_90) {
1785 swap(bufWidth, bufHeight);
1788 int actualScalingMode = overrideScalingMode >= 0 ?
1789 overrideScalingMode : item.mScalingMode;
1790 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE;
1791 if (front.active != front.requested) {
1794 (bufWidth == front.requested.w &&
1795 bufHeight == front.requested.h))
1797 // Here we pretend the transaction happened by updating the
1798 // current and drawing states. Drawing state is only accessed
1799 // in this thread, no need to have it locked
1800 front.active = front.requested;
1802 // We also need to update the current state so that
1803 // we don't end-up overwriting the drawing state with
1804 // this stale current state during the next transaction
1806 // NOTE: We don't need to hold the transaction lock here
1807 // because State::active is only accessed from this thread.
1808 current.active = front.active;
1810 // recompute visible region
1811 recomputeVisibleRegions = true;
1814 ALOGD_IF(DEBUG_RESIZE,
1815 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n"
1816 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n"
1817 " requested={ wh={%4u,%4u} }}\n",
1819 bufWidth, bufHeight, item.mTransform, item.mScalingMode,
1820 front.active.w, front.active.h,
1825 front.crop.getWidth(),
1826 front.crop.getHeight(),
1827 front.requested.w, front.requested.h);
1830 if (!isFixedSize && !stickyTransformSet) {
1831 if (front.active.w != bufWidth ||
1832 front.active.h != bufHeight) {
1833 // reject this buffer
1834 ALOGE("[%s] rejecting buffer: "
1835 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}",
1836 name, bufWidth, bufHeight, front.active.w, front.active.h);
1841 // if the transparent region has changed (this test is
1842 // conservative, but that's fine, worst case we're doing
1843 // a bit of extra work), we latch the new one and we
1844 // trigger a visible-region recompute.
1845 if (!front.activeTransparentRegion.isTriviallyEqual(
1846 front.requestedTransparentRegion)) {
1847 front.activeTransparentRegion = front.requestedTransparentRegion;
1849 // We also need to update the current state so that
1850 // we don't end-up overwriting the drawing state with
1851 // this stale current state during the next transaction
1853 // NOTE: We don't need to hold the transaction lock here
1854 // because State::active is only accessed from this thread.
1855 current.activeTransparentRegion = front.activeTransparentRegion;
1857 // recompute visible region
1858 recomputeVisibleRegions = true;
1865 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions,
1866 getProducerStickyTransform() != 0, mName.string(),
1867 mOverrideScalingMode);
1870 // Check all of our local sync points to ensure that all transactions
1871 // which need to have been applied prior to the frame which is about to
1872 // be latched have signaled
1874 auto headFrameNumber = getHeadFrameNumber();
1875 bool matchingFramesFound = false;
1876 bool allTransactionsApplied = true;
1878 Mutex::Autolock lock(mLocalSyncPointMutex);
1879 for (auto& point : mLocalSyncPoints) {
1880 if (point->getFrameNumber() > headFrameNumber) {
1884 matchingFramesFound = true;
1886 if (!point->frameIsAvailable()) {
1887 // We haven't notified the remote layer that the frame for
1888 // this point is available yet. Notify it now, and then
1889 // abort this attempt to latch.
1890 point->setFrameAvailable();
1891 allTransactionsApplied = false;
1895 allTransactionsApplied &= point->transactionIsApplied();
1899 if (matchingFramesFound && !allTransactionsApplied) {
1900 mFlinger->signalLayerUpdate();
1901 return outDirtyRegion;
1904 // This boolean is used to make sure that SurfaceFlinger's shadow copy
1905 // of the buffer queue isn't modified when the buffer queue is returning
1906 // BufferItem's that weren't actually queued. This can happen in shared
1908 bool queuedBuffer = false;
1909 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r,
1910 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer,
1911 mLastFrameNumberReceived);
1912 if (updateResult == BufferQueue::PRESENT_LATER) {
1913 // Producer doesn't want buffer to be displayed yet. Signal a
1914 // layer update so we check again at the next opportunity.
1915 mFlinger->signalLayerUpdate();
1916 return outDirtyRegion;
1917 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) {
1918 // If the buffer has been rejected, remove it from the shadow queue
1921 Mutex::Autolock lock(mQueueItemLock);
1922 mQueueItems.removeAt(0);
1923 android_atomic_dec(&mQueuedFrames);
1925 return outDirtyRegion;
1926 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) {
1927 // This can occur if something goes wrong when trying to create the
1928 // EGLImage for this buffer. If this happens, the buffer has already
1929 // been released, so we need to clean up the queue and bug out
1932 Mutex::Autolock lock(mQueueItemLock);
1933 mQueueItems.clear();
1934 android_atomic_and(0, &mQueuedFrames);
1937 // Once we have hit this state, the shadow queue may no longer
1938 // correctly reflect the incoming BufferQueue's contents, so even if
1939 // updateTexImage starts working, the only safe course of action is
1940 // to continue to ignore updates.
1941 mUpdateTexImageFailed = true;
1943 return outDirtyRegion;
1948 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
1950 Mutex::Autolock lock(mQueueItemLock);
1952 // Remove any stale buffers that have been dropped during
1954 while (mQueueItems[0].mFrameNumber != currentFrameNumber) {
1955 mQueueItems.removeAt(0);
1956 android_atomic_dec(&mQueuedFrames);
1959 mQueueItems.removeAt(0);
1963 // Decrement the queued-frames count. Signal another event if we
1964 // have more frames pending.
1965 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1)
1967 mFlinger->signalLayerUpdate();
1970 if (updateResult != NO_ERROR) {
1971 // something happened!
1972 recomputeVisibleRegions = true;
1973 return outDirtyRegion;
1976 // update the active buffer
1977 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer();
1978 if (mActiveBuffer == NULL) {
1979 // this can only happen if the very first buffer was rejected.
1980 return outDirtyRegion;
1983 mRefreshPending = true;
1984 mFrameLatencyNeeded = true;
1985 if (oldActiveBuffer == NULL) {
1986 // the first time we receive a buffer, we need to trigger a
1987 // geometry invalidation.
1988 recomputeVisibleRegions = true;
1991 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop());
1992 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform());
1993 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode());
1994 if ((crop != mCurrentCrop) ||
1995 (transform != mCurrentTransform) ||
1996 (scalingMode != mCurrentScalingMode))
1998 mCurrentCrop = crop;
1999 mCurrentTransform = transform;
2000 mCurrentScalingMode = scalingMode;
2001 recomputeVisibleRegions = true;
2004 if (oldActiveBuffer != NULL) {
2005 uint32_t bufWidth = mActiveBuffer->getWidth();
2006 uint32_t bufHeight = mActiveBuffer->getHeight();
2007 if (bufWidth != uint32_t(oldActiveBuffer->width) ||
2008 bufHeight != uint32_t(oldActiveBuffer->height)) {
2009 recomputeVisibleRegions = true;
2013 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format);
2014 if (oldOpacity != isOpaque(s)) {
2015 recomputeVisibleRegions = true;
2018 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2020 // Remove any sync points corresponding to the buffer which was just
2023 Mutex::Autolock lock(mLocalSyncPointMutex);
2024 auto point = mLocalSyncPoints.begin();
2025 while (point != mLocalSyncPoints.end()) {
2026 if (!(*point)->frameIsAvailable() ||
2027 !(*point)->transactionIsApplied()) {
2028 // This sync point must have been added since we started
2029 // latching. Don't drop it yet.
2034 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) {
2035 point = mLocalSyncPoints.erase(point);
2042 // FIXME: postedRegion should be dirty & bounds
2043 Region dirtyRegion(Rect(s.active.w, s.active.h));
2045 // transform the dirty region to window-manager space
2046 outDirtyRegion = (s.active.transform.transform(dirtyRegion));
2048 return outDirtyRegion;
2051 uint32_t Layer::getEffectiveUsage(uint32_t usage) const
2053 // TODO: should we do something special if mSecure is set?
2054 if (mProtectedByApp) {
2055 // need a hardware-protected path to external video sink
2056 usage |= GraphicBuffer::USAGE_PROTECTED;
2058 if (mPotentialCursor) {
2059 usage |= GraphicBuffer::USAGE_CURSOR;
2061 usage |= GraphicBuffer::USAGE_HW_COMPOSER;
2065 void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const {
2066 uint32_t orientation = 0;
2067 if (!mFlinger->mDebugDisableTransformHint) {
2068 // The transform hint is used to improve performance, but we can
2069 // only have a single transform hint, it cannot
2070 // apply to all displays.
2071 const Transform& planeTransform(hw->getTransform());
2072 orientation = planeTransform.getOrientation();
2073 if (orientation & Transform::ROT_INVALID) {
2077 mSurfaceFlingerConsumer->setTransformHint(orientation);
2080 // ----------------------------------------------------------------------------
2082 // ----------------------------------------------------------------------------
2084 void Layer::dump(String8& result, Colorizer& colorizer) const
2086 const Layer::State& s(getDrawingState());
2088 colorizer.colorize(result, Colorizer::GREEN);
2089 result.appendFormat(
2091 getTypeId(), this, getName().string());
2092 colorizer.reset(result);
2094 s.activeTransparentRegion.dump(result, "transparentRegion");
2095 visibleRegion.dump(result, "visibleRegion");
2096 surfaceDamageRegion.dump(result, "surfaceDamageRegion");
2097 sp<Client> client(mClientRef.promote());
2099 result.appendFormat( " "
2100 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), "
2101 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), "
2102 "isOpaque=%1d, invalidate=%1d, "
2104 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2106 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n"
2109 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h,
2110 s.crop.left, s.crop.top,
2111 s.crop.right, s.crop.bottom,
2112 s.finalCrop.left, s.finalCrop.top,
2113 s.finalCrop.right, s.finalCrop.bottom,
2114 isOpaque(s), contentDirty,
2116 s.active.transform[0][0], s.active.transform[0][1],
2117 s.active.transform[1][0], s.active.transform[1][1],
2120 sp<const GraphicBuffer> buf0(mActiveBuffer);
2121 uint32_t w0=0, h0=0, s0=0, f0=0;
2123 w0 = buf0->getWidth();
2124 h0 = buf0->getHeight();
2125 s0 = buf0->getStride();
2128 result.appendFormat(
2130 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X],"
2131 " queued-frames=%d, mRefreshPending=%d\n",
2132 mFormat, w0, h0, s0,f0,
2133 mQueuedFrames, mRefreshPending);
2135 if (mSurfaceFlingerConsumer != 0) {
2136 mSurfaceFlingerConsumer->dump(result, " ");
2140 void Layer::dumpFrameStats(String8& result) const {
2141 mFrameTracker.dumpStats(result);
2144 void Layer::clearFrameStats() {
2145 mFrameTracker.clearStats();
2148 void Layer::logFrameStats() {
2149 mFrameTracker.logAndResetStats(mName);
2152 void Layer::getFrameStats(FrameStats* outStats) const {
2153 mFrameTracker.getStats(outStats);
2156 void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber,
2157 bool* outIsGlesComposition, nsecs_t* outPostedTime,
2158 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const {
2160 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber();
2163 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ?
2164 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType ==
2165 HWC2::Composition::Client : true;
2167 *outIsGlesComposition = mIsGlesComposition;
2169 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp();
2170 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence();
2171 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence();
2173 // ---------------------------------------------------------------------------
2175 Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger,
2176 const sp<Layer>& layer)
2177 : mFlinger(flinger), mLayer(layer) {
2180 Layer::LayerCleaner::~LayerCleaner() {
2181 // destroy client resources
2182 mFlinger->onLayerDestroyed(mLayer);
2185 // ---------------------------------------------------------------------------
2186 }; // namespace android
2188 #if defined(__gl_h_)
2189 #error "don't include gl/gl.h in this file"
2192 #if defined(__gl2_h_)
2193 #error "don't include gl2/gl2.h in this file"