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