Layer.cpp revision 76ddac5f35f6c5967fffb49103e750bb69ec707e
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#ifndef TARGET_DISABLE_TRIPLE_BUFFERING 163 mProducer->setMaxDequeuedBufferCount(2); 164#endif 165 166 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice()); 167 updateTransformHint(hw); 168} 169 170Layer::~Layer() { 171 sp<Client> c(mClientRef.promote()); 172 if (c != 0) { 173 c->detachLayer(this); 174 } 175 176 for (auto& point : mRemoteSyncPoints) { 177 point->setTransactionApplied(); 178 } 179 mFlinger->deleteTextureAsync(mTextureName); 180 mFrameTracker.logAndResetStats(mName); 181} 182 183// --------------------------------------------------------------------------- 184// callbacks 185// --------------------------------------------------------------------------- 186 187#ifdef USE_HWC2 188void Layer::onLayerDisplayed(const sp<Fence>& releaseFence) { 189 if (mHwcLayers.empty()) { 190 return; 191 } 192 mSurfaceFlingerConsumer->setReleaseFence(releaseFence); 193} 194#else 195void Layer::onLayerDisplayed(const sp<const DisplayDevice>& /* hw */, 196 HWComposer::HWCLayerInterface* layer) { 197 if (layer) { 198 layer->onDisplayed(); 199 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence()); 200 } 201} 202#endif 203 204void Layer::onFrameAvailable(const BufferItem& item) { 205 // Add this buffer from our internal queue tracker 206 { // Autolock scope 207 Mutex::Autolock lock(mQueueItemLock); 208 209 // Reset the frame number tracker when we receive the first buffer after 210 // a frame number reset 211 if (item.mFrameNumber == 1) { 212 mLastFrameNumberReceived = 0; 213 } 214 215 // Ensure that callbacks are handled in order 216 while (item.mFrameNumber != mLastFrameNumberReceived + 1) { 217 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, 218 ms2ns(500)); 219 if (result != NO_ERROR) { 220 ALOGE("[%s] Timed out waiting on callback", mName.string()); 221 } 222 } 223 224 mQueueItems.push_back(item); 225 android_atomic_inc(&mQueuedFrames); 226 227 // Wake up any pending callbacks 228 mLastFrameNumberReceived = item.mFrameNumber; 229 mQueueItemCondition.broadcast(); 230 } 231 232 mFlinger->signalLayerUpdate(); 233} 234 235void Layer::onFrameReplaced(const BufferItem& item) { 236 { // Autolock scope 237 Mutex::Autolock lock(mQueueItemLock); 238 239 // Ensure that callbacks are handled in order 240 while (item.mFrameNumber != mLastFrameNumberReceived + 1) { 241 status_t result = mQueueItemCondition.waitRelative(mQueueItemLock, 242 ms2ns(500)); 243 if (result != NO_ERROR) { 244 ALOGE("[%s] Timed out waiting on callback", mName.string()); 245 } 246 } 247 248 if (mQueueItems.empty()) { 249 ALOGE("Can't replace a frame on an empty queue"); 250 return; 251 } 252 mQueueItems.editItemAt(mQueueItems.size() - 1) = item; 253 254 // Wake up any pending callbacks 255 mLastFrameNumberReceived = item.mFrameNumber; 256 mQueueItemCondition.broadcast(); 257 } 258} 259 260void Layer::onSidebandStreamChanged() { 261 if (android_atomic_release_cas(false, true, &mSidebandStreamChanged) == 0) { 262 // mSidebandStreamChanged was false 263 mFlinger->signalLayerUpdate(); 264 } 265} 266 267// called with SurfaceFlinger::mStateLock from the drawing thread after 268// the layer has been remove from the current state list (and just before 269// it's removed from the drawing state list) 270void Layer::onRemoved() { 271 mSurfaceFlingerConsumer->abandon(); 272} 273 274// --------------------------------------------------------------------------- 275// set-up 276// --------------------------------------------------------------------------- 277 278const String8& Layer::getName() const { 279 return mName; 280} 281 282status_t Layer::setBuffers( uint32_t w, uint32_t h, 283 PixelFormat format, uint32_t flags) 284{ 285 uint32_t const maxSurfaceDims = min( 286 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims()); 287 288 // never allow a surface larger than what our underlying GL implementation 289 // can handle. 290 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { 291 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h)); 292 return BAD_VALUE; 293 } 294 295 mFormat = format; 296 297 mPotentialCursor = (flags & ISurfaceComposerClient::eCursorWindow) ? true : false; 298 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false; 299 mCurrentOpacity = getOpacityForFormat(format); 300 301 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h); 302 mSurfaceFlingerConsumer->setDefaultBufferFormat(format); 303 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0)); 304 305 return NO_ERROR; 306} 307 308/* 309 * The layer handle is just a BBinder object passed to the client 310 * (remote process) -- we don't keep any reference on our side such that 311 * the dtor is called when the remote side let go of its reference. 312 * 313 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for 314 * this layer when the handle is destroyed. 315 */ 316class Layer::Handle : public BBinder, public LayerCleaner { 317 public: 318 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) 319 : LayerCleaner(flinger, layer), owner(layer) {} 320 321 wp<Layer> owner; 322}; 323 324sp<IBinder> Layer::getHandle() { 325 Mutex::Autolock _l(mLock); 326 327 LOG_ALWAYS_FATAL_IF(mHasSurface, 328 "Layer::getHandle() has already been called"); 329 330 mHasSurface = true; 331 332 return new Handle(mFlinger, this); 333} 334 335sp<IGraphicBufferProducer> Layer::getProducer() const { 336 return mProducer; 337} 338 339// --------------------------------------------------------------------------- 340// h/w composer set-up 341// --------------------------------------------------------------------------- 342 343Rect Layer::getContentCrop() const { 344 // this is the crop rectangle that applies to the buffer 345 // itself (as opposed to the window) 346 Rect crop; 347 if (!mCurrentCrop.isEmpty()) { 348 // if the buffer crop is defined, we use that 349 crop = mCurrentCrop; 350 } else if (mActiveBuffer != NULL) { 351 // otherwise we use the whole buffer 352 crop = mActiveBuffer->getBounds(); 353 } else { 354 // if we don't have a buffer yet, we use an empty/invalid crop 355 crop.makeInvalid(); 356 } 357 return crop; 358} 359 360static Rect reduce(const Rect& win, const Region& exclude) { 361 if (CC_LIKELY(exclude.isEmpty())) { 362 return win; 363 } 364 if (exclude.isRect()) { 365 return win.reduce(exclude.getBounds()); 366 } 367 return Region(win).subtract(exclude).getBounds(); 368} 369 370Rect Layer::computeBounds() const { 371 const Layer::State& s(getDrawingState()); 372 return computeBounds(s.activeTransparentRegion); 373} 374 375Rect Layer::computeBounds(const Region& activeTransparentRegion) const { 376 const Layer::State& s(getDrawingState()); 377 Rect win(s.active.w, s.active.h); 378 379 if (!s.crop.isEmpty()) { 380 win.intersect(s.crop, &win); 381 } 382 // subtract the transparent region and snap to the bounds 383 return reduce(win, activeTransparentRegion); 384} 385 386FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const { 387 // the content crop is the area of the content that gets scaled to the 388 // layer's size. 389 FloatRect crop(getContentCrop()); 390 391 // the crop is the area of the window that gets cropped, but not 392 // scaled in any ways. 393 const State& s(getDrawingState()); 394 395 // apply the projection's clipping to the window crop in 396 // layerstack space, and convert-back to layer space. 397 // if there are no window scaling involved, this operation will map to full 398 // pixels in the buffer. 399 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have 400 // a viewport clipping and a window transform. we should use floating point to fix this. 401 402 Rect activeCrop(s.active.w, s.active.h); 403 if (!s.crop.isEmpty()) { 404 activeCrop = s.crop; 405 } 406 407 activeCrop = s.active.transform.transform(activeCrop); 408 if (!activeCrop.intersect(hw->getViewport(), &activeCrop)) { 409 activeCrop.clear(); 410 } 411 if (!s.finalCrop.isEmpty()) { 412 if(!activeCrop.intersect(s.finalCrop, &activeCrop)) { 413 activeCrop.clear(); 414 } 415 } 416 activeCrop = s.active.transform.inverse().transform(activeCrop); 417 418 // This needs to be here as transform.transform(Rect) computes the 419 // transformed rect and then takes the bounding box of the result before 420 // returning. This means 421 // transform.inverse().transform(transform.transform(Rect)) != Rect 422 // in which case we need to make sure the final rect is clipped to the 423 // display bounds. 424 if (!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) { 425 activeCrop.clear(); 426 } 427 428 // subtract the transparent region and snap to the bounds 429 activeCrop = reduce(activeCrop, s.activeTransparentRegion); 430 431 // Transform the window crop to match the buffer coordinate system, 432 // which means using the inverse of the current transform set on the 433 // SurfaceFlingerConsumer. 434 uint32_t invTransform = mCurrentTransform; 435 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { 436 /* 437 * the code below applies the primary display's inverse transform to the 438 * buffer 439 */ 440 uint32_t invTransformOrient = 441 DisplayDevice::getPrimaryDisplayOrientationTransform(); 442 // calculate the inverse transform 443 if (invTransformOrient & NATIVE_WINDOW_TRANSFORM_ROT_90) { 444 invTransformOrient ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 445 NATIVE_WINDOW_TRANSFORM_FLIP_H; 446 // If the transform has been rotated the axis of flip has been swapped 447 // so we need to swap which flip operations we are performing 448 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0; 449 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0; 450 if (is_h_flipped != is_v_flipped) { 451 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 452 NATIVE_WINDOW_TRANSFORM_FLIP_H; 453 } 454 } 455 // and apply to the current transform 456 invTransform = (Transform(invTransform) * Transform(invTransformOrient)).getOrientation(); 457 } 458 459 int winWidth = s.active.w; 460 int winHeight = s.active.h; 461 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 462 // If the activeCrop has been rotate the ends are rotated but not 463 // the space itself so when transforming ends back we can't rely on 464 // a modification of the axes of rotation. To account for this we 465 // need to reorient the inverse rotation in terms of the current 466 // axes of rotation. 467 bool is_h_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0; 468 bool is_v_flipped = (invTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0; 469 if (is_h_flipped == is_v_flipped) { 470 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 471 NATIVE_WINDOW_TRANSFORM_FLIP_H; 472 } 473 winWidth = s.active.h; 474 winHeight = s.active.w; 475 } 476 const Rect winCrop = activeCrop.transform( 477 invTransform, s.active.w, s.active.h); 478 479 // below, crop is intersected with winCrop expressed in crop's coordinate space 480 float xScale = crop.getWidth() / float(winWidth); 481 float yScale = crop.getHeight() / float(winHeight); 482 483 float insetL = winCrop.left * xScale; 484 float insetT = winCrop.top * yScale; 485 float insetR = (winWidth - winCrop.right ) * xScale; 486 float insetB = (winHeight - winCrop.bottom) * yScale; 487 488 crop.left += insetL; 489 crop.top += insetT; 490 crop.right -= insetR; 491 crop.bottom -= insetB; 492 493 return crop; 494} 495 496#ifdef USE_HWC2 497void Layer::setGeometry(const sp<const DisplayDevice>& displayDevice) 498#else 499void Layer::setGeometry( 500 const sp<const DisplayDevice>& hw, 501 HWComposer::HWCLayerInterface& layer) 502#endif 503{ 504#ifdef USE_HWC2 505 const auto hwcId = displayDevice->getHwcDisplayId(); 506 auto& hwcInfo = mHwcLayers[hwcId]; 507#else 508 layer.setDefaultState(); 509#endif 510 511 // enable this layer 512#ifdef USE_HWC2 513 hwcInfo.forceClientComposition = false; 514 515 if (isSecure() && !displayDevice->isSecure()) { 516 hwcInfo.forceClientComposition = true; 517 } 518 519 auto& hwcLayer = hwcInfo.layer; 520#else 521 layer.setSkip(false); 522 523 if (isSecure() && !hw->isSecure()) { 524 layer.setSkip(true); 525 } 526#endif 527 528 // this gives us only the "orientation" component of the transform 529 const State& s(getDrawingState()); 530#ifdef USE_HWC2 531 if (!isOpaque(s) || s.alpha != 1.0f) { 532 auto blendMode = mPremultipliedAlpha ? 533 HWC2::BlendMode::Premultiplied : HWC2::BlendMode::Coverage; 534 auto error = hwcLayer->setBlendMode(blendMode); 535 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set blend mode %s:" 536 " %s (%d)", mName.string(), to_string(blendMode).c_str(), 537 to_string(error).c_str(), static_cast<int32_t>(error)); 538 } 539#else 540 if (!isOpaque(s) || s.alpha != 0xFF) { 541 layer.setBlending(mPremultipliedAlpha ? 542 HWC_BLENDING_PREMULT : 543 HWC_BLENDING_COVERAGE); 544 } 545#endif 546 547 // apply the layer's transform, followed by the display's global transform 548 // here we're guaranteed that the layer's transform preserves rects 549 Region activeTransparentRegion(s.activeTransparentRegion); 550 if (!s.crop.isEmpty()) { 551 Rect activeCrop(s.crop); 552 activeCrop = s.active.transform.transform(activeCrop); 553#ifdef USE_HWC2 554 if(!activeCrop.intersect(displayDevice->getViewport(), &activeCrop)) { 555#else 556 if(!activeCrop.intersect(hw->getViewport(), &activeCrop)) { 557#endif 558 activeCrop.clear(); 559 } 560 activeCrop = s.active.transform.inverse().transform(activeCrop); 561 // This needs to be here as transform.transform(Rect) computes the 562 // transformed rect and then takes the bounding box of the result before 563 // returning. This means 564 // transform.inverse().transform(transform.transform(Rect)) != Rect 565 // in which case we need to make sure the final rect is clipped to the 566 // display bounds. 567 if(!activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop)) { 568 activeCrop.clear(); 569 } 570 // mark regions outside the crop as transparent 571 activeTransparentRegion.orSelf(Rect(0, 0, s.active.w, activeCrop.top)); 572 activeTransparentRegion.orSelf(Rect(0, activeCrop.bottom, 573 s.active.w, s.active.h)); 574 activeTransparentRegion.orSelf(Rect(0, activeCrop.top, 575 activeCrop.left, activeCrop.bottom)); 576 activeTransparentRegion.orSelf(Rect(activeCrop.right, activeCrop.top, 577 s.active.w, activeCrop.bottom)); 578 } 579 Rect frame(s.active.transform.transform(computeBounds(activeTransparentRegion))); 580 if (!s.finalCrop.isEmpty()) { 581 if(!frame.intersect(s.finalCrop, &frame)) { 582 frame.clear(); 583 } 584 } 585#ifdef USE_HWC2 586 if (!frame.intersect(displayDevice->getViewport(), &frame)) { 587 frame.clear(); 588 } 589 const Transform& tr(displayDevice->getTransform()); 590 Rect transformedFrame = tr.transform(frame); 591 auto error = hwcLayer->setDisplayFrame(transformedFrame); 592 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set display frame " 593 "[%d, %d, %d, %d]: %s (%d)", mName.string(), transformedFrame.left, 594 transformedFrame.top, transformedFrame.right, 595 transformedFrame.bottom, to_string(error).c_str(), 596 static_cast<int32_t>(error)); 597 598 FloatRect sourceCrop = computeCrop(displayDevice); 599 error = hwcLayer->setSourceCrop(sourceCrop); 600 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set source crop " 601 "[%.3f, %.3f, %.3f, %.3f]: %s (%d)", mName.string(), 602 sourceCrop.left, sourceCrop.top, sourceCrop.right, 603 sourceCrop.bottom, to_string(error).c_str(), 604 static_cast<int32_t>(error)); 605 606 error = hwcLayer->setPlaneAlpha(s.alpha); 607 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set plane alpha %.3f: " 608 "%s (%d)", mName.string(), s.alpha, to_string(error).c_str(), 609 static_cast<int32_t>(error)); 610 611 error = hwcLayer->setZOrder(s.z); 612 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set Z %u: %s (%d)", 613 mName.string(), s.z, to_string(error).c_str(), 614 static_cast<int32_t>(error)); 615#else 616 if (!frame.intersect(hw->getViewport(), &frame)) { 617 frame.clear(); 618 } 619 const Transform& tr(hw->getTransform()); 620 layer.setFrame(tr.transform(frame)); 621 layer.setCrop(computeCrop(hw)); 622 layer.setPlaneAlpha(s.alpha); 623#endif 624 625 /* 626 * Transformations are applied in this order: 627 * 1) buffer orientation/flip/mirror 628 * 2) state transformation (window manager) 629 * 3) layer orientation (screen orientation) 630 * (NOTE: the matrices are multiplied in reverse order) 631 */ 632 633 const Transform bufferOrientation(mCurrentTransform); 634 Transform transform(tr * s.active.transform * bufferOrientation); 635 636 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { 637 /* 638 * the code below applies the primary display's inverse transform to the 639 * buffer 640 */ 641 uint32_t invTransform = 642 DisplayDevice::getPrimaryDisplayOrientationTransform(); 643 644 uint32_t t_orientation = transform.getOrientation(); 645 // calculate the inverse transform 646 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 647 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 648 NATIVE_WINDOW_TRANSFORM_FLIP_H; 649 // If the transform has been rotated the axis of flip has been swapped 650 // so we need to swap which flip operations we are performing 651 bool is_h_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_H) != 0; 652 bool is_v_flipped = (t_orientation & NATIVE_WINDOW_TRANSFORM_FLIP_V) != 0; 653 if (is_h_flipped != is_v_flipped) { 654 t_orientation ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 655 NATIVE_WINDOW_TRANSFORM_FLIP_H; 656 } 657 } 658 // and apply to the current transform 659 transform = Transform(t_orientation) * Transform(invTransform); 660 } 661 662 // this gives us only the "orientation" component of the transform 663 const uint32_t orientation = transform.getOrientation(); 664#ifdef USE_HWC2 665 if (orientation & Transform::ROT_INVALID) { 666 // we can only handle simple transformation 667 hwcInfo.forceClientComposition = true; 668 } else { 669 auto transform = static_cast<HWC2::Transform>(orientation); 670 auto error = hwcLayer->setTransform(transform); 671 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set transform %s: " 672 "%s (%d)", mName.string(), to_string(transform).c_str(), 673 to_string(error).c_str(), static_cast<int32_t>(error)); 674 } 675#else 676 if (orientation & Transform::ROT_INVALID) { 677 // we can only handle simple transformation 678 layer.setSkip(true); 679 } else { 680 layer.setTransform(orientation); 681 } 682#endif 683} 684 685#ifdef USE_HWC2 686void Layer::forceClientComposition(int32_t hwcId) { 687 if (mHwcLayers.count(hwcId) == 0) { 688 ALOGE("forceClientComposition: no HWC layer found (%d)", hwcId); 689 return; 690 } 691 692 mHwcLayers[hwcId].forceClientComposition = true; 693} 694#endif 695 696#ifdef USE_HWC2 697void Layer::setPerFrameData(const sp<const DisplayDevice>& displayDevice) { 698 // Apply this display's projection's viewport to the visible region 699 // before giving it to the HWC HAL. 700 const Transform& tr = displayDevice->getTransform(); 701 const auto& viewport = displayDevice->getViewport(); 702 Region visible = tr.transform(visibleRegion.intersect(viewport)); 703 auto hwcId = displayDevice->getHwcDisplayId(); 704 auto& hwcLayer = mHwcLayers[hwcId].layer; 705 auto error = hwcLayer->setVisibleRegion(visible); 706 if (error != HWC2::Error::None) { 707 ALOGE("[%s] Failed to set visible region: %s (%d)", mName.string(), 708 to_string(error).c_str(), static_cast<int32_t>(error)); 709 visible.dump(LOG_TAG); 710 } 711 712 error = hwcLayer->setSurfaceDamage(surfaceDamageRegion); 713 if (error != HWC2::Error::None) { 714 ALOGE("[%s] Failed to set surface damage: %s (%d)", mName.string(), 715 to_string(error).c_str(), static_cast<int32_t>(error)); 716 surfaceDamageRegion.dump(LOG_TAG); 717 } 718 719 auto compositionType = HWC2::Composition::Invalid; 720 if (mSidebandStream.get()) { 721 compositionType = HWC2::Composition::Sideband; 722 auto error = hwcLayer->setSidebandStream(mSidebandStream->handle()); 723 if (error != HWC2::Error::None) { 724 ALOGE("[%s] Failed to set sideband stream %p: %s (%d)", 725 mName.string(), mSidebandStream->handle(), 726 to_string(error).c_str(), static_cast<int32_t>(error)); 727 return; 728 } 729 } else { 730 if (mActiveBuffer == nullptr || mActiveBuffer->handle == nullptr) { 731 compositionType = HWC2::Composition::Client; 732 auto error = hwcLayer->setBuffer(nullptr, Fence::NO_FENCE); 733 if (error != HWC2::Error::None) { 734 ALOGE("[%s] Failed to set null buffer: %s (%d)", mName.string(), 735 to_string(error).c_str(), static_cast<int32_t>(error)); 736 return; 737 } 738 } else { 739 if (mPotentialCursor) { 740 compositionType = HWC2::Composition::Cursor; 741 } 742 auto acquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 743 auto error = hwcLayer->setBuffer(mActiveBuffer->handle, 744 acquireFence); 745 if (error != HWC2::Error::None) { 746 ALOGE("[%s] Failed to set buffer %p: %s (%d)", mName.string(), 747 mActiveBuffer->handle, to_string(error).c_str(), 748 static_cast<int32_t>(error)); 749 return; 750 } 751 // If it's not a cursor, default to device composition 752 } 753 } 754 755 if (mHwcLayers[hwcId].forceClientComposition) { 756 ALOGV("[%s] Forcing Client composition", mName.string()); 757 setCompositionType(hwcId, HWC2::Composition::Client); 758 } else if (compositionType != HWC2::Composition::Invalid) { 759 ALOGV("[%s] Requesting %s composition", mName.string(), 760 to_string(compositionType).c_str()); 761 setCompositionType(hwcId, compositionType); 762 } else { 763 ALOGV("[%s] Requesting Device composition", mName.string()); 764 setCompositionType(hwcId, HWC2::Composition::Device); 765 } 766} 767#else 768void Layer::setPerFrameData(const sp<const DisplayDevice>& hw, 769 HWComposer::HWCLayerInterface& layer) { 770 // we have to set the visible region on every frame because 771 // we currently free it during onLayerDisplayed(), which is called 772 // after HWComposer::commit() -- every frame. 773 // Apply this display's projection's viewport to the visible region 774 // before giving it to the HWC HAL. 775 const Transform& tr = hw->getTransform(); 776 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport())); 777 layer.setVisibleRegionScreen(visible); 778 layer.setSurfaceDamage(surfaceDamageRegion); 779 mIsGlesComposition = (layer.getCompositionType() == HWC_FRAMEBUFFER); 780 781 if (mSidebandStream.get()) { 782 layer.setSidebandStream(mSidebandStream); 783 } else { 784 // NOTE: buffer can be NULL if the client never drew into this 785 // layer yet, or if we ran out of memory 786 layer.setBuffer(mActiveBuffer); 787 } 788} 789#endif 790 791#ifdef USE_HWC2 792void Layer::updateCursorPosition(const sp<const DisplayDevice>& displayDevice) { 793 auto hwcId = displayDevice->getHwcDisplayId(); 794 if (mHwcLayers.count(hwcId) == 0 || 795 getCompositionType(hwcId) != HWC2::Composition::Cursor) { 796 return; 797 } 798 799 // This gives us only the "orientation" component of the transform 800 const State& s(getCurrentState()); 801 802 // Apply the layer's transform, followed by the display's global transform 803 // Here we're guaranteed that the layer's transform preserves rects 804 Rect win(s.active.w, s.active.h); 805 if (!s.crop.isEmpty()) { 806 win.intersect(s.crop, &win); 807 } 808 // Subtract the transparent region and snap to the bounds 809 Rect bounds = reduce(win, s.activeTransparentRegion); 810 Rect frame(s.active.transform.transform(bounds)); 811 frame.intersect(displayDevice->getViewport(), &frame); 812 if (!s.finalCrop.isEmpty()) { 813 frame.intersect(s.finalCrop, &frame); 814 } 815 auto& displayTransform(displayDevice->getTransform()); 816 auto position = displayTransform.transform(frame); 817 818 auto error = mHwcLayers[hwcId].layer->setCursorPosition(position.left, 819 position.top); 820 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set cursor position " 821 "to (%d, %d): %s (%d)", mName.string(), position.left, 822 position.top, to_string(error).c_str(), 823 static_cast<int32_t>(error)); 824} 825#else 826void Layer::setAcquireFence(const sp<const DisplayDevice>& /* hw */, 827 HWComposer::HWCLayerInterface& layer) { 828 int fenceFd = -1; 829 830 // TODO: there is a possible optimization here: we only need to set the 831 // acquire fence the first time a new buffer is acquired on EACH display. 832 833 if (layer.getCompositionType() == HWC_OVERLAY || layer.getCompositionType() == HWC_CURSOR_OVERLAY) { 834 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence(); 835 if (fence->isValid()) { 836 fenceFd = fence->dup(); 837 if (fenceFd == -1) { 838 ALOGW("failed to dup layer fence, skipping sync: %d", errno); 839 } 840 } 841 } 842 layer.setAcquireFenceFd(fenceFd); 843} 844 845Rect Layer::getPosition( 846 const sp<const DisplayDevice>& hw) 847{ 848 // this gives us only the "orientation" component of the transform 849 const State& s(getCurrentState()); 850 851 // apply the layer's transform, followed by the display's global transform 852 // here we're guaranteed that the layer's transform preserves rects 853 Rect win(s.active.w, s.active.h); 854 if (!s.crop.isEmpty()) { 855 win.intersect(s.crop, &win); 856 } 857 // subtract the transparent region and snap to the bounds 858 Rect bounds = reduce(win, s.activeTransparentRegion); 859 Rect frame(s.active.transform.transform(bounds)); 860 frame.intersect(hw->getViewport(), &frame); 861 if (!s.finalCrop.isEmpty()) { 862 frame.intersect(s.finalCrop, &frame); 863 } 864 const Transform& tr(hw->getTransform()); 865 return Rect(tr.transform(frame)); 866} 867#endif 868 869// --------------------------------------------------------------------------- 870// drawing... 871// --------------------------------------------------------------------------- 872 873void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const { 874 onDraw(hw, clip, false); 875} 876 877void Layer::draw(const sp<const DisplayDevice>& hw, 878 bool useIdentityTransform) const { 879 onDraw(hw, Region(hw->bounds()), useIdentityTransform); 880} 881 882void Layer::draw(const sp<const DisplayDevice>& hw) const { 883 onDraw(hw, Region(hw->bounds()), false); 884} 885 886void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip, 887 bool useIdentityTransform) const 888{ 889 ATRACE_CALL(); 890 891 if (CC_UNLIKELY(mActiveBuffer == 0)) { 892 // the texture has not been created yet, this Layer has 893 // in fact never been drawn into. This happens frequently with 894 // SurfaceView because the WindowManager can't know when the client 895 // has drawn the first time. 896 897 // If there is nothing under us, we paint the screen in black, otherwise 898 // we just skip this update. 899 900 // figure out if there is something below us 901 Region under; 902 const SurfaceFlinger::LayerVector& drawingLayers( 903 mFlinger->mDrawingState.layersSortedByZ); 904 const size_t count = drawingLayers.size(); 905 for (size_t i=0 ; i<count ; ++i) { 906 const sp<Layer>& layer(drawingLayers[i]); 907 if (layer.get() == static_cast<Layer const*>(this)) 908 break; 909 under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); 910 } 911 // if not everything below us is covered, we plug the holes! 912 Region holes(clip.subtract(under)); 913 if (!holes.isEmpty()) { 914 clearWithOpenGL(hw, holes, 0, 0, 0, 1); 915 } 916 return; 917 } 918 919 // Bind the current buffer to the GL texture, and wait for it to be 920 // ready for us to draw into. 921 status_t err = mSurfaceFlingerConsumer->bindTextureImage(); 922 if (err != NO_ERROR) { 923 ALOGW("onDraw: bindTextureImage failed (err=%d)", err); 924 // Go ahead and draw the buffer anyway; no matter what we do the screen 925 // is probably going to have something visibly wrong. 926 } 927 928 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure()); 929 930 RenderEngine& engine(mFlinger->getRenderEngine()); 931 932 if (!blackOutLayer) { 933 // TODO: we could be more subtle with isFixedSize() 934 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize(); 935 936 // Query the texture matrix given our current filtering mode. 937 float textureMatrix[16]; 938 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering); 939 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix); 940 941 if (mSurfaceFlingerConsumer->getTransformToDisplayInverse()) { 942 943 /* 944 * the code below applies the primary display's inverse transform to 945 * the texture transform 946 */ 947 948 // create a 4x4 transform matrix from the display transform flags 949 const mat4 flipH(-1,0,0,0, 0,1,0,0, 0,0,1,0, 1,0,0,1); 950 const mat4 flipV( 1,0,0,0, 0,-1,0,0, 0,0,1,0, 0,1,0,1); 951 const mat4 rot90( 0,1,0,0, -1,0,0,0, 0,0,1,0, 1,0,0,1); 952 953 mat4 tr; 954 uint32_t transform = 955 DisplayDevice::getPrimaryDisplayOrientationTransform(); 956 if (transform & NATIVE_WINDOW_TRANSFORM_ROT_90) 957 tr = tr * rot90; 958 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_H) 959 tr = tr * flipH; 960 if (transform & NATIVE_WINDOW_TRANSFORM_FLIP_V) 961 tr = tr * flipV; 962 963 // calculate the inverse 964 tr = inverse(tr); 965 966 // and finally apply it to the original texture matrix 967 const mat4 texTransform(mat4(static_cast<const float*>(textureMatrix)) * tr); 968 memcpy(textureMatrix, texTransform.asArray(), sizeof(textureMatrix)); 969 } 970 971 // Set things up for texturing. 972 mTexture.setDimensions(mActiveBuffer->getWidth(), mActiveBuffer->getHeight()); 973 mTexture.setFiltering(useFiltering); 974 mTexture.setMatrix(textureMatrix); 975 976 engine.setupLayerTexturing(mTexture); 977 } else { 978 engine.setupLayerBlackedOut(); 979 } 980 drawWithOpenGL(hw, clip, useIdentityTransform); 981 engine.disableTexturing(); 982} 983 984 985void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw, 986 const Region& /* clip */, float red, float green, float blue, 987 float alpha) const 988{ 989 RenderEngine& engine(mFlinger->getRenderEngine()); 990 computeGeometry(hw, mMesh, false); 991 engine.setupFillWithColor(red, green, blue, alpha); 992 engine.drawMesh(mMesh); 993} 994 995void Layer::clearWithOpenGL( 996 const sp<const DisplayDevice>& hw, const Region& clip) const { 997 clearWithOpenGL(hw, clip, 0,0,0,0); 998} 999 1000void Layer::drawWithOpenGL(const sp<const DisplayDevice>& hw, 1001 const Region& /* clip */, bool useIdentityTransform) const { 1002 const State& s(getDrawingState()); 1003 1004 computeGeometry(hw, mMesh, useIdentityTransform); 1005 1006 /* 1007 * NOTE: the way we compute the texture coordinates here produces 1008 * different results than when we take the HWC path -- in the later case 1009 * the "source crop" is rounded to texel boundaries. 1010 * This can produce significantly different results when the texture 1011 * is scaled by a large amount. 1012 * 1013 * The GL code below is more logical (imho), and the difference with 1014 * HWC is due to a limitation of the HWC API to integers -- a question 1015 * is suspend is whether we should ignore this problem or revert to 1016 * GL composition when a buffer scaling is applied (maybe with some 1017 * minimal value)? Or, we could make GL behave like HWC -- but this feel 1018 * like more of a hack. 1019 */ 1020 Rect win(computeBounds()); 1021 1022 if (!s.finalCrop.isEmpty()) { 1023 win = s.active.transform.transform(win); 1024 if (!win.intersect(s.finalCrop, &win)) { 1025 win.clear(); 1026 } 1027 win = s.active.transform.inverse().transform(win); 1028 if (!win.intersect(computeBounds(), &win)) { 1029 win.clear(); 1030 } 1031 } 1032 1033 float left = float(win.left) / float(s.active.w); 1034 float top = float(win.top) / float(s.active.h); 1035 float right = float(win.right) / float(s.active.w); 1036 float bottom = float(win.bottom) / float(s.active.h); 1037 1038 // TODO: we probably want to generate the texture coords with the mesh 1039 // here we assume that we only have 4 vertices 1040 Mesh::VertexArray<vec2> texCoords(mMesh.getTexCoordArray<vec2>()); 1041 texCoords[0] = vec2(left, 1.0f - top); 1042 texCoords[1] = vec2(left, 1.0f - bottom); 1043 texCoords[2] = vec2(right, 1.0f - bottom); 1044 texCoords[3] = vec2(right, 1.0f - top); 1045 1046 RenderEngine& engine(mFlinger->getRenderEngine()); 1047 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(s), s.alpha); 1048 engine.drawMesh(mMesh); 1049 engine.disableBlending(); 1050} 1051 1052#ifdef USE_HWC2 1053void Layer::setCompositionType(int32_t hwcId, HWC2::Composition type, 1054 bool callIntoHwc) { 1055 if (mHwcLayers.count(hwcId) == 0) { 1056 ALOGE("setCompositionType called without a valid HWC layer"); 1057 return; 1058 } 1059 auto& hwcInfo = mHwcLayers[hwcId]; 1060 auto& hwcLayer = hwcInfo.layer; 1061 ALOGV("setCompositionType(%" PRIx64 ", %s, %d)", hwcLayer->getId(), 1062 to_string(type).c_str(), static_cast<int>(callIntoHwc)); 1063 if (hwcInfo.compositionType != type) { 1064 ALOGV(" actually setting"); 1065 hwcInfo.compositionType = type; 1066 if (callIntoHwc) { 1067 auto error = hwcLayer->setCompositionType(type); 1068 ALOGE_IF(error != HWC2::Error::None, "[%s] Failed to set " 1069 "composition type %s: %s (%d)", mName.string(), 1070 to_string(type).c_str(), to_string(error).c_str(), 1071 static_cast<int32_t>(error)); 1072 } 1073 } 1074} 1075 1076HWC2::Composition Layer::getCompositionType(int32_t hwcId) const { 1077 if (mHwcLayers.count(hwcId) == 0) { 1078 ALOGE("getCompositionType called without a valid HWC layer"); 1079 return HWC2::Composition::Invalid; 1080 } 1081 return mHwcLayers.at(hwcId).compositionType; 1082} 1083 1084void Layer::setClearClientTarget(int32_t hwcId, bool clear) { 1085 if (mHwcLayers.count(hwcId) == 0) { 1086 ALOGE("setClearClientTarget called without a valid HWC layer"); 1087 return; 1088 } 1089 mHwcLayers[hwcId].clearClientTarget = clear; 1090} 1091 1092bool Layer::getClearClientTarget(int32_t hwcId) const { 1093 if (mHwcLayers.count(hwcId) == 0) { 1094 ALOGE("getClearClientTarget called without a valid HWC layer"); 1095 return false; 1096 } 1097 return mHwcLayers.at(hwcId).clearClientTarget; 1098} 1099#endif 1100 1101uint32_t Layer::getProducerStickyTransform() const { 1102 int producerStickyTransform = 0; 1103 int ret = mProducer->query(NATIVE_WINDOW_STICKY_TRANSFORM, &producerStickyTransform); 1104 if (ret != OK) { 1105 ALOGW("%s: Error %s (%d) while querying window sticky transform.", __FUNCTION__, 1106 strerror(-ret), ret); 1107 return 0; 1108 } 1109 return static_cast<uint32_t>(producerStickyTransform); 1110} 1111 1112uint64_t Layer::getHeadFrameNumber() const { 1113 Mutex::Autolock lock(mQueueItemLock); 1114 if (!mQueueItems.empty()) { 1115 return mQueueItems[0].mFrameNumber; 1116 } else { 1117 return mCurrentFrameNumber; 1118 } 1119} 1120 1121bool Layer::addSyncPoint(const std::shared_ptr<SyncPoint>& point) { 1122 if (point->getFrameNumber() <= mCurrentFrameNumber) { 1123 // Don't bother with a SyncPoint, since we've already latched the 1124 // relevant frame 1125 return false; 1126 } 1127 1128 Mutex::Autolock lock(mLocalSyncPointMutex); 1129 mLocalSyncPoints.push_back(point); 1130 return true; 1131} 1132 1133void Layer::setFiltering(bool filtering) { 1134 mFiltering = filtering; 1135} 1136 1137bool Layer::getFiltering() const { 1138 return mFiltering; 1139} 1140 1141// As documented in libhardware header, formats in the range 1142// 0x100 - 0x1FF are specific to the HAL implementation, and 1143// are known to have no alpha channel 1144// TODO: move definition for device-specific range into 1145// hardware.h, instead of using hard-coded values here. 1146#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 1147 1148bool Layer::getOpacityForFormat(uint32_t format) { 1149 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 1150 return true; 1151 } 1152 switch (format) { 1153 case HAL_PIXEL_FORMAT_RGBA_8888: 1154 case HAL_PIXEL_FORMAT_BGRA_8888: 1155 return false; 1156 } 1157 // in all other case, we have no blending (also for unknown formats) 1158 return true; 1159} 1160 1161// ---------------------------------------------------------------------------- 1162// local state 1163// ---------------------------------------------------------------------------- 1164 1165static void boundPoint(vec2* point, const Rect& crop) { 1166 if (point->x < crop.left) { 1167 point->x = crop.left; 1168 } 1169 if (point->x > crop.right) { 1170 point->x = crop.right; 1171 } 1172 if (point->y < crop.top) { 1173 point->y = crop.top; 1174 } 1175 if (point->y > crop.bottom) { 1176 point->y = crop.bottom; 1177 } 1178} 1179 1180void Layer::computeGeometry(const sp<const DisplayDevice>& hw, Mesh& mesh, 1181 bool useIdentityTransform) const 1182{ 1183 const Layer::State& s(getDrawingState()); 1184 const Transform tr(hw->getTransform()); 1185 const uint32_t hw_h = hw->getHeight(); 1186 Rect win(s.active.w, s.active.h); 1187 if (!s.crop.isEmpty()) { 1188 win.intersect(s.crop, &win); 1189 } 1190 // subtract the transparent region and snap to the bounds 1191 win = reduce(win, s.activeTransparentRegion); 1192 1193 vec2 lt = vec2(win.left, win.top); 1194 vec2 lb = vec2(win.left, win.bottom); 1195 vec2 rb = vec2(win.right, win.bottom); 1196 vec2 rt = vec2(win.right, win.top); 1197 1198 if (!useIdentityTransform) { 1199 lt = s.active.transform.transform(lt); 1200 lb = s.active.transform.transform(lb); 1201 rb = s.active.transform.transform(rb); 1202 rt = s.active.transform.transform(rt); 1203 } 1204 1205 if (!s.finalCrop.isEmpty()) { 1206 boundPoint(<, s.finalCrop); 1207 boundPoint(&lb, s.finalCrop); 1208 boundPoint(&rb, s.finalCrop); 1209 boundPoint(&rt, s.finalCrop); 1210 } 1211 1212 Mesh::VertexArray<vec2> position(mesh.getPositionArray<vec2>()); 1213 position[0] = tr.transform(lt); 1214 position[1] = tr.transform(lb); 1215 position[2] = tr.transform(rb); 1216 position[3] = tr.transform(rt); 1217 for (size_t i=0 ; i<4 ; i++) { 1218 position[i].y = hw_h - position[i].y; 1219 } 1220} 1221 1222bool Layer::isOpaque(const Layer::State& s) const 1223{ 1224 // if we don't have a buffer yet, we're translucent regardless of the 1225 // layer's opaque flag. 1226 if (mActiveBuffer == 0) { 1227 return false; 1228 } 1229 1230 // if the layer has the opaque flag, then we're always opaque, 1231 // otherwise we use the current buffer's format. 1232 return ((s.flags & layer_state_t::eLayerOpaque) != 0) || mCurrentOpacity; 1233} 1234 1235bool Layer::isSecure() const 1236{ 1237 const Layer::State& s(mDrawingState); 1238 return (s.flags & layer_state_t::eLayerSecure); 1239} 1240 1241bool Layer::isProtected() const 1242{ 1243 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 1244 return (activeBuffer != 0) && 1245 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 1246} 1247 1248bool Layer::isFixedSize() const { 1249 return getEffectiveScalingMode() != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1250} 1251 1252bool Layer::isCropped() const { 1253 return !mCurrentCrop.isEmpty(); 1254} 1255 1256bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const { 1257 return mNeedsFiltering || hw->needsFiltering(); 1258} 1259 1260void Layer::setVisibleRegion(const Region& visibleRegion) { 1261 // always called from main thread 1262 this->visibleRegion = visibleRegion; 1263} 1264 1265void Layer::setCoveredRegion(const Region& coveredRegion) { 1266 // always called from main thread 1267 this->coveredRegion = coveredRegion; 1268} 1269 1270void Layer::setVisibleNonTransparentRegion(const Region& 1271 setVisibleNonTransparentRegion) { 1272 // always called from main thread 1273 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion; 1274} 1275 1276// ---------------------------------------------------------------------------- 1277// transaction 1278// ---------------------------------------------------------------------------- 1279 1280void Layer::pushPendingState() { 1281 if (!mCurrentState.modified) { 1282 return; 1283 } 1284 1285 // If this transaction is waiting on the receipt of a frame, generate a sync 1286 // point and send it to the remote layer. 1287 if (mCurrentState.handle != nullptr) { 1288 sp<Handle> handle = static_cast<Handle*>(mCurrentState.handle.get()); 1289 sp<Layer> handleLayer = handle->owner.promote(); 1290 if (handleLayer == nullptr) { 1291 ALOGE("[%s] Unable to promote Layer handle", mName.string()); 1292 // If we can't promote the layer we are intended to wait on, 1293 // then it is expired or otherwise invalid. Allow this transaction 1294 // to be applied as per normal (no synchronization). 1295 mCurrentState.handle = nullptr; 1296 } else { 1297 auto syncPoint = std::make_shared<SyncPoint>( 1298 mCurrentState.frameNumber); 1299 if (handleLayer->addSyncPoint(syncPoint)) { 1300 mRemoteSyncPoints.push_back(std::move(syncPoint)); 1301 } else { 1302 // We already missed the frame we're supposed to synchronize 1303 // on, so go ahead and apply the state update 1304 mCurrentState.handle = nullptr; 1305 } 1306 } 1307 1308 // Wake us up to check if the frame has been received 1309 setTransactionFlags(eTransactionNeeded); 1310 } 1311 mPendingStates.push_back(mCurrentState); 1312} 1313 1314void Layer::popPendingState(State* stateToCommit) { 1315 auto oldFlags = stateToCommit->flags; 1316 *stateToCommit = mPendingStates[0]; 1317 stateToCommit->flags = (oldFlags & ~stateToCommit->mask) | 1318 (stateToCommit->flags & stateToCommit->mask); 1319 1320 mPendingStates.removeAt(0); 1321} 1322 1323bool Layer::applyPendingStates(State* stateToCommit) { 1324 bool stateUpdateAvailable = false; 1325 while (!mPendingStates.empty()) { 1326 if (mPendingStates[0].handle != nullptr) { 1327 if (mRemoteSyncPoints.empty()) { 1328 // If we don't have a sync point for this, apply it anyway. It 1329 // will be visually wrong, but it should keep us from getting 1330 // into too much trouble. 1331 ALOGE("[%s] No local sync point found", mName.string()); 1332 popPendingState(stateToCommit); 1333 stateUpdateAvailable = true; 1334 continue; 1335 } 1336 1337 if (mRemoteSyncPoints.front()->getFrameNumber() != 1338 mPendingStates[0].frameNumber) { 1339 ALOGE("[%s] Unexpected sync point frame number found", 1340 mName.string()); 1341 1342 // Signal our end of the sync point and then dispose of it 1343 mRemoteSyncPoints.front()->setTransactionApplied(); 1344 mRemoteSyncPoints.pop_front(); 1345 continue; 1346 } 1347 1348 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 1349 // Apply the state update 1350 popPendingState(stateToCommit); 1351 stateUpdateAvailable = true; 1352 1353 // Signal our end of the sync point and then dispose of it 1354 mRemoteSyncPoints.front()->setTransactionApplied(); 1355 mRemoteSyncPoints.pop_front(); 1356 } else { 1357 break; 1358 } 1359 } else { 1360 popPendingState(stateToCommit); 1361 stateUpdateAvailable = true; 1362 } 1363 } 1364 1365 // If we still have pending updates, wake SurfaceFlinger back up and point 1366 // it at this layer so we can process them 1367 if (!mPendingStates.empty()) { 1368 setTransactionFlags(eTransactionNeeded); 1369 mFlinger->setTransactionFlags(eTraversalNeeded); 1370 } 1371 1372 mCurrentState.modified = false; 1373 return stateUpdateAvailable; 1374} 1375 1376void Layer::notifyAvailableFrames() { 1377 auto headFrameNumber = getHeadFrameNumber(); 1378 Mutex::Autolock lock(mLocalSyncPointMutex); 1379 for (auto& point : mLocalSyncPoints) { 1380 if (headFrameNumber >= point->getFrameNumber()) { 1381 point->setFrameAvailable(); 1382 } 1383 } 1384} 1385 1386uint32_t Layer::doTransaction(uint32_t flags) { 1387 ATRACE_CALL(); 1388 1389 pushPendingState(); 1390 Layer::State c = getCurrentState(); 1391 if (!applyPendingStates(&c)) { 1392 return 0; 1393 } 1394 1395 const Layer::State& s(getDrawingState()); 1396 1397 const bool sizeChanged = (c.requested.w != s.requested.w) || 1398 (c.requested.h != s.requested.h); 1399 1400 if (sizeChanged) { 1401 // the size changed, we need to ask our client to request a new buffer 1402 ALOGD_IF(DEBUG_RESIZE, 1403 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1404 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1405 " requested={ wh={%4u,%4u} }}\n" 1406 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1407 " requested={ wh={%4u,%4u} }}\n", 1408 this, getName().string(), mCurrentTransform, 1409 getEffectiveScalingMode(), 1410 c.active.w, c.active.h, 1411 c.crop.left, 1412 c.crop.top, 1413 c.crop.right, 1414 c.crop.bottom, 1415 c.crop.getWidth(), 1416 c.crop.getHeight(), 1417 c.requested.w, c.requested.h, 1418 s.active.w, s.active.h, 1419 s.crop.left, 1420 s.crop.top, 1421 s.crop.right, 1422 s.crop.bottom, 1423 s.crop.getWidth(), 1424 s.crop.getHeight(), 1425 s.requested.w, s.requested.h); 1426 1427 // record the new size, form this point on, when the client request 1428 // a buffer, it'll get the new size. 1429 mSurfaceFlingerConsumer->setDefaultBufferSize( 1430 c.requested.w, c.requested.h); 1431 } 1432 1433 if (!isFixedSize()) { 1434 1435 const bool resizePending = (c.requested.w != c.active.w) || 1436 (c.requested.h != c.active.h); 1437 1438 if (resizePending && mSidebandStream == NULL) { 1439 // don't let Layer::doTransaction update the drawing state 1440 // if we have a pending resize, unless we are in fixed-size mode. 1441 // the drawing state will be updated only once we receive a buffer 1442 // with the correct size. 1443 // 1444 // in particular, we want to make sure the clip (which is part 1445 // of the geometry state) is latched together with the size but is 1446 // latched immediately when no resizing is involved. 1447 // 1448 // If a sideband stream is attached, however, we want to skip this 1449 // optimization so that transactions aren't missed when a buffer 1450 // never arrives 1451 1452 flags |= eDontUpdateGeometryState; 1453 } 1454 } 1455 1456 // always set active to requested, unless we're asked not to 1457 // this is used by Layer, which special cases resizes. 1458 if (flags & eDontUpdateGeometryState) { 1459 } else { 1460 c.active = c.requested; 1461 } 1462 1463 if (s.active != c.active) { 1464 // invalidate and recompute the visible regions if needed 1465 flags |= Layer::eVisibleRegion; 1466 } 1467 1468 if (c.sequence != s.sequence) { 1469 // invalidate and recompute the visible regions if needed 1470 flags |= eVisibleRegion; 1471 this->contentDirty = true; 1472 1473 // we may use linear filtering, if the matrix scales us 1474 const uint8_t type = c.active.transform.getType(); 1475 mNeedsFiltering = (!c.active.transform.preserveRects() || 1476 (type >= Transform::SCALE)); 1477 } 1478 1479 // Commit the transaction 1480 commitTransaction(c); 1481 return flags; 1482} 1483 1484void Layer::commitTransaction(const State& stateToCommit) { 1485 mDrawingState = stateToCommit; 1486} 1487 1488uint32_t Layer::getTransactionFlags(uint32_t flags) { 1489 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1490} 1491 1492uint32_t Layer::setTransactionFlags(uint32_t flags) { 1493 return android_atomic_or(flags, &mTransactionFlags); 1494} 1495 1496bool Layer::setPosition(float x, float y) { 1497 if (mCurrentState.requested.transform.tx() == x && mCurrentState.requested.transform.ty() == y) 1498 return false; 1499 mCurrentState.sequence++; 1500 1501 // We update the requested and active position simultaneously because 1502 // we want to apply the position portion of the transform matrix immediately, 1503 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1504 mCurrentState.requested.transform.set(x, y); 1505 mCurrentState.active.transform.set(x, y); 1506 1507 mCurrentState.modified = true; 1508 setTransactionFlags(eTransactionNeeded); 1509 return true; 1510} 1511bool Layer::setLayer(uint32_t z) { 1512 if (mCurrentState.z == z) 1513 return false; 1514 mCurrentState.sequence++; 1515 mCurrentState.z = z; 1516 mCurrentState.modified = true; 1517 setTransactionFlags(eTransactionNeeded); 1518 return true; 1519} 1520bool Layer::setSize(uint32_t w, uint32_t h) { 1521 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1522 return false; 1523 mCurrentState.requested.w = w; 1524 mCurrentState.requested.h = h; 1525 mCurrentState.modified = true; 1526 setTransactionFlags(eTransactionNeeded); 1527 return true; 1528} 1529#ifdef USE_HWC2 1530bool Layer::setAlpha(float alpha) { 1531#else 1532bool Layer::setAlpha(uint8_t alpha) { 1533#endif 1534 if (mCurrentState.alpha == alpha) 1535 return false; 1536 mCurrentState.sequence++; 1537 mCurrentState.alpha = alpha; 1538 mCurrentState.modified = true; 1539 setTransactionFlags(eTransactionNeeded); 1540 return true; 1541} 1542bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1543 mCurrentState.sequence++; 1544 mCurrentState.requested.transform.set( 1545 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1546 mCurrentState.modified = true; 1547 setTransactionFlags(eTransactionNeeded); 1548 return true; 1549} 1550bool Layer::setTransparentRegionHint(const Region& transparent) { 1551 mCurrentState.requestedTransparentRegion = transparent; 1552 mCurrentState.modified = true; 1553 setTransactionFlags(eTransactionNeeded); 1554 return true; 1555} 1556bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1557 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1558 if (mCurrentState.flags == newFlags) 1559 return false; 1560 mCurrentState.sequence++; 1561 mCurrentState.flags = newFlags; 1562 mCurrentState.mask = mask; 1563 mCurrentState.modified = true; 1564 setTransactionFlags(eTransactionNeeded); 1565 return true; 1566} 1567bool Layer::setCrop(const Rect& crop) { 1568 if (mCurrentState.crop == crop) 1569 return false; 1570 mCurrentState.sequence++; 1571 mCurrentState.crop = crop; 1572 mCurrentState.modified = true; 1573 setTransactionFlags(eTransactionNeeded); 1574 return true; 1575} 1576bool Layer::setFinalCrop(const Rect& crop) { 1577 if (mCurrentState.finalCrop == crop) 1578 return false; 1579 mCurrentState.sequence++; 1580 mCurrentState.finalCrop = crop; 1581 mCurrentState.modified = true; 1582 setTransactionFlags(eTransactionNeeded); 1583 return true; 1584} 1585 1586bool Layer::setOverrideScalingMode(int32_t scalingMode) { 1587 if (scalingMode == mOverrideScalingMode) 1588 return false; 1589 mOverrideScalingMode = scalingMode; 1590 return true; 1591} 1592 1593uint32_t Layer::getEffectiveScalingMode() const { 1594 if (mOverrideScalingMode >= 0) { 1595 return mOverrideScalingMode; 1596 } 1597 return mCurrentScalingMode; 1598} 1599 1600bool Layer::setLayerStack(uint32_t layerStack) { 1601 if (mCurrentState.layerStack == layerStack) 1602 return false; 1603 mCurrentState.sequence++; 1604 mCurrentState.layerStack = layerStack; 1605 mCurrentState.modified = true; 1606 setTransactionFlags(eTransactionNeeded); 1607 return true; 1608} 1609 1610void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1611 uint64_t frameNumber) { 1612 mCurrentState.handle = handle; 1613 mCurrentState.frameNumber = frameNumber; 1614 // We don't set eTransactionNeeded, because just receiving a deferral 1615 // request without any other state updates shouldn't actually induce a delay 1616 mCurrentState.modified = true; 1617 pushPendingState(); 1618 mCurrentState.handle = nullptr; 1619 mCurrentState.frameNumber = 0; 1620 mCurrentState.modified = false; 1621} 1622 1623void Layer::useSurfaceDamage() { 1624 if (mFlinger->mForceFullDamage) { 1625 surfaceDamageRegion = Region::INVALID_REGION; 1626 } else { 1627 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1628 } 1629} 1630 1631void Layer::useEmptyDamage() { 1632 surfaceDamageRegion.clear(); 1633} 1634 1635// ---------------------------------------------------------------------------- 1636// pageflip handling... 1637// ---------------------------------------------------------------------------- 1638 1639bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1640 if (mSidebandStreamChanged || mAutoRefresh) { 1641 return true; 1642 } 1643 1644 Mutex::Autolock lock(mQueueItemLock); 1645 if (mQueueItems.empty()) { 1646 return false; 1647 } 1648 auto timestamp = mQueueItems[0].mTimestamp; 1649 nsecs_t expectedPresent = 1650 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1651 1652 // Ignore timestamps more than a second in the future 1653 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1654 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1655 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1656 expectedPresent); 1657 1658 bool isDue = timestamp < expectedPresent; 1659 return isDue || !isPlausible; 1660} 1661 1662bool Layer::onPreComposition() { 1663 mRefreshPending = false; 1664 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1665} 1666 1667void Layer::onPostComposition() { 1668 if (mFrameLatencyNeeded) { 1669 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1670 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1671 1672 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 1673 if (frameReadyFence->isValid()) { 1674 mFrameTracker.setFrameReadyFence(frameReadyFence); 1675 } else { 1676 // There was no fence for this frame, so assume that it was ready 1677 // to be presented at the desired present time. 1678 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1679 } 1680 1681 const HWComposer& hwc = mFlinger->getHwComposer(); 1682#ifdef USE_HWC2 1683 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY); 1684#else 1685 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 1686#endif 1687 if (presentFence->isValid()) { 1688 mFrameTracker.setActualPresentFence(presentFence); 1689 } else { 1690 // The HWC doesn't support present fences, so use the refresh 1691 // timestamp instead. 1692 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1693 mFrameTracker.setActualPresentTime(presentTime); 1694 } 1695 1696 mFrameTracker.advanceFrame(); 1697 mFrameLatencyNeeded = false; 1698 } 1699} 1700 1701#ifdef USE_HWC2 1702void Layer::releasePendingBuffer() { 1703 mSurfaceFlingerConsumer->releasePendingBuffer(); 1704} 1705#endif 1706 1707bool Layer::isVisible() const { 1708 const Layer::State& s(mDrawingState); 1709#ifdef USE_HWC2 1710 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f 1711 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1712#else 1713 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1714 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1715#endif 1716} 1717 1718Region Layer::latchBuffer(bool& recomputeVisibleRegions) 1719{ 1720 ATRACE_CALL(); 1721 1722 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1723 // mSidebandStreamChanged was true 1724 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1725 if (mSidebandStream != NULL) { 1726 setTransactionFlags(eTransactionNeeded); 1727 mFlinger->setTransactionFlags(eTraversalNeeded); 1728 } 1729 recomputeVisibleRegions = true; 1730 1731 const State& s(getDrawingState()); 1732 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h))); 1733 } 1734 1735 Region outDirtyRegion; 1736 if (mQueuedFrames > 0 || mAutoRefresh) { 1737 1738 // if we've already called updateTexImage() without going through 1739 // a composition step, we have to skip this layer at this point 1740 // because we cannot call updateTeximage() without a corresponding 1741 // compositionComplete() call. 1742 // we'll trigger an update in onPreComposition(). 1743 if (mRefreshPending) { 1744 return outDirtyRegion; 1745 } 1746 1747 // Capture the old state of the layer for comparisons later 1748 const State& s(getDrawingState()); 1749 const bool oldOpacity = isOpaque(s); 1750 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1751 1752 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 1753 Layer::State& front; 1754 Layer::State& current; 1755 bool& recomputeVisibleRegions; 1756 bool stickyTransformSet; 1757 const char* name; 1758 int32_t overrideScalingMode; 1759 1760 Reject(Layer::State& front, Layer::State& current, 1761 bool& recomputeVisibleRegions, bool stickySet, 1762 const char* name, 1763 int32_t overrideScalingMode) 1764 : front(front), current(current), 1765 recomputeVisibleRegions(recomputeVisibleRegions), 1766 stickyTransformSet(stickySet), 1767 name(name), 1768 overrideScalingMode(overrideScalingMode) { 1769 } 1770 1771 virtual bool reject(const sp<GraphicBuffer>& buf, 1772 const BufferItem& item) { 1773 if (buf == NULL) { 1774 return false; 1775 } 1776 1777 uint32_t bufWidth = buf->getWidth(); 1778 uint32_t bufHeight = buf->getHeight(); 1779 1780 // check that we received a buffer of the right size 1781 // (Take the buffer's orientation into account) 1782 if (item.mTransform & Transform::ROT_90) { 1783 swap(bufWidth, bufHeight); 1784 } 1785 1786 int actualScalingMode = overrideScalingMode >= 0 ? 1787 overrideScalingMode : item.mScalingMode; 1788 bool isFixedSize = actualScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1789 if (front.active != front.requested) { 1790 1791 if (isFixedSize || 1792 (bufWidth == front.requested.w && 1793 bufHeight == front.requested.h)) 1794 { 1795 // Here we pretend the transaction happened by updating the 1796 // current and drawing states. Drawing state is only accessed 1797 // in this thread, no need to have it locked 1798 front.active = front.requested; 1799 1800 // We also need to update the current state so that 1801 // we don't end-up overwriting the drawing state with 1802 // this stale current state during the next transaction 1803 // 1804 // NOTE: We don't need to hold the transaction lock here 1805 // because State::active is only accessed from this thread. 1806 current.active = front.active; 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