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