Layer.cpp revision 1725eeeb7db8a2c933dcc9d01cce14e17c76c6e6
1/* 2 * Copyright (C) 2007 The Android Open Source Project 3 * 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 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 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. 15 */ 16 17//#define LOG_NDEBUG 0 18#undef LOG_TAG 19#define LOG_TAG "Layer" 20#define ATRACE_TAG ATRACE_TAG_GRAPHICS 21 22#include <stdlib.h> 23#include <stdint.h> 24#include <sys/types.h> 25#include <math.h> 26 27#include <cutils/compiler.h> 28#include <cutils/native_handle.h> 29#include <cutils/properties.h> 30 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> 36 37#include <ui/GraphicBuffer.h> 38#include <ui/PixelFormat.h> 39 40#include <gui/BufferItem.h> 41#include <gui/BufferQueue.h> 42#include <gui/Surface.h> 43 44#include "clz.h" 45#include "Colorizer.h" 46#include "DisplayDevice.h" 47#include "Layer.h" 48#include "LayerRejecter.h" 49#include "MonitoredProducer.h" 50#include "SurfaceFlinger.h" 51 52#include "DisplayHardware/HWComposer.h" 53 54#include "RenderEngine/RenderEngine.h" 55 56#include <mutex> 57 58#define DEBUG_RESIZE 0 59 60namespace android { 61 62// --------------------------------------------------------------------------- 63 64int32_t Layer::sSequence = 1; 65 66Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client, 67 const String8& name, uint32_t w, uint32_t h, uint32_t flags) 68 : contentDirty(false), 69 sequence(uint32_t(android_atomic_inc(&sSequence))), 70 mFlinger(flinger), 71 mTextureName(-1U), 72 mPremultipliedAlpha(true), 73 mName("unnamed"), 74 mFormat(PIXEL_FORMAT_NONE), 75 mTransactionFlags(0), 76 mPendingStateMutex(), 77 mPendingStates(), 78 mQueuedFrames(0), 79 mSidebandStreamChanged(false), 80 mActiveBufferSlot(BufferQueue::INVALID_BUFFER_SLOT), 81 mCurrentTransform(0), 82 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 83 mOverrideScalingMode(-1), 84 mCurrentOpacity(true), 85 mBufferLatched(false), 86 mCurrentFrameNumber(0), 87 mPreviousFrameNumber(0), 88 mRefreshPending(false), 89 mFrameLatencyNeeded(false), 90 mFiltering(false), 91 mNeedsFiltering(false), 92 mMesh(Mesh::TRIANGLE_FAN, 4, 2, 2), 93#ifndef USE_HWC2 94 mIsGlesComposition(false), 95#endif 96 mProtectedByApp(false), 97 mHasSurface(false), 98 mClientRef(client), 99 mPotentialCursor(false), 100 mQueueItemLock(), 101 mQueueItemCondition(), 102 mQueueItems(), 103 mLastFrameNumberReceived(0), 104 mUpdateTexImageFailed(false), 105 mAutoRefresh(false), 106 mFreezePositionUpdates(false) 107{ 108#ifdef USE_HWC2 109 ALOGV("Creating Layer %s", name.string()); 110#endif 111 112 mCurrentCrop.makeInvalid(); 113 mFlinger->getRenderEngine().genTextures(1, &mTextureName); 114 mTexture.init(Texture::TEXTURE_EXTERNAL, mTextureName); 115 116 uint32_t layerFlags = 0; 117 if (flags & ISurfaceComposerClient::eHidden) 118 layerFlags |= layer_state_t::eLayerHidden; 119 if (flags & ISurfaceComposerClient::eOpaque) 120 layerFlags |= layer_state_t::eLayerOpaque; 121 if (flags & ISurfaceComposerClient::eSecure) 122 layerFlags |= layer_state_t::eLayerSecure; 123 124 if (flags & ISurfaceComposerClient::eNonPremultiplied) 125 mPremultipliedAlpha = false; 126 127 mName = name; 128 129 mCurrentState.active.w = w; 130 mCurrentState.active.h = h; 131 mCurrentState.active.transform.set(0, 0); 132 mCurrentState.crop.makeInvalid(); 133 mCurrentState.finalCrop.makeInvalid(); 134 mCurrentState.z = 0; 135#ifdef USE_HWC2 136 mCurrentState.alpha = 1.0f; 137#else 138 mCurrentState.alpha = 0xFF; 139#endif 140 mCurrentState.layerStack = 0; 141 mCurrentState.flags = layerFlags; 142 mCurrentState.sequence = 0; 143 mCurrentState.requested = mCurrentState.active; 144 mCurrentState.dataSpace = HAL_DATASPACE_UNKNOWN; 145 mCurrentState.appId = 0; 146 mCurrentState.type = 0; 147 148 // drawing state & current state are identical 149 mDrawingState = mCurrentState; 150 151#ifdef USE_HWC2 152 const auto& hwc = flinger->getHwComposer(); 153 const auto& activeConfig = hwc.getActiveConfig(HWC_DISPLAY_PRIMARY); 154 nsecs_t displayPeriod = activeConfig->getVsyncPeriod(); 155#else 156 nsecs_t displayPeriod = 157 flinger->getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY); 158#endif 159 mFrameTracker.setDisplayRefreshPeriod(displayPeriod); 160 161 CompositorTiming compositorTiming; 162 flinger->getCompositorTiming(&compositorTiming); 163 mFrameEventHistory.initializeCompositorTiming(compositorTiming); 164} 165 166void Layer::onFirstRef() { 167 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use 168 sp<IGraphicBufferProducer> producer; 169 sp<IGraphicBufferConsumer> consumer; 170 BufferQueue::createBufferQueue(&producer, &consumer, true); 171 mProducer = new MonitoredProducer(producer, mFlinger, this); 172 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(consumer, mTextureName, this); 173 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0)); 174 mSurfaceFlingerConsumer->setContentsChangedListener(this); 175 mSurfaceFlingerConsumer->setName(mName); 176 177 if (mFlinger->isLayerTripleBufferingDisabled()) { 178 mProducer->setMaxDequeuedBufferCount(2); 179 } 180 181 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice()); 182 updateTransformHint(hw); 183} 184 185Layer::~Layer() { 186 sp<Client> c(mClientRef.promote()); 187 if (c != 0) { 188 c->detachLayer(this); 189 } 190 191 for (auto& point : mRemoteSyncPoints) { 192 point->setTransactionApplied(); 193 } 194 for (auto& point : mLocalSyncPoints) { 195 point->setFrameAvailable(); 196 } 197 mFlinger->deleteTextureAsync(mTextureName); 198 mFrameTracker.logAndResetStats(mName); 199} 200 201// --------------------------------------------------------------------------- 202// callbacks 203// --------------------------------------------------------------------------- 204 205#ifdef USE_HWC2 206void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) { 207 if (mHwcLayers.empty()) { 208 return; 209 } 210 mSurfaceFlingerConsumer->setReleaseFence(releaseFence); 211} 212#else 213void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */, 214 HWComposer::HWCLayerInterface* layer) { 215 if (layer) { 216 layer->onDisplayed(); 217 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence()); 218 } 219} 220#endif 221 222void Layer::onFrameAvailable(const BufferItem& item) { 223 // Add this buffer from our internal queue tracker 224 { // Autolock scope 225 Mutex::Autolock lock(mQueueItemLock); 226 mFlinger->mInterceptor.saveBufferUpdate(this, item.mGraphicBuffer->getWidth(), 227 item.mGraphicBuffer->getHeight(), item.mFrameNumber); 228 // Reset the frame number tracker when we receive the first buffer after 229 // a frame number reset 230 if (item.mFrameNumber == 1) { 231 mLastFrameNumberReceived = 0; 232 } 233 234 // Ensure that callbacks are handled in order 235 while (item.mFrameNumber != mLastFrameNumberReceived + 1) { 236 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, 237 ms2ns(500)); 238 if (result != NO_ERROR) { 239 ALOGE("[%s] Timed out waiting on callback", mName.string()); 240 } 241 } 242 243 mQueueItems.push_back(item); 244 android_atomic_inc(&mQueuedFrames); 245 246 // Wake up any pending callbacks 247 mLastFrameNumberReceived = item.mFrameNumber; 248 mQueueItemCondition.broadcast(); 249 } 250 251 mFlinger->signalLayerUpdate(); 252} 253 254void Layer::onFrameReplaced(const BufferItem& item) { 255 { // Autolock scope 256 Mutex::Autolock lock(mQueueItemLock); 257 258 // Ensure that callbacks are handled in order 259 while (item.mFrameNumber != mLastFrameNumberReceived + 1) { 260 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, 261 ms2ns(500)); 262 if (result != NO_ERROR) { 263 ALOGE("[%s] Timed out waiting on callback", mName.string()); 264 } 265 } 266 267 if (mQueueItems.empty()) { 268 ALOGE("Can't replace a frame on an empty queue"); 269 return; 270 } 271 mQueueItems.editItemAt(mQueueItems.size() - 1) = item; 272 273 // Wake up any pending callbacks 274 mLastFrameNumberReceived = item.mFrameNumber; 275 mQueueItemCondition.broadcast(); 276 } 277} 278 279void Layer::onSidebandStreamChanged() { 280 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) { 281 // mSidebandStreamChanged was false 282 mFlinger->signalLayerUpdate(); 283 } 284} 285 286// called with SurfaceFlinger::mStateLock from the drawing thread after 287// the layer has been remove from the current state list (and just before 288// it's removed from the drawing state list) 289void Layer::onRemoved() { 290 if (mCurrentState.zOrderRelativeOf != nullptr) { 291 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote(); 292 if (strongRelative != nullptr) { 293 strongRelative->removeZOrderRelative(this); 294 } 295 mCurrentState.zOrderRelativeOf = nullptr; 296 } 297 298 mSurfaceFlingerConsumer->abandon(); 299 for (const auto& child : mCurrentChildren) { 300 child->onRemoved(); 301 } 302} 303 304// --------------------------------------------------------------------------- 305// set-up 306// --------------------------------------------------------------------------- 307 308const String8& Layer::getName() const { 309 return mName; 310} 311 312status_t Layer::setBuffers( uint32_t w, uint32_t h, 313 PixelFormat format, uint32_t flags) 314{ 315 uint32_t const maxSurfaceDims = min( 316 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims()); 317 318 // never allow a surface larger than what our underlying GL implementation 319 // can handle. 320 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { 321 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h)); 322 return BAD_VALUE; 323 } 324 325 mFormat = format; 326 327 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false; 328 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false; 329 mCurrentOpacity = getOpacityForFormat(format); 330 331 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h); 332 mSurfaceFlingerConsumer->setDefaultBufferFormat(format); 333 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0)); 334 335 return NO_ERROR; 336} 337 338sp<IBinder> Layer::getHandle() { 339 Mutex::Autolock _l(mLock); 340 341 LOG_ALWAYS_FATAL_IF(mHasSurface, 342 "Layer::getHandle() has already been called"); 343 344 mHasSurface = true; 345 346 return new Handle(mFlinger, this); 347} 348 349sp<IGraphicBufferProducer> Layer::getProducer() const { 350 return mProducer; 351} 352 353// --------------------------------------------------------------------------- 354// h/w composer set-up 355// --------------------------------------------------------------------------- 356 357Rect Layer::getContentCrop() const { 358 // this is the crop rectangle that applies to the buffer 359 // itself (as opposed to the window) 360 Rect crop; 361 if (!mCurrentCrop.isEmpty()) { 362 // if the buffer crop is defined, we use that 363 crop = mCurrentCrop; 364 } else if (mActiveBuffer != NULL) { 365 // otherwise we use the whole buffer 366 crop = mActiveBuffer->getBounds(); 367 } else { 368 // if we don't have a buffer yet, we use an empty/invalid crop 369 crop.makeInvalid(); 370 } 371 return crop; 372} 373 374static Rect reduce(const Rect& win, const Region& exclude) { 375 if (CC_LIKELY(exclude.isEmpty())) { 376 return win; 377 } 378 if (exclude.isRect()) { 379 return win.reduce(exclude.getBounds()); 380 } 381 return Region(win).subtract(exclude).getBounds(); 382} 383 384Rect Layer::computeScreenBounds(bool reduceTransparentRegion) const { 385 const Layer::State& s(getDrawingState()); 386 Rect win(s.active.w, s.active.h); 387 388 if (!s.crop.isEmpty()) { 389 win.intersect(s.crop, &win); 390 } 391 392 Transform t = getTransform(); 393 win = t.transform(win); 394 395 const sp<Layer>& p = getParent(); 396 // Now we need to calculate the parent bounds, so we can clip ourselves to those. 397 // When calculating the parent bounds for purposes of clipping, 398 // we don't need to constrain the parent to its transparent region. 399 // The transparent region is an optimization based on the 400 // buffer contents of the layer, but does not affect the space allocated to 401 // it by policy, and thus children should be allowed to extend into the 402 // parent's transparent region. In fact one of the main uses, is to reduce 403 // buffer allocation size in cases where a child window sits behind a main window 404 // (by marking the hole in the parent window as a transparent region) 405 if (p != nullptr) { 406 Rect bounds = p->computeScreenBounds(false); 407 bounds.intersect(win, &win); 408 } 409 410 if (reduceTransparentRegion) { 411 auto const screenTransparentRegion = t.transform(s.activeTransparentRegion); 412 win = reduce(win, screenTransparentRegion); 413 } 414 415 return win; 416} 417 418Rect Layer::computeBounds() const { 419 const Layer::State& s(getDrawingState()); 420 return computeBounds(s.activeTransparentRegion); 421} 422 423Rect Layer::computeBounds(const Region& activeTransparentRegion) const { 424 const Layer::State& s(getDrawingState()); 425 Rect win(s.active.w, s.active.h); 426 427 if (!s.crop.isEmpty()) { 428 win.intersect(s.crop, &win); 429 } 430 431 Rect bounds = win; 432 const auto& p = getParent(); 433 if (p != nullptr) { 434 // Look in computeScreenBounds recursive call for explanation of 435 // why we pass false here. 436 bounds = p->computeScreenBounds(false /* reduceTransparentRegion */); 437 } 438 439 Transform t = getTransform(); 440 if (p != nullptr) { 441 win = t.transform(win); 442 win.intersect(bounds, &win); 443 win = t.inverse().transform(win); 444 } 445 446 // subtract the transparent region and snap to the bounds 447 return reduce(win, activeTransparentRegion); 448} 449 450Rect Layer::computeInitialCrop(const sp<const DisplayDevice>& hw) const { 451 // the crop is the area of the window that gets cropped, but not 452 // scaled in any ways. 453 const State& s(getDrawingState()); 454 455 // apply the projection's clipping to the window crop in 456 // layerstack space, and convert-back to layer space. 457 // if there are no window scaling involved, this operation will map to full 458 // pixels in the buffer. 459 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have 460 // a viewport clipping and a window transform. we should use floating point to fix this. 461 462 Rect activeCrop(s.active.w, s.active.h); 463 if (!s.crop.isEmpty()) { 464 activeCrop = s.crop; 465 } 466 467 Transform t = getTransform(); 468 activeCrop = t.transform(activeCrop); 469 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) { 470 activeCrop.clear(); 471 } 472 if (!s.finalCrop.isEmpty()) { 473 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) { 474 activeCrop.clear(); 475 } 476 } 477 return activeCrop; 478} 479 480FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const { 481 // the content crop is the area of the content that gets scaled to the 482 // layer's size. This is in buffer space. 483 FloatRect crop = getContentCrop().toFloatRect(); 484 485 // In addition there is a WM-specified crop we pull from our drawing state. 486 const State& s(getDrawingState()); 487 488 // Screen space to make reduction to parent crop clearer. 489 Rect activeCrop = computeInitialCrop(hw); 490 const auto& p = getParent(); 491 if (p != nullptr) { 492 auto parentCrop = p->computeInitialCrop(hw); 493 activeCrop.intersect(parentCrop, &activeCrop); 494 } 495 Transform t = getTransform(); 496 // Back to layer space to work with the content crop. 497 activeCrop = t.inverse().transform(activeCrop); 498 499 // This needs to be here as transform.transform(Rect) computes the 500 // transformed rect and then takes the bounding box of the result before 501 // returning. This means 502 // transform.inverse().transform(transform.transform(Rect)) != Rect 503 // in which case we need to make sure the final rect is clipped to the 504 // display bounds. 505 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) { 506 activeCrop.clear(); 507 } 508 509 // subtract the transparent region and snap to the bounds 510 activeCrop = reduce(activeCrop, s.activeTransparentRegion); 511 512 // Transform the window crop to match the buffer coordinate system, 513 // which means using the inverse of the current transform set on the 514 // SurfaceFlingerConsumer. 515 uint32_t invTransform = mCurrentTransform; 516 if (getTransformToDisplayInverse()) { 517 /* 518 * the code below applies the primary display's inverse transform to the 519 * buffer 520 */ 521 uint32_t invTransformOrient = 522 DisplayDevice::getPrimaryDisplayOrientationTransform(); 523 // calculate the inverse transform 524 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) { 525 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 526 NATIVE_WINDOW_TRANSFORM_FLIP_H; 527 } 528 // and apply to the current transform 529 invTransform = (Transform(invTransformOrient) * Transform(invTransform)) 530 .getOrientation(); 531 } 532 533 int winWidth = s.active.w; 534 int winHeight = s.active.h; 535 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 536 // If the activeCrop has been rotate the ends are rotated but not 537 // the space itself so when transforming ends back we can't rely on 538 // a modification of the axes of rotation. To account for this we 539 // need to reorient the inverse rotation in terms of the current 540 // axes of rotation. 541 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0; 542 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0; 543 if (is_h_flipped == is_v_flipped) { 544 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 545 NATIVE_WINDOW_TRANSFORM_FLIP_H; 546 } 547 winWidth = s.active.h; 548 winHeight = s.active.w; 549 } 550 const Rect winCrop = activeCrop.transform( 551 invTransform, s.active.w, s.active.h); 552 553 // below, crop is intersected with winCrop expressed in crop's coordinate space 554 float xScale = crop.getWidth() / float(winWidth); 555 float yScale = crop.getHeight() / float(winHeight); 556 557 float insetL = winCrop.left * xScale; 558 float insetT = winCrop.top * yScale; 559 float insetR = (winWidth - winCrop.right ) * xScale; 560 float insetB = (winHeight - winCrop.bottom) * yScale; 561 562 crop.left += insetL; 563 crop.top += insetT; 564 crop.right -= insetR; 565 crop.bottom -= insetB; 566 567 return crop; 568} 569 570#ifdef USE_HWC2 571void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice, uint32_t z) 572#else 573void Layer::setGeometry( 574 const sp<const DisplayDevice>& hw, 575 HWComposer::HWCLayerInterface& layer) 576#endif 577{ 578#ifdef USE_HWC2 579 const auto hwcId = displayDevice->getHwcDisplayId(); 580 auto& hwcInfo = mHwcLayers[hwcId]; 581#else 582 layer.setDefaultState(); 583#endif 584 585 // enable this layer 586#ifdef USE_HWC2 587 hwcInfo.forceClientComposition = false; 588 589 if (isSecure() && !displayDevice->isSecure()) { 590 hwcInfo.forceClientComposition = true; 591 } 592 593 auto& hwcLayer = hwcInfo.layer; 594#else 595 layer.setSkip(false); 596 597 if (isSecure() && !hw->isSecure()) { 598 layer.setSkip(true); 599 } 600#endif 601 602 // this gives us only the "orientation" component of the transform 603 const State& s(getDrawingState()); 604#ifdef USE_HWC2 605 auto blendMode = HWC2::BlendMode::None; 606 if (!isOpaque(s) || getAlpha() != 1.0f) { 607 blendMode = mPremultipliedAlpha ? 608 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage; 609 } 610 auto error = hwcLayer->setBlendMode(blendMode); 611 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:" 612 " %s (%d)", mName.string(), to_string(blendMode).c_str(), 613 to_string(error).c_str(), static_cast<int32_t>(error)); 614#else 615 if (!isOpaque(s) || getAlpha() != 0xFF) { 616 layer.setBlending(mPremultipliedAlpha ? 617 HWC_BLENDING_PREMULT : 618 HWC_BLENDING_COVERAGE); 619 } 620#endif 621 622 // apply the layer's transform, followed by the display's global transform 623 // here we're guaranteed that the layer's transform preserves rects 624 Region activeTransparentRegion(s.activeTransparentRegion); 625 Transform t = getTransform(); 626 if (!s.crop.isEmpty()) { 627 Rect activeCrop(s.crop); 628 activeCrop = t.transform(activeCrop); 629#ifdef USE_HWC2 630 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) { 631#else 632 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) { 633#endif 634 activeCrop.clear(); 635 } 636 activeCrop = t.inverse().transform(activeCrop, true); 637 // This needs to be here as transform.transform(Rect) computes the 638 // transformed rect and then takes the bounding box of the result before 639 // returning. This means 640 // transform.inverse().transform(transform.transform(Rect)) != Rect 641 // in which case we need to make sure the final rect is clipped to the 642 // display bounds. 643 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) { 644 activeCrop.clear(); 645 } 646 // mark regions outside the crop as transparent 647 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top)); 648 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom, 649 s.active.w, s.active.h)); 650 activeTransparentRegion.orSelf(Rect(0, activeCrop.top, 651 activeCrop.left, activeCrop.bottom)); 652 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top, 653 s.active.w, activeCrop.bottom)); 654 } 655 656 Rect frame(t.transform(computeBounds(activeTransparentRegion))); 657 if (!s.finalCrop.isEmpty()) { 658 if(!frame.intersect(s.finalCrop, &frame)) { 659 frame.clear(); 660 } 661 } 662#ifdef USE_HWC2 663 if (!frame.intersect(displayDevice->getViewport(), &frame)) { 664 frame.clear(); 665 } 666 const Transform& tr(displayDevice->getTransform()); 667 Rect transformedFrame = tr.transform(frame); 668 error = hwcLayer->setDisplayFrame(transformedFrame); 669 if (error != HWC2::Error::None) { 670 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)", 671 mName.string(), transformedFrame.left, transformedFrame.top, 672 transformedFrame.right, transformedFrame.bottom, 673 to_string(error).c_str(), static_cast<int32_t>(error)); 674 } else { 675 hwcInfo.displayFrame = transformedFrame; 676 } 677 678 FloatRect sourceCrop = computeCrop(displayDevice); 679 error = hwcLayer->setSourceCrop(sourceCrop); 680 if (error != HWC2::Error::None) { 681 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: " 682 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top, 683 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(), 684 static_cast<int32_t>(error)); 685 } else { 686 hwcInfo.sourceCrop = sourceCrop; 687 } 688 689 float alpha = getAlpha(); 690 error = hwcLayer->setPlaneAlpha(alpha); 691 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: " 692 "%s (%d)", mName.string(), alpha, to_string(error).c_str(), 693 static_cast<int32_t>(error)); 694 695 error = hwcLayer->setZOrder(z); 696 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)", 697 mName.string(), z, to_string(error).c_str(), 698 static_cast<int32_t>(error)); 699 700 error = hwcLayer->setInfo(s.type, s.appId); 701 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set info (%d)", 702 mName.string(), static_cast<int32_t>(error)); 703#else 704 if (!frame.intersect(hw->getViewport(), &frame)) { 705 frame.clear(); 706 } 707 const Transform& tr(hw->getTransform()); 708 layer.setFrame(tr.transform(frame)); 709 layer.setCrop(computeCrop(hw)); 710 layer.setPlaneAlpha(getAlpha()); 711#endif 712 713 /* 714 * Transformations are applied in this order: 715 * 1) buffer orientation/flip/mirror 716 * 2) state transformation (window manager) 717 * 3) layer orientation (screen orientation) 718 * (NOTE: the matrices are multiplied in reverse order) 719 */ 720 721 const Transform bufferOrientation(mCurrentTransform); 722 Transform transform(tr * t * bufferOrientation); 723 724 if (getTransformToDisplayInverse()) { 725 /* 726 * the code below applies the primary display's inverse transform to the 727 * buffer 728 */ 729 uint32_t invTransform = 730 DisplayDevice::getPrimaryDisplayOrientationTransform(); 731 // calculate the inverse transform 732 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 733 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 734 NATIVE_WINDOW_TRANSFORM_FLIP_H; 735 } 736 737 /* 738 * Here we cancel out the orientation component of the WM transform. 739 * The scaling and translate components are already included in our bounds 740 * computation so it's enough to just omit it in the composition. 741 * See comment in onDraw with ref to b/36727915 for why. 742 */ 743 transform = Transform(invTransform) * tr * bufferOrientation; 744 } 745 746 // this gives us only the "orientation" component of the transform 747 const uint32_t orientation = transform.getOrientation(); 748#ifdef USE_HWC2 749 if (orientation & Transform::ROT_INVALID) { 750 // we can only handle simple transformation 751 hwcInfo.forceClientComposition = true; 752 } else { 753 auto transform = static_cast<HWC2::Transform>(orientation); 754 auto error = hwcLayer->setTransform(transform); 755 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: " 756 "%s (%d)", mName.string(), to_string(transform).c_str(), 757 to_string(error).c_str(), static_cast<int32_t>(error)); 758 } 759#else 760 if (orientation & Transform::ROT_INVALID) { 761 // we can only handle simple transformation 762 layer.setSkip(true); 763 } else { 764 layer.setTransform(orientation); 765 } 766#endif 767} 768 769#ifdef USE_HWC2 770void Layer::forceClientComposition(int32_t hwcId) { 771 if (mHwcLayers.count(hwcId) == 0) { 772 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId); 773 return; 774 } 775 776 mHwcLayers[hwcId].forceClientComposition = true; 777} 778 779void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) { 780 // Apply this display's projection's viewport to the visible region 781 // before giving it to the HWC HAL. 782 const Transform& tr = displayDevice->getTransform(); 783 const auto& viewport = displayDevice->getViewport(); 784 Region visible = tr.transform(visibleRegion.intersect(viewport)); 785 auto hwcId = displayDevice->getHwcDisplayId(); 786 auto& hwcInfo = mHwcLayers[hwcId]; 787 auto& hwcLayer = hwcInfo.layer; 788 auto error = hwcLayer->setVisibleRegion(visible); 789 if (error != HWC2::Error::None) { 790 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(), 791 to_string(error).c_str(), static_cast<int32_t>(error)); 792 visible.dump(LOG_TAG); 793 } 794 795 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion); 796 if (error != HWC2::Error::None) { 797 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(), 798 to_string(error).c_str(), static_cast<int32_t>(error)); 799 surfaceDamageRegion.dump(LOG_TAG); 800 } 801 802 // Sideband layers 803 if (mSidebandStream.get()) { 804 setCompositionType(hwcId, HWC2::Composition::Sideband); 805 ALOGV("[%s] Requesting Sideband composition", mName.string()); 806 error = hwcLayer->setSidebandStream(mSidebandStream->handle()); 807 if (error != HWC2::Error::None) { 808 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", 809 mName.string(), mSidebandStream->handle(), 810 to_string(error).c_str(), static_cast<int32_t>(error)); 811 } 812 return; 813 } 814 815 // Client layers 816 if (hwcInfo.forceClientComposition || 817 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) { 818 ALOGV("[%s] Requesting Client composition", mName.string()); 819 setCompositionType(hwcId, HWC2::Composition::Client); 820 return; 821 } 822 823 // SolidColor layers 824 if (mActiveBuffer == nullptr) { 825 setCompositionType(hwcId, HWC2::Composition::SolidColor); 826 827 // For now, we only support black for DimLayer 828 error = hwcLayer->setColor({0, 0, 0, 255}); 829 if (error != HWC2::Error::None) { 830 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(), 831 to_string(error).c_str(), static_cast<int32_t>(error)); 832 } 833 834 // Clear out the transform, because it doesn't make sense absent a 835 // source buffer 836 error = hwcLayer->setTransform(HWC2::Transform::None); 837 if (error != HWC2::Error::None) { 838 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(), 839 to_string(error).c_str(), static_cast<int32_t>(error)); 840 } 841 842 return; 843 } 844 845 // Device or Cursor layers 846 if (mPotentialCursor) { 847 ALOGV("[%s] Requesting Cursor composition", mName.string()); 848 setCompositionType(hwcId, HWC2::Composition::Cursor); 849 } else { 850 ALOGV("[%s] Requesting Device composition", mName.string()); 851 setCompositionType(hwcId, HWC2::Composition::Device); 852 } 853 854 ALOGV("setPerFrameData: dataspace = %d", mCurrentState.dataSpace); 855 error = hwcLayer->setDataspace(mCurrentState.dataSpace); 856 if (error != HWC2::Error::None) { 857 ALOGE("[%s] Failed to set dataspace %d: %s (%d)", mName.string(), 858 mCurrentState.dataSpace, to_string(error).c_str(), 859 static_cast<int32_t>(error)); 860 } 861 862 uint32_t hwcSlot = 0; 863 sp<GraphicBuffer> hwcBuffer; 864 hwcInfo.bufferCache.getHwcBuffer(mActiveBufferSlot, mActiveBuffer, 865 &hwcSlot, &hwcBuffer); 866 867 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 868 error = hwcLayer->setBuffer(hwcSlot, hwcBuffer, acquireFence); 869 if (error != HWC2::Error::None) { 870 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), 871 mActiveBuffer->handle, to_string(error).c_str(), 872 static_cast<int32_t>(error)); 873 } 874} 875 876android_dataspace Layer::getDataSpace() const { 877 return mCurrentState.dataSpace; 878} 879#else 880void Layer::setPerFrameData(const sp<const DisplayDevice>& hw, 881 HWComposer::HWCLayerInterface& layer) { 882 // we have to set the visible region on every frame because 883 // we currently free it during onLayerDisplayed(), which is called 884 // after HWComposer::commit() -- every frame. 885 // Apply this display's projection's viewport to the visible region 886 // before giving it to the HWC HAL. 887 const Transform& tr = hw->getTransform(); 888 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport())); 889 layer.setVisibleRegionScreen(visible); 890 layer.setSurfaceDamage(surfaceDamageRegion); 891 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER); 892 893 if (mSidebandStream.get()) { 894 layer.setSidebandStream(mSidebandStream); 895 } else { 896 // NOTE: buffer can be NULL if the client never drew into this 897 // layer yet, or if we ran out of memory 898 layer.setBuffer(mActiveBuffer); 899 } 900} 901#endif 902 903#ifdef USE_HWC2 904void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) { 905 auto hwcId = displayDevice->getHwcDisplayId(); 906 if (mHwcLayers.count(hwcId) == 0 || 907 getCompositionType(hwcId) != HWC2::Composition::Cursor) { 908 return; 909 } 910 911 // This gives us only the "orientation" component of the transform 912 const State& s(getCurrentState()); 913 914 // Apply the layer's transform, followed by the display's global transform 915 // Here we're guaranteed that the layer's transform preserves rects 916 Rect win(s.active.w, s.active.h); 917 if (!s.crop.isEmpty()) { 918 win.intersect(s.crop, &win); 919 } 920 // Subtract the transparent region and snap to the bounds 921 Rect bounds = reduce(win, s.activeTransparentRegion); 922 Rect frame(getTransform().transform(bounds)); 923 frame.intersect(displayDevice->getViewport(), &frame); 924 if (!s.finalCrop.isEmpty()) { 925 frame.intersect(s.finalCrop, &frame); 926 } 927 auto& displayTransform(displayDevice->getTransform()); 928 auto position = displayTransform.transform(frame); 929 930 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left, 931 position.top); 932 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position " 933 "to (%d, %d): %s (%d)", mName.string(), position.left, 934 position.top, to_string(error).c_str(), 935 static_cast<int32_t>(error)); 936} 937#else 938void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */, 939 HWComposer::HWCLayerInterface& layer) { 940 int fenceFd = -1; 941 942 // TODO: there is a possible optimization here: we only need to set the 943 // acquire fence the first time a new buffer is acquired on EACH display. 944 945 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) { 946 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence(); 947 if (fence->isValid()) { 948 fenceFd = fence->dup(); 949 if (fenceFd == -1) { 950 ALOGW("failed to dup layer fence, skipping sync: %d", errno); 951 } 952 } 953 } 954 layer.setAcquireFenceFd(fenceFd); 955} 956 957Rect Layer::getPosition( 958 const sp<const DisplayDevice>& hw) 959{ 960 // this gives us only the "orientation" component of the transform 961 const State& s(getCurrentState()); 962 963 // apply the layer's transform, followed by the display's global transform 964 // here we're guaranteed that the layer's transform preserves rects 965 Rect win(s.active.w, s.active.h); 966 if (!s.crop.isEmpty()) { 967 win.intersect(s.crop, &win); 968 } 969 // subtract the transparent region and snap to the bounds 970 Rect bounds = reduce(win, s.activeTransparentRegion); 971 Rect frame(getTransform().transform(bounds)); 972 frame.intersect(hw->getViewport(), &frame); 973 if (!s.finalCrop.isEmpty()) { 974 frame.intersect(s.finalCrop, &frame); 975 } 976 const Transform& tr(hw->getTransform()); 977 return Rect(tr.transform(frame)); 978} 979#endif 980 981// --------------------------------------------------------------------------- 982// drawing... 983// --------------------------------------------------------------------------- 984 985void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const { 986 onDraw(hw, clip, false); 987} 988 989void Layer::draw(const sp<const DisplayDevice>& hw, 990 bool useIdentityTransform) const { 991 onDraw(hw, Region(hw->bounds()), useIdentityTransform); 992} 993 994void Layer::draw(const sp<const DisplayDevice>& hw) const { 995 onDraw(hw, Region(hw->bounds()), false); 996} 997 998static constexpr mat4 inverseOrientation(uint32_t transform) { 999 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1); 1000 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1); 1001 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1); 1002 mat4 tr; 1003 1004 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 1005 tr = tr * rot90; 1006 } 1007 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) { 1008 tr = tr * flipH; 1009 } 1010 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) { 1011 tr = tr * flipV; 1012 } 1013 return inverse(tr); 1014} 1015 1016/* 1017 * onDraw will draw the current layer onto the presentable buffer 1018 */ 1019void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip, 1020 bool useIdentityTransform) const 1021{ 1022 ATRACE_CALL(); 1023 1024 if (CC_UNLIKELY(mActiveBuffer == 0)) { 1025 // the texture has not been created yet, this Layer has 1026 // in fact never been drawn into. This happens frequently with 1027 // SurfaceView because the WindowManager can't know when the client 1028 // has drawn the first time. 1029 1030 // If there is nothing under us, we paint the screen in black, otherwise 1031 // we just skip this update. 1032 1033 // figure out if there is something below us 1034 Region under; 1035 bool finished = false; 1036 mFlinger->mDrawingState.layersSortedByZ.traverseInZOrder([&](Layer* layer) { 1037 if (finished || layer == static_cast<Layer const*>(this)) { 1038 finished = true; 1039 return; 1040 } 1041 under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); 1042 }); 1043 // if not everything below us is covered, we plug the holes! 1044 Region holes(clip.subtract(under)); 1045 if (!holes.isEmpty()) { 1046 clearWithOpenGL(hw, 0, 0, 0, 1); 1047 } 1048 return; 1049 } 1050 1051 // Bind the current buffer to the GL texture, and wait for it to be 1052 // ready for us to draw into. 1053 status_t err = mSurfaceFlingerConsumer->bindTextureImage(); 1054 if (err != NO_ERROR) { 1055 ALOGW("onDraw: bindTextureImage failed (err=%d)", err); 1056 // Go ahead and draw the buffer anyway; no matter what we do the screen 1057 // is probably going to have something visibly wrong. 1058 } 1059 1060 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure()); 1061 1062 RenderEngine& engine(mFlinger->getRenderEngine()); 1063 1064 if (!blackOutLayer) { 1065 // TODO: we could be more subtle with isFixedSize() 1066 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize(); 1067 1068 // Query the texture matrix given our current filtering mode. 1069 float textureMatrix[16]; 1070 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering); 1071 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix); 1072 1073 if (getTransformToDisplayInverse()) { 1074 1075 /* 1076 * the code below applies the primary display's inverse transform to 1077 * the texture transform 1078 */ 1079 uint32_t transform = 1080 DisplayDevice::getPrimaryDisplayOrientationTransform(); 1081 mat4 tr = inverseOrientation(transform); 1082 1083 /** 1084 * TODO(b/36727915): This is basically a hack. 1085 * 1086 * Ensure that regardless of the parent transformation, 1087 * this buffer is always transformed from native display 1088 * orientation to display orientation. For example, in the case 1089 * of a camera where the buffer remains in native orientation, 1090 * we want the pixels to always be upright. 1091 */ 1092 if (getParent() != nullptr) { 1093 const auto parentTransform = getParent()->getTransform(); 1094 tr = tr * inverseOrientation(parentTransform.getOrientation()); 1095 } 1096 1097 // and finally apply it to the original texture matrix 1098 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr); 1099 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix)); 1100 } 1101 1102 // Set things up for texturing. 1103 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight()); 1104 mTexture.setFiltering(useFiltering); 1105 mTexture.setMatrix(textureMatrix); 1106 1107 engine.setupLayerTexturing(mTexture); 1108 } else { 1109 engine.setupLayerBlackedOut(); 1110 } 1111 drawWithOpenGL(hw, useIdentityTransform); 1112 engine.disableTexturing(); 1113} 1114 1115 1116void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw, 1117 float red, float green, float blue, 1118 float alpha) const 1119{ 1120 RenderEngine& engine(mFlinger->getRenderEngine()); 1121 computeGeometry(hw, mMesh, false); 1122 engine.setupFillWithColor(red, green, blue, alpha); 1123 engine.drawMesh(mMesh); 1124} 1125 1126void Layer::clearWithOpenGL( 1127 const sp<const DisplayDevice>& hw) const { 1128 clearWithOpenGL(hw, 0,0,0,0); 1129} 1130 1131void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw, 1132 bool useIdentityTransform) const { 1133 const State& s(getDrawingState()); 1134 1135 computeGeometry(hw, mMesh, useIdentityTransform); 1136 1137 /* 1138 * NOTE: the way we compute the texture coordinates here produces 1139 * different results than when we take the HWC path -- in the later case 1140 * the "source crop" is rounded to texel boundaries. 1141 * This can produce significantly different results when the texture 1142 * is scaled by a large amount. 1143 * 1144 * The GL code below is more logical (imho), and the difference with 1145 * HWC is due to a limitation of the HWC API to integers -- a question 1146 * is suspend is whether we should ignore this problem or revert to 1147 * GL composition when a buffer scaling is applied (maybe with some 1148 * minimal value)? Or, we could make GL behave like HWC -- but this feel 1149 * like more of a hack. 1150 */ 1151 Rect win(computeBounds()); 1152 1153 Transform t = getTransform(); 1154 if (!s.finalCrop.isEmpty()) { 1155 win = t.transform(win); 1156 if (!win.intersect(s.finalCrop, &win)) { 1157 win.clear(); 1158 } 1159 win = t.inverse().transform(win); 1160 if (!win.intersect(computeBounds(), &win)) { 1161 win.clear(); 1162 } 1163 } 1164 1165 float left = float(win.left) / float(s.active.w); 1166 float top = float(win.top) / float(s.active.h); 1167 float right = float(win.right) / float(s.active.w); 1168 float bottom = float(win.bottom) / float(s.active.h); 1169 1170 // TODO: we probably want to generate the texture coords with the mesh 1171 // here we assume that we only have 4 vertices 1172 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>()); 1173 texCoords[0] = vec2(left, 1.0f - top); 1174 texCoords[1] = vec2(left, 1.0f - bottom); 1175 texCoords[2] = vec2(right, 1.0f - bottom); 1176 texCoords[3] = vec2(right, 1.0f - top); 1177 1178 RenderEngine& engine(mFlinger->getRenderEngine()); 1179 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), getAlpha()); 1180#ifdef USE_HWC2 1181 engine.setSourceDataSpace(mCurrentState.dataSpace); 1182#endif 1183 engine.drawMesh(mMesh); 1184 engine.disableBlending(); 1185} 1186 1187#ifdef USE_HWC2 1188void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type, 1189 bool callIntoHwc) { 1190 if (mHwcLayers.count(hwcId) == 0) { 1191 ALOGE("setCompositionType called without a valid HWC layer"); 1192 return; 1193 } 1194 auto& hwcInfo = mHwcLayers[hwcId]; 1195 auto& hwcLayer = hwcInfo.layer; 1196 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(), 1197 to_string(type).c_str(), static_cast<int>(callIntoHwc)); 1198 if (hwcInfo.compositionType != type) { 1199 ALOGV(" actually setting"); 1200 hwcInfo.compositionType = type; 1201 if (callIntoHwc) { 1202 auto error = hwcLayer->setCompositionType(type); 1203 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set " 1204 "composition type %s: %s (%d)", mName.string(), 1205 to_string(type).c_str(), to_string(error).c_str(), 1206 static_cast<int32_t>(error)); 1207 } 1208 } 1209} 1210 1211HWC2::Composition Layer::getCompositionType(int32_t hwcId) const { 1212 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) { 1213 // If we're querying the composition type for a display that does not 1214 // have a HWC counterpart, then it will always be Client 1215 return HWC2::Composition::Client; 1216 } 1217 if (mHwcLayers.count(hwcId) == 0) { 1218 ALOGE("getCompositionType called with an invalid HWC layer"); 1219 return HWC2::Composition::Invalid; 1220 } 1221 return mHwcLayers.at(hwcId).compositionType; 1222} 1223 1224void Layer::setClearClientTarget(int32_t hwcId, bool clear) { 1225 if (mHwcLayers.count(hwcId) == 0) { 1226 ALOGE("setClearClientTarget called without a valid HWC layer"); 1227 return; 1228 } 1229 mHwcLayers[hwcId].clearClientTarget = clear; 1230} 1231 1232bool Layer::getClearClientTarget(int32_t hwcId) const { 1233 if (mHwcLayers.count(hwcId) == 0) { 1234 ALOGE("getClearClientTarget called without a valid HWC layer"); 1235 return false; 1236 } 1237 return mHwcLayers.at(hwcId).clearClientTarget; 1238} 1239#endif 1240 1241uint32_t Layer::getProducerStickyTransform() const { 1242 int producerStickyTransform = 0; 1243 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform); 1244 if (ret != OK) { 1245 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__, 1246 strerror(-ret), ret); 1247 return 0; 1248 } 1249 return static_cast<uint32_t>(producerStickyTransform); 1250} 1251 1252bool Layer::latchUnsignaledBuffers() { 1253 static bool propertyLoaded = false; 1254 static bool latch = false; 1255 static std::mutex mutex; 1256 std::lock_guard<std::mutex> lock(mutex); 1257 if (!propertyLoaded) { 1258 char value[PROPERTY_VALUE_MAX] = {}; 1259 property_get("debug.sf.latch_unsignaled", value, "0"); 1260 latch = atoi(value); 1261 propertyLoaded = true; 1262 } 1263 return latch; 1264} 1265 1266uint64_t Layer::getHeadFrameNumber() const { 1267 Mutex::Autolock lock(mQueueItemLock); 1268 if (!mQueueItems.empty()) { 1269 return mQueueItems[0].mFrameNumber; 1270 } else { 1271 return mCurrentFrameNumber; 1272 } 1273} 1274 1275bool Layer::headFenceHasSignaled() const { 1276#ifdef USE_HWC2 1277 if (latchUnsignaledBuffers()) { 1278 return true; 1279 } 1280 1281 Mutex::Autolock lock(mQueueItemLock); 1282 if (mQueueItems.empty()) { 1283 return true; 1284 } 1285 if (mQueueItems[0].mIsDroppable) { 1286 // Even though this buffer's fence may not have signaled yet, it could 1287 // be replaced by another buffer before it has a chance to, which means 1288 // that it's possible to get into a situation where a buffer is never 1289 // able to be latched. To avoid this, grab this buffer anyway. 1290 return true; 1291 } 1292 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX; 1293#else 1294 return true; 1295#endif 1296} 1297 1298bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) { 1299 if (point->getFrameNumber() <= mCurrentFrameNumber) { 1300 // Don't bother with a SyncPoint, since we've already latched the 1301 // relevant frame 1302 return false; 1303 } 1304 1305 Mutex::Autolock lock(mLocalSyncPointMutex); 1306 mLocalSyncPoints.push_back(point); 1307 return true; 1308} 1309 1310void Layer::setFiltering(bool filtering) { 1311 mFiltering = filtering; 1312} 1313 1314bool Layer::getFiltering() const { 1315 return mFiltering; 1316} 1317 1318// As documented in libhardware header, formats in the range 1319// 0x100 - 0x1FF are specific to the HAL implementation, and 1320// are known to have no alpha channel 1321// TODO: move definition for device-specific range into 1322// hardware.h, instead of using hard-coded values here. 1323#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 1324 1325bool Layer::getOpacityForFormat(uint32_t format) { 1326 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 1327 return true; 1328 } 1329 switch (format) { 1330 case HAL_PIXEL_FORMAT_RGBA_8888: 1331 case HAL_PIXEL_FORMAT_BGRA_8888: 1332 case HAL_PIXEL_FORMAT_RGBA_FP16: 1333 case HAL_PIXEL_FORMAT_RGBA_1010102: 1334 return false; 1335 } 1336 // in all other case, we have no blending (also for unknown formats) 1337 return true; 1338} 1339 1340// ---------------------------------------------------------------------------- 1341// local state 1342// ---------------------------------------------------------------------------- 1343 1344static void boundPoint(vec2* point, const Rect& crop) { 1345 if (point->x < crop.left) { 1346 point->x = crop.left; 1347 } 1348 if (point->x > crop.right) { 1349 point->x = crop.right; 1350 } 1351 if (point->y < crop.top) { 1352 point->y = crop.top; 1353 } 1354 if (point->y > crop.bottom) { 1355 point->y = crop.bottom; 1356 } 1357} 1358 1359void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh, 1360 bool useIdentityTransform) const 1361{ 1362 const Layer::State& s(getDrawingState()); 1363 const Transform hwTransform(hw->getTransform()); 1364 const uint32_t hw_h = hw->getHeight(); 1365 Rect win = computeBounds(); 1366 1367 vec2 lt = vec2(win.left, win.top); 1368 vec2 lb = vec2(win.left, win.bottom); 1369 vec2 rb = vec2(win.right, win.bottom); 1370 vec2 rt = vec2(win.right, win.top); 1371 1372 Transform layerTransform = getTransform(); 1373 if (!useIdentityTransform) { 1374 lt = layerTransform.transform(lt); 1375 lb = layerTransform.transform(lb); 1376 rb = layerTransform.transform(rb); 1377 rt = layerTransform.transform(rt); 1378 } 1379 1380 if (!s.finalCrop.isEmpty()) { 1381 boundPoint(<, s.finalCrop); 1382 boundPoint(&lb, s.finalCrop); 1383 boundPoint(&rb, s.finalCrop); 1384 boundPoint(&rt, s.finalCrop); 1385 } 1386 1387 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>()); 1388 position[0] = hwTransform.transform(lt); 1389 position[1] = hwTransform.transform(lb); 1390 position[2] = hwTransform.transform(rb); 1391 position[3] = hwTransform.transform(rt); 1392 for (size_t i=0 ; i<4 ; i++) { 1393 position[i].y = hw_h - position[i].y; 1394 } 1395} 1396 1397bool Layer::isOpaque(const Layer::State& s) const 1398{ 1399 // if we don't have a buffer yet, we're translucent regardless of the 1400 // layer's opaque flag. 1401 if (mActiveBuffer == 0) { 1402 return false; 1403 } 1404 1405 // if the layer has the opaque flag, then we're always opaque, 1406 // otherwise we use the current buffer's format. 1407 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity; 1408} 1409 1410bool Layer::isSecure() const 1411{ 1412 const Layer::State& s(mDrawingState); 1413 return (s.flags & layer_state_t::eLayerSecure); 1414} 1415 1416bool Layer::isProtected() const 1417{ 1418 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 1419 return (activeBuffer != 0) && 1420 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 1421} 1422 1423bool Layer::isFixedSize() const { 1424 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1425} 1426 1427bool Layer::isCropped() const { 1428 return !mCurrentCrop.isEmpty(); 1429} 1430 1431bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const { 1432 return mNeedsFiltering || hw->needsFiltering(); 1433} 1434 1435void Layer::setVisibleRegion(const Region& visibleRegion) { 1436 // always called from main thread 1437 this->visibleRegion = visibleRegion; 1438} 1439 1440void Layer::setCoveredRegion(const Region& coveredRegion) { 1441 // always called from main thread 1442 this->coveredRegion = coveredRegion; 1443} 1444 1445void Layer::setVisibleNonTransparentRegion(const Region& 1446 setVisibleNonTransparentRegion) { 1447 // always called from main thread 1448 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion; 1449} 1450 1451// ---------------------------------------------------------------------------- 1452// transaction 1453// ---------------------------------------------------------------------------- 1454 1455void Layer::pushPendingState() { 1456 if (!mCurrentState.modified) { 1457 return; 1458 } 1459 1460 // If this transaction is waiting on the receipt of a frame, generate a sync 1461 // point and send it to the remote layer. 1462 if (mCurrentState.barrierLayer != nullptr) { 1463 sp<Layer> barrierLayer = mCurrentState.barrierLayer.promote(); 1464 if (barrierLayer == nullptr) { 1465 ALOGE("[%s] Unable to promote barrier Layer.", mName.string()); 1466 // If we can't promote the layer we are intended to wait on, 1467 // then it is expired or otherwise invalid. Allow this transaction 1468 // to be applied as per normal (no synchronization). 1469 mCurrentState.barrierLayer = nullptr; 1470 } else { 1471 auto syncPoint = std::make_shared<SyncPoint>( 1472 mCurrentState.frameNumber); 1473 if (barrierLayer->addSyncPoint(syncPoint)) { 1474 mRemoteSyncPoints.push_back(std::move(syncPoint)); 1475 } else { 1476 // We already missed the frame we're supposed to synchronize 1477 // on, so go ahead and apply the state update 1478 mCurrentState.barrierLayer = nullptr; 1479 } 1480 } 1481 1482 // Wake us up to check if the frame has been received 1483 setTransactionFlags(eTransactionNeeded); 1484 mFlinger->setTransactionFlags(eTraversalNeeded); 1485 } 1486 mPendingStates.push_back(mCurrentState); 1487} 1488 1489void Layer::popPendingState(State* stateToCommit) { 1490 auto oldFlags = stateToCommit->flags; 1491 *stateToCommit = mPendingStates[0]; 1492 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) | 1493 (stateToCommit->flags & stateToCommit->mask); 1494 1495 mPendingStates.removeAt(0); 1496} 1497 1498bool Layer::applyPendingStates(State* stateToCommit) { 1499 bool stateUpdateAvailable = false; 1500 while (!mPendingStates.empty()) { 1501 if (mPendingStates[0].barrierLayer != nullptr) { 1502 if (mRemoteSyncPoints.empty()) { 1503 // If we don't have a sync point for this, apply it anyway. It 1504 // will be visually wrong, but it should keep us from getting 1505 // into too much trouble. 1506 ALOGE("[%s] No local sync point found", mName.string()); 1507 popPendingState(stateToCommit); 1508 stateUpdateAvailable = true; 1509 continue; 1510 } 1511 1512 if (mRemoteSyncPoints.front()->getFrameNumber() != 1513 mPendingStates[0].frameNumber) { 1514 ALOGE("[%s] Unexpected sync point frame number found", 1515 mName.string()); 1516 1517 // Signal our end of the sync point and then dispose of it 1518 mRemoteSyncPoints.front()->setTransactionApplied(); 1519 mRemoteSyncPoints.pop_front(); 1520 continue; 1521 } 1522 1523 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 1524 // Apply the state update 1525 popPendingState(stateToCommit); 1526 stateUpdateAvailable = true; 1527 1528 // Signal our end of the sync point and then dispose of it 1529 mRemoteSyncPoints.front()->setTransactionApplied(); 1530 mRemoteSyncPoints.pop_front(); 1531 } else { 1532 break; 1533 } 1534 } else { 1535 popPendingState(stateToCommit); 1536 stateUpdateAvailable = true; 1537 } 1538 } 1539 1540 // If we still have pending updates, wake SurfaceFlinger back up and point 1541 // it at this layer so we can process them 1542 if (!mPendingStates.empty()) { 1543 setTransactionFlags(eTransactionNeeded); 1544 mFlinger->setTransactionFlags(eTraversalNeeded); 1545 } 1546 1547 mCurrentState.modified = false; 1548 return stateUpdateAvailable; 1549} 1550 1551void Layer::notifyAvailableFrames() { 1552 auto headFrameNumber = getHeadFrameNumber(); 1553 bool headFenceSignaled = headFenceHasSignaled(); 1554 Mutex::Autolock lock(mLocalSyncPointMutex); 1555 for (auto& point : mLocalSyncPoints) { 1556 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) { 1557 point->setFrameAvailable(); 1558 } 1559 } 1560} 1561 1562uint32_t Layer::doTransaction(uint32_t flags) { 1563 ATRACE_CALL(); 1564 1565 pushPendingState(); 1566 Layer::State c = getCurrentState(); 1567 if (!applyPendingStates(&c)) { 1568 return 0; 1569 } 1570 1571 const Layer::State& s(getDrawingState()); 1572 1573 const bool sizeChanged = (c.requested.w != s.requested.w) || 1574 (c.requested.h != s.requested.h); 1575 1576 if (sizeChanged) { 1577 // the size changed, we need to ask our client to request a new buffer 1578 ALOGD_IF(DEBUG_RESIZE, 1579 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1580 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1581 " requested={ wh={%4u,%4u} }}\n" 1582 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1583 " requested={ wh={%4u,%4u} }}\n", 1584 this, getName().string(), mCurrentTransform, 1585 getEffectiveScalingMode(), 1586 c.active.w, c.active.h, 1587 c.crop.left, 1588 c.crop.top, 1589 c.crop.right, 1590 c.crop.bottom, 1591 c.crop.getWidth(), 1592 c.crop.getHeight(), 1593 c.requested.w, c.requested.h, 1594 s.active.w, s.active.h, 1595 s.crop.left, 1596 s.crop.top, 1597 s.crop.right, 1598 s.crop.bottom, 1599 s.crop.getWidth(), 1600 s.crop.getHeight(), 1601 s.requested.w, s.requested.h); 1602 1603 // record the new size, form this point on, when the client request 1604 // a buffer, it'll get the new size. 1605 mSurfaceFlingerConsumer->setDefaultBufferSize( 1606 c.requested.w, c.requested.h); 1607 } 1608 1609 const bool resizePending = (c.requested.w != c.active.w) || 1610 (c.requested.h != c.active.h); 1611 if (!isFixedSize()) { 1612 if (resizePending && mSidebandStream == NULL) { 1613 // don't let Layer::doTransaction update the drawing state 1614 // if we have a pending resize, unless we are in fixed-size mode. 1615 // the drawing state will be updated only once we receive a buffer 1616 // with the correct size. 1617 // 1618 // in particular, we want to make sure the clip (which is part 1619 // of the geometry state) is latched together with the size but is 1620 // latched immediately when no resizing is involved. 1621 // 1622 // If a sideband stream is attached, however, we want to skip this 1623 // optimization so that transactions aren't missed when a buffer 1624 // never arrives 1625 1626 flags |= eDontUpdateGeometryState; 1627 } 1628 } 1629 1630 // always set active to requested, unless we're asked not to 1631 // this is used by Layer, which special cases resizes. 1632 if (flags & eDontUpdateGeometryState) { 1633 } else { 1634 Layer::State& editCurrentState(getCurrentState()); 1635 if (mFreezePositionUpdates) { 1636 float tx = c.active.transform.tx(); 1637 float ty = c.active.transform.ty(); 1638 c.active = c.requested; 1639 c.active.transform.set(tx, ty); 1640 editCurrentState.active = c.active; 1641 } else { 1642 editCurrentState.active = editCurrentState.requested; 1643 c.active = c.requested; 1644 } 1645 } 1646 1647 if (s.active != c.active) { 1648 // invalidate and recompute the visible regions if needed 1649 flags |= Layer::eVisibleRegion; 1650 } 1651 1652 if (c.sequence != s.sequence) { 1653 // invalidate and recompute the visible regions if needed 1654 flags |= eVisibleRegion; 1655 this->contentDirty = true; 1656 1657 // we may use linear filtering, if the matrix scales us 1658 const uint8_t type = c.active.transform.getType(); 1659 mNeedsFiltering = (!c.active.transform.preserveRects() || 1660 (type >= Transform::SCALE)); 1661 } 1662 1663 // If the layer is hidden, signal and clear out all local sync points so 1664 // that transactions for layers depending on this layer's frames becoming 1665 // visible are not blocked 1666 if (c.flags & layer_state_t::eLayerHidden) { 1667 clearSyncPoints(); 1668 } 1669 1670 // Commit the transaction 1671 commitTransaction(c); 1672 return flags; 1673} 1674 1675void Layer::commitTransaction(const State& stateToCommit) { 1676 mDrawingState = stateToCommit; 1677} 1678 1679uint32_t Layer::getTransactionFlags(uint32_t flags) { 1680 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1681} 1682 1683uint32_t Layer::setTransactionFlags(uint32_t flags) { 1684 return android_atomic_or(flags, &mTransactionFlags); 1685} 1686 1687bool Layer::setPosition(float x, float y, bool immediate) { 1688 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y) 1689 return false; 1690 mCurrentState.sequence++; 1691 1692 // We update the requested and active position simultaneously because 1693 // we want to apply the position portion of the transform matrix immediately, 1694 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1695 mCurrentState.requested.transform.set(x, y); 1696 if (immediate && !mFreezePositionUpdates) { 1697 mCurrentState.active.transform.set(x, y); 1698 } 1699 mFreezePositionUpdates = mFreezePositionUpdates || !immediate; 1700 1701 mCurrentState.modified = true; 1702 setTransactionFlags(eTransactionNeeded); 1703 return true; 1704} 1705 1706bool Layer::setChildLayer(const sp<Layer>& childLayer, int32_t z) { 1707 ssize_t idx = mCurrentChildren.indexOf(childLayer); 1708 if (idx < 0) { 1709 return false; 1710 } 1711 if (childLayer->setLayer(z)) { 1712 mCurrentChildren.removeAt(idx); 1713 mCurrentChildren.add(childLayer); 1714 } 1715 return true; 1716} 1717 1718bool Layer::setLayer(int32_t z) { 1719 if (mCurrentState.z == z) 1720 return false; 1721 mCurrentState.sequence++; 1722 mCurrentState.z = z; 1723 mCurrentState.modified = true; 1724 1725 // Discard all relative layering. 1726 if (mCurrentState.zOrderRelativeOf != nullptr) { 1727 sp<Layer> strongRelative = mCurrentState.zOrderRelativeOf.promote(); 1728 if (strongRelative != nullptr) { 1729 strongRelative->removeZOrderRelative(this); 1730 } 1731 mCurrentState.zOrderRelativeOf = nullptr; 1732 } 1733 setTransactionFlags(eTransactionNeeded); 1734 return true; 1735} 1736 1737void Layer::removeZOrderRelative(const wp<Layer>& relative) { 1738 mCurrentState.zOrderRelatives.remove(relative); 1739 mCurrentState.sequence++; 1740 mCurrentState.modified = true; 1741 setTransactionFlags(eTransactionNeeded); 1742} 1743 1744void Layer::addZOrderRelative(const wp<Layer>& relative) { 1745 mCurrentState.zOrderRelatives.add(relative); 1746 mCurrentState.modified = true; 1747 mCurrentState.sequence++; 1748 setTransactionFlags(eTransactionNeeded); 1749} 1750 1751bool Layer::setRelativeLayer(const sp<IBinder>& relativeToHandle, int32_t z) { 1752 sp<Handle> handle = static_cast<Handle*>(relativeToHandle.get()); 1753 if (handle == nullptr) { 1754 return false; 1755 } 1756 sp<Layer> relative = handle->owner.promote(); 1757 if (relative == nullptr) { 1758 return false; 1759 } 1760 1761 mCurrentState.sequence++; 1762 mCurrentState.modified = true; 1763 mCurrentState.z = z; 1764 1765 mCurrentState.zOrderRelativeOf = relative; 1766 relative->addZOrderRelative(this); 1767 1768 setTransactionFlags(eTransactionNeeded); 1769 1770 return true; 1771} 1772 1773bool Layer::setSize(uint32_t w, uint32_t h) { 1774 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1775 return false; 1776 mCurrentState.requested.w = w; 1777 mCurrentState.requested.h = h; 1778 mCurrentState.modified = true; 1779 setTransactionFlags(eTransactionNeeded); 1780 return true; 1781} 1782#ifdef USE_HWC2 1783bool Layer::setAlpha(float alpha) { 1784#else 1785bool Layer::setAlpha(uint8_t alpha) { 1786#endif 1787 if (mCurrentState.alpha == alpha) 1788 return false; 1789 mCurrentState.sequence++; 1790 mCurrentState.alpha = alpha; 1791 mCurrentState.modified = true; 1792 setTransactionFlags(eTransactionNeeded); 1793 return true; 1794} 1795bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1796 mCurrentState.sequence++; 1797 mCurrentState.requested.transform.set( 1798 matrix.dsdx, matrix.dtdy, matrix.dtdx, matrix.dsdy); 1799 mCurrentState.modified = true; 1800 setTransactionFlags(eTransactionNeeded); 1801 return true; 1802} 1803bool Layer::setTransparentRegionHint(const Region& transparent) { 1804 mCurrentState.requestedTransparentRegion = transparent; 1805 mCurrentState.modified = true; 1806 setTransactionFlags(eTransactionNeeded); 1807 return true; 1808} 1809bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1810 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1811 if (mCurrentState.flags == newFlags) 1812 return false; 1813 mCurrentState.sequence++; 1814 mCurrentState.flags = newFlags; 1815 mCurrentState.mask = mask; 1816 mCurrentState.modified = true; 1817 setTransactionFlags(eTransactionNeeded); 1818 return true; 1819} 1820 1821bool Layer::setCrop(const Rect& crop, bool immediate) { 1822 if (mCurrentState.crop == crop) 1823 return false; 1824 mCurrentState.sequence++; 1825 mCurrentState.requestedCrop = crop; 1826 if (immediate) { 1827 mCurrentState.crop = crop; 1828 } 1829 mCurrentState.modified = true; 1830 setTransactionFlags(eTransactionNeeded); 1831 return true; 1832} 1833 1834bool Layer::setFinalCrop(const Rect& crop, bool immediate) { 1835 if (mCurrentState.finalCrop == crop) 1836 return false; 1837 mCurrentState.sequence++; 1838 mCurrentState.requestedFinalCrop = crop; 1839 if (immediate) { 1840 mCurrentState.finalCrop = crop; 1841 } 1842 mCurrentState.modified = true; 1843 setTransactionFlags(eTransactionNeeded); 1844 return true; 1845} 1846 1847bool Layer::setOverrideScalingMode(int32_t scalingMode) { 1848 if (scalingMode == mOverrideScalingMode) 1849 return false; 1850 mOverrideScalingMode = scalingMode; 1851 setTransactionFlags(eTransactionNeeded); 1852 return true; 1853} 1854 1855void Layer::setInfo(uint32_t type, uint32_t appId) { 1856 mCurrentState.appId = appId; 1857 mCurrentState.type = type; 1858 mCurrentState.modified = true; 1859 setTransactionFlags(eTransactionNeeded); 1860} 1861 1862uint32_t Layer::getEffectiveScalingMode() const { 1863 if (mOverrideScalingMode >= 0) { 1864 return mOverrideScalingMode; 1865 } 1866 return mCurrentScalingMode; 1867} 1868 1869bool Layer::setLayerStack(uint32_t layerStack) { 1870 if (mCurrentState.layerStack == layerStack) 1871 return false; 1872 mCurrentState.sequence++; 1873 mCurrentState.layerStack = layerStack; 1874 mCurrentState.modified = true; 1875 setTransactionFlags(eTransactionNeeded); 1876 return true; 1877} 1878 1879bool Layer::setDataSpace(android_dataspace dataSpace) { 1880 if (mCurrentState.dataSpace == dataSpace) 1881 return false; 1882 mCurrentState.sequence++; 1883 mCurrentState.dataSpace = dataSpace; 1884 mCurrentState.modified = true; 1885 setTransactionFlags(eTransactionNeeded); 1886 return true; 1887} 1888 1889uint32_t Layer::getLayerStack() const { 1890 auto p = getParent(); 1891 if (p == nullptr) { 1892 return getDrawingState().layerStack; 1893 } 1894 return p->getLayerStack(); 1895} 1896 1897void Layer::deferTransactionUntil(const sp<Layer>& barrierLayer, 1898 uint64_t frameNumber) { 1899 mCurrentState.barrierLayer = barrierLayer; 1900 mCurrentState.frameNumber = frameNumber; 1901 // We don't set eTransactionNeeded, because just receiving a deferral 1902 // request without any other state updates shouldn't actually induce a delay 1903 mCurrentState.modified = true; 1904 pushPendingState(); 1905 mCurrentState.barrierLayer = nullptr; 1906 mCurrentState.frameNumber = 0; 1907 mCurrentState.modified = false; 1908 ALOGE("Deferred transaction"); 1909} 1910 1911void Layer::deferTransactionUntil(const sp<IBinder>& barrierHandle, 1912 uint64_t frameNumber) { 1913 sp<Handle> handle = static_cast<Handle*>(barrierHandle.get()); 1914 deferTransactionUntil(handle->owner.promote(), frameNumber); 1915} 1916 1917void Layer::useSurfaceDamage() { 1918 if (mFlinger->mForceFullDamage) { 1919 surfaceDamageRegion = Region::INVALID_REGION; 1920 } else { 1921 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1922 } 1923} 1924 1925void Layer::useEmptyDamage() { 1926 surfaceDamageRegion.clear(); 1927} 1928 1929// ---------------------------------------------------------------------------- 1930// pageflip handling... 1931// ---------------------------------------------------------------------------- 1932 1933bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1934 if (mSidebandStreamChanged || mAutoRefresh) { 1935 return true; 1936 } 1937 1938 Mutex::Autolock lock(mQueueItemLock); 1939 if (mQueueItems.empty()) { 1940 return false; 1941 } 1942 auto timestamp = mQueueItems[0].mTimestamp; 1943 nsecs_t expectedPresent = 1944 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1945 1946 // Ignore timestamps more than a second in the future 1947 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1948 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1949 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1950 expectedPresent); 1951 1952 bool isDue = timestamp < expectedPresent; 1953 return isDue || !isPlausible; 1954} 1955 1956bool Layer::onPreComposition(nsecs_t refreshStartTime) { 1957 if (mBufferLatched) { 1958 Mutex::Autolock lock(mFrameEventHistoryMutex); 1959 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime); 1960 } 1961 mRefreshPending = false; 1962 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1963} 1964 1965bool Layer::onPostComposition(const std::shared_ptr<FenceTime>& glDoneFence, 1966 const std::shared_ptr<FenceTime>& presentFence, 1967 const CompositorTiming& compositorTiming) { 1968 mAcquireTimeline.updateSignalTimes(); 1969 mReleaseTimeline.updateSignalTimes(); 1970 1971 // mFrameLatencyNeeded is true when a new frame was latched for the 1972 // composition. 1973 if (!mFrameLatencyNeeded) 1974 return false; 1975 1976 // Update mFrameEventHistory. 1977 { 1978 Mutex::Autolock lock(mFrameEventHistoryMutex); 1979 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, 1980 glDoneFence, presentFence, compositorTiming); 1981 } 1982 1983 // Update mFrameTracker. 1984 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1985 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1986 1987 std::shared_ptr<FenceTime> frameReadyFence = 1988 mSurfaceFlingerConsumer->getCurrentFenceTime(); 1989 if (frameReadyFence->isValid()) { 1990 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence)); 1991 } else { 1992 // There was no fence for this frame, so assume that it was ready 1993 // to be presented at the desired present time. 1994 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1995 } 1996 1997 if (presentFence->isValid()) { 1998 mFrameTracker.setActualPresentFence( 1999 std::shared_ptr<FenceTime>(presentFence)); 2000 } else { 2001 // The HWC doesn't support present fences, so use the refresh 2002 // timestamp instead. 2003 mFrameTracker.setActualPresentTime( 2004 mFlinger->getHwComposer().getRefreshTimestamp( 2005 HWC_DISPLAY_PRIMARY)); 2006 } 2007 2008 mFrameTracker.advanceFrame(); 2009 mFrameLatencyNeeded = false; 2010 return true; 2011} 2012 2013#ifdef USE_HWC2 2014void Layer::releasePendingBuffer(nsecs_t dequeueReadyTime) { 2015 if (!mSurfaceFlingerConsumer->releasePendingBuffer()) { 2016 return; 2017 } 2018 2019 auto releaseFenceTime = std::make_shared<FenceTime>( 2020 mSurfaceFlingerConsumer->getPrevFinalReleaseFence()); 2021 mReleaseTimeline.push(releaseFenceTime); 2022 2023 Mutex::Autolock lock(mFrameEventHistoryMutex); 2024 if (mPreviousFrameNumber != 0) { 2025 mFrameEventHistory.addRelease(mPreviousFrameNumber, 2026 dequeueReadyTime, std::move(releaseFenceTime)); 2027 } 2028} 2029#endif 2030 2031bool Layer::isHiddenByPolicy() const { 2032 const Layer::State& s(mDrawingState); 2033 const auto& parent = getParent(); 2034 if (parent != nullptr && parent->isHiddenByPolicy()) { 2035 return true; 2036 } 2037 return s.flags & layer_state_t::eLayerHidden; 2038} 2039 2040bool Layer::isVisible() const { 2041#ifdef USE_HWC2 2042 return !(isHiddenByPolicy()) && getAlpha() > 0.0f 2043 && (mActiveBuffer != NULL || mSidebandStream != NULL); 2044#else 2045 return !(isHiddenByPolicy()) && getAlpha() 2046 && (mActiveBuffer != NULL || mSidebandStream != NULL); 2047#endif 2048} 2049 2050bool Layer::allTransactionsSignaled() { 2051 auto headFrameNumber = getHeadFrameNumber(); 2052 bool matchingFramesFound = false; 2053 bool allTransactionsApplied = true; 2054 Mutex::Autolock lock(mLocalSyncPointMutex); 2055 2056 for (auto& point : mLocalSyncPoints) { 2057 if (point->getFrameNumber() > headFrameNumber) { 2058 break; 2059 } 2060 matchingFramesFound = true; 2061 2062 if (!point->frameIsAvailable()) { 2063 // We haven't notified the remote layer that the frame for 2064 // this point is available yet. Notify it now, and then 2065 // abort this attempt to latch. 2066 point->setFrameAvailable(); 2067 allTransactionsApplied = false; 2068 break; 2069 } 2070 2071 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied(); 2072 } 2073 return !matchingFramesFound || allTransactionsApplied; 2074} 2075 2076Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) 2077{ 2078 ATRACE_CALL(); 2079 2080 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 2081 // mSidebandStreamChanged was true 2082 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 2083 if (mSidebandStream != NULL) { 2084 setTransactionFlags(eTransactionNeeded); 2085 mFlinger->setTransactionFlags(eTraversalNeeded); 2086 } 2087 recomputeVisibleRegions = true; 2088 2089 const State& s(getDrawingState()); 2090 return getTransform().transform(Region(Rect(s.active.w, s.active.h))); 2091 } 2092 2093 Region outDirtyRegion; 2094 if (mQueuedFrames <= 0 && !mAutoRefresh) { 2095 return outDirtyRegion; 2096 } 2097 2098 // if we've already called updateTexImage() without going through 2099 // a composition step, we have to skip this layer at this point 2100 // because we cannot call updateTeximage() without a corresponding 2101 // compositionComplete() call. 2102 // we'll trigger an update in onPreComposition(). 2103 if (mRefreshPending) { 2104 return outDirtyRegion; 2105 } 2106 2107 // If the head buffer's acquire fence hasn't signaled yet, return and 2108 // try again later 2109 if (!headFenceHasSignaled()) { 2110 mFlinger->signalLayerUpdate(); 2111 return outDirtyRegion; 2112 } 2113 2114 // Capture the old state of the layer for comparisons later 2115 const State& s(getDrawingState()); 2116 const bool oldOpacity = isOpaque(s); 2117 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 2118 2119 if (!allTransactionsSignaled()) { 2120 mFlinger->signalLayerUpdate(); 2121 return outDirtyRegion; 2122 } 2123 2124 // This boolean is used to make sure that SurfaceFlinger's shadow copy 2125 // of the buffer queue isn't modified when the buffer queue is returning 2126 // BufferItem's that weren't actually queued. This can happen in shared 2127 // buffer mode. 2128 bool queuedBuffer = false; 2129 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 2130 getProducerStickyTransform() != 0, mName.string(), 2131 mOverrideScalingMode, mFreezePositionUpdates); 2132 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 2133 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer, 2134 mLastFrameNumberReceived); 2135 if (updateResult == BufferQueue::PRESENT_LATER) { 2136 // Producer doesn't want buffer to be displayed yet. Signal a 2137 // layer update so we check again at the next opportunity. 2138 mFlinger->signalLayerUpdate(); 2139 return outDirtyRegion; 2140 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 2141 // If the buffer has been rejected, remove it from the shadow queue 2142 // and return early 2143 if (queuedBuffer) { 2144 Mutex::Autolock lock(mQueueItemLock); 2145 mQueueItems.removeAt(0); 2146 android_atomic_dec(&mQueuedFrames); 2147 } 2148 return outDirtyRegion; 2149 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 2150 // This can occur if something goes wrong when trying to create the 2151 // EGLImage for this buffer. If this happens, the buffer has already 2152 // been released, so we need to clean up the queue and bug out 2153 // early. 2154 if (queuedBuffer) { 2155 Mutex::Autolock lock(mQueueItemLock); 2156 mQueueItems.clear(); 2157 android_atomic_and(0, &mQueuedFrames); 2158 } 2159 2160 // Once we have hit this state, the shadow queue may no longer 2161 // correctly reflect the incoming BufferQueue's contents, so even if 2162 // updateTexImage starts working, the only safe course of action is 2163 // to continue to ignore updates. 2164 mUpdateTexImageFailed = true; 2165 2166 return outDirtyRegion; 2167 } 2168 2169 if (queuedBuffer) { 2170 // Autolock scope 2171 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2172 2173 Mutex::Autolock lock(mQueueItemLock); 2174 2175 // Remove any stale buffers that have been dropped during 2176 // updateTexImage 2177 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 2178 mQueueItems.removeAt(0); 2179 android_atomic_dec(&mQueuedFrames); 2180 } 2181 2182 mQueueItems.removeAt(0); 2183 } 2184 2185 2186 // Decrement the queued-frames count. Signal another event if we 2187 // have more frames pending. 2188 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 2189 || mAutoRefresh) { 2190 mFlinger->signalLayerUpdate(); 2191 } 2192 2193 // update the active buffer 2194 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer( 2195 &mActiveBufferSlot); 2196 if (mActiveBuffer == NULL) { 2197 // this can only happen if the very first buffer was rejected. 2198 return outDirtyRegion; 2199 } 2200 2201 mBufferLatched = true; 2202 mPreviousFrameNumber = mCurrentFrameNumber; 2203 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2204 2205 { 2206 Mutex::Autolock lock(mFrameEventHistoryMutex); 2207 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime); 2208#ifndef USE_HWC2 2209 auto releaseFenceTime = std::make_shared<FenceTime>( 2210 mSurfaceFlingerConsumer->getPrevFinalReleaseFence()); 2211 mReleaseTimeline.push(releaseFenceTime); 2212 if (mPreviousFrameNumber != 0) { 2213 mFrameEventHistory.addRelease(mPreviousFrameNumber, 2214 latchTime, std::move(releaseFenceTime)); 2215 } 2216#endif 2217 } 2218 2219 mRefreshPending = true; 2220 mFrameLatencyNeeded = true; 2221 if (oldActiveBuffer == NULL) { 2222 // the first time we receive a buffer, we need to trigger a 2223 // geometry invalidation. 2224 recomputeVisibleRegions = true; 2225 } 2226 2227 setDataSpace(mSurfaceFlingerConsumer->getCurrentDataSpace()); 2228 2229 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 2230 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 2231 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 2232 if ((crop != mCurrentCrop) || 2233 (transform != mCurrentTransform) || 2234 (scalingMode != mCurrentScalingMode)) 2235 { 2236 mCurrentCrop = crop; 2237 mCurrentTransform = transform; 2238 mCurrentScalingMode = scalingMode; 2239 recomputeVisibleRegions = true; 2240 } 2241 2242 if (oldActiveBuffer != NULL) { 2243 uint32_t bufWidth = mActiveBuffer->getWidth(); 2244 uint32_t bufHeight = mActiveBuffer->getHeight(); 2245 if (bufWidth != uint32_t(oldActiveBuffer->width) || 2246 bufHeight != uint32_t(oldActiveBuffer->height)) { 2247 recomputeVisibleRegions = true; 2248 } 2249 } 2250 2251 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 2252 if (oldOpacity != isOpaque(s)) { 2253 recomputeVisibleRegions = true; 2254 } 2255 2256 // Remove any sync points corresponding to the buffer which was just 2257 // latched 2258 { 2259 Mutex::Autolock lock(mLocalSyncPointMutex); 2260 auto point = mLocalSyncPoints.begin(); 2261 while (point != mLocalSyncPoints.end()) { 2262 if (!(*point)->frameIsAvailable() || 2263 !(*point)->transactionIsApplied()) { 2264 // This sync point must have been added since we started 2265 // latching. Don't drop it yet. 2266 ++point; 2267 continue; 2268 } 2269 2270 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) { 2271 point = mLocalSyncPoints.erase(point); 2272 } else { 2273 ++point; 2274 } 2275 } 2276 } 2277 2278 // FIXME: postedRegion should be dirty & bounds 2279 Region dirtyRegion(Rect(s.active.w, s.active.h)); 2280 2281 // transform the dirty region to window-manager space 2282 outDirtyRegion = (getTransform().transform(dirtyRegion)); 2283 2284 return outDirtyRegion; 2285} 2286 2287uint32_t Layer::getEffectiveUsage(uint32_t usage) const 2288{ 2289 // TODO: should we do something special if mSecure is set? 2290 if (mProtectedByApp) { 2291 // need a hardware-protected path to external video sink 2292 usage |= GraphicBuffer::USAGE_PROTECTED; 2293 } 2294 if (mPotentialCursor) { 2295 usage |= GraphicBuffer::USAGE_CURSOR; 2296 } 2297 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 2298 return usage; 2299} 2300 2301void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 2302 uint32_t orientation = 0; 2303 if (!mFlinger->mDebugDisableTransformHint) { 2304 // The transform hint is used to improve performance, but we can 2305 // only have a single transform hint, it cannot 2306 // apply to all displays. 2307 const Transform& planeTransform(hw->getTransform()); 2308 orientation = planeTransform.getOrientation(); 2309 if (orientation & Transform::ROT_INVALID) { 2310 orientation = 0; 2311 } 2312 } 2313 mSurfaceFlingerConsumer->setTransformHint(orientation); 2314} 2315 2316// ---------------------------------------------------------------------------- 2317// debugging 2318// ---------------------------------------------------------------------------- 2319 2320void Layer::dump(String8& result, Colorizer& colorizer) const 2321{ 2322 const Layer::State& s(getDrawingState()); 2323 2324 colorizer.colorize(result, Colorizer::GREEN); 2325 result.appendFormat( 2326 "+ %s %p (%s)\n", 2327 getTypeId(), this, getName().string()); 2328 colorizer.reset(result); 2329 2330 s.activeTransparentRegion.dump(result, "transparentRegion"); 2331 visibleRegion.dump(result, "visibleRegion"); 2332 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 2333 sp<Client> client(mClientRef.promote()); 2334 2335 result.appendFormat( " " 2336 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), " 2337 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), " 2338 "isOpaque=%1d, invalidate=%1d, " 2339#ifdef USE_HWC2 2340 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2341#else 2342 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2343#endif 2344 " client=%p\n", 2345 getLayerStack(), s.z, 2346 s.active.transform.tx(), s.active.transform.ty(), 2347 s.active.w, s.active.h, 2348 s.crop.left, s.crop.top, 2349 s.crop.right, s.crop.bottom, 2350 s.finalCrop.left, s.finalCrop.top, 2351 s.finalCrop.right, s.finalCrop.bottom, 2352 isOpaque(s), contentDirty, 2353 s.alpha, s.flags, 2354 s.active.transform[0][0], s.active.transform[0][1], 2355 s.active.transform[1][0], s.active.transform[1][1], 2356 client.get()); 2357 2358 sp<const GraphicBuffer> buf0(mActiveBuffer); 2359 uint32_t w0=0, h0=0, s0=0, f0=0; 2360 if (buf0 != 0) { 2361 w0 = buf0->getWidth(); 2362 h0 = buf0->getHeight(); 2363 s0 = buf0->getStride(); 2364 f0 = buf0->format; 2365 } 2366 result.appendFormat( 2367 " " 2368 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 2369 " queued-frames=%d, mRefreshPending=%d\n", 2370 mFormat, w0, h0, s0,f0, 2371 mQueuedFrames, mRefreshPending); 2372 2373 if (mSurfaceFlingerConsumer != 0) { 2374 mSurfaceFlingerConsumer->dumpState(result, " "); 2375 } 2376} 2377 2378#ifdef USE_HWC2 2379void Layer::miniDumpHeader(String8& result) { 2380 result.append("----------------------------------------"); 2381 result.append("---------------------------------------\n"); 2382 result.append(" Layer name\n"); 2383 result.append(" Z | "); 2384 result.append(" Comp Type | "); 2385 result.append(" Disp Frame (LTRB) | "); 2386 result.append(" Source Crop (LTRB)\n"); 2387 result.append("----------------------------------------"); 2388 result.append("---------------------------------------\n"); 2389} 2390 2391void Layer::miniDump(String8& result, int32_t hwcId) const { 2392 if (mHwcLayers.count(hwcId) == 0) { 2393 return; 2394 } 2395 2396 String8 name; 2397 if (mName.length() > 77) { 2398 std::string shortened; 2399 shortened.append(mName.string(), 36); 2400 shortened.append("[...]"); 2401 shortened.append(mName.string() + (mName.length() - 36), 36); 2402 name = shortened.c_str(); 2403 } else { 2404 name = mName; 2405 } 2406 2407 result.appendFormat(" %s\n", name.string()); 2408 2409 const Layer::State& layerState(getDrawingState()); 2410 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId); 2411 result.appendFormat(" %10u | ", layerState.z); 2412 result.appendFormat("%10s | ", 2413 to_string(getCompositionType(hwcId)).c_str()); 2414 const Rect& frame = hwcInfo.displayFrame; 2415 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, 2416 frame.right, frame.bottom); 2417 const FloatRect& crop = hwcInfo.sourceCrop; 2418 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, 2419 crop.right, crop.bottom); 2420 2421 result.append("- - - - - - - - - - - - - - - - - - - - "); 2422 result.append("- - - - - - - - - - - - - - - - - - - -\n"); 2423} 2424#endif 2425 2426void Layer::dumpFrameStats(String8& result) const { 2427 mFrameTracker.dumpStats(result); 2428} 2429 2430void Layer::clearFrameStats() { 2431 mFrameTracker.clearStats(); 2432} 2433 2434void Layer::logFrameStats() { 2435 mFrameTracker.logAndResetStats(mName); 2436} 2437 2438void Layer::getFrameStats(FrameStats* outStats) const { 2439 mFrameTracker.getStats(outStats); 2440} 2441 2442void Layer::dumpFrameEvents(String8& result) { 2443 result.appendFormat("- Layer %s (%s, %p)\n", 2444 getName().string(), getTypeId(), this); 2445 Mutex::Autolock lock(mFrameEventHistoryMutex); 2446 mFrameEventHistory.checkFencesForCompletion(); 2447 mFrameEventHistory.dump(result); 2448} 2449 2450void Layer::onDisconnect() { 2451 Mutex::Autolock lock(mFrameEventHistoryMutex); 2452 mFrameEventHistory.onDisconnect(); 2453} 2454 2455void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps, 2456 FrameEventHistoryDelta *outDelta) { 2457 Mutex::Autolock lock(mFrameEventHistoryMutex); 2458 if (newTimestamps) { 2459 mAcquireTimeline.push(newTimestamps->acquireFence); 2460 mFrameEventHistory.addQueue(*newTimestamps); 2461 } 2462 2463 if (outDelta) { 2464 mFrameEventHistory.getAndResetDelta(outDelta); 2465 } 2466} 2467 2468std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory( 2469 bool forceFlush) { 2470 std::vector<OccupancyTracker::Segment> history; 2471 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, 2472 &history); 2473 if (result != NO_ERROR) { 2474 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), 2475 result); 2476 return {}; 2477 } 2478 return history; 2479} 2480 2481bool Layer::getTransformToDisplayInverse() const { 2482 return mSurfaceFlingerConsumer->getTransformToDisplayInverse(); 2483} 2484 2485void Layer::addChild(const sp<Layer>& layer) { 2486 mCurrentChildren.add(layer); 2487 layer->setParent(this); 2488} 2489 2490ssize_t Layer::removeChild(const sp<Layer>& layer) { 2491 layer->setParent(nullptr); 2492 return mCurrentChildren.remove(layer); 2493} 2494 2495bool Layer::reparentChildren(const sp<IBinder>& newParentHandle) { 2496 sp<Handle> handle = nullptr; 2497 sp<Layer> newParent = nullptr; 2498 if (newParentHandle == nullptr) { 2499 return false; 2500 } 2501 handle = static_cast<Handle*>(newParentHandle.get()); 2502 newParent = handle->owner.promote(); 2503 if (newParent == nullptr) { 2504 ALOGE("Unable to promote Layer handle"); 2505 return false; 2506 } 2507 2508 for (const sp<Layer>& child : mCurrentChildren) { 2509 newParent->addChild(child); 2510 2511 sp<Client> client(child->mClientRef.promote()); 2512 if (client != nullptr) { 2513 client->setParentLayer(newParent); 2514 } 2515 } 2516 mCurrentChildren.clear(); 2517 2518 return true; 2519} 2520 2521bool Layer::detachChildren() { 2522 traverseInZOrder([this](Layer* child) { 2523 if (child == this) { 2524 return; 2525 } 2526 2527 sp<Client> client(child->mClientRef.promote()); 2528 if (client != nullptr) { 2529 client->detachLayer(child); 2530 } 2531 }); 2532 2533 return true; 2534} 2535 2536void Layer::setParent(const sp<Layer>& layer) { 2537 mParent = layer; 2538} 2539 2540void Layer::clearSyncPoints() { 2541 for (const auto& child : mCurrentChildren) { 2542 child->clearSyncPoints(); 2543 } 2544 2545 Mutex::Autolock lock(mLocalSyncPointMutex); 2546 for (auto& point : mLocalSyncPoints) { 2547 point->setFrameAvailable(); 2548 } 2549 mLocalSyncPoints.clear(); 2550} 2551 2552int32_t Layer::getZ() const { 2553 return mDrawingState.z; 2554} 2555 2556LayerVector Layer::makeTraversalList() { 2557 if (mDrawingState.zOrderRelatives.size() == 0) { 2558 return mDrawingChildren; 2559 } 2560 LayerVector traverse; 2561 2562 for (const wp<Layer>& weakRelative : mDrawingState.zOrderRelatives) { 2563 sp<Layer> strongRelative = weakRelative.promote(); 2564 if (strongRelative != nullptr) { 2565 traverse.add(strongRelative); 2566 } 2567 } 2568 2569 for (const sp<Layer>& child : mDrawingChildren) { 2570 traverse.add(child); 2571 } 2572 2573 return traverse; 2574} 2575 2576/** 2577 * Negatively signed relatives are before 'this' in Z-order. 2578 */ 2579void Layer::traverseInZOrder(const std::function<void(Layer*)>& exec) { 2580 LayerVector list = makeTraversalList(); 2581 2582 size_t i = 0; 2583 for (; i < list.size(); i++) { 2584 const auto& relative = list[i]; 2585 if (relative->getZ() >= 0) { 2586 break; 2587 } 2588 relative->traverseInZOrder(exec); 2589 } 2590 exec(this); 2591 for (; i < list.size(); i++) { 2592 const auto& relative = list[i]; 2593 relative->traverseInZOrder(exec); 2594 } 2595} 2596 2597/** 2598 * Positively signed relatives are before 'this' in reverse Z-order. 2599 */ 2600void Layer::traverseInReverseZOrder(const std::function<void(Layer*)>& exec) { 2601 LayerVector list = makeTraversalList(); 2602 2603 int32_t i = 0; 2604 for (i = list.size()-1; i>=0; i--) { 2605 const auto& relative = list[i]; 2606 if (relative->getZ() < 0) { 2607 break; 2608 } 2609 relative->traverseInReverseZOrder(exec); 2610 } 2611 exec(this); 2612 for (; i>=0; i--) { 2613 const auto& relative = list[i]; 2614 relative->traverseInReverseZOrder(exec); 2615 } 2616} 2617 2618Transform Layer::getTransform() const { 2619 Transform t; 2620 const auto& p = getParent(); 2621 if (p != nullptr) { 2622 t = p->getTransform(); 2623 2624 // If the parent is not using NATIVE_WINDOW_SCALING_MODE_FREEZE (e.g. 2625 // it isFixedSize) then there may be additional scaling not accounted 2626 // for in the transform. We need to mirror this scaling in child surfaces 2627 // or we will break the contract where WM can treat child surfaces as 2628 // pixels in the parent surface. 2629 if (p->isFixedSize()) { 2630 int bufferWidth; 2631 int bufferHeight; 2632 if ((p->mCurrentTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) == 0) { 2633 bufferWidth = p->mActiveBuffer->getWidth(); 2634 bufferHeight = p->mActiveBuffer->getHeight(); 2635 } else { 2636 bufferHeight = p->mActiveBuffer->getWidth(); 2637 bufferWidth = p->mActiveBuffer->getHeight(); 2638 } 2639 float sx = p->getDrawingState().active.w / 2640 static_cast<float>(bufferWidth); 2641 float sy = p->getDrawingState().active.h / 2642 static_cast<float>(bufferHeight); 2643 Transform extraParentScaling; 2644 extraParentScaling.set(sx, 0, 0, sy); 2645 t = t * extraParentScaling; 2646 } 2647 } 2648 return t * getDrawingState().active.transform; 2649} 2650 2651#ifdef USE_HWC2 2652float Layer::getAlpha() const { 2653 const auto& p = getParent(); 2654 2655 float parentAlpha = (p != nullptr) ? p->getAlpha() : 1.0; 2656 return parentAlpha * getDrawingState().alpha; 2657} 2658#else 2659uint8_t Layer::getAlpha() const { 2660 const auto& p = getParent(); 2661 2662 float parentAlpha = (p != nullptr) ? (p->getAlpha() / 255.0f) : 1.0; 2663 float drawingAlpha = getDrawingState().alpha / 255.0f; 2664 drawingAlpha = drawingAlpha * parentAlpha; 2665 return static_cast<uint8_t>(std::round(drawingAlpha * 255)); 2666} 2667#endif 2668 2669void Layer::commitChildList() { 2670 for (size_t i = 0; i < mCurrentChildren.size(); i++) { 2671 const auto& child = mCurrentChildren[i]; 2672 child->commitChildList(); 2673 } 2674 mDrawingChildren = mCurrentChildren; 2675} 2676 2677// --------------------------------------------------------------------------- 2678 2679}; // namespace android 2680 2681#if defined(__gl_h_) 2682#error "don't include gl/gl.h in this file" 2683#endif 2684 2685#if defined(__gl2_h_) 2686#error "don't include gl2/gl2.h in this file" 2687#endif 2688