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