Layer.cpp revision abddf727041d2ea0e678442b2d7905afc8b33bd4
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 1499 // We update the requested and active position simultaneously because 1500 // we want to apply the position portion of the transform matrix immediately, 1501 // but still delay scaling when resizing a SCALING_MODE_FREEZE layer. 1502 mCurrentState.requested.transform.set(x, y); 1503 mCurrentState.active.transform.set(x, y); 1504 1505 mCurrentState.modified = true; 1506 setTransactionFlags(eTransactionNeeded); 1507 return true; 1508} 1509bool Layer::setLayer(uint32_t z) { 1510 if (mCurrentState.z == z) 1511 return false; 1512 mCurrentState.sequence++; 1513 mCurrentState.z = z; 1514 mCurrentState.modified = true; 1515 setTransactionFlags(eTransactionNeeded); 1516 return true; 1517} 1518bool Layer::setSize(uint32_t w, uint32_t h) { 1519 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1520 return false; 1521 mCurrentState.requested.w = w; 1522 mCurrentState.requested.h = h; 1523 mCurrentState.modified = true; 1524 setTransactionFlags(eTransactionNeeded); 1525 return true; 1526} 1527#ifdef USE_HWC2 1528bool Layer::setAlpha(float alpha) { 1529#else 1530bool Layer::setAlpha(uint8_t alpha) { 1531#endif 1532 if (mCurrentState.alpha == alpha) 1533 return false; 1534 mCurrentState.sequence++; 1535 mCurrentState.alpha = alpha; 1536 mCurrentState.modified = true; 1537 setTransactionFlags(eTransactionNeeded); 1538 return true; 1539} 1540bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1541 mCurrentState.sequence++; 1542 mCurrentState.requested.transform.set( 1543 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1544 mCurrentState.modified = true; 1545 setTransactionFlags(eTransactionNeeded); 1546 return true; 1547} 1548bool Layer::setTransparentRegionHint(const Region& transparent) { 1549 mCurrentState.requestedTransparentRegion = transparent; 1550 mCurrentState.modified = true; 1551 setTransactionFlags(eTransactionNeeded); 1552 return true; 1553} 1554bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1555 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1556 if (mCurrentState.flags == newFlags) 1557 return false; 1558 mCurrentState.sequence++; 1559 mCurrentState.flags = newFlags; 1560 mCurrentState.mask = mask; 1561 mCurrentState.modified = true; 1562 setTransactionFlags(eTransactionNeeded); 1563 return true; 1564} 1565bool Layer::setCrop(const Rect& crop) { 1566 if (mCurrentState.crop == crop) 1567 return false; 1568 mCurrentState.sequence++; 1569 mCurrentState.crop = crop; 1570 mCurrentState.modified = true; 1571 setTransactionFlags(eTransactionNeeded); 1572 return true; 1573} 1574bool Layer::setFinalCrop(const Rect& crop) { 1575 if (mCurrentState.finalCrop == crop) 1576 return false; 1577 mCurrentState.sequence++; 1578 mCurrentState.finalCrop = crop; 1579 mCurrentState.modified = true; 1580 setTransactionFlags(eTransactionNeeded); 1581 return true; 1582} 1583 1584bool Layer::setLayerStack(uint32_t layerStack) { 1585 if (mCurrentState.layerStack == layerStack) 1586 return false; 1587 mCurrentState.sequence++; 1588 mCurrentState.layerStack = layerStack; 1589 mCurrentState.modified = true; 1590 setTransactionFlags(eTransactionNeeded); 1591 return true; 1592} 1593 1594void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1595 uint64_t frameNumber) { 1596 mCurrentState.handle = handle; 1597 mCurrentState.frameNumber = frameNumber; 1598 // We don't set eTransactionNeeded, because just receiving a deferral 1599 // request without any other state updates shouldn't actually induce a delay 1600 mCurrentState.modified = true; 1601 pushPendingState(); 1602 mCurrentState.handle = nullptr; 1603 mCurrentState.frameNumber = 0; 1604 mCurrentState.modified = false; 1605} 1606 1607void Layer::useSurfaceDamage() { 1608 if (mFlinger->mForceFullDamage) { 1609 surfaceDamageRegion = Region::INVALID_REGION; 1610 } else { 1611 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1612 } 1613} 1614 1615void Layer::useEmptyDamage() { 1616 surfaceDamageRegion.clear(); 1617} 1618 1619// ---------------------------------------------------------------------------- 1620// pageflip handling... 1621// ---------------------------------------------------------------------------- 1622 1623bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1624 if (mSidebandStreamChanged || mAutoRefresh) { 1625 return true; 1626 } 1627 1628 Mutex::Autolock lock(mQueueItemLock); 1629 if (mQueueItems.empty()) { 1630 return false; 1631 } 1632 auto timestamp = mQueueItems[0].mTimestamp; 1633 nsecs_t expectedPresent = 1634 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1635 1636 // Ignore timestamps more than a second in the future 1637 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1638 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1639 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1640 expectedPresent); 1641 1642 bool isDue = timestamp < expectedPresent; 1643 return isDue || !isPlausible; 1644} 1645 1646bool Layer::onPreComposition() { 1647 mRefreshPending = false; 1648 return mQueuedFrames > 0 || mSidebandStreamChanged || mAutoRefresh; 1649} 1650 1651void Layer::onPostComposition() { 1652 if (mFrameLatencyNeeded) { 1653 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1654 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1655 1656 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 1657 if (frameReadyFence->isValid()) { 1658 mFrameTracker.setFrameReadyFence(frameReadyFence); 1659 } else { 1660 // There was no fence for this frame, so assume that it was ready 1661 // to be presented at the desired present time. 1662 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1663 } 1664 1665 const HWComposer& hwc = mFlinger->getHwComposer(); 1666#ifdef USE_HWC2 1667 sp<Fence> presentFence = hwc.getRetireFence(HWC_DISPLAY_PRIMARY); 1668#else 1669 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 1670#endif 1671 if (presentFence->isValid()) { 1672 mFrameTracker.setActualPresentFence(presentFence); 1673 } else { 1674 // The HWC doesn't support present fences, so use the refresh 1675 // timestamp instead. 1676 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1677 mFrameTracker.setActualPresentTime(presentTime); 1678 } 1679 1680 mFrameTracker.advanceFrame(); 1681 mFrameLatencyNeeded = false; 1682 } 1683} 1684 1685#ifdef USE_HWC2 1686void Layer::releasePendingBuffer() { 1687 mSurfaceFlingerConsumer->releasePendingBuffer(); 1688} 1689#endif 1690 1691bool Layer::isVisible() const { 1692 const Layer::State& s(mDrawingState); 1693#ifdef USE_HWC2 1694 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha > 0.0f 1695 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1696#else 1697 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1698 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1699#endif 1700} 1701 1702Region Layer::latchBuffer(bool& recomputeVisibleRegions) 1703{ 1704 ATRACE_CALL(); 1705 1706 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1707 // mSidebandStreamChanged was true 1708 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1709 if (mSidebandStream != NULL) { 1710 setTransactionFlags(eTransactionNeeded); 1711 mFlinger->setTransactionFlags(eTraversalNeeded); 1712 } 1713 recomputeVisibleRegions = true; 1714 1715 const State& s(getDrawingState()); 1716 return s.active.transform.transform(Region(Rect(s.active.w, s.active.h))); 1717 } 1718 1719 Region outDirtyRegion; 1720 if (mQueuedFrames > 0 || mAutoRefresh) { 1721 1722 // if we've already called updateTexImage() without going through 1723 // a composition step, we have to skip this layer at this point 1724 // because we cannot call updateTeximage() without a corresponding 1725 // compositionComplete() call. 1726 // we'll trigger an update in onPreComposition(). 1727 if (mRefreshPending) { 1728 return outDirtyRegion; 1729 } 1730 1731 // Capture the old state of the layer for comparisons later 1732 const State& s(getDrawingState()); 1733 const bool oldOpacity = isOpaque(s); 1734 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1735 1736 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 1737 Layer::State& front; 1738 Layer::State& current; 1739 bool& recomputeVisibleRegions; 1740 bool stickyTransformSet; 1741 const char* name; 1742 1743 Reject(Layer::State& front, Layer::State& current, 1744 bool& recomputeVisibleRegions, bool stickySet, 1745 const char* name) 1746 : front(front), current(current), 1747 recomputeVisibleRegions(recomputeVisibleRegions), 1748 stickyTransformSet(stickySet), 1749 name(name) { 1750 } 1751 1752 virtual bool reject(const sp<GraphicBuffer>& buf, 1753 const BufferItem& item) { 1754 if (buf == NULL) { 1755 return false; 1756 } 1757 1758 uint32_t bufWidth = buf->getWidth(); 1759 uint32_t bufHeight = buf->getHeight(); 1760 1761 // check that we received a buffer of the right size 1762 // (Take the buffer's orientation into account) 1763 if (item.mTransform & Transform::ROT_90) { 1764 swap(bufWidth, bufHeight); 1765 } 1766 1767 bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1768 if (front.active != front.requested) { 1769 1770 if (isFixedSize || 1771 (bufWidth == front.requested.w && 1772 bufHeight == front.requested.h)) 1773 { 1774 // Here we pretend the transaction happened by updating the 1775 // current and drawing states. Drawing state is only accessed 1776 // in this thread, no need to have it locked 1777 front.active = front.requested; 1778 1779 // We also need to update the current state so that 1780 // we don't end-up overwriting the drawing state with 1781 // this stale current state during the next transaction 1782 // 1783 // NOTE: We don't need to hold the transaction lock here 1784 // because State::active is only accessed from this thread. 1785 current.active = front.active; 1786 1787 // recompute visible region 1788 recomputeVisibleRegions = true; 1789 } 1790 1791 ALOGD_IF(DEBUG_RESIZE, 1792 "[%s] latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n" 1793 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1794 " requested={ wh={%4u,%4u} }}\n", 1795 name, 1796 bufWidth, bufHeight, item.mTransform, item.mScalingMode, 1797 front.active.w, front.active.h, 1798 front.crop.left, 1799 front.crop.top, 1800 front.crop.right, 1801 front.crop.bottom, 1802 front.crop.getWidth(), 1803 front.crop.getHeight(), 1804 front.requested.w, front.requested.h); 1805 } 1806 1807 if (!isFixedSize && !stickyTransformSet) { 1808 if (front.active.w != bufWidth || 1809 front.active.h != bufHeight) { 1810 // reject this buffer 1811 ALOGE("[%s] rejecting buffer: " 1812 "bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}", 1813 name, bufWidth, bufHeight, front.active.w, front.active.h); 1814 return true; 1815 } 1816 } 1817 1818 // if the transparent region has changed (this test is 1819 // conservative, but that's fine, worst case we're doing 1820 // a bit of extra work), we latch the new one and we 1821 // trigger a visible-region recompute. 1822 if (!front.activeTransparentRegion.isTriviallyEqual( 1823 front.requestedTransparentRegion)) { 1824 front.activeTransparentRegion = front.requestedTransparentRegion; 1825 1826 // We also need to update the current state so that 1827 // we don't end-up overwriting the drawing state with 1828 // this stale current state during the next transaction 1829 // 1830 // NOTE: We don't need to hold the transaction lock here 1831 // because State::active is only accessed from this thread. 1832 current.activeTransparentRegion = front.activeTransparentRegion; 1833 1834 // recompute visible region 1835 recomputeVisibleRegions = true; 1836 } 1837 1838 return false; 1839 } 1840 }; 1841 1842 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 1843 getProducerStickyTransform() != 0, mName.string()); 1844 1845 1846 // Check all of our local sync points to ensure that all transactions 1847 // which need to have been applied prior to the frame which is about to 1848 // be latched have signaled 1849 1850 auto headFrameNumber = getHeadFrameNumber(); 1851 bool matchingFramesFound = false; 1852 bool allTransactionsApplied = true; 1853 { 1854 Mutex::Autolock lock(mLocalSyncPointMutex); 1855 for (auto& point : mLocalSyncPoints) { 1856 if (point->getFrameNumber() > headFrameNumber) { 1857 break; 1858 } 1859 1860 matchingFramesFound = true; 1861 1862 if (!point->frameIsAvailable()) { 1863 // We haven't notified the remote layer that the frame for 1864 // this point is available yet. Notify it now, and then 1865 // abort this attempt to latch. 1866 point->setFrameAvailable(); 1867 allTransactionsApplied = false; 1868 break; 1869 } 1870 1871 allTransactionsApplied &= point->transactionIsApplied(); 1872 } 1873 } 1874 1875 if (matchingFramesFound && !allTransactionsApplied) { 1876 mFlinger->signalLayerUpdate(); 1877 return outDirtyRegion; 1878 } 1879 1880 // This boolean is used to make sure that SurfaceFlinger's shadow copy 1881 // of the buffer queue isn't modified when the buffer queue is returning 1882 // BufferItem's that weren't actually queued. This can happen in shared 1883 // buffer mode. 1884 bool queuedBuffer = false; 1885 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 1886 mFlinger->mPrimaryDispSync, &mAutoRefresh, &queuedBuffer, 1887 mLastFrameNumberReceived); 1888 if (updateResult == BufferQueue::PRESENT_LATER) { 1889 // Producer doesn't want buffer to be displayed yet. Signal a 1890 // layer update so we check again at the next opportunity. 1891 mFlinger->signalLayerUpdate(); 1892 return outDirtyRegion; 1893 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 1894 // If the buffer has been rejected, remove it from the shadow queue 1895 // and return early 1896 if (queuedBuffer) { 1897 Mutex::Autolock lock(mQueueItemLock); 1898 mQueueItems.removeAt(0); 1899 android_atomic_dec(&mQueuedFrames); 1900 } 1901 return outDirtyRegion; 1902 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 1903 // This can occur if something goes wrong when trying to create the 1904 // EGLImage for this buffer. If this happens, the buffer has already 1905 // been released, so we need to clean up the queue and bug out 1906 // early. 1907 if (queuedBuffer) { 1908 Mutex::Autolock lock(mQueueItemLock); 1909 mQueueItems.clear(); 1910 android_atomic_and(0, &mQueuedFrames); 1911 } 1912 1913 // Once we have hit this state, the shadow queue may no longer 1914 // correctly reflect the incoming BufferQueue's contents, so even if 1915 // updateTexImage starts working, the only safe course of action is 1916 // to continue to ignore updates. 1917 mUpdateTexImageFailed = true; 1918 1919 return outDirtyRegion; 1920 } 1921 1922 if (queuedBuffer) { 1923 // Autolock scope 1924 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1925 1926 Mutex::Autolock lock(mQueueItemLock); 1927 1928 // Remove any stale buffers that have been dropped during 1929 // updateTexImage 1930 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 1931 mQueueItems.removeAt(0); 1932 android_atomic_dec(&mQueuedFrames); 1933 } 1934 1935 mQueueItems.removeAt(0); 1936 } 1937 1938 1939 // Decrement the queued-frames count. Signal another event if we 1940 // have more frames pending. 1941 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 1942 || mAutoRefresh) { 1943 mFlinger->signalLayerUpdate(); 1944 } 1945 1946 if (updateResult != NO_ERROR) { 1947 // something happened! 1948 recomputeVisibleRegions = true; 1949 return outDirtyRegion; 1950 } 1951 1952 // update the active buffer 1953 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 1954 if (mActiveBuffer == NULL) { 1955 // this can only happen if the very first buffer was rejected. 1956 return outDirtyRegion; 1957 } 1958 1959 mRefreshPending = true; 1960 mFrameLatencyNeeded = true; 1961 if (oldActiveBuffer == NULL) { 1962 // the first time we receive a buffer, we need to trigger a 1963 // geometry invalidation. 1964 recomputeVisibleRegions = true; 1965 } 1966 1967 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 1968 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 1969 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 1970 if ((crop != mCurrentCrop) || 1971 (transform != mCurrentTransform) || 1972 (scalingMode != mCurrentScalingMode)) 1973 { 1974 mCurrentCrop = crop; 1975 mCurrentTransform = transform; 1976 mCurrentScalingMode = scalingMode; 1977 recomputeVisibleRegions = true; 1978 } 1979 1980 if (oldActiveBuffer != NULL) { 1981 uint32_t bufWidth = mActiveBuffer->getWidth(); 1982 uint32_t bufHeight = mActiveBuffer->getHeight(); 1983 if (bufWidth != uint32_t(oldActiveBuffer->width) || 1984 bufHeight != uint32_t(oldActiveBuffer->height)) { 1985 recomputeVisibleRegions = true; 1986 } 1987 } 1988 1989 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 1990 if (oldOpacity != isOpaque(s)) { 1991 recomputeVisibleRegions = true; 1992 } 1993 1994 mCurrentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1995 1996 // Remove any sync points corresponding to the buffer which was just 1997 // latched 1998 { 1999 Mutex::Autolock lock(mLocalSyncPointMutex); 2000 auto point = mLocalSyncPoints.begin(); 2001 while (point != mLocalSyncPoints.end()) { 2002 if (!(*point)->frameIsAvailable() || 2003 !(*point)->transactionIsApplied()) { 2004 // This sync point must have been added since we started 2005 // latching. Don't drop it yet. 2006 ++point; 2007 continue; 2008 } 2009 2010 if ((*point)->getFrameNumber() <= mCurrentFrameNumber) { 2011 point = mLocalSyncPoints.erase(point); 2012 } else { 2013 ++point; 2014 } 2015 } 2016 } 2017 2018 // FIXME: postedRegion should be dirty & bounds 2019 Region dirtyRegion(Rect(s.active.w, s.active.h)); 2020 2021 // transform the dirty region to window-manager space 2022 outDirtyRegion = (s.active.transform.transform(dirtyRegion)); 2023 } 2024 return outDirtyRegion; 2025} 2026 2027uint32_t Layer::getEffectiveUsage(uint32_t usage) const 2028{ 2029 // TODO: should we do something special if mSecure is set? 2030 if (mProtectedByApp) { 2031 // need a hardware-protected path to external video sink 2032 usage |= GraphicBuffer::USAGE_PROTECTED; 2033 } 2034 if (mPotentialCursor) { 2035 usage |= GraphicBuffer::USAGE_CURSOR; 2036 } 2037 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 2038 return usage; 2039} 2040 2041void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 2042 uint32_t orientation = 0; 2043 if (!mFlinger->mDebugDisableTransformHint) { 2044 // The transform hint is used to improve performance, but we can 2045 // only have a single transform hint, it cannot 2046 // apply to all displays. 2047 const Transform& planeTransform(hw->getTransform()); 2048 orientation = planeTransform.getOrientation(); 2049 if (orientation & Transform::ROT_INVALID) { 2050 orientation = 0; 2051 } 2052 } 2053 mSurfaceFlingerConsumer->setTransformHint(orientation); 2054} 2055 2056// ---------------------------------------------------------------------------- 2057// debugging 2058// ---------------------------------------------------------------------------- 2059 2060void Layer::dump(String8& result, Colorizer& colorizer) const 2061{ 2062 const Layer::State& s(getDrawingState()); 2063 2064 colorizer.colorize(result, Colorizer::GREEN); 2065 result.appendFormat( 2066 "+ %s %p (%s)\n", 2067 getTypeId(), this, getName().string()); 2068 colorizer.reset(result); 2069 2070 s.activeTransparentRegion.dump(result, "transparentRegion"); 2071 visibleRegion.dump(result, "visibleRegion"); 2072 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 2073 sp<Client> client(mClientRef.promote()); 2074 2075 result.appendFormat( " " 2076 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), " 2077 "crop=(%4d,%4d,%4d,%4d), finalCrop=(%4d,%4d,%4d,%4d), " 2078 "isOpaque=%1d, invalidate=%1d, " 2079#ifdef USE_HWC2 2080 "alpha=%.3f, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2081#else 2082 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 2083#endif 2084 " client=%p\n", 2085 s.layerStack, s.z, s.active.transform.tx(), s.active.transform.ty(), s.active.w, s.active.h, 2086 s.crop.left, s.crop.top, 2087 s.crop.right, s.crop.bottom, 2088 s.finalCrop.left, s.finalCrop.top, 2089 s.finalCrop.right, s.finalCrop.bottom, 2090 isOpaque(s), contentDirty, 2091 s.alpha, s.flags, 2092 s.active.transform[0][0], s.active.transform[0][1], 2093 s.active.transform[1][0], s.active.transform[1][1], 2094 client.get()); 2095 2096 sp<const GraphicBuffer> buf0(mActiveBuffer); 2097 uint32_t w0=0, h0=0, s0=0, f0=0; 2098 if (buf0 != 0) { 2099 w0 = buf0->getWidth(); 2100 h0 = buf0->getHeight(); 2101 s0 = buf0->getStride(); 2102 f0 = buf0->format; 2103 } 2104 result.appendFormat( 2105 " " 2106 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 2107 " queued-frames=%d, mRefreshPending=%d\n", 2108 mFormat, w0, h0, s0,f0, 2109 mQueuedFrames, mRefreshPending); 2110 2111 if (mSurfaceFlingerConsumer != 0) { 2112 mSurfaceFlingerConsumer->dump(result, " "); 2113 } 2114} 2115 2116void Layer::dumpFrameStats(String8& result) const { 2117 mFrameTracker.dumpStats(result); 2118} 2119 2120void Layer::clearFrameStats() { 2121 mFrameTracker.clearStats(); 2122} 2123 2124void Layer::logFrameStats() { 2125 mFrameTracker.logAndResetStats(mName); 2126} 2127 2128void Layer::getFrameStats(FrameStats* outStats) const { 2129 mFrameTracker.getStats(outStats); 2130} 2131 2132void Layer::getFenceData(String8* outName, uint64_t* outFrameNumber, 2133 bool* outIsGlesComposition, nsecs_t* outPostedTime, 2134 sp<Fence>* outAcquireFence, sp<Fence>* outPrevReleaseFence) const { 2135 *outName = mName; 2136 *outFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 2137 2138#ifdef USE_HWC2 2139 *outIsGlesComposition = mHwcLayers.count(HWC_DISPLAY_PRIMARY) ? 2140 mHwcLayers.at(HWC_DISPLAY_PRIMARY).compositionType == 2141 HWC2::Composition::Client : true; 2142#else 2143 *outIsGlesComposition = mIsGlesComposition; 2144#endif 2145 *outPostedTime = mSurfaceFlingerConsumer->getTimestamp(); 2146 *outAcquireFence = mSurfaceFlingerConsumer->getCurrentFence(); 2147 *outPrevReleaseFence = mSurfaceFlingerConsumer->getPrevReleaseFence(); 2148} 2149// --------------------------------------------------------------------------- 2150 2151Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger, 2152 const sp<Layer>& layer) 2153 : mFlinger(flinger), mLayer(layer) { 2154} 2155 2156Layer::LayerCleaner::~LayerCleaner() { 2157 // destroy client resources 2158 mFlinger->onLayerDestroyed(mLayer); 2159} 2160 2161// --------------------------------------------------------------------------- 2162}; // namespace android 2163 2164#if defined(__gl_h_) 2165#error "don't include gl/gl.h in this file" 2166#endif 2167 2168#if defined(__gl2_h_) 2169#error "don't include gl2/gl2.h in this file" 2170#endif 2171