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