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