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