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