Layer.cpp revision 9d96de49673cb6c916bfb797aad4f4e024ea73ca
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, true); 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 if (error != HWC2::Error::None) { 577 ALOGE("[%s] Failed to set display frame [%d, %d, %d, %d]: %s (%d)", 578 mName.string(), transformedFrame.left, transformedFrame.top, 579 transformedFrame.right, transformedFrame.bottom, 580 to_string(error).c_str(), static_cast<int32_t>(error)); 581 } else { 582 hwcInfo.displayFrame = transformedFrame; 583 } 584 585 FloatRect sourceCrop = computeCrop(displayDevice); 586 error = hwcLayer->setSourceCrop(sourceCrop); 587 if (error != HWC2::Error::None) { 588 ALOGE("[%s] Failed to set source crop [%.3f, %.3f, %.3f, %.3f]: " 589 "%s (%d)", mName.string(), sourceCrop.left, sourceCrop.top, 590 sourceCrop.right, sourceCrop.bottom, to_string(error).c_str(), 591 static_cast<int32_t>(error)); 592 } else { 593 hwcInfo.sourceCrop = sourceCrop; 594 } 595 596 error = hwcLayer->setPlaneAlpha(s.alpha); 597 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: " 598 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(), 599 static_cast<int32_t>(error)); 600 601 error = hwcLayer->setZOrder(s.z); 602 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)", 603 mName.string(), s.z, to_string(error).c_str(), 604 static_cast<int32_t>(error)); 605#else 606 if (!frame.intersect(hw->getViewport(), &frame)) { 607 frame.clear(); 608 } 609 const Transform& tr(hw->getTransform()); 610 layer.setFrame(tr.transform(frame)); 611 layer.setCrop(computeCrop(hw)); 612 layer.setPlaneAlpha(s.alpha); 613#endif 614 615 /* 616 * Transformations are applied in this order: 617 * 1) buffer orientation/flip/mirror 618 * 2) state transformation (window manager) 619 * 3) layer orientation (screen orientation) 620 * (NOTE: the matrices are multiplied in reverse order) 621 */ 622 623 const Transform bufferOrientation(mCurrentTransform); 624 Transform transform(tr * s.active.transform * bufferOrientation); 625 626 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { 627 /* 628 * the code below applies the primary display's inverse transform to the 629 * buffer 630 */ 631 uint32_t invTransform = 632 DisplayDevice::getPrimaryDisplayOrientationTransform(); 633 // calculate the inverse transform 634 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 635 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 636 NATIVE_WINDOW_TRANSFORM_FLIP_H; 637 } 638 // and apply to the current transform 639 transform = Transform(invTransform) * transform; 640 } 641 642 // this gives us only the "orientation" component of the transform 643 const uint32_t orientation = transform.getOrientation(); 644#ifdef USE_HWC2 645 if (orientation & Transform::ROT_INVALID) { 646 // we can only handle simple transformation 647 hwcInfo.forceClientComposition = true; 648 } else { 649 auto transform = static_cast<HWC2::Transform>(orientation); 650 auto error = hwcLayer->setTransform(transform); 651 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: " 652 "%s (%d)", mName.string(), to_string(transform).c_str(), 653 to_string(error).c_str(), static_cast<int32_t>(error)); 654 } 655#else 656 if (orientation & Transform::ROT_INVALID) { 657 // we can only handle simple transformation 658 layer.setSkip(true); 659 } else { 660 layer.setTransform(orientation); 661 } 662#endif 663} 664 665#ifdef USE_HWC2 666void Layer::forceClientComposition(int32_t hwcId) { 667 if (mHwcLayers.count(hwcId) == 0) { 668 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId); 669 return; 670 } 671 672 mHwcLayers[hwcId].forceClientComposition = true; 673} 674#endif 675 676#ifdef USE_HWC2 677void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) { 678 // Apply this display's projection's viewport to the visible region 679 // before giving it to the HWC HAL. 680 const Transform& tr = displayDevice->getTransform(); 681 const auto& viewport = displayDevice->getViewport(); 682 Region visible = tr.transform(visibleRegion.intersect(viewport)); 683 auto hwcId = displayDevice->getHwcDisplayId(); 684 auto& hwcLayer = mHwcLayers[hwcId].layer; 685 auto error = hwcLayer->setVisibleRegion(visible); 686 if (error != HWC2::Error::None) { 687 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(), 688 to_string(error).c_str(), static_cast<int32_t>(error)); 689 visible.dump(LOG_TAG); 690 } 691 692 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion); 693 if (error != HWC2::Error::None) { 694 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(), 695 to_string(error).c_str(), static_cast<int32_t>(error)); 696 surfaceDamageRegion.dump(LOG_TAG); 697 } 698 699 // Sideband layers 700 if (mSidebandStream.get()) { 701 setCompositionType(hwcId, HWC2::Composition::Sideband); 702 ALOGV("[%s] Requesting Sideband composition", mName.string()); 703 error = hwcLayer->setSidebandStream(mSidebandStream->handle()); 704 if (error != HWC2::Error::None) { 705 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", 706 mName.string(), mSidebandStream->handle(), 707 to_string(error).c_str(), static_cast<int32_t>(error)); 708 } 709 return; 710 } 711 712 // Client layers 713 if (mHwcLayers[hwcId].forceClientComposition || 714 (mActiveBuffer != nullptr && mActiveBuffer->handle == nullptr)) { 715 ALOGV("[%s] Requesting Client composition", mName.string()); 716 setCompositionType(hwcId, HWC2::Composition::Client); 717 return; 718 } 719 720 // SolidColor layers 721 if (mActiveBuffer == nullptr) { 722 setCompositionType(hwcId, HWC2::Composition::SolidColor); 723 724 // For now, we only support black for DimLayer 725 error = hwcLayer->setColor({0, 0, 0, 255}); 726 if (error != HWC2::Error::None) { 727 ALOGE("[%s] Failed to set color: %s (%d)", mName.string(), 728 to_string(error).c_str(), static_cast<int32_t>(error)); 729 } 730 731 // Clear out the transform, because it doesn't make sense absent a 732 // source buffer 733 error = hwcLayer->setTransform(HWC2::Transform::None); 734 if (error != HWC2::Error::None) { 735 ALOGE("[%s] Failed to clear transform: %s (%d)", mName.string(), 736 to_string(error).c_str(), static_cast<int32_t>(error)); 737 } 738 739 return; 740 } 741 742 // Device or Cursor layers 743 if (mPotentialCursor) { 744 ALOGV("[%s] Requesting Cursor composition", mName.string()); 745 setCompositionType(hwcId, HWC2::Composition::Cursor); 746 } else { 747 ALOGV("[%s] Requesting Device composition", mName.string()); 748 setCompositionType(hwcId, HWC2::Composition::Device); 749 } 750 751 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 752 error = hwcLayer->setBuffer(mActiveBuffer->handle, acquireFence); 753 if (error != HWC2::Error::None) { 754 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), 755 mActiveBuffer->handle, to_string(error).c_str(), 756 static_cast<int32_t>(error)); 757 } 758} 759#else 760void Layer::setPerFrameData(const sp<const DisplayDevice>& hw, 761 HWComposer::HWCLayerInterface& layer) { 762 // we have to set the visible region on every frame because 763 // we currently free it during onLayerDisplayed(), which is called 764 // after HWComposer::commit() -- every frame. 765 // Apply this display's projection's viewport to the visible region 766 // before giving it to the HWC HAL. 767 const Transform& tr = hw->getTransform(); 768 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport())); 769 layer.setVisibleRegionScreen(visible); 770 layer.setSurfaceDamage(surfaceDamageRegion); 771 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER); 772 773 if (mSidebandStream.get()) { 774 layer.setSidebandStream(mSidebandStream); 775 } else { 776 // NOTE: buffer can be NULL if the client never drew into this 777 // layer yet, or if we ran out of memory 778 layer.setBuffer(mActiveBuffer); 779 } 780} 781#endif 782 783#ifdef USE_HWC2 784void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) { 785 auto hwcId = displayDevice->getHwcDisplayId(); 786 if (mHwcLayers.count(hwcId) == 0 || 787 getCompositionType(hwcId) != HWC2::Composition::Cursor) { 788 return; 789 } 790 791 // This gives us only the "orientation" component of the transform 792 const State& s(getCurrentState()); 793 794 // Apply the layer's transform, followed by the display's global transform 795 // Here we're guaranteed that the layer's transform preserves rects 796 Rect win(s.active.w, s.active.h); 797 if (!s.crop.isEmpty()) { 798 win.intersect(s.crop, &win); 799 } 800 // Subtract the transparent region and snap to the bounds 801 Rect bounds = reduce(win, s.activeTransparentRegion); 802 Rect frame(s.active.transform.transform(bounds)); 803 frame.intersect(displayDevice->getViewport(), &frame); 804 if (!s.finalCrop.isEmpty()) { 805 frame.intersect(s.finalCrop, &frame); 806 } 807 auto& displayTransform(displayDevice->getTransform()); 808 auto position = displayTransform.transform(frame); 809 810 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left, 811 position.top); 812 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position " 813 "to (%d, %d): %s (%d)", mName.string(), position.left, 814 position.top, to_string(error).c_str(), 815 static_cast<int32_t>(error)); 816} 817#else 818void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */, 819 HWComposer::HWCLayerInterface& layer) { 820 int fenceFd = -1; 821 822 // TODO: there is a possible optimization here: we only need to set the 823 // acquire fence the first time a new buffer is acquired on EACH display. 824 825 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) { 826 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence(); 827 if (fence->isValid()) { 828 fenceFd = fence->dup(); 829 if (fenceFd == -1) { 830 ALOGW("failed to dup layer fence, skipping sync: %d", errno); 831 } 832 } 833 } 834 layer.setAcquireFenceFd(fenceFd); 835} 836 837Rect Layer::getPosition( 838 const sp<const DisplayDevice>& hw) 839{ 840 // this gives us only the "orientation" component of the transform 841 const State& s(getCurrentState()); 842 843 // apply the layer's transform, followed by the display's global transform 844 // here we're guaranteed that the layer's transform preserves rects 845 Rect win(s.active.w, s.active.h); 846 if (!s.crop.isEmpty()) { 847 win.intersect(s.crop, &win); 848 } 849 // subtract the transparent region and snap to the bounds 850 Rect bounds = reduce(win, s.activeTransparentRegion); 851 Rect frame(s.active.transform.transform(bounds)); 852 frame.intersect(hw->getViewport(), &frame); 853 if (!s.finalCrop.isEmpty()) { 854 frame.intersect(s.finalCrop, &frame); 855 } 856 const Transform& tr(hw->getTransform()); 857 return Rect(tr.transform(frame)); 858} 859#endif 860 861// --------------------------------------------------------------------------- 862// drawing... 863// --------------------------------------------------------------------------- 864 865void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const { 866 onDraw(hw, clip, false); 867} 868 869void Layer::draw(const sp<const DisplayDevice>& hw, 870 bool useIdentityTransform) const { 871 onDraw(hw, Region(hw->bounds()), useIdentityTransform); 872} 873 874void Layer::draw(const sp<const DisplayDevice>& hw) const { 875 onDraw(hw, Region(hw->bounds()), false); 876} 877 878void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip, 879 bool useIdentityTransform) const 880{ 881 ATRACE_CALL(); 882 883 if (CC_UNLIKELY(mActiveBuffer == 0)) { 884 // the texture has not been created yet, this Layer has 885 // in fact never been drawn into. This happens frequently with 886 // SurfaceView because the WindowManager can't know when the client 887 // has drawn the first time. 888 889 // If there is nothing under us, we paint the screen in black, otherwise 890 // we just skip this update. 891 892 // figure out if there is something below us 893 Region under; 894 const SurfaceFlinger::LayerVector& drawingLayers( 895 mFlinger->mDrawingState.layersSortedByZ); 896 const size_t count = drawingLayers.size(); 897 for (size_t i=0 ; i<count ; ++i) { 898 const sp<Layer>& layer(drawingLayers[i]); 899 if (layer.get() == static_cast<Layer const*>(this)) 900 break; 901 under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); 902 } 903 // if not everything below us is covered, we plug the holes! 904 Region holes(clip.subtract(under)); 905 if (!holes.isEmpty()) { 906 clearWithOpenGL(hw, holes, 0, 0, 0, 1); 907 } 908 return; 909 } 910 911 // Bind the current buffer to the GL texture, and wait for it to be 912 // ready for us to draw into. 913 status_t err = mSurfaceFlingerConsumer->bindTextureImage(); 914 if (err != NO_ERROR) { 915 ALOGW("onDraw: bindTextureImage failed (err=%d)", err); 916 // Go ahead and draw the buffer anyway; no matter what we do the screen 917 // is probably going to have something visibly wrong. 918 } 919 920 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure()); 921 922 RenderEngine& engine(mFlinger->getRenderEngine()); 923 924 if (!blackOutLayer) { 925 // TODO: we could be more subtle with isFixedSize() 926 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize(); 927 928 // Query the texture matrix given our current filtering mode. 929 float textureMatrix[16]; 930 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering); 931 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix); 932 933 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { 934 935 /* 936 * the code below applies the primary display's inverse transform to 937 * the texture transform 938 */ 939 940 // create a 4x4 transform matrix from the display transform flags 941 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1); 942 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1); 943 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1); 944 945 mat4 tr; 946 uint32_t transform = 947 DisplayDevice::getPrimaryDisplayOrientationTransform(); 948 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) 949 tr = tr * rot90; 950 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) 951 tr = tr * flipH; 952 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) 953 tr = tr * flipV; 954 955 // calculate the inverse 956 tr = inverse(tr); 957 958 // and finally apply it to the original texture matrix 959 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr); 960 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix)); 961 } 962 963 // Set things up for texturing. 964 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight()); 965 mTexture.setFiltering(useFiltering); 966 mTexture.setMatrix(textureMatrix); 967 968 engine.setupLayerTexturing(mTexture); 969 } else { 970 engine.setupLayerBlackedOut(); 971 } 972 drawWithOpenGL(hw, clip, useIdentityTransform); 973 engine.disableTexturing(); 974} 975 976 977void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw, 978 const Region& /* clip */, float red, float green, float blue, 979 float alpha) const 980{ 981 RenderEngine& engine(mFlinger->getRenderEngine()); 982 computeGeometry(hw, mMesh, false); 983 engine.setupFillWithColor(red, green, blue, alpha); 984 engine.drawMesh(mMesh); 985} 986 987void Layer::clearWithOpenGL( 988 const sp<const DisplayDevice>& hw, const Region& clip) const { 989 clearWithOpenGL(hw, clip, 0,0,0,0); 990} 991 992void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw, 993 const Region& /* clip */, bool useIdentityTransform) const { 994 const State& s(getDrawingState()); 995 996 computeGeometry(hw, mMesh, useIdentityTransform); 997 998 /* 999 * NOTE: the way we compute the texture coordinates here produces 1000 * different results than when we take the HWC path -- in the later case 1001 * the "source crop" is rounded to texel boundaries. 1002 * This can produce significantly different results when the texture 1003 * is scaled by a large amount. 1004 * 1005 * The GL code below is more logical (imho), and the difference with 1006 * HWC is due to a limitation of the HWC API to integers -- a question 1007 * is suspend is whether we should ignore this problem or revert to 1008 * GL composition when a buffer scaling is applied (maybe with some 1009 * minimal value)? Or, we could make GL behave like HWC -- but this feel 1010 * like more of a hack. 1011 */ 1012 Rect win(computeBounds()); 1013 1014 if (!s.finalCrop.isEmpty()) { 1015 win = s.active.transform.transform(win); 1016 if (!win.intersect(s.finalCrop, &win)) { 1017 win.clear(); 1018 } 1019 win = s.active.transform.inverse().transform(win); 1020 if (!win.intersect(computeBounds(), &win)) { 1021 win.clear(); 1022 } 1023 } 1024 1025 float left = float(win.left) / float(s.active.w); 1026 float top = float(win.top) / float(s.active.h); 1027 float right = float(win.right) / float(s.active.w); 1028 float bottom = float(win.bottom) / float(s.active.h); 1029 1030 // TODO: we probably want to generate the texture coords with the mesh 1031 // here we assume that we only have 4 vertices 1032 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>()); 1033 texCoords[0] = vec2(left, 1.0f - top); 1034 texCoords[1] = vec2(left, 1.0f - bottom); 1035 texCoords[2] = vec2(right, 1.0f - bottom); 1036 texCoords[3] = vec2(right, 1.0f - top); 1037 1038 RenderEngine& engine(mFlinger->getRenderEngine()); 1039 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha); 1040 engine.drawMesh(mMesh); 1041 engine.disableBlending(); 1042} 1043 1044#ifdef USE_HWC2 1045void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type, 1046 bool callIntoHwc) { 1047 if (mHwcLayers.count(hwcId) == 0) { 1048 ALOGE("setCompositionType called without a valid HWC layer"); 1049 return; 1050 } 1051 auto& hwcInfo = mHwcLayers[hwcId]; 1052 auto& hwcLayer = hwcInfo.layer; 1053 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(), 1054 to_string(type).c_str(), static_cast<int>(callIntoHwc)); 1055 if (hwcInfo.compositionType != type) { 1056 ALOGV(" actually setting"); 1057 hwcInfo.compositionType = type; 1058 if (callIntoHwc) { 1059 auto error = hwcLayer->setCompositionType(type); 1060 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set " 1061 "composition type %s: %s (%d)", mName.string(), 1062 to_string(type).c_str(), to_string(error).c_str(), 1063 static_cast<int32_t>(error)); 1064 } 1065 } 1066} 1067 1068HWC2::Composition Layer::getCompositionType(int32_t hwcId) const { 1069 if (hwcId == DisplayDevice::DISPLAY_ID_INVALID) { 1070 // If we're querying the composition type for a display that does not 1071 // have a HWC counterpart, then it will always be Client 1072 return HWC2::Composition::Client; 1073 } 1074 if (mHwcLayers.count(hwcId) == 0) { 1075 ALOGE("getCompositionType called with an invalid HWC layer"); 1076 return HWC2::Composition::Invalid; 1077 } 1078 return mHwcLayers.at(hwcId).compositionType; 1079} 1080 1081void Layer::setClearClientTarget(int32_t hwcId, bool clear) { 1082 if (mHwcLayers.count(hwcId) == 0) { 1083 ALOGE("setClearClientTarget called without a valid HWC layer"); 1084 return; 1085 } 1086 mHwcLayers[hwcId].clearClientTarget = clear; 1087} 1088 1089bool Layer::getClearClientTarget(int32_t hwcId) const { 1090 if (mHwcLayers.count(hwcId) == 0) { 1091 ALOGE("getClearClientTarget called without a valid HWC layer"); 1092 return false; 1093 } 1094 return mHwcLayers.at(hwcId).clearClientTarget; 1095} 1096#endif 1097 1098uint32_t Layer::getProducerStickyTransform() const { 1099 int producerStickyTransform = 0; 1100 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform); 1101 if (ret != OK) { 1102 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__, 1103 strerror(-ret), ret); 1104 return 0; 1105 } 1106 return static_cast<uint32_t>(producerStickyTransform); 1107} 1108 1109bool Layer::latchUnsignaledBuffers() { 1110 static bool propertyLoaded = false; 1111 static bool latch = false; 1112 static std::mutex mutex; 1113 std::lock_guard<std::mutex> lock(mutex); 1114 if (!propertyLoaded) { 1115 char value[PROPERTY_VALUE_MAX] = {}; 1116 property_get("debug.sf.latch_unsignaled", value, "0"); 1117 latch = atoi(value); 1118 propertyLoaded = true; 1119 } 1120 return latch; 1121} 1122 1123uint64_t Layer::getHeadFrameNumber() const { 1124 Mutex::Autolock lock(mQueueItemLock); 1125 if (!mQueueItems.empty()) { 1126 return mQueueItems[0].mFrameNumber; 1127 } else { 1128 return mCurrentFrameNumber; 1129 } 1130} 1131 1132bool Layer::headFenceHasSignaled() const { 1133#ifdef USE_HWC2 1134 if (latchUnsignaledBuffers()) { 1135 return true; 1136 } 1137 1138 Mutex::Autolock lock(mQueueItemLock); 1139 if (mQueueItems.empty()) { 1140 return true; 1141 } 1142 if (mQueueItems[0].mIsDroppable) { 1143 // Even though this buffer's fence may not have signaled yet, it could 1144 // be replaced by another buffer before it has a chance to, which means 1145 // that it's possible to get into a situation where a buffer is never 1146 // able to be latched. To avoid this, grab this buffer anyway. 1147 return true; 1148 } 1149 return mQueueItems[0].mFence->getSignalTime() != INT64_MAX; 1150#else 1151 return true; 1152#endif 1153} 1154 1155bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) { 1156 if (point->getFrameNumber() <= mCurrentFrameNumber) { 1157 // Don't bother with a SyncPoint, since we've already latched the 1158 // relevant frame 1159 return false; 1160 } 1161 1162 Mutex::Autolock lock(mLocalSyncPointMutex); 1163 mLocalSyncPoints.push_back(point); 1164 return true; 1165} 1166 1167void Layer::setFiltering(bool filtering) { 1168 mFiltering = filtering; 1169} 1170 1171bool Layer::getFiltering() const { 1172 return mFiltering; 1173} 1174 1175// As documented in libhardware header, formats in the range 1176// 0x100 - 0x1FF are specific to the HAL implementation, and 1177// are known to have no alpha channel 1178// TODO: move definition for device-specific range into 1179// hardware.h, instead of using hard-coded values here. 1180#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 1181 1182bool Layer::getOpacityForFormat(uint32_t format) { 1183 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 1184 return true; 1185 } 1186 switch (format) { 1187 case HAL_PIXEL_FORMAT_RGBA_8888: 1188 case HAL_PIXEL_FORMAT_BGRA_8888: 1189 return false; 1190 } 1191 // in all other case, we have no blending (also for unknown formats) 1192 return true; 1193} 1194 1195// ---------------------------------------------------------------------------- 1196// local state 1197// ---------------------------------------------------------------------------- 1198 1199static void boundPoint(vec2* point, const Rect& crop) { 1200 if (point->x < crop.left) { 1201 point->x = crop.left; 1202 } 1203 if (point->x > crop.right) { 1204 point->x = crop.right; 1205 } 1206 if (point->y < crop.top) { 1207 point->y = crop.top; 1208 } 1209 if (point->y > crop.bottom) { 1210 point->y = crop.bottom; 1211 } 1212} 1213 1214void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh, 1215 bool useIdentityTransform) const 1216{ 1217 const Layer::State& s(getDrawingState()); 1218 const Transform tr(hw->getTransform()); 1219 const uint32_t hw_h = hw->getHeight(); 1220 Rect win(s.active.w, s.active.h); 1221 if (!s.crop.isEmpty()) { 1222 win.intersect(s.crop, &win); 1223 } 1224 // subtract the transparent region and snap to the bounds 1225 win = reduce(win, s.activeTransparentRegion); 1226 1227 vec2 lt = vec2(win.left, win.top); 1228 vec2 lb = vec2(win.left, win.bottom); 1229 vec2 rb = vec2(win.right, win.bottom); 1230 vec2 rt = vec2(win.right, win.top); 1231 1232 if (!useIdentityTransform) { 1233 lt = s.active.transform.transform(lt); 1234 lb = s.active.transform.transform(lb); 1235 rb = s.active.transform.transform(rb); 1236 rt = s.active.transform.transform(rt); 1237 } 1238 1239 if (!s.finalCrop.isEmpty()) { 1240 boundPoint(<, s.finalCrop); 1241 boundPoint(&lb, s.finalCrop); 1242 boundPoint(&rb, s.finalCrop); 1243 boundPoint(&rt, s.finalCrop); 1244 } 1245 1246 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>()); 1247 position[0] = tr.transform(lt); 1248 position[1] = tr.transform(lb); 1249 position[2] = tr.transform(rb); 1250 position[3] = tr.transform(rt); 1251 for (size_t i=0 ; i<4 ; i++) { 1252 position[i].y = hw_h - position[i].y; 1253 } 1254} 1255 1256bool Layer::isOpaque(const Layer::State& s) const 1257{ 1258 // if we don't have a buffer yet, we're translucent regardless of the 1259 // layer's opaque flag. 1260 if (mActiveBuffer == 0) { 1261 return false; 1262 } 1263 1264 // if the layer has the opaque flag, then we're always opaque, 1265 // otherwise we use the current buffer's format. 1266 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity; 1267} 1268 1269bool Layer::isSecure() const 1270{ 1271 const Layer::State& s(mDrawingState); 1272 return (s.flags & layer_state_t::eLayerSecure); 1273} 1274 1275bool Layer::isProtected() const 1276{ 1277 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 1278 return (activeBuffer != 0) && 1279 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 1280} 1281 1282bool Layer::isFixedSize() const { 1283 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1284} 1285 1286bool Layer::isCropped() const { 1287 return !mCurrentCrop.isEmpty(); 1288} 1289 1290bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const { 1291 return mNeedsFiltering || hw->needsFiltering(); 1292} 1293 1294void Layer::setVisibleRegion(const Region& visibleRegion) { 1295 // always called from main thread 1296 this->visibleRegion = visibleRegion; 1297} 1298 1299void Layer::setCoveredRegion(const Region& coveredRegion) { 1300 // always called from main thread 1301 this->coveredRegion = coveredRegion; 1302} 1303 1304void Layer::setVisibleNonTransparentRegion(const Region& 1305 setVisibleNonTransparentRegion) { 1306 // always called from main thread 1307 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion; 1308} 1309 1310// ---------------------------------------------------------------------------- 1311// transaction 1312// ---------------------------------------------------------------------------- 1313 1314void Layer::pushPendingState() { 1315 if (!mCurrentState.modified) { 1316 return; 1317 } 1318 1319 // If this transaction is waiting on the receipt of a frame, generate a sync 1320 // point and send it to the remote layer. 1321 if (mCurrentState.handle != nullptr) { 1322 sp<IBinder> strongBinder = mCurrentState.handle.promote(); 1323 sp<Handle> handle = nullptr; 1324 sp<Layer> handleLayer = nullptr; 1325 if (strongBinder != nullptr) { 1326 handle = static_cast<Handle*>(strongBinder.get()); 1327 handleLayer = handle->owner.promote(); 1328 } 1329 if (strongBinder == nullptr || handleLayer == nullptr) { 1330 ALOGE("[%s] Unable to promote Layer handle", mName.string()); 1331 // If we can't promote the layer we are intended to wait on, 1332 // then it is expired or otherwise invalid. Allow this transaction 1333 // to be applied as per normal (no synchronization). 1334 mCurrentState.handle = nullptr; 1335 } else { 1336 auto syncPoint = std::make_shared<SyncPoint>( 1337 mCurrentState.frameNumber); 1338 if (handleLayer->addSyncPoint(syncPoint)) { 1339 mRemoteSyncPoints.push_back(std::move(syncPoint)); 1340 } else { 1341 // We already missed the frame we're supposed to synchronize 1342 // on, so go ahead and apply the state update 1343 mCurrentState.handle = nullptr; 1344 } 1345 } 1346 1347 // Wake us up to check if the frame has been received 1348 setTransactionFlags(eTransactionNeeded); 1349 } 1350 mPendingStates.push_back(mCurrentState); 1351} 1352 1353void Layer::popPendingState(State* stateToCommit) { 1354 auto oldFlags = stateToCommit->flags; 1355 *stateToCommit = mPendingStates[0]; 1356 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) | 1357 (stateToCommit->flags & stateToCommit->mask); 1358 1359 mPendingStates.removeAt(0); 1360} 1361 1362bool Layer::applyPendingStates(State* stateToCommit) { 1363 bool stateUpdateAvailable = false; 1364 while (!mPendingStates.empty()) { 1365 if (mPendingStates[0].handle != nullptr) { 1366 if (mRemoteSyncPoints.empty()) { 1367 // If we don't have a sync point for this, apply it anyway. It 1368 // will be visually wrong, but it should keep us from getting 1369 // into too much trouble. 1370 ALOGE("[%s] No local sync point found", mName.string()); 1371 popPendingState(stateToCommit); 1372 stateUpdateAvailable = true; 1373 continue; 1374 } 1375 1376 if (mRemoteSyncPoints.front()->getFrameNumber() != 1377 mPendingStates[0].frameNumber) { 1378 ALOGE("[%s] Unexpected sync point frame number found", 1379 mName.string()); 1380 1381 // Signal our end of the sync point and then dispose of it 1382 mRemoteSyncPoints.front()->setTransactionApplied(); 1383 mRemoteSyncPoints.pop_front(); 1384 continue; 1385 } 1386 1387 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 1388 // Apply the state update 1389 popPendingState(stateToCommit); 1390 stateUpdateAvailable = true; 1391 1392 // Signal our end of the sync point and then dispose of it 1393 mRemoteSyncPoints.front()->setTransactionApplied(); 1394 mRemoteSyncPoints.pop_front(); 1395 } else { 1396 break; 1397 } 1398 } else { 1399 popPendingState(stateToCommit); 1400 stateUpdateAvailable = true; 1401 } 1402 } 1403 1404 // If we still have pending updates, wake SurfaceFlinger back up and point 1405 // it at this layer so we can process them 1406 if (!mPendingStates.empty()) { 1407 setTransactionFlags(eTransactionNeeded); 1408 mFlinger->setTransactionFlags(eTraversalNeeded); 1409 } 1410 1411 mCurrentState.modified = false; 1412 return stateUpdateAvailable; 1413} 1414 1415void Layer::notifyAvailableFrames() { 1416 auto headFrameNumber = getHeadFrameNumber(); 1417 bool headFenceSignaled = headFenceHasSignaled(); 1418 Mutex::Autolock lock(mLocalSyncPointMutex); 1419 for (auto& point : mLocalSyncPoints) { 1420 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) { 1421 point->setFrameAvailable(); 1422 } 1423 } 1424} 1425 1426uint32_t Layer::doTransaction(uint32_t flags) { 1427 ATRACE_CALL(); 1428 1429 pushPendingState(); 1430 Layer::State c = getCurrentState(); 1431 if (!applyPendingStates(&c)) { 1432 return 0; 1433 } 1434 1435 const Layer::State& s(getDrawingState()); 1436 1437 const bool sizeChanged = (c.requested.w != s.requested.w) || 1438 (c.requested.h != s.requested.h); 1439 1440 if (sizeChanged) { 1441 // the size changed, we need to ask our client to request a new buffer 1442 ALOGD_IF(DEBUG_RESIZE, 1443 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1444 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1445 " requested={ wh={%4u,%4u} }}\n" 1446 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1447 " requested={ wh={%4u,%4u} }}\n", 1448 this, getName().string(), mCurrentTransform, 1449 getEffectiveScalingMode(), 1450 c.active.w, c.active.h, 1451 c.crop.left, 1452 c.crop.top, 1453 c.crop.right, 1454 c.crop.bottom, 1455 c.crop.getWidth(), 1456 c.crop.getHeight(), 1457 c.requested.w, c.requested.h, 1458 s.active.w, s.active.h, 1459 s.crop.left, 1460 s.crop.top, 1461 s.crop.right, 1462 s.crop.bottom, 1463 s.crop.getWidth(), 1464 s.crop.getHeight(), 1465 s.requested.w, s.requested.h); 1466 1467 // record the new size, form this point on, when the client request 1468 // a buffer, it'll get the new size. 1469 mSurfaceFlingerConsumer->setDefaultBufferSize( 1470 c.requested.w, c.requested.h); 1471 } 1472 1473 const bool resizePending = (c.requested.w != c.active.w) || 1474 (c.requested.h != c.active.h); 1475 if (!isFixedSize()) { 1476 if (resizePending && mSidebandStream == NULL) { 1477 // don't let Layer::doTransaction update the drawing state 1478 // if we have a pending resize, unless we are in fixed-size mode. 1479 // the drawing state will be updated only once we receive a buffer 1480 // with the correct size. 1481 // 1482 // in particular, we want to make sure the clip (which is part 1483 // of the geometry state) is latched together with the size but is 1484 // latched immediately when no resizing is involved. 1485 // 1486 // If a sideband stream is attached, however, we want to skip this 1487 // optimization so that transactions aren't missed when a buffer 1488 // never arrives 1489 1490 flags |= eDontUpdateGeometryState; 1491 } 1492 } 1493 1494 // always set active to requested, unless we're asked not to 1495 // this is used by Layer, which special cases resizes. 1496 if (flags & eDontUpdateGeometryState) { 1497 } else { 1498 Layer::State& editCurrentState(getCurrentState()); 1499 if (mFreezePositionUpdates) { 1500 float tx = c.active.transform.tx(); 1501 float ty = c.active.transform.ty(); 1502 c.active = c.requested; 1503 c.active.transform.set(tx, ty); 1504 editCurrentState.active = c.active; 1505 } else { 1506 editCurrentState.active = editCurrentState.requested; 1507 c.active = c.requested; 1508 } 1509 } 1510 1511 if (s.active != c.active) { 1512 // invalidate and recompute the visible regions if needed 1513 flags |= Layer::eVisibleRegion; 1514 } 1515 1516 if (c.sequence != s.sequence) { 1517 // invalidate and recompute the visible regions if needed 1518 flags |= eVisibleRegion; 1519 this->contentDirty = true; 1520 1521 // we may use linear filtering, if the matrix scales us 1522 const uint8_t type = c.active.transform.getType(); 1523 mNeedsFiltering = (!c.active.transform.preserveRects() || 1524 (type >= Transform::SCALE)); 1525 } 1526 1527 // If the layer is hidden, signal and clear out all local sync points so 1528 // that transactions for layers depending on this layer's frames becoming 1529 // visible are not blocked 1530 if (c.flags & layer_state_t::eLayerHidden) { 1531 Mutex::Autolock lock(mLocalSyncPointMutex); 1532 for (auto& point : mLocalSyncPoints) { 1533 point->setFrameAvailable(); 1534 } 1535 mLocalSyncPoints.clear(); 1536 } 1537 1538 // Commit the transaction 1539 commitTransaction(c); 1540 return flags; 1541} 1542 1543void Layer::commitTransaction(const State& stateToCommit) { 1544 mDrawingState = stateToCommit; 1545} 1546 1547uint32_t Layer::getTransactionFlags(uint32_t flags) { 1548 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1549} 1550 1551uint32_t Layer::setTransactionFlags(uint32_t flags) { 1552 return android_atomic_or(flags, &mTransactionFlags); 1553} 1554 1555bool Layer::setPosition(float x, float y, bool immediate) { 1556 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y) 1557 return false; 1558 mCurrentState.sequence++; 1559 1560 // We update the requested and active position simultaneously because 1561 // we want to apply the position portion of the transform matrix immediately, 1562 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1563 mCurrentState.requested.transform.set(x, y); 1564 if (immediate && !mFreezePositionUpdates) { 1565 mCurrentState.active.transform.set(x, y); 1566 } 1567 mFreezePositionUpdates = mFreezePositionUpdates || !immediate; 1568 1569 mCurrentState.modified = true; 1570 setTransactionFlags(eTransactionNeeded); 1571 return true; 1572} 1573 1574bool Layer::setLayer(uint32_t z) { 1575 if (mCurrentState.z == z) 1576 return false; 1577 mCurrentState.sequence++; 1578 mCurrentState.z = z; 1579 mCurrentState.modified = true; 1580 setTransactionFlags(eTransactionNeeded); 1581 return true; 1582} 1583bool Layer::setSize(uint32_t w, uint32_t h) { 1584 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1585 return false; 1586 mCurrentState.requested.w = w; 1587 mCurrentState.requested.h = h; 1588 mCurrentState.modified = true; 1589 setTransactionFlags(eTransactionNeeded); 1590 return true; 1591} 1592#ifdef USE_HWC2 1593bool Layer::setAlpha(float alpha) { 1594#else 1595bool Layer::setAlpha(uint8_t alpha) { 1596#endif 1597 if (mCurrentState.alpha == alpha) 1598 return false; 1599 mCurrentState.sequence++; 1600 mCurrentState.alpha = alpha; 1601 mCurrentState.modified = true; 1602 setTransactionFlags(eTransactionNeeded); 1603 return true; 1604} 1605bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1606 mCurrentState.sequence++; 1607 mCurrentState.requested.transform.set( 1608 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1609 mCurrentState.modified = true; 1610 setTransactionFlags(eTransactionNeeded); 1611 return true; 1612} 1613bool Layer::setTransparentRegionHint(const Region& transparent) { 1614 mCurrentState.requestedTransparentRegion = transparent; 1615 mCurrentState.modified = true; 1616 setTransactionFlags(eTransactionNeeded); 1617 return true; 1618} 1619bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1620 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1621 if (mCurrentState.flags == newFlags) 1622 return false; 1623 mCurrentState.sequence++; 1624 mCurrentState.flags = newFlags; 1625 mCurrentState.mask = mask; 1626 mCurrentState.modified = true; 1627 setTransactionFlags(eTransactionNeeded); 1628 return true; 1629} 1630 1631bool Layer::setCrop(const Rect& crop, bool immediate) { 1632 if (mCurrentState.crop == crop) 1633 return false; 1634 mCurrentState.sequence++; 1635 mCurrentState.requestedCrop = crop; 1636 if (immediate) { 1637 mCurrentState.crop = crop; 1638 } 1639 mCurrentState.modified = true; 1640 setTransactionFlags(eTransactionNeeded); 1641 return true; 1642} 1643bool Layer::setFinalCrop(const Rect& crop) { 1644 if (mCurrentState.finalCrop == crop) 1645 return false; 1646 mCurrentState.sequence++; 1647 mCurrentState.finalCrop = crop; 1648 mCurrentState.modified = true; 1649 setTransactionFlags(eTransactionNeeded); 1650 return true; 1651} 1652 1653bool Layer::setOverrideScalingMode(int32_t scalingMode) { 1654 if (scalingMode == mOverrideScalingMode) 1655 return false; 1656 mOverrideScalingMode = scalingMode; 1657 setTransactionFlags(eTransactionNeeded); 1658 return true; 1659} 1660 1661uint32_t Layer::getEffectiveScalingMode() const { 1662 if (mOverrideScalingMode >= 0) { 1663 return mOverrideScalingMode; 1664 } 1665 return mCurrentScalingMode; 1666} 1667 1668bool Layer::setLayerStack(uint32_t layerStack) { 1669 if (mCurrentState.layerStack == layerStack) 1670 return false; 1671 mCurrentState.sequence++; 1672 mCurrentState.layerStack = layerStack; 1673 mCurrentState.modified = true; 1674 setTransactionFlags(eTransactionNeeded); 1675 return true; 1676} 1677 1678void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1679 uint64_t frameNumber) { 1680 mCurrentState.handle = handle; 1681 mCurrentState.frameNumber = frameNumber; 1682 // We don't set eTransactionNeeded, because just receiving a deferral 1683 // request without any other state updates shouldn't actually induce a delay 1684 mCurrentState.modified = true; 1685 pushPendingState(); 1686 mCurrentState.handle = nullptr; 1687 mCurrentState.frameNumber = 0; 1688 mCurrentState.modified = false; 1689} 1690 1691void Layer::useSurfaceDamage() { 1692 if (mFlinger->mForceFullDamage) { 1693 surfaceDamageRegion = Region::INVALID_REGION; 1694 } else { 1695 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1696 } 1697} 1698 1699void Layer::useEmptyDamage() { 1700 surfaceDamageRegion.clear(); 1701} 1702 1703// ---------------------------------------------------------------------------- 1704// pageflip handling... 1705// ---------------------------------------------------------------------------- 1706 1707bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1708 if (mSidebandStreamChanged || mAutoRefresh) { 1709 return true; 1710 } 1711 1712 Mutex::Autolock lock(mQueueItemLock); 1713 if (mQueueItems.empty()) { 1714 return false; 1715 } 1716 auto timestamp = mQueueItems[0].mTimestamp; 1717 nsecs_t expectedPresent = 1718 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1719 1720 // Ignore timestamps more than a second in the future 1721 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1722 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1723 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1724 expectedPresent); 1725 1726 bool isDue = timestamp < expectedPresent; 1727 return isDue || !isPlausible; 1728} 1729 1730bool Layer::onPreComposition() { 1731 mRefreshPending = false; 1732 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1733} 1734 1735bool Layer::onPostComposition() { 1736 bool frameLatencyNeeded = mFrameLatencyNeeded; 1737 if (mFrameLatencyNeeded) { 1738 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1739 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1740 1741 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 1742 if (frameReadyFence->isValid()) { 1743 mFrameTracker.setFrameReadyFence(frameReadyFence); 1744 } else { 1745 // There was no fence for this frame, so assume that it was ready 1746 // to be presented at the desired present time. 1747 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1748 } 1749 1750 const HWComposer& hwc = mFlinger->getHwComposer(); 1751#ifdef USE_HWC2 1752 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY); 1753#else 1754 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 1755#endif 1756 if (presentFence->isValid()) { 1757 mFrameTracker.setActualPresentFence(presentFence); 1758 } else { 1759 // The HWC doesn't support present fences, so use the refresh 1760 // timestamp instead. 1761 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1762 mFrameTracker.setActualPresentTime(presentTime); 1763 } 1764 1765 mFrameTracker.advanceFrame(); 1766 mFrameLatencyNeeded = false; 1767 } 1768 return frameLatencyNeeded; 1769} 1770 1771#ifdef USE_HWC2 1772void Layer::releasePendingBuffer() { 1773 mSurfaceFlingerConsumer->releasePendingBuffer(); 1774} 1775#endif 1776 1777bool Layer::isVisible() const { 1778 const Layer::State& s(mDrawingState); 1779#ifdef USE_HWC2 1780 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f 1781 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1782#else 1783 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1784 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1785#endif 1786} 1787 1788Region Layer::latchBuffer(bool& recomputeVisibleRegions) 1789{ 1790 ATRACE_CALL(); 1791 1792 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1793 // mSidebandStreamChanged was true 1794 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1795 if (mSidebandStream != NULL) { 1796 setTransactionFlags(eTransactionNeeded); 1797 mFlinger->setTransactionFlags(eTraversalNeeded); 1798 } 1799 recomputeVisibleRegions = true; 1800 1801 const State& s(getDrawingState()); 1802 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h))); 1803 } 1804 1805 Region outDirtyRegion; 1806 if (mQueuedFrames > 0 || mAutoRefresh) { 1807 1808 // if we've already called updateTexImage() without going through 1809 // a composition step, we have to skip this layer at this point 1810 // because we cannot call updateTeximage() without a corresponding 1811 // compositionComplete() call. 1812 // we'll trigger an update in onPreComposition(). 1813 if (mRefreshPending) { 1814 return outDirtyRegion; 1815 } 1816 1817 // If the head buffer's acquire fence hasn't signaled yet, return and 1818 // try again later 1819 if (!headFenceHasSignaled()) { 1820 mFlinger->signalLayerUpdate(); 1821 return outDirtyRegion; 1822 } 1823 1824 // Capture the old state of the layer for comparisons later 1825 const State& s(getDrawingState()); 1826 const bool oldOpacity = isOpaque(s); 1827 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1828 1829 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 1830 Layer::State& front; 1831 Layer::State& current; 1832 bool& recomputeVisibleRegions; 1833 bool stickyTransformSet; 1834 const char* name; 1835 int32_t overrideScalingMode; 1836 bool& freezePositionUpdates; 1837 1838 Reject(Layer::State& front, Layer::State& current, 1839 bool& recomputeVisibleRegions, bool stickySet, 1840 const char* name, 1841 int32_t overrideScalingMode, 1842 bool& freezePositionUpdates) 1843 : front(front), current(current), 1844 recomputeVisibleRegions(recomputeVisibleRegions), 1845 stickyTransformSet(stickySet), 1846 name(name), 1847 overrideScalingMode(overrideScalingMode), 1848 freezePositionUpdates(freezePositionUpdates) { 1849 } 1850 1851 virtual bool reject(const sp<GraphicBuffer>& buf, 1852 const BufferItem& item) { 1853 if (buf == NULL) { 1854 return false; 1855 } 1856 1857 uint32_t bufWidth = buf->getWidth(); 1858 uint32_t bufHeight = buf->getHeight(); 1859 1860 // check that we received a buffer of the right size 1861 // (Take the buffer's orientation into account) 1862 if (item.mTransform & Transform::ROT_90) { 1863 swap(bufWidth, bufHeight); 1864 } 1865 1866 int actualScalingMode = overrideScalingMode >= 0 ? 1867 overrideScalingMode : item.mScalingMode; 1868 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1869 if (front.active != front.requested) { 1870 1871 if (isFixedSize || 1872 (bufWidth == front.requested.w && 1873 bufHeight == front.requested.h)) 1874 { 1875 // Here we pretend the transaction happened by updating the 1876 // current and drawing states. Drawing state is only accessed 1877 // in this thread, no need to have it locked 1878 front.active = front.requested; 1879 1880 // We also need to update the current state so that 1881 // we don't end-up overwriting the drawing state with 1882 // this stale current state during the next transaction 1883 // 1884 // NOTE: We don't need to hold the transaction lock here 1885 // because State::active is only accessed from this thread. 1886 current.active = front.active; 1887 current.modified = true; 1888 1889 // recompute visible region 1890 recomputeVisibleRegions = true; 1891 } 1892 1893 ALOGD_IF(DEBUG_RESIZE, 1894 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n" 1895 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1896 " requested={ wh={%4u,%4u} }}\n", 1897 name, 1898 bufWidth, bufHeight, item.mTransform, item.mScalingMode, 1899 front.active.w, front.active.h, 1900 front.crop.left, 1901 front.crop.top, 1902 front.crop.right, 1903 front.crop.bottom, 1904 front.crop.getWidth(), 1905 front.crop.getHeight(), 1906 front.requested.w, front.requested.h); 1907 } 1908 1909 if (!isFixedSize && !stickyTransformSet) { 1910 if (front.active.w != bufWidth || 1911 front.active.h != bufHeight) { 1912 // reject this buffer 1913 ALOGE("[%s] rejecting buffer: " 1914 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}", 1915 name, bufWidth, bufHeight, front.active.w, front.active.h); 1916 return true; 1917 } 1918 } 1919 1920 // if the transparent region has changed (this test is 1921 // conservative, but that's fine, worst case we're doing 1922 // a bit of extra work), we latch the new one and we 1923 // trigger a visible-region recompute. 1924 if (!front.activeTransparentRegion.isTriviallyEqual( 1925 front.requestedTransparentRegion)) { 1926 front.activeTransparentRegion = front.requestedTransparentRegion; 1927 1928 // We also need to update the current state so that 1929 // we don't end-up overwriting the drawing state with 1930 // this stale current state during the next transaction 1931 // 1932 // NOTE: We don't need to hold the transaction lock here 1933 // because State::active is only accessed from this thread. 1934 current.activeTransparentRegion = front.activeTransparentRegion; 1935 1936 // recompute visible region 1937 recomputeVisibleRegions = true; 1938 } 1939 1940 if (front.crop != front.requestedCrop) { 1941 front.crop = front.requestedCrop; 1942 current.crop = front.requestedCrop; 1943 recomputeVisibleRegions = true; 1944 } 1945 freezePositionUpdates = false; 1946 1947 return false; 1948 } 1949 }; 1950 1951 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 1952 getProducerStickyTransform() != 0, mName.string(), 1953 mOverrideScalingMode, mFreezePositionUpdates); 1954 1955 1956 // Check all of our local sync points to ensure that all transactions 1957 // which need to have been applied prior to the frame which is about to 1958 // be latched have signaled 1959 1960 auto headFrameNumber = getHeadFrameNumber(); 1961 bool matchingFramesFound = false; 1962 bool allTransactionsApplied = true; 1963 { 1964 Mutex::Autolock lock(mLocalSyncPointMutex); 1965 for (auto& point : mLocalSyncPoints) { 1966 if (point->getFrameNumber() > headFrameNumber) { 1967 break; 1968 } 1969 1970 matchingFramesFound = true; 1971 1972 if (!point->frameIsAvailable()) { 1973 // We haven't notified the remote layer that the frame for 1974 // this point is available yet. Notify it now, and then 1975 // abort this attempt to latch. 1976 point->setFrameAvailable(); 1977 allTransactionsApplied = false; 1978 break; 1979 } 1980 1981 allTransactionsApplied &= point->transactionIsApplied(); 1982 } 1983 } 1984 1985 if (matchingFramesFound && !allTransactionsApplied) { 1986 mFlinger->signalLayerUpdate(); 1987 return outDirtyRegion; 1988 } 1989 1990 // This boolean is used to make sure that SurfaceFlinger's shadow copy 1991 // of the buffer queue isn't modified when the buffer queue is returning 1992 // BufferItem's that weren't actually queued. This can happen in shared 1993 // buffer mode. 1994 bool queuedBuffer = false; 1995 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 1996 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer, 1997 mLastFrameNumberReceived); 1998 if (updateResult == BufferQueue::PRESENT_LATER) { 1999 // Producer doesn't want buffer to be displayed yet. Signal a 2000 // layer update so we check again at the next opportunity. 2001 mFlinger->signalLayerUpdate(); 2002 return outDirtyRegion; 2003 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 2004 // If the buffer has been rejected, remove it from the shadow queue 2005 // and return early 2006 if (queuedBuffer) { 2007 Mutex::Autolock lock(mQueueItemLock); 2008 mQueueItems.removeAt(0); 2009 android_atomic_dec(&mQueuedFrames); 2010 } 2011 return outDirtyRegion; 2012 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 2013 // This can occur if something goes wrong when trying to create the 2014 // EGLImage for this buffer. If this happens, the buffer has already 2015 // been released, so we need to clean up the queue and bug out 2016 // early. 2017 if (queuedBuffer) { 2018 Mutex::Autolock lock(mQueueItemLock); 2019 mQueueItems.clear(); 2020 android_atomic_and(0, &mQueuedFrames); 2021 } 2022 2023 // Once we have hit this state, the shadow queue may no longer 2024 // correctly reflect the incoming BufferQueue's contents, so even if 2025 // updateTexImage starts working, the only safe course of action is 2026 // to continue to ignore updates. 2027 mUpdateTexImageFailed = true; 2028 2029 return outDirtyRegion; 2030 } 2031 2032 if (queuedBuffer) { 2033 // Autolock scope 2034 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2035 2036 Mutex::Autolock lock(mQueueItemLock); 2037 2038 // Remove any stale buffers that have been dropped during 2039 // updateTexImage 2040 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 2041 mQueueItems.removeAt(0); 2042 android_atomic_dec(&mQueuedFrames); 2043 } 2044 2045 mQueueItems.removeAt(0); 2046 } 2047 2048 2049 // Decrement the queued-frames count. Signal another event if we 2050 // have more frames pending. 2051 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 2052 || mAutoRefresh) { 2053 mFlinger->signalLayerUpdate(); 2054 } 2055 2056 if (updateResult != NO_ERROR) { 2057 // something happened! 2058 recomputeVisibleRegions = true; 2059 return outDirtyRegion; 2060 } 2061 2062 // update the active buffer 2063 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 2064 if (mActiveBuffer == NULL) { 2065 // this can only happen if the very first buffer was rejected. 2066 return outDirtyRegion; 2067 } 2068 2069 mRefreshPending = true; 2070 mFrameLatencyNeeded = true; 2071 if (oldActiveBuffer == NULL) { 2072 // the first time we receive a buffer, we need to trigger a 2073 // geometry invalidation. 2074 recomputeVisibleRegions = true; 2075 } 2076 2077 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 2078 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 2079 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 2080 if ((crop != mCurrentCrop) || 2081 (transform != mCurrentTransform) || 2082 (scalingMode != mCurrentScalingMode)) 2083 { 2084 mCurrentCrop = crop; 2085 mCurrentTransform = transform; 2086 mCurrentScalingMode = scalingMode; 2087 recomputeVisibleRegions = true; 2088 } 2089 2090 if (oldActiveBuffer != NULL) { 2091 uint32_t bufWidth = mActiveBuffer->getWidth(); 2092 uint32_t bufHeight = mActiveBuffer->getHeight(); 2093 if (bufWidth != uint32_t(oldActiveBuffer->width) || 2094 bufHeight != uint32_t(oldActiveBuffer->height)) { 2095 recomputeVisibleRegions = true; 2096 } 2097 } 2098 2099 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 2100 if (oldOpacity != isOpaque(s)) { 2101 recomputeVisibleRegions = true; 2102 } 2103 2104 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2105 2106 // Remove any sync points corresponding to the buffer which was just 2107 // latched 2108 { 2109 Mutex::Autolock lock(mLocalSyncPointMutex); 2110 auto point = mLocalSyncPoints.begin(); 2111 while (point != mLocalSyncPoints.end()) { 2112 if (!(*point)->frameIsAvailable() || 2113 !(*point)->transactionIsApplied()) { 2114 // This sync point must have been added since we started 2115 // latching. Don't drop it yet. 2116 ++point; 2117 continue; 2118 } 2119 2120 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) { 2121 point = mLocalSyncPoints.erase(point); 2122 } else { 2123 ++point; 2124 } 2125 } 2126 } 2127 2128 // FIXME: postedRegion should be dirty & bounds 2129 Region dirtyRegion(Rect(s.active.w, s.active.h)); 2130 2131 // transform the dirty region to window-manager space 2132 outDirtyRegion = (s.active.transform.transform(dirtyRegion)); 2133 } 2134 return outDirtyRegion; 2135} 2136 2137uint32_t Layer::getEffectiveUsage(uint32_t usage) const 2138{ 2139 // TODO: should we do something special if mSecure is set? 2140 if (mProtectedByApp) { 2141 // need a hardware-protected path to external video sink 2142 usage |= GraphicBuffer::USAGE_PROTECTED; 2143 } 2144 if (mPotentialCursor) { 2145 usage |= GraphicBuffer::USAGE_CURSOR; 2146 } 2147 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 2148 return usage; 2149} 2150 2151void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 2152 uint32_t orientation = 0; 2153 if (!mFlinger->mDebugDisableTransformHint) { 2154 // The transform hint is used to improve performance, but we can 2155 // only have a single transform hint, it cannot 2156 // apply to all displays. 2157 const Transform& planeTransform(hw->getTransform()); 2158 orientation = planeTransform.getOrientation(); 2159 if (orientation & Transform::ROT_INVALID) { 2160 orientation = 0; 2161 } 2162 } 2163 mSurfaceFlingerConsumer->setTransformHint(orientation); 2164} 2165 2166// ---------------------------------------------------------------------------- 2167// debugging 2168// ---------------------------------------------------------------------------- 2169 2170void Layer::dump(String8& result, Colorizer& colorizer) const 2171{ 2172 const Layer::State& s(getDrawingState()); 2173 2174 colorizer.colorize(result, Colorizer::GREEN); 2175 result.appendFormat( 2176 "+ %s %p (%s)\n", 2177 getTypeId(), this, getName().string()); 2178 colorizer.reset(result); 2179 2180 s.activeTransparentRegion.dump(result, "transparentRegion"); 2181 visibleRegion.dump(result, "visibleRegion"); 2182 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 2183 sp<Client> client(mClientRef.promote()); 2184 2185 result.appendFormat( " " 2186 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), " 2187 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), " 2188 "isOpaque=%1d, invalidate=%1d, " 2189#ifdef USE_HWC2 2190 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2191#else 2192 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2193#endif 2194 " client=%p\n", 2195 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h, 2196 s.crop.left, s.crop.top, 2197 s.crop.right, s.crop.bottom, 2198 s.finalCrop.left, s.finalCrop.top, 2199 s.finalCrop.right, s.finalCrop.bottom, 2200 isOpaque(s), contentDirty, 2201 s.alpha, s.flags, 2202 s.active.transform[0][0], s.active.transform[0][1], 2203 s.active.transform[1][0], s.active.transform[1][1], 2204 client.get()); 2205 2206 sp<const GraphicBuffer> buf0(mActiveBuffer); 2207 uint32_t w0=0, h0=0, s0=0, f0=0; 2208 if (buf0 != 0) { 2209 w0 = buf0->getWidth(); 2210 h0 = buf0->getHeight(); 2211 s0 = buf0->getStride(); 2212 f0 = buf0->format; 2213 } 2214 result.appendFormat( 2215 " " 2216 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 2217 " queued-frames=%d, mRefreshPending=%d\n", 2218 mFormat, w0, h0, s0,f0, 2219 mQueuedFrames, mRefreshPending); 2220 2221 if (mSurfaceFlingerConsumer != 0) { 2222 mSurfaceFlingerConsumer->dumpState(result, " "); 2223 } 2224} 2225 2226#ifdef USE_HWC2 2227void Layer::miniDumpHeader(String8& result) { 2228 result.append("----------------------------------------"); 2229 result.append("---------------------------------------\n"); 2230 result.append(" Layer name\n"); 2231 result.append(" Z | "); 2232 result.append(" Comp Type | "); 2233 result.append(" Disp Frame (LTRB) | "); 2234 result.append(" Source Crop (LTRB)\n"); 2235 result.append("----------------------------------------"); 2236 result.append("---------------------------------------\n"); 2237} 2238 2239void Layer::miniDump(String8& result, int32_t hwcId) const { 2240 if (mHwcLayers.count(hwcId) == 0) { 2241 return; 2242 } 2243 2244 String8 name; 2245 if (mName.length() > 77) { 2246 std::string shortened; 2247 shortened.append(mName.string(), 36); 2248 shortened.append("[...]"); 2249 shortened.append(mName.string() + (mName.length() - 36), 36); 2250 name = shortened.c_str(); 2251 } else { 2252 name = mName; 2253 } 2254 2255 result.appendFormat(" %s\n", name.string()); 2256 2257 const Layer::State& layerState(getDrawingState()); 2258 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId); 2259 result.appendFormat(" %10u | ", layerState.z); 2260 result.appendFormat("%10s | ", 2261 to_string(getCompositionType(hwcId)).c_str()); 2262 const Rect& frame = hwcInfo.displayFrame; 2263 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, 2264 frame.right, frame.bottom); 2265 const FloatRect& crop = hwcInfo.sourceCrop; 2266 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, 2267 crop.right, crop.bottom); 2268 2269 result.append("- - - - - - - - - - - - - - - - - - - - "); 2270 result.append("- - - - - - - - - - - - - - - - - - - -\n"); 2271} 2272#endif 2273 2274void Layer::dumpFrameStats(String8& result) const { 2275 mFrameTracker.dumpStats(result); 2276} 2277 2278void Layer::clearFrameStats() { 2279 mFrameTracker.clearStats(); 2280} 2281 2282void Layer::logFrameStats() { 2283 mFrameTracker.logAndResetStats(mName); 2284} 2285 2286void Layer::getFrameStats(FrameStats* outStats) const { 2287 mFrameTracker.getStats(outStats); 2288} 2289 2290void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber, 2291 bool* outIsGlesComposition, nsecs_t* outPostedTime, 2292 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const { 2293 *outName = mName; 2294 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2295 2296#ifdef USE_HWC2 2297 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ? 2298 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType == 2299 HWC2::Composition::Client : true; 2300#else 2301 *outIsGlesComposition = mIsGlesComposition; 2302#endif 2303 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp(); 2304 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 2305 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence(); 2306} 2307 2308std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory( 2309 bool forceFlush) { 2310 std::vector<OccupancyTracker::Segment> history; 2311 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, 2312 &history); 2313 if (result != NO_ERROR) { 2314 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), 2315 result); 2316 return {}; 2317 } 2318 return history; 2319} 2320 2321bool Layer::getTransformToDisplayInverse() const { 2322 return mSurfaceFlingerConsumer->getTransformToDisplayInverse(); 2323} 2324 2325// --------------------------------------------------------------------------- 2326 2327}; // namespace android 2328 2329#if defined(__gl_h_) 2330#error "don't include gl/gl.h in this file" 2331#endif 2332 2333#if defined(__gl2_h_) 2334#error "don't include gl2/gl2.h in this file" 2335#endif 2336