Layer.cpp revision 63a5fcd2aa55c8eb0ccba621517a4215d8504df6
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 if (mFlinger->isLayerTripleBufferingDisabled()) { 169 mProducer->setMaxDequeuedBufferCount(2); 170 } 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 380gfx::FloatRect 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 gfx::FloatRect crop = getContentCrop().toFloatRect(); 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 gfx::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 case HAL_PIXEL_FORMAT_RGBA_FP16: 1193 return false; 1194 } 1195 // in all other case, we have no blending (also for unknown formats) 1196 return true; 1197} 1198 1199// ---------------------------------------------------------------------------- 1200// local state 1201// ---------------------------------------------------------------------------- 1202 1203static void boundPoint(vec2* point, const Rect& crop) { 1204 if (point->x < crop.left) { 1205 point->x = crop.left; 1206 } 1207 if (point->x > crop.right) { 1208 point->x = crop.right; 1209 } 1210 if (point->y < crop.top) { 1211 point->y = crop.top; 1212 } 1213 if (point->y > crop.bottom) { 1214 point->y = crop.bottom; 1215 } 1216} 1217 1218void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh, 1219 bool useIdentityTransform) const 1220{ 1221 const Layer::State& s(getDrawingState()); 1222 const Transform tr(hw->getTransform()); 1223 const uint32_t hw_h = hw->getHeight(); 1224 Rect win(s.active.w, s.active.h); 1225 if (!s.crop.isEmpty()) { 1226 win.intersect(s.crop, &win); 1227 } 1228 // subtract the transparent region and snap to the bounds 1229 win = reduce(win, s.activeTransparentRegion); 1230 1231 vec2 lt = vec2(win.left, win.top); 1232 vec2 lb = vec2(win.left, win.bottom); 1233 vec2 rb = vec2(win.right, win.bottom); 1234 vec2 rt = vec2(win.right, win.top); 1235 1236 if (!useIdentityTransform) { 1237 lt = s.active.transform.transform(lt); 1238 lb = s.active.transform.transform(lb); 1239 rb = s.active.transform.transform(rb); 1240 rt = s.active.transform.transform(rt); 1241 } 1242 1243 if (!s.finalCrop.isEmpty()) { 1244 boundPoint(<, s.finalCrop); 1245 boundPoint(&lb, s.finalCrop); 1246 boundPoint(&rb, s.finalCrop); 1247 boundPoint(&rt, s.finalCrop); 1248 } 1249 1250 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>()); 1251 position[0] = tr.transform(lt); 1252 position[1] = tr.transform(lb); 1253 position[2] = tr.transform(rb); 1254 position[3] = tr.transform(rt); 1255 for (size_t i=0 ; i<4 ; i++) { 1256 position[i].y = hw_h - position[i].y; 1257 } 1258} 1259 1260bool Layer::isOpaque(const Layer::State& s) const 1261{ 1262 // if we don't have a buffer yet, we're translucent regardless of the 1263 // layer's opaque flag. 1264 if (mActiveBuffer == 0) { 1265 return false; 1266 } 1267 1268 // if the layer has the opaque flag, then we're always opaque, 1269 // otherwise we use the current buffer's format. 1270 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity; 1271} 1272 1273bool Layer::isSecure() const 1274{ 1275 const Layer::State& s(mDrawingState); 1276 return (s.flags & layer_state_t::eLayerSecure); 1277} 1278 1279bool Layer::isProtected() const 1280{ 1281 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 1282 return (activeBuffer != 0) && 1283 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 1284} 1285 1286bool Layer::isFixedSize() const { 1287 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1288} 1289 1290bool Layer::isCropped() const { 1291 return !mCurrentCrop.isEmpty(); 1292} 1293 1294bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const { 1295 return mNeedsFiltering || hw->needsFiltering(); 1296} 1297 1298void Layer::setVisibleRegion(const Region& visibleRegion) { 1299 // always called from main thread 1300 this->visibleRegion = visibleRegion; 1301} 1302 1303void Layer::setCoveredRegion(const Region& coveredRegion) { 1304 // always called from main thread 1305 this->coveredRegion = coveredRegion; 1306} 1307 1308void Layer::setVisibleNonTransparentRegion(const Region& 1309 setVisibleNonTransparentRegion) { 1310 // always called from main thread 1311 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion; 1312} 1313 1314// ---------------------------------------------------------------------------- 1315// transaction 1316// ---------------------------------------------------------------------------- 1317 1318void Layer::pushPendingState() { 1319 if (!mCurrentState.modified) { 1320 return; 1321 } 1322 1323 // If this transaction is waiting on the receipt of a frame, generate a sync 1324 // point and send it to the remote layer. 1325 if (mCurrentState.handle != nullptr) { 1326 sp<IBinder> strongBinder = mCurrentState.handle.promote(); 1327 sp<Handle> handle = nullptr; 1328 sp<Layer> handleLayer = nullptr; 1329 if (strongBinder != nullptr) { 1330 handle = static_cast<Handle*>(strongBinder.get()); 1331 handleLayer = handle->owner.promote(); 1332 } 1333 if (strongBinder == nullptr || handleLayer == nullptr) { 1334 ALOGE("[%s] Unable to promote Layer handle", mName.string()); 1335 // If we can't promote the layer we are intended to wait on, 1336 // then it is expired or otherwise invalid. Allow this transaction 1337 // to be applied as per normal (no synchronization). 1338 mCurrentState.handle = nullptr; 1339 } else { 1340 auto syncPoint = std::make_shared<SyncPoint>( 1341 mCurrentState.frameNumber); 1342 if (handleLayer->addSyncPoint(syncPoint)) { 1343 mRemoteSyncPoints.push_back(std::move(syncPoint)); 1344 } else { 1345 // We already missed the frame we're supposed to synchronize 1346 // on, so go ahead and apply the state update 1347 mCurrentState.handle = nullptr; 1348 } 1349 } 1350 1351 // Wake us up to check if the frame has been received 1352 setTransactionFlags(eTransactionNeeded); 1353 mFlinger->setTransactionFlags(eTraversalNeeded); 1354 } 1355 mPendingStates.push_back(mCurrentState); 1356} 1357 1358void Layer::popPendingState(State* stateToCommit) { 1359 auto oldFlags = stateToCommit->flags; 1360 *stateToCommit = mPendingStates[0]; 1361 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) | 1362 (stateToCommit->flags & stateToCommit->mask); 1363 1364 mPendingStates.removeAt(0); 1365} 1366 1367bool Layer::applyPendingStates(State* stateToCommit) { 1368 bool stateUpdateAvailable = false; 1369 while (!mPendingStates.empty()) { 1370 if (mPendingStates[0].handle != nullptr) { 1371 if (mRemoteSyncPoints.empty()) { 1372 // If we don't have a sync point for this, apply it anyway. It 1373 // will be visually wrong, but it should keep us from getting 1374 // into too much trouble. 1375 ALOGE("[%s] No local sync point found", mName.string()); 1376 popPendingState(stateToCommit); 1377 stateUpdateAvailable = true; 1378 continue; 1379 } 1380 1381 if (mRemoteSyncPoints.front()->getFrameNumber() != 1382 mPendingStates[0].frameNumber) { 1383 ALOGE("[%s] Unexpected sync point frame number found", 1384 mName.string()); 1385 1386 // Signal our end of the sync point and then dispose of it 1387 mRemoteSyncPoints.front()->setTransactionApplied(); 1388 mRemoteSyncPoints.pop_front(); 1389 continue; 1390 } 1391 1392 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 1393 // Apply the state update 1394 popPendingState(stateToCommit); 1395 stateUpdateAvailable = true; 1396 1397 // Signal our end of the sync point and then dispose of it 1398 mRemoteSyncPoints.front()->setTransactionApplied(); 1399 mRemoteSyncPoints.pop_front(); 1400 } else { 1401 break; 1402 } 1403 } else { 1404 popPendingState(stateToCommit); 1405 stateUpdateAvailable = true; 1406 } 1407 } 1408 1409 // If we still have pending updates, wake SurfaceFlinger back up and point 1410 // it at this layer so we can process them 1411 if (!mPendingStates.empty()) { 1412 setTransactionFlags(eTransactionNeeded); 1413 mFlinger->setTransactionFlags(eTraversalNeeded); 1414 } 1415 1416 mCurrentState.modified = false; 1417 return stateUpdateAvailable; 1418} 1419 1420void Layer::notifyAvailableFrames() { 1421 auto headFrameNumber = getHeadFrameNumber(); 1422 bool headFenceSignaled = headFenceHasSignaled(); 1423 Mutex::Autolock lock(mLocalSyncPointMutex); 1424 for (auto& point : mLocalSyncPoints) { 1425 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) { 1426 point->setFrameAvailable(); 1427 } 1428 } 1429} 1430 1431uint32_t Layer::doTransaction(uint32_t flags) { 1432 ATRACE_CALL(); 1433 1434 pushPendingState(); 1435 Layer::State c = getCurrentState(); 1436 if (!applyPendingStates(&c)) { 1437 return 0; 1438 } 1439 1440 const Layer::State& s(getDrawingState()); 1441 1442 const bool sizeChanged = (c.requested.w != s.requested.w) || 1443 (c.requested.h != s.requested.h); 1444 1445 if (sizeChanged) { 1446 // the size changed, we need to ask our client to request a new buffer 1447 ALOGD_IF(DEBUG_RESIZE, 1448 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1449 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1450 " requested={ wh={%4u,%4u} }}\n" 1451 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1452 " requested={ wh={%4u,%4u} }}\n", 1453 this, getName().string(), mCurrentTransform, 1454 getEffectiveScalingMode(), 1455 c.active.w, c.active.h, 1456 c.crop.left, 1457 c.crop.top, 1458 c.crop.right, 1459 c.crop.bottom, 1460 c.crop.getWidth(), 1461 c.crop.getHeight(), 1462 c.requested.w, c.requested.h, 1463 s.active.w, s.active.h, 1464 s.crop.left, 1465 s.crop.top, 1466 s.crop.right, 1467 s.crop.bottom, 1468 s.crop.getWidth(), 1469 s.crop.getHeight(), 1470 s.requested.w, s.requested.h); 1471 1472 // record the new size, form this point on, when the client request 1473 // a buffer, it'll get the new size. 1474 mSurfaceFlingerConsumer->setDefaultBufferSize( 1475 c.requested.w, c.requested.h); 1476 } 1477 1478 const bool resizePending = (c.requested.w != c.active.w) || 1479 (c.requested.h != c.active.h); 1480 if (!isFixedSize()) { 1481 if (resizePending && mSidebandStream == NULL) { 1482 // don't let Layer::doTransaction update the drawing state 1483 // if we have a pending resize, unless we are in fixed-size mode. 1484 // the drawing state will be updated only once we receive a buffer 1485 // with the correct size. 1486 // 1487 // in particular, we want to make sure the clip (which is part 1488 // of the geometry state) is latched together with the size but is 1489 // latched immediately when no resizing is involved. 1490 // 1491 // If a sideband stream is attached, however, we want to skip this 1492 // optimization so that transactions aren't missed when a buffer 1493 // never arrives 1494 1495 flags |= eDontUpdateGeometryState; 1496 } 1497 } 1498 1499 // always set active to requested, unless we're asked not to 1500 // this is used by Layer, which special cases resizes. 1501 if (flags & eDontUpdateGeometryState) { 1502 } else { 1503 Layer::State& editCurrentState(getCurrentState()); 1504 if (mFreezePositionUpdates) { 1505 float tx = c.active.transform.tx(); 1506 float ty = c.active.transform.ty(); 1507 c.active = c.requested; 1508 c.active.transform.set(tx, ty); 1509 editCurrentState.active = c.active; 1510 } else { 1511 editCurrentState.active = editCurrentState.requested; 1512 c.active = c.requested; 1513 } 1514 } 1515 1516 if (s.active != c.active) { 1517 // invalidate and recompute the visible regions if needed 1518 flags |= Layer::eVisibleRegion; 1519 } 1520 1521 if (c.sequence != s.sequence) { 1522 // invalidate and recompute the visible regions if needed 1523 flags |= eVisibleRegion; 1524 this->contentDirty = true; 1525 1526 // we may use linear filtering, if the matrix scales us 1527 const uint8_t type = c.active.transform.getType(); 1528 mNeedsFiltering = (!c.active.transform.preserveRects() || 1529 (type >= Transform::SCALE)); 1530 } 1531 1532 // If the layer is hidden, signal and clear out all local sync points so 1533 // that transactions for layers depending on this layer's frames becoming 1534 // visible are not blocked 1535 if (c.flags & layer_state_t::eLayerHidden) { 1536 Mutex::Autolock lock(mLocalSyncPointMutex); 1537 for (auto& point : mLocalSyncPoints) { 1538 point->setFrameAvailable(); 1539 } 1540 mLocalSyncPoints.clear(); 1541 } 1542 1543 // Commit the transaction 1544 commitTransaction(c); 1545 return flags; 1546} 1547 1548void Layer::commitTransaction(const State& stateToCommit) { 1549 mDrawingState = stateToCommit; 1550} 1551 1552uint32_t Layer::getTransactionFlags(uint32_t flags) { 1553 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1554} 1555 1556uint32_t Layer::setTransactionFlags(uint32_t flags) { 1557 return android_atomic_or(flags, &mTransactionFlags); 1558} 1559 1560bool Layer::setPosition(float x, float y, bool immediate) { 1561 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y) 1562 return false; 1563 mCurrentState.sequence++; 1564 1565 // We update the requested and active position simultaneously because 1566 // we want to apply the position portion of the transform matrix immediately, 1567 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1568 mCurrentState.requested.transform.set(x, y); 1569 if (immediate && !mFreezePositionUpdates) { 1570 mCurrentState.active.transform.set(x, y); 1571 } 1572 mFreezePositionUpdates = mFreezePositionUpdates || !immediate; 1573 1574 mCurrentState.modified = true; 1575 setTransactionFlags(eTransactionNeeded); 1576 return true; 1577} 1578 1579bool Layer::setLayer(uint32_t z) { 1580 if (mCurrentState.z == z) 1581 return false; 1582 mCurrentState.sequence++; 1583 mCurrentState.z = z; 1584 mCurrentState.modified = true; 1585 setTransactionFlags(eTransactionNeeded); 1586 return true; 1587} 1588bool Layer::setSize(uint32_t w, uint32_t h) { 1589 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1590 return false; 1591 mCurrentState.requested.w = w; 1592 mCurrentState.requested.h = h; 1593 mCurrentState.modified = true; 1594 setTransactionFlags(eTransactionNeeded); 1595 return true; 1596} 1597#ifdef USE_HWC2 1598bool Layer::setAlpha(float alpha) { 1599#else 1600bool Layer::setAlpha(uint8_t alpha) { 1601#endif 1602 if (mCurrentState.alpha == alpha) 1603 return false; 1604 mCurrentState.sequence++; 1605 mCurrentState.alpha = alpha; 1606 mCurrentState.modified = true; 1607 setTransactionFlags(eTransactionNeeded); 1608 return true; 1609} 1610bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1611 mCurrentState.sequence++; 1612 mCurrentState.requested.transform.set( 1613 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1614 mCurrentState.modified = true; 1615 setTransactionFlags(eTransactionNeeded); 1616 return true; 1617} 1618bool Layer::setTransparentRegionHint(const Region& transparent) { 1619 mCurrentState.requestedTransparentRegion = transparent; 1620 mCurrentState.modified = true; 1621 setTransactionFlags(eTransactionNeeded); 1622 return true; 1623} 1624bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1625 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1626 if (mCurrentState.flags == newFlags) 1627 return false; 1628 mCurrentState.sequence++; 1629 mCurrentState.flags = newFlags; 1630 mCurrentState.mask = mask; 1631 mCurrentState.modified = true; 1632 setTransactionFlags(eTransactionNeeded); 1633 return true; 1634} 1635 1636bool Layer::setCrop(const Rect& crop, bool immediate) { 1637 if (mCurrentState.crop == crop) 1638 return false; 1639 mCurrentState.sequence++; 1640 mCurrentState.requestedCrop = crop; 1641 if (immediate) { 1642 mCurrentState.crop = crop; 1643 } 1644 mCurrentState.modified = true; 1645 setTransactionFlags(eTransactionNeeded); 1646 return true; 1647} 1648bool Layer::setFinalCrop(const Rect& crop) { 1649 if (mCurrentState.finalCrop == crop) 1650 return false; 1651 mCurrentState.sequence++; 1652 mCurrentState.finalCrop = crop; 1653 mCurrentState.modified = true; 1654 setTransactionFlags(eTransactionNeeded); 1655 return true; 1656} 1657 1658bool Layer::setOverrideScalingMode(int32_t scalingMode) { 1659 if (scalingMode == mOverrideScalingMode) 1660 return false; 1661 mOverrideScalingMode = scalingMode; 1662 setTransactionFlags(eTransactionNeeded); 1663 return true; 1664} 1665 1666uint32_t Layer::getEffectiveScalingMode() const { 1667 if (mOverrideScalingMode >= 0) { 1668 return mOverrideScalingMode; 1669 } 1670 return mCurrentScalingMode; 1671} 1672 1673bool Layer::setLayerStack(uint32_t layerStack) { 1674 if (mCurrentState.layerStack == layerStack) 1675 return false; 1676 mCurrentState.sequence++; 1677 mCurrentState.layerStack = layerStack; 1678 mCurrentState.modified = true; 1679 setTransactionFlags(eTransactionNeeded); 1680 return true; 1681} 1682 1683void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1684 uint64_t frameNumber) { 1685 mCurrentState.handle = handle; 1686 mCurrentState.frameNumber = frameNumber; 1687 // We don't set eTransactionNeeded, because just receiving a deferral 1688 // request without any other state updates shouldn't actually induce a delay 1689 mCurrentState.modified = true; 1690 pushPendingState(); 1691 mCurrentState.handle = nullptr; 1692 mCurrentState.frameNumber = 0; 1693 mCurrentState.modified = false; 1694} 1695 1696void Layer::useSurfaceDamage() { 1697 if (mFlinger->mForceFullDamage) { 1698 surfaceDamageRegion = Region::INVALID_REGION; 1699 } else { 1700 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1701 } 1702} 1703 1704void Layer::useEmptyDamage() { 1705 surfaceDamageRegion.clear(); 1706} 1707 1708// ---------------------------------------------------------------------------- 1709// pageflip handling... 1710// ---------------------------------------------------------------------------- 1711 1712bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1713 if (mSidebandStreamChanged || mAutoRefresh) { 1714 return true; 1715 } 1716 1717 Mutex::Autolock lock(mQueueItemLock); 1718 if (mQueueItems.empty()) { 1719 return false; 1720 } 1721 auto timestamp = mQueueItems[0].mTimestamp; 1722 nsecs_t expectedPresent = 1723 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1724 1725 // Ignore timestamps more than a second in the future 1726 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1727 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1728 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1729 expectedPresent); 1730 1731 bool isDue = timestamp < expectedPresent; 1732 return isDue || !isPlausible; 1733} 1734 1735bool Layer::onPreComposition(nsecs_t refreshStartTime) { 1736 if (mBufferLatched) { 1737 Mutex::Autolock lock(mFrameEventHistoryMutex); 1738 mFrameEventHistory.addPreComposition(mCurrentFrameNumber, refreshStartTime); 1739 } 1740 mRefreshPending = false; 1741 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1742} 1743 1744bool Layer::onPostComposition( 1745 const std::shared_ptr<FenceTime>& glDoneFence, 1746 const std::shared_ptr<FenceTime>& presentFence, 1747 const std::shared_ptr<FenceTime>& retireFence) { 1748 mAcquireTimeline.updateSignalTimes(); 1749 mReleaseTimeline.updateSignalTimes(); 1750 1751 // mFrameLatencyNeeded is true when a new frame was latched for the 1752 // composition. 1753 if (!mFrameLatencyNeeded) 1754 return false; 1755 1756 // Update mFrameEventHistory. 1757 { 1758 Mutex::Autolock lock(mFrameEventHistoryMutex); 1759 mFrameEventHistory.addPostComposition(mCurrentFrameNumber, 1760 glDoneFence, presentFence); 1761 mFrameEventHistory.addRetire(mPreviousFrameNumber, 1762 retireFence); 1763 } 1764 1765 // Update mFrameTracker. 1766 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1767 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1768 1769 std::shared_ptr<FenceTime> frameReadyFence = 1770 mSurfaceFlingerConsumer->getCurrentFenceTime(); 1771 if (frameReadyFence->isValid()) { 1772 mFrameTracker.setFrameReadyFence(std::move(frameReadyFence)); 1773 } else { 1774 // There was no fence for this frame, so assume that it was ready 1775 // to be presented at the desired present time. 1776 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1777 } 1778 1779 if (presentFence->isValid()) { 1780 mFrameTracker.setActualPresentFence( 1781 std::shared_ptr<FenceTime>(presentFence)); 1782 } else if (retireFence->isValid()) { 1783 mFrameTracker.setActualPresentFence( 1784 std::shared_ptr<FenceTime>(retireFence)); 1785 } else { 1786 // The HWC doesn't support present fences, so use the refresh 1787 // timestamp instead. 1788 mFrameTracker.setActualPresentTime( 1789 mFlinger->getHwComposer().getRefreshTimestamp( 1790 HWC_DISPLAY_PRIMARY)); 1791 } 1792 1793 mFrameTracker.advanceFrame(); 1794 mFrameLatencyNeeded = false; 1795 return true; 1796} 1797 1798#ifdef USE_HWC2 1799void Layer::releasePendingBuffer() { 1800 mSurfaceFlingerConsumer->releasePendingBuffer(); 1801 auto releaseFenceTime = std::make_shared<FenceTime>( 1802 mSurfaceFlingerConsumer->getPrevFinalReleaseFence()); 1803 mReleaseTimeline.push(releaseFenceTime); 1804 1805 Mutex::Autolock lock(mFrameEventHistoryMutex); 1806 mFrameEventHistory.addRelease( 1807 mPreviousFrameNumber, std::move(releaseFenceTime)); 1808} 1809#endif 1810 1811bool Layer::isVisible() const { 1812 const Layer::State& s(mDrawingState); 1813#ifdef USE_HWC2 1814 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f 1815 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1816#else 1817 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1818 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1819#endif 1820} 1821 1822bool Layer::allTransactionsSignaled() { 1823 auto headFrameNumber = getHeadFrameNumber(); 1824 bool matchingFramesFound = false; 1825 bool allTransactionsApplied = true; 1826 Mutex::Autolock lock(mLocalSyncPointMutex); 1827 1828 for (auto& point : mLocalSyncPoints) { 1829 if (point->getFrameNumber() > headFrameNumber) { 1830 break; 1831 } 1832 matchingFramesFound = true; 1833 1834 if (!point->frameIsAvailable()) { 1835 // We haven't notified the remote layer that the frame for 1836 // this point is available yet. Notify it now, and then 1837 // abort this attempt to latch. 1838 point->setFrameAvailable(); 1839 allTransactionsApplied = false; 1840 break; 1841 } 1842 1843 allTransactionsApplied = allTransactionsApplied && point->transactionIsApplied(); 1844 } 1845 return !matchingFramesFound || allTransactionsApplied; 1846} 1847 1848Region Layer::latchBuffer(bool& recomputeVisibleRegions, nsecs_t latchTime) 1849{ 1850 ATRACE_CALL(); 1851 1852 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1853 // mSidebandStreamChanged was true 1854 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1855 if (mSidebandStream != NULL) { 1856 setTransactionFlags(eTransactionNeeded); 1857 mFlinger->setTransactionFlags(eTraversalNeeded); 1858 } 1859 recomputeVisibleRegions = true; 1860 1861 const State& s(getDrawingState()); 1862 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h))); 1863 } 1864 1865 Region outDirtyRegion; 1866 if (mQueuedFrames <= 0 && !mAutoRefresh) { 1867 return outDirtyRegion; 1868 } 1869 1870 // if we've already called updateTexImage() without going through 1871 // a composition step, we have to skip this layer at this point 1872 // because we cannot call updateTeximage() without a corresponding 1873 // compositionComplete() call. 1874 // we'll trigger an update in onPreComposition(). 1875 if (mRefreshPending) { 1876 return outDirtyRegion; 1877 } 1878 1879 // If the head buffer's acquire fence hasn't signaled yet, return and 1880 // try again later 1881 if (!headFenceHasSignaled()) { 1882 mFlinger->signalLayerUpdate(); 1883 return outDirtyRegion; 1884 } 1885 1886 // Capture the old state of the layer for comparisons later 1887 const State& s(getDrawingState()); 1888 const bool oldOpacity = isOpaque(s); 1889 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1890 1891 if (!allTransactionsSignaled()) { 1892 mFlinger->signalLayerUpdate(); 1893 return outDirtyRegion; 1894 } 1895 1896 // This boolean is used to make sure that SurfaceFlinger's shadow copy 1897 // of the buffer queue isn't modified when the buffer queue is returning 1898 // BufferItem's that weren't actually queued. This can happen in shared 1899 // buffer mode. 1900 bool queuedBuffer = false; 1901 LayerRejecter r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 1902 getProducerStickyTransform() != 0, mName.string(), 1903 mOverrideScalingMode, mFreezePositionUpdates); 1904 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 1905 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer, 1906 mLastFrameNumberReceived); 1907 if (updateResult == BufferQueue::PRESENT_LATER) { 1908 // Producer doesn't want buffer to be displayed yet. Signal a 1909 // layer update so we check again at the next opportunity. 1910 mFlinger->signalLayerUpdate(); 1911 return outDirtyRegion; 1912 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 1913 // If the buffer has been rejected, remove it from the shadow queue 1914 // and return early 1915 if (queuedBuffer) { 1916 Mutex::Autolock lock(mQueueItemLock); 1917 mQueueItems.removeAt(0); 1918 android_atomic_dec(&mQueuedFrames); 1919 } 1920 return outDirtyRegion; 1921 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 1922 // This can occur if something goes wrong when trying to create the 1923 // EGLImage for this buffer. If this happens, the buffer has already 1924 // been released, so we need to clean up the queue and bug out 1925 // early. 1926 if (queuedBuffer) { 1927 Mutex::Autolock lock(mQueueItemLock); 1928 mQueueItems.clear(); 1929 android_atomic_and(0, &mQueuedFrames); 1930 } 1931 1932 // Once we have hit this state, the shadow queue may no longer 1933 // correctly reflect the incoming BufferQueue's contents, so even if 1934 // updateTexImage starts working, the only safe course of action is 1935 // to continue to ignore updates. 1936 mUpdateTexImageFailed = true; 1937 1938 return outDirtyRegion; 1939 } 1940 1941 if (queuedBuffer) { 1942 // Autolock scope 1943 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1944 1945 Mutex::Autolock lock(mQueueItemLock); 1946 1947 // Remove any stale buffers that have been dropped during 1948 // updateTexImage 1949 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 1950 mQueueItems.removeAt(0); 1951 android_atomic_dec(&mQueuedFrames); 1952 } 1953 1954 mQueueItems.removeAt(0); 1955 } 1956 1957 1958 // Decrement the queued-frames count. Signal another event if we 1959 // have more frames pending. 1960 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 1961 || mAutoRefresh) { 1962 mFlinger->signalLayerUpdate(); 1963 } 1964 1965 // update the active buffer 1966 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 1967 if (mActiveBuffer == NULL) { 1968 // this can only happen if the very first buffer was rejected. 1969 return outDirtyRegion; 1970 } 1971 1972 mBufferLatched = true; 1973 mPreviousFrameNumber = mCurrentFrameNumber; 1974 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1975 1976 { 1977 Mutex::Autolock lock(mFrameEventHistoryMutex); 1978 mFrameEventHistory.addLatch(mCurrentFrameNumber, latchTime); 1979#ifndef USE_HWC2 1980 auto releaseFenceTime = std::make_shared<FenceTime>( 1981 mSurfaceFlingerConsumer->getPrevFinalReleaseFence()); 1982 mReleaseTimeline.push(releaseFenceTime); 1983 mFrameEventHistory.addRelease( 1984 mPreviousFrameNumber, std::move(releaseFenceTime)); 1985#endif 1986 } 1987 1988 mRefreshPending = true; 1989 mFrameLatencyNeeded = true; 1990 if (oldActiveBuffer == NULL) { 1991 // the first time we receive a buffer, we need to trigger a 1992 // geometry invalidation. 1993 recomputeVisibleRegions = true; 1994 } 1995 1996 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 1997 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 1998 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 1999 if ((crop != mCurrentCrop) || 2000 (transform != mCurrentTransform) || 2001 (scalingMode != mCurrentScalingMode)) 2002 { 2003 mCurrentCrop = crop; 2004 mCurrentTransform = transform; 2005 mCurrentScalingMode = scalingMode; 2006 recomputeVisibleRegions = true; 2007 } 2008 2009 if (oldActiveBuffer != NULL) { 2010 uint32_t bufWidth = mActiveBuffer->getWidth(); 2011 uint32_t bufHeight = mActiveBuffer->getHeight(); 2012 if (bufWidth != uint32_t(oldActiveBuffer->width) || 2013 bufHeight != uint32_t(oldActiveBuffer->height)) { 2014 recomputeVisibleRegions = true; 2015 } 2016 } 2017 2018 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 2019 if (oldOpacity != isOpaque(s)) { 2020 recomputeVisibleRegions = true; 2021 } 2022 2023 // Remove any sync points corresponding to the buffer which was just 2024 // latched 2025 { 2026 Mutex::Autolock lock(mLocalSyncPointMutex); 2027 auto point = mLocalSyncPoints.begin(); 2028 while (point != mLocalSyncPoints.end()) { 2029 if (!(*point)->frameIsAvailable() || 2030 !(*point)->transactionIsApplied()) { 2031 // This sync point must have been added since we started 2032 // latching. Don't drop it yet. 2033 ++point; 2034 continue; 2035 } 2036 2037 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) { 2038 point = mLocalSyncPoints.erase(point); 2039 } else { 2040 ++point; 2041 } 2042 } 2043 } 2044 2045 // FIXME: postedRegion should be dirty & bounds 2046 Region dirtyRegion(Rect(s.active.w, s.active.h)); 2047 2048 // transform the dirty region to window-manager space 2049 outDirtyRegion = (s.active.transform.transform(dirtyRegion)); 2050 2051 return outDirtyRegion; 2052} 2053 2054uint32_t Layer::getEffectiveUsage(uint32_t usage) const 2055{ 2056 // TODO: should we do something special if mSecure is set? 2057 if (mProtectedByApp) { 2058 // need a hardware-protected path to external video sink 2059 usage |= GraphicBuffer::USAGE_PROTECTED; 2060 } 2061 if (mPotentialCursor) { 2062 usage |= GraphicBuffer::USAGE_CURSOR; 2063 } 2064 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 2065 return usage; 2066} 2067 2068void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 2069 uint32_t orientation = 0; 2070 if (!mFlinger->mDebugDisableTransformHint) { 2071 // The transform hint is used to improve performance, but we can 2072 // only have a single transform hint, it cannot 2073 // apply to all displays. 2074 const Transform& planeTransform(hw->getTransform()); 2075 orientation = planeTransform.getOrientation(); 2076 if (orientation & Transform::ROT_INVALID) { 2077 orientation = 0; 2078 } 2079 } 2080 mSurfaceFlingerConsumer->setTransformHint(orientation); 2081} 2082 2083// ---------------------------------------------------------------------------- 2084// debugging 2085// ---------------------------------------------------------------------------- 2086 2087void Layer::dump(String8& result, Colorizer& colorizer) const 2088{ 2089 const Layer::State& s(getDrawingState()); 2090 2091 colorizer.colorize(result, Colorizer::GREEN); 2092 result.appendFormat( 2093 "+ %s %p (%s)\n", 2094 getTypeId(), this, getName().string()); 2095 colorizer.reset(result); 2096 2097 s.activeTransparentRegion.dump(result, "transparentRegion"); 2098 visibleRegion.dump(result, "visibleRegion"); 2099 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 2100 sp<Client> client(mClientRef.promote()); 2101 2102 result.appendFormat( " " 2103 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), " 2104 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), " 2105 "isOpaque=%1d, invalidate=%1d, " 2106#ifdef USE_HWC2 2107 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2108#else 2109 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2110#endif 2111 " client=%p\n", 2112 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h, 2113 s.crop.left, s.crop.top, 2114 s.crop.right, s.crop.bottom, 2115 s.finalCrop.left, s.finalCrop.top, 2116 s.finalCrop.right, s.finalCrop.bottom, 2117 isOpaque(s), contentDirty, 2118 s.alpha, s.flags, 2119 s.active.transform[0][0], s.active.transform[0][1], 2120 s.active.transform[1][0], s.active.transform[1][1], 2121 client.get()); 2122 2123 sp<const GraphicBuffer> buf0(mActiveBuffer); 2124 uint32_t w0=0, h0=0, s0=0, f0=0; 2125 if (buf0 != 0) { 2126 w0 = buf0->getWidth(); 2127 h0 = buf0->getHeight(); 2128 s0 = buf0->getStride(); 2129 f0 = buf0->format; 2130 } 2131 result.appendFormat( 2132 " " 2133 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 2134 " queued-frames=%d, mRefreshPending=%d\n", 2135 mFormat, w0, h0, s0,f0, 2136 mQueuedFrames, mRefreshPending); 2137 2138 if (mSurfaceFlingerConsumer != 0) { 2139 mSurfaceFlingerConsumer->dumpState(result, " "); 2140 } 2141} 2142 2143#ifdef USE_HWC2 2144void Layer::miniDumpHeader(String8& result) { 2145 result.append("----------------------------------------"); 2146 result.append("---------------------------------------\n"); 2147 result.append(" Layer name\n"); 2148 result.append(" Z | "); 2149 result.append(" Comp Type | "); 2150 result.append(" Disp Frame (LTRB) | "); 2151 result.append(" Source Crop (LTRB)\n"); 2152 result.append("----------------------------------------"); 2153 result.append("---------------------------------------\n"); 2154} 2155 2156void Layer::miniDump(String8& result, int32_t hwcId) const { 2157 if (mHwcLayers.count(hwcId) == 0) { 2158 return; 2159 } 2160 2161 String8 name; 2162 if (mName.length() > 77) { 2163 std::string shortened; 2164 shortened.append(mName.string(), 36); 2165 shortened.append("[...]"); 2166 shortened.append(mName.string() + (mName.length() - 36), 36); 2167 name = shortened.c_str(); 2168 } else { 2169 name = mName; 2170 } 2171 2172 result.appendFormat(" %s\n", name.string()); 2173 2174 const Layer::State& layerState(getDrawingState()); 2175 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId); 2176 result.appendFormat(" %10u | ", layerState.z); 2177 result.appendFormat("%10s | ", 2178 to_string(getCompositionType(hwcId)).c_str()); 2179 const Rect& frame = hwcInfo.displayFrame; 2180 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, 2181 frame.right, frame.bottom); 2182 const gfx::FloatRect& crop = hwcInfo.sourceCrop; 2183 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, 2184 crop.right, crop.bottom); 2185 2186 result.append("- - - - - - - - - - - - - - - - - - - - "); 2187 result.append("- - - - - - - - - - - - - - - - - - - -\n"); 2188} 2189#endif 2190 2191void Layer::dumpFrameStats(String8& result) const { 2192 mFrameTracker.dumpStats(result); 2193} 2194 2195void Layer::clearFrameStats() { 2196 mFrameTracker.clearStats(); 2197} 2198 2199void Layer::logFrameStats() { 2200 mFrameTracker.logAndResetStats(mName); 2201} 2202 2203void Layer::getFrameStats(FrameStats* outStats) const { 2204 mFrameTracker.getStats(outStats); 2205} 2206 2207void Layer::dumpFrameEvents(String8& result) { 2208 result.appendFormat("- Layer %s (%s, %p)\n", 2209 getName().string(), getTypeId(), this); 2210 Mutex::Autolock lock(mFrameEventHistoryMutex); 2211 mFrameEventHistory.checkFencesForCompletion(); 2212 mFrameEventHistory.dump(result); 2213} 2214 2215void Layer::addAndGetFrameTimestamps(const NewFrameEventsEntry* newTimestamps, 2216 FrameEventHistoryDelta *outDelta) { 2217 Mutex::Autolock lock(mFrameEventHistoryMutex); 2218 if (newTimestamps) { 2219 mAcquireTimeline.push(newTimestamps->acquireFence); 2220 mFrameEventHistory.addQueue(*newTimestamps); 2221 } 2222 2223 if (outDelta) { 2224 mFrameEventHistory.getAndResetDelta(outDelta); 2225 } 2226} 2227 2228std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory( 2229 bool forceFlush) { 2230 std::vector<OccupancyTracker::Segment> history; 2231 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, 2232 &history); 2233 if (result != NO_ERROR) { 2234 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), 2235 result); 2236 return {}; 2237 } 2238 return history; 2239} 2240 2241bool Layer::getTransformToDisplayInverse() const { 2242 return mSurfaceFlingerConsumer->getTransformToDisplayInverse(); 2243} 2244 2245// --------------------------------------------------------------------------- 2246 2247}; // namespace android 2248 2249#if defined(__gl_h_) 2250#error "don't include gl/gl.h in this file" 2251#endif 2252 2253#if defined(__gl2_h_) 2254#error "don't include gl2/gl2.h in this file" 2255#endif 2256