Layer.cpp revision f5702ff8b1919e0a5d342ad04ac486bbcde41461
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 mFlinger->setTransactionFlags(eTraversalNeeded); 1350 } 1351 mPendingStates.push_back(mCurrentState); 1352} 1353 1354void Layer::popPendingState(State* stateToCommit) { 1355 auto oldFlags = stateToCommit->flags; 1356 *stateToCommit = mPendingStates[0]; 1357 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) | 1358 (stateToCommit->flags & stateToCommit->mask); 1359 1360 mPendingStates.removeAt(0); 1361} 1362 1363bool Layer::applyPendingStates(State* stateToCommit) { 1364 bool stateUpdateAvailable = false; 1365 while (!mPendingStates.empty()) { 1366 if (mPendingStates[0].handle != nullptr) { 1367 if (mRemoteSyncPoints.empty()) { 1368 // If we don't have a sync point for this, apply it anyway. It 1369 // will be visually wrong, but it should keep us from getting 1370 // into too much trouble. 1371 ALOGE("[%s] No local sync point found", mName.string()); 1372 popPendingState(stateToCommit); 1373 stateUpdateAvailable = true; 1374 continue; 1375 } 1376 1377 if (mRemoteSyncPoints.front()->getFrameNumber() != 1378 mPendingStates[0].frameNumber) { 1379 ALOGE("[%s] Unexpected sync point frame number found", 1380 mName.string()); 1381 1382 // Signal our end of the sync point and then dispose of it 1383 mRemoteSyncPoints.front()->setTransactionApplied(); 1384 mRemoteSyncPoints.pop_front(); 1385 continue; 1386 } 1387 1388 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 1389 // Apply the state update 1390 popPendingState(stateToCommit); 1391 stateUpdateAvailable = true; 1392 1393 // Signal our end of the sync point and then dispose of it 1394 mRemoteSyncPoints.front()->setTransactionApplied(); 1395 mRemoteSyncPoints.pop_front(); 1396 } else { 1397 break; 1398 } 1399 } else { 1400 popPendingState(stateToCommit); 1401 stateUpdateAvailable = true; 1402 } 1403 } 1404 1405 // If we still have pending updates, wake SurfaceFlinger back up and point 1406 // it at this layer so we can process them 1407 if (!mPendingStates.empty()) { 1408 setTransactionFlags(eTransactionNeeded); 1409 mFlinger->setTransactionFlags(eTraversalNeeded); 1410 } 1411 1412 mCurrentState.modified = false; 1413 return stateUpdateAvailable; 1414} 1415 1416void Layer::notifyAvailableFrames() { 1417 auto headFrameNumber = getHeadFrameNumber(); 1418 bool headFenceSignaled = headFenceHasSignaled(); 1419 Mutex::Autolock lock(mLocalSyncPointMutex); 1420 for (auto& point : mLocalSyncPoints) { 1421 if (headFrameNumber >= point->getFrameNumber() && headFenceSignaled) { 1422 point->setFrameAvailable(); 1423 } 1424 } 1425} 1426 1427uint32_t Layer::doTransaction(uint32_t flags) { 1428 ATRACE_CALL(); 1429 1430 pushPendingState(); 1431 Layer::State c = getCurrentState(); 1432 if (!applyPendingStates(&c)) { 1433 return 0; 1434 } 1435 1436 const Layer::State& s(getDrawingState()); 1437 1438 const bool sizeChanged = (c.requested.w != s.requested.w) || 1439 (c.requested.h != s.requested.h); 1440 1441 if (sizeChanged) { 1442 // the size changed, we need to ask our client to request a new buffer 1443 ALOGD_IF(DEBUG_RESIZE, 1444 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1445 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1446 " requested={ wh={%4u,%4u} }}\n" 1447 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1448 " requested={ wh={%4u,%4u} }}\n", 1449 this, getName().string(), mCurrentTransform, 1450 getEffectiveScalingMode(), 1451 c.active.w, c.active.h, 1452 c.crop.left, 1453 c.crop.top, 1454 c.crop.right, 1455 c.crop.bottom, 1456 c.crop.getWidth(), 1457 c.crop.getHeight(), 1458 c.requested.w, c.requested.h, 1459 s.active.w, s.active.h, 1460 s.crop.left, 1461 s.crop.top, 1462 s.crop.right, 1463 s.crop.bottom, 1464 s.crop.getWidth(), 1465 s.crop.getHeight(), 1466 s.requested.w, s.requested.h); 1467 1468 // record the new size, form this point on, when the client request 1469 // a buffer, it'll get the new size. 1470 mSurfaceFlingerConsumer->setDefaultBufferSize( 1471 c.requested.w, c.requested.h); 1472 } 1473 1474 const bool resizePending = (c.requested.w != c.active.w) || 1475 (c.requested.h != c.active.h); 1476 if (!isFixedSize()) { 1477 if (resizePending && mSidebandStream == NULL) { 1478 // don't let Layer::doTransaction update the drawing state 1479 // if we have a pending resize, unless we are in fixed-size mode. 1480 // the drawing state will be updated only once we receive a buffer 1481 // with the correct size. 1482 // 1483 // in particular, we want to make sure the clip (which is part 1484 // of the geometry state) is latched together with the size but is 1485 // latched immediately when no resizing is involved. 1486 // 1487 // If a sideband stream is attached, however, we want to skip this 1488 // optimization so that transactions aren't missed when a buffer 1489 // never arrives 1490 1491 flags |= eDontUpdateGeometryState; 1492 } 1493 } 1494 1495 // always set active to requested, unless we're asked not to 1496 // this is used by Layer, which special cases resizes. 1497 if (flags & eDontUpdateGeometryState) { 1498 } else { 1499 Layer::State& editCurrentState(getCurrentState()); 1500 if (mFreezePositionUpdates) { 1501 float tx = c.active.transform.tx(); 1502 float ty = c.active.transform.ty(); 1503 c.active = c.requested; 1504 c.active.transform.set(tx, ty); 1505 editCurrentState.active = c.active; 1506 } else { 1507 editCurrentState.active = editCurrentState.requested; 1508 c.active = c.requested; 1509 } 1510 } 1511 1512 if (s.active != c.active) { 1513 // invalidate and recompute the visible regions if needed 1514 flags |= Layer::eVisibleRegion; 1515 } 1516 1517 if (c.sequence != s.sequence) { 1518 // invalidate and recompute the visible regions if needed 1519 flags |= eVisibleRegion; 1520 this->contentDirty = true; 1521 1522 // we may use linear filtering, if the matrix scales us 1523 const uint8_t type = c.active.transform.getType(); 1524 mNeedsFiltering = (!c.active.transform.preserveRects() || 1525 (type >= Transform::SCALE)); 1526 } 1527 1528 // If the layer is hidden, signal and clear out all local sync points so 1529 // that transactions for layers depending on this layer's frames becoming 1530 // visible are not blocked 1531 if (c.flags & layer_state_t::eLayerHidden) { 1532 Mutex::Autolock lock(mLocalSyncPointMutex); 1533 for (auto& point : mLocalSyncPoints) { 1534 point->setFrameAvailable(); 1535 } 1536 mLocalSyncPoints.clear(); 1537 } 1538 1539 // Commit the transaction 1540 commitTransaction(c); 1541 return flags; 1542} 1543 1544void Layer::commitTransaction(const State& stateToCommit) { 1545 mDrawingState = stateToCommit; 1546} 1547 1548uint32_t Layer::getTransactionFlags(uint32_t flags) { 1549 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1550} 1551 1552uint32_t Layer::setTransactionFlags(uint32_t flags) { 1553 return android_atomic_or(flags, &mTransactionFlags); 1554} 1555 1556bool Layer::setPosition(float x, float y, bool immediate) { 1557 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y) 1558 return false; 1559 mCurrentState.sequence++; 1560 1561 // We update the requested and active position simultaneously because 1562 // we want to apply the position portion of the transform matrix immediately, 1563 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1564 mCurrentState.requested.transform.set(x, y); 1565 if (immediate && !mFreezePositionUpdates) { 1566 mCurrentState.active.transform.set(x, y); 1567 } 1568 mFreezePositionUpdates = mFreezePositionUpdates || !immediate; 1569 1570 mCurrentState.modified = true; 1571 setTransactionFlags(eTransactionNeeded); 1572 return true; 1573} 1574 1575bool Layer::setLayer(uint32_t z) { 1576 if (mCurrentState.z == z) 1577 return false; 1578 mCurrentState.sequence++; 1579 mCurrentState.z = z; 1580 mCurrentState.modified = true; 1581 setTransactionFlags(eTransactionNeeded); 1582 return true; 1583} 1584bool Layer::setSize(uint32_t w, uint32_t h) { 1585 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1586 return false; 1587 mCurrentState.requested.w = w; 1588 mCurrentState.requested.h = h; 1589 mCurrentState.modified = true; 1590 setTransactionFlags(eTransactionNeeded); 1591 return true; 1592} 1593#ifdef USE_HWC2 1594bool Layer::setAlpha(float alpha) { 1595#else 1596bool Layer::setAlpha(uint8_t alpha) { 1597#endif 1598 if (mCurrentState.alpha == alpha) 1599 return false; 1600 mCurrentState.sequence++; 1601 mCurrentState.alpha = alpha; 1602 mCurrentState.modified = true; 1603 setTransactionFlags(eTransactionNeeded); 1604 return true; 1605} 1606bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1607 mCurrentState.sequence++; 1608 mCurrentState.requested.transform.set( 1609 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1610 mCurrentState.modified = true; 1611 setTransactionFlags(eTransactionNeeded); 1612 return true; 1613} 1614bool Layer::setTransparentRegionHint(const Region& transparent) { 1615 mCurrentState.requestedTransparentRegion = transparent; 1616 mCurrentState.modified = true; 1617 setTransactionFlags(eTransactionNeeded); 1618 return true; 1619} 1620bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1621 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1622 if (mCurrentState.flags == newFlags) 1623 return false; 1624 mCurrentState.sequence++; 1625 mCurrentState.flags = newFlags; 1626 mCurrentState.mask = mask; 1627 mCurrentState.modified = true; 1628 setTransactionFlags(eTransactionNeeded); 1629 return true; 1630} 1631 1632bool Layer::setCrop(const Rect& crop, bool immediate) { 1633 if (mCurrentState.crop == crop) 1634 return false; 1635 mCurrentState.sequence++; 1636 mCurrentState.requestedCrop = crop; 1637 if (immediate) { 1638 mCurrentState.crop = crop; 1639 } 1640 mCurrentState.modified = true; 1641 setTransactionFlags(eTransactionNeeded); 1642 return true; 1643} 1644bool Layer::setFinalCrop(const Rect& crop) { 1645 if (mCurrentState.finalCrop == crop) 1646 return false; 1647 mCurrentState.sequence++; 1648 mCurrentState.finalCrop = crop; 1649 mCurrentState.modified = true; 1650 setTransactionFlags(eTransactionNeeded); 1651 return true; 1652} 1653 1654bool Layer::setOverrideScalingMode(int32_t scalingMode) { 1655 if (scalingMode == mOverrideScalingMode) 1656 return false; 1657 mOverrideScalingMode = scalingMode; 1658 setTransactionFlags(eTransactionNeeded); 1659 return true; 1660} 1661 1662uint32_t Layer::getEffectiveScalingMode() const { 1663 if (mOverrideScalingMode >= 0) { 1664 return mOverrideScalingMode; 1665 } 1666 return mCurrentScalingMode; 1667} 1668 1669bool Layer::setLayerStack(uint32_t layerStack) { 1670 if (mCurrentState.layerStack == layerStack) 1671 return false; 1672 mCurrentState.sequence++; 1673 mCurrentState.layerStack = layerStack; 1674 mCurrentState.modified = true; 1675 setTransactionFlags(eTransactionNeeded); 1676 return true; 1677} 1678 1679void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1680 uint64_t frameNumber) { 1681 mCurrentState.handle = handle; 1682 mCurrentState.frameNumber = frameNumber; 1683 // We don't set eTransactionNeeded, because just receiving a deferral 1684 // request without any other state updates shouldn't actually induce a delay 1685 mCurrentState.modified = true; 1686 pushPendingState(); 1687 mCurrentState.handle = nullptr; 1688 mCurrentState.frameNumber = 0; 1689 mCurrentState.modified = false; 1690} 1691 1692void Layer::useSurfaceDamage() { 1693 if (mFlinger->mForceFullDamage) { 1694 surfaceDamageRegion = Region::INVALID_REGION; 1695 } else { 1696 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1697 } 1698} 1699 1700void Layer::useEmptyDamage() { 1701 surfaceDamageRegion.clear(); 1702} 1703 1704// ---------------------------------------------------------------------------- 1705// pageflip handling... 1706// ---------------------------------------------------------------------------- 1707 1708bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1709 if (mSidebandStreamChanged || mAutoRefresh) { 1710 return true; 1711 } 1712 1713 Mutex::Autolock lock(mQueueItemLock); 1714 if (mQueueItems.empty()) { 1715 return false; 1716 } 1717 auto timestamp = mQueueItems[0].mTimestamp; 1718 nsecs_t expectedPresent = 1719 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1720 1721 // Ignore timestamps more than a second in the future 1722 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1723 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1724 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1725 expectedPresent); 1726 1727 bool isDue = timestamp < expectedPresent; 1728 return isDue || !isPlausible; 1729} 1730 1731bool Layer::onPreComposition() { 1732 mRefreshPending = false; 1733 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1734} 1735 1736bool Layer::onPostComposition() { 1737 bool frameLatencyNeeded = mFrameLatencyNeeded; 1738 if (mFrameLatencyNeeded) { 1739 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1740 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1741 1742 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 1743 if (frameReadyFence->isValid()) { 1744 mFrameTracker.setFrameReadyFence(frameReadyFence); 1745 } else { 1746 // There was no fence for this frame, so assume that it was ready 1747 // to be presented at the desired present time. 1748 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1749 } 1750 1751 const HWComposer& hwc = mFlinger->getHwComposer(); 1752#ifdef USE_HWC2 1753 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY); 1754#else 1755 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 1756#endif 1757 if (presentFence->isValid()) { 1758 mFrameTracker.setActualPresentFence(presentFence); 1759 } else { 1760 // The HWC doesn't support present fences, so use the refresh 1761 // timestamp instead. 1762 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1763 mFrameTracker.setActualPresentTime(presentTime); 1764 } 1765 1766 mFrameTracker.advanceFrame(); 1767 mFrameLatencyNeeded = false; 1768 } 1769 return frameLatencyNeeded; 1770} 1771 1772#ifdef USE_HWC2 1773void Layer::releasePendingBuffer() { 1774 mSurfaceFlingerConsumer->releasePendingBuffer(); 1775} 1776#endif 1777 1778bool Layer::isVisible() const { 1779 const Layer::State& s(mDrawingState); 1780#ifdef USE_HWC2 1781 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f 1782 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1783#else 1784 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1785 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1786#endif 1787} 1788 1789Region Layer::latchBuffer(bool& recomputeVisibleRegions) 1790{ 1791 ATRACE_CALL(); 1792 1793 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1794 // mSidebandStreamChanged was true 1795 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1796 if (mSidebandStream != NULL) { 1797 setTransactionFlags(eTransactionNeeded); 1798 mFlinger->setTransactionFlags(eTraversalNeeded); 1799 } 1800 recomputeVisibleRegions = true; 1801 1802 const State& s(getDrawingState()); 1803 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h))); 1804 } 1805 1806 Region outDirtyRegion; 1807 if (mQueuedFrames <= 0 && !mAutoRefresh) { 1808 return outDirtyRegion; 1809 } 1810 1811 // if we've already called updateTexImage() without going through 1812 // a composition step, we have to skip this layer at this point 1813 // because we cannot call updateTeximage() without a corresponding 1814 // compositionComplete() call. 1815 // we'll trigger an update in onPreComposition(). 1816 if (mRefreshPending) { 1817 return outDirtyRegion; 1818 } 1819 1820 // If the head buffer's acquire fence hasn't signaled yet, return and 1821 // try again later 1822 if (!headFenceHasSignaled()) { 1823 mFlinger->signalLayerUpdate(); 1824 return outDirtyRegion; 1825 } 1826 1827 // Capture the old state of the layer for comparisons later 1828 const State& s(getDrawingState()); 1829 const bool oldOpacity = isOpaque(s); 1830 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1831 1832 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 1833 Layer::State& front; 1834 Layer::State& current; 1835 bool& recomputeVisibleRegions; 1836 bool stickyTransformSet; 1837 const char* name; 1838 int32_t overrideScalingMode; 1839 bool& freezePositionUpdates; 1840 1841 Reject(Layer::State& front, Layer::State& current, 1842 bool& recomputeVisibleRegions, bool stickySet, 1843 const char* name, 1844 int32_t overrideScalingMode, 1845 bool& freezePositionUpdates) 1846 : front(front), current(current), 1847 recomputeVisibleRegions(recomputeVisibleRegions), 1848 stickyTransformSet(stickySet), 1849 name(name), 1850 overrideScalingMode(overrideScalingMode), 1851 freezePositionUpdates(freezePositionUpdates) { 1852 } 1853 1854 virtual bool reject(const sp<GraphicBuffer>& buf, 1855 const BufferItem& item) { 1856 if (buf == NULL) { 1857 return false; 1858 } 1859 1860 uint32_t bufWidth = buf->getWidth(); 1861 uint32_t bufHeight = buf->getHeight(); 1862 1863 // check that we received a buffer of the right size 1864 // (Take the buffer's orientation into account) 1865 if (item.mTransform & Transform::ROT_90) { 1866 swap(bufWidth, bufHeight); 1867 } 1868 1869 int actualScalingMode = overrideScalingMode >= 0 ? 1870 overrideScalingMode : item.mScalingMode; 1871 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1872 if (front.active != front.requested) { 1873 1874 if (isFixedSize || 1875 (bufWidth == front.requested.w && 1876 bufHeight == front.requested.h)) 1877 { 1878 // Here we pretend the transaction happened by updating the 1879 // current and drawing states. Drawing state is only accessed 1880 // in this thread, no need to have it locked 1881 front.active = front.requested; 1882 1883 // We also need to update the current state so that 1884 // we don't end-up overwriting the drawing state with 1885 // this stale current state during the next transaction 1886 // 1887 // NOTE: We don't need to hold the transaction lock here 1888 // because State::active is only accessed from this thread. 1889 current.active = front.active; 1890 current.modified = true; 1891 1892 // recompute visible region 1893 recomputeVisibleRegions = true; 1894 } 1895 1896 ALOGD_IF(DEBUG_RESIZE, 1897 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n" 1898 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1899 " requested={ wh={%4u,%4u} }}\n", 1900 name, 1901 bufWidth, bufHeight, item.mTransform, item.mScalingMode, 1902 front.active.w, front.active.h, 1903 front.crop.left, 1904 front.crop.top, 1905 front.crop.right, 1906 front.crop.bottom, 1907 front.crop.getWidth(), 1908 front.crop.getHeight(), 1909 front.requested.w, front.requested.h); 1910 } 1911 1912 if (!isFixedSize && !stickyTransformSet) { 1913 if (front.active.w != bufWidth || 1914 front.active.h != bufHeight) { 1915 // reject this buffer 1916 ALOGE("[%s] rejecting buffer: " 1917 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}", 1918 name, bufWidth, bufHeight, front.active.w, front.active.h); 1919 return true; 1920 } 1921 } 1922 1923 // if the transparent region has changed (this test is 1924 // conservative, but that's fine, worst case we're doing 1925 // a bit of extra work), we latch the new one and we 1926 // trigger a visible-region recompute. 1927 if (!front.activeTransparentRegion.isTriviallyEqual( 1928 front.requestedTransparentRegion)) { 1929 front.activeTransparentRegion = front.requestedTransparentRegion; 1930 1931 // We also need to update the current state so that 1932 // we don't end-up overwriting the drawing state with 1933 // this stale current state during the next transaction 1934 // 1935 // NOTE: We don't need to hold the transaction lock here 1936 // because State::active is only accessed from this thread. 1937 current.activeTransparentRegion = front.activeTransparentRegion; 1938 1939 // recompute visible region 1940 recomputeVisibleRegions = true; 1941 } 1942 1943 if (front.crop != front.requestedCrop) { 1944 front.crop = front.requestedCrop; 1945 current.crop = front.requestedCrop; 1946 recomputeVisibleRegions = true; 1947 } 1948 freezePositionUpdates = false; 1949 1950 return false; 1951 } 1952 }; 1953 1954 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 1955 getProducerStickyTransform() != 0, mName.string(), 1956 mOverrideScalingMode, mFreezePositionUpdates); 1957 1958 1959 // Check all of our local sync points to ensure that all transactions 1960 // which need to have been applied prior to the frame which is about to 1961 // be latched have signaled 1962 1963 auto headFrameNumber = getHeadFrameNumber(); 1964 bool matchingFramesFound = false; 1965 bool allTransactionsApplied = true; 1966 { 1967 Mutex::Autolock lock(mLocalSyncPointMutex); 1968 for (auto& point : mLocalSyncPoints) { 1969 if (point->getFrameNumber() > headFrameNumber) { 1970 break; 1971 } 1972 1973 matchingFramesFound = true; 1974 1975 if (!point->frameIsAvailable()) { 1976 // We haven't notified the remote layer that the frame for 1977 // this point is available yet. Notify it now, and then 1978 // abort this attempt to latch. 1979 point->setFrameAvailable(); 1980 allTransactionsApplied = false; 1981 break; 1982 } 1983 1984 allTransactionsApplied &= point->transactionIsApplied(); 1985 } 1986 } 1987 1988 if (matchingFramesFound && !allTransactionsApplied) { 1989 mFlinger->signalLayerUpdate(); 1990 return outDirtyRegion; 1991 } 1992 1993 // This boolean is used to make sure that SurfaceFlinger's shadow copy 1994 // of the buffer queue isn't modified when the buffer queue is returning 1995 // BufferItem's that weren't actually queued. This can happen in shared 1996 // buffer mode. 1997 bool queuedBuffer = false; 1998 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 1999 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer, 2000 mLastFrameNumberReceived); 2001 if (updateResult == BufferQueue::PRESENT_LATER) { 2002 // Producer doesn't want buffer to be displayed yet. Signal a 2003 // layer update so we check again at the next opportunity. 2004 mFlinger->signalLayerUpdate(); 2005 return outDirtyRegion; 2006 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 2007 // If the buffer has been rejected, remove it from the shadow queue 2008 // and return early 2009 if (queuedBuffer) { 2010 Mutex::Autolock lock(mQueueItemLock); 2011 mQueueItems.removeAt(0); 2012 android_atomic_dec(&mQueuedFrames); 2013 } 2014 return outDirtyRegion; 2015 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 2016 // This can occur if something goes wrong when trying to create the 2017 // EGLImage for this buffer. If this happens, the buffer has already 2018 // been released, so we need to clean up the queue and bug out 2019 // early. 2020 if (queuedBuffer) { 2021 Mutex::Autolock lock(mQueueItemLock); 2022 mQueueItems.clear(); 2023 android_atomic_and(0, &mQueuedFrames); 2024 } 2025 2026 // Once we have hit this state, the shadow queue may no longer 2027 // correctly reflect the incoming BufferQueue's contents, so even if 2028 // updateTexImage starts working, the only safe course of action is 2029 // to continue to ignore updates. 2030 mUpdateTexImageFailed = true; 2031 2032 return outDirtyRegion; 2033 } 2034 2035 if (queuedBuffer) { 2036 // Autolock scope 2037 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2038 2039 Mutex::Autolock lock(mQueueItemLock); 2040 2041 // Remove any stale buffers that have been dropped during 2042 // updateTexImage 2043 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 2044 mQueueItems.removeAt(0); 2045 android_atomic_dec(&mQueuedFrames); 2046 } 2047 2048 mQueueItems.removeAt(0); 2049 } 2050 2051 2052 // Decrement the queued-frames count. Signal another event if we 2053 // have more frames pending. 2054 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 2055 || mAutoRefresh) { 2056 mFlinger->signalLayerUpdate(); 2057 } 2058 2059 if (updateResult != NO_ERROR) { 2060 // something happened! 2061 recomputeVisibleRegions = true; 2062 return outDirtyRegion; 2063 } 2064 2065 // update the active buffer 2066 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 2067 if (mActiveBuffer == NULL) { 2068 // this can only happen if the very first buffer was rejected. 2069 return outDirtyRegion; 2070 } 2071 2072 mRefreshPending = true; 2073 mFrameLatencyNeeded = true; 2074 if (oldActiveBuffer == NULL) { 2075 // the first time we receive a buffer, we need to trigger a 2076 // geometry invalidation. 2077 recomputeVisibleRegions = true; 2078 } 2079 2080 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 2081 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 2082 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 2083 if ((crop != mCurrentCrop) || 2084 (transform != mCurrentTransform) || 2085 (scalingMode != mCurrentScalingMode)) 2086 { 2087 mCurrentCrop = crop; 2088 mCurrentTransform = transform; 2089 mCurrentScalingMode = scalingMode; 2090 recomputeVisibleRegions = true; 2091 } 2092 2093 if (oldActiveBuffer != NULL) { 2094 uint32_t bufWidth = mActiveBuffer->getWidth(); 2095 uint32_t bufHeight = mActiveBuffer->getHeight(); 2096 if (bufWidth != uint32_t(oldActiveBuffer->width) || 2097 bufHeight != uint32_t(oldActiveBuffer->height)) { 2098 recomputeVisibleRegions = true; 2099 } 2100 } 2101 2102 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 2103 if (oldOpacity != isOpaque(s)) { 2104 recomputeVisibleRegions = true; 2105 } 2106 2107 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2108 2109 // Remove any sync points corresponding to the buffer which was just 2110 // latched 2111 { 2112 Mutex::Autolock lock(mLocalSyncPointMutex); 2113 auto point = mLocalSyncPoints.begin(); 2114 while (point != mLocalSyncPoints.end()) { 2115 if (!(*point)->frameIsAvailable() || 2116 !(*point)->transactionIsApplied()) { 2117 // This sync point must have been added since we started 2118 // latching. Don't drop it yet. 2119 ++point; 2120 continue; 2121 } 2122 2123 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) { 2124 point = mLocalSyncPoints.erase(point); 2125 } else { 2126 ++point; 2127 } 2128 } 2129 } 2130 2131 // FIXME: postedRegion should be dirty & bounds 2132 Region dirtyRegion(Rect(s.active.w, s.active.h)); 2133 2134 // transform the dirty region to window-manager space 2135 outDirtyRegion = (s.active.transform.transform(dirtyRegion)); 2136 2137 return outDirtyRegion; 2138} 2139 2140uint32_t Layer::getEffectiveUsage(uint32_t usage) const 2141{ 2142 // TODO: should we do something special if mSecure is set? 2143 if (mProtectedByApp) { 2144 // need a hardware-protected path to external video sink 2145 usage |= GraphicBuffer::USAGE_PROTECTED; 2146 } 2147 if (mPotentialCursor) { 2148 usage |= GraphicBuffer::USAGE_CURSOR; 2149 } 2150 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 2151 return usage; 2152} 2153 2154void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 2155 uint32_t orientation = 0; 2156 if (!mFlinger->mDebugDisableTransformHint) { 2157 // The transform hint is used to improve performance, but we can 2158 // only have a single transform hint, it cannot 2159 // apply to all displays. 2160 const Transform& planeTransform(hw->getTransform()); 2161 orientation = planeTransform.getOrientation(); 2162 if (orientation & Transform::ROT_INVALID) { 2163 orientation = 0; 2164 } 2165 } 2166 mSurfaceFlingerConsumer->setTransformHint(orientation); 2167} 2168 2169// ---------------------------------------------------------------------------- 2170// debugging 2171// ---------------------------------------------------------------------------- 2172 2173void Layer::dump(String8& result, Colorizer& colorizer) const 2174{ 2175 const Layer::State& s(getDrawingState()); 2176 2177 colorizer.colorize(result, Colorizer::GREEN); 2178 result.appendFormat( 2179 "+ %s %p (%s)\n", 2180 getTypeId(), this, getName().string()); 2181 colorizer.reset(result); 2182 2183 s.activeTransparentRegion.dump(result, "transparentRegion"); 2184 visibleRegion.dump(result, "visibleRegion"); 2185 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 2186 sp<Client> client(mClientRef.promote()); 2187 2188 result.appendFormat( " " 2189 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), " 2190 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), " 2191 "isOpaque=%1d, invalidate=%1d, " 2192#ifdef USE_HWC2 2193 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2194#else 2195 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2196#endif 2197 " client=%p\n", 2198 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h, 2199 s.crop.left, s.crop.top, 2200 s.crop.right, s.crop.bottom, 2201 s.finalCrop.left, s.finalCrop.top, 2202 s.finalCrop.right, s.finalCrop.bottom, 2203 isOpaque(s), contentDirty, 2204 s.alpha, s.flags, 2205 s.active.transform[0][0], s.active.transform[0][1], 2206 s.active.transform[1][0], s.active.transform[1][1], 2207 client.get()); 2208 2209 sp<const GraphicBuffer> buf0(mActiveBuffer); 2210 uint32_t w0=0, h0=0, s0=0, f0=0; 2211 if (buf0 != 0) { 2212 w0 = buf0->getWidth(); 2213 h0 = buf0->getHeight(); 2214 s0 = buf0->getStride(); 2215 f0 = buf0->format; 2216 } 2217 result.appendFormat( 2218 " " 2219 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 2220 " queued-frames=%d, mRefreshPending=%d\n", 2221 mFormat, w0, h0, s0,f0, 2222 mQueuedFrames, mRefreshPending); 2223 2224 if (mSurfaceFlingerConsumer != 0) { 2225 mSurfaceFlingerConsumer->dumpState(result, " "); 2226 } 2227} 2228 2229#ifdef USE_HWC2 2230void Layer::miniDumpHeader(String8& result) { 2231 result.append("----------------------------------------"); 2232 result.append("---------------------------------------\n"); 2233 result.append(" Layer name\n"); 2234 result.append(" Z | "); 2235 result.append(" Comp Type | "); 2236 result.append(" Disp Frame (LTRB) | "); 2237 result.append(" Source Crop (LTRB)\n"); 2238 result.append("----------------------------------------"); 2239 result.append("---------------------------------------\n"); 2240} 2241 2242void Layer::miniDump(String8& result, int32_t hwcId) const { 2243 if (mHwcLayers.count(hwcId) == 0) { 2244 return; 2245 } 2246 2247 String8 name; 2248 if (mName.length() > 77) { 2249 std::string shortened; 2250 shortened.append(mName.string(), 36); 2251 shortened.append("[...]"); 2252 shortened.append(mName.string() + (mName.length() - 36), 36); 2253 name = shortened.c_str(); 2254 } else { 2255 name = mName; 2256 } 2257 2258 result.appendFormat(" %s\n", name.string()); 2259 2260 const Layer::State& layerState(getDrawingState()); 2261 const HWCInfo& hwcInfo = mHwcLayers.at(hwcId); 2262 result.appendFormat(" %10u | ", layerState.z); 2263 result.appendFormat("%10s | ", 2264 to_string(getCompositionType(hwcId)).c_str()); 2265 const Rect& frame = hwcInfo.displayFrame; 2266 result.appendFormat("%4d %4d %4d %4d | ", frame.left, frame.top, 2267 frame.right, frame.bottom); 2268 const FloatRect& crop = hwcInfo.sourceCrop; 2269 result.appendFormat("%6.1f %6.1f %6.1f %6.1f\n", crop.left, crop.top, 2270 crop.right, crop.bottom); 2271 2272 result.append("- - - - - - - - - - - - - - - - - - - - "); 2273 result.append("- - - - - - - - - - - - - - - - - - - -\n"); 2274} 2275#endif 2276 2277void Layer::dumpFrameStats(String8& result) const { 2278 mFrameTracker.dumpStats(result); 2279} 2280 2281void Layer::clearFrameStats() { 2282 mFrameTracker.clearStats(); 2283} 2284 2285void Layer::logFrameStats() { 2286 mFrameTracker.logAndResetStats(mName); 2287} 2288 2289void Layer::getFrameStats(FrameStats* outStats) const { 2290 mFrameTracker.getStats(outStats); 2291} 2292 2293void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber, 2294 bool* outIsGlesComposition, nsecs_t* outPostedTime, 2295 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const { 2296 *outName = mName; 2297 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2298 2299#ifdef USE_HWC2 2300 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ? 2301 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType == 2302 HWC2::Composition::Client : true; 2303#else 2304 *outIsGlesComposition = mIsGlesComposition; 2305#endif 2306 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp(); 2307 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 2308 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence(); 2309} 2310 2311std::vector<OccupancyTracker::Segment> Layer::getOccupancyHistory( 2312 bool forceFlush) { 2313 std::vector<OccupancyTracker::Segment> history; 2314 status_t result = mSurfaceFlingerConsumer->getOccupancyHistory(forceFlush, 2315 &history); 2316 if (result != NO_ERROR) { 2317 ALOGW("[%s] Failed to obtain occupancy history (%d)", mName.string(), 2318 result); 2319 return {}; 2320 } 2321 return history; 2322} 2323 2324bool Layer::getTransformToDisplayInverse() const { 2325 return mSurfaceFlingerConsumer->getTransformToDisplayInverse(); 2326} 2327 2328// --------------------------------------------------------------------------- 2329 2330}; // namespace android 2331 2332#if defined(__gl_h_) 2333#error "don't include gl/gl.h in this file" 2334#endif 2335 2336#if defined(__gl2_h_) 2337#error "don't include gl2/gl2.h in this file" 2338#endif 2339