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