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