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