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