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