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