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