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