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