Layer.cpp revision 3bddd5b7731fafd2c60e75416ccd091972d196ae
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 } else { 957 auto syncPoint = std::make_shared<SyncPoint>( 958 mCurrentState.frameNumber); 959 handleLayer->addSyncPoint(syncPoint); 960 mRemoteSyncPoints.push_back(std::move(syncPoint)); 961 } 962 963 // Wake us up to check if the frame has been received 964 setTransactionFlags(eTransactionNeeded); 965 } 966 mPendingStates.push_back(mCurrentState); 967} 968 969void Layer::popPendingState() { 970 auto oldFlags = mCurrentState.flags; 971 mCurrentState = mPendingStates[0]; 972 mCurrentState.flags = (oldFlags & ~mCurrentState.mask) | 973 (mCurrentState.flags & mCurrentState.mask); 974 975 mPendingStates.removeAt(0); 976} 977 978bool Layer::applyPendingStates() { 979 Mutex::Autolock lock(mPendingStateMutex); 980 981 bool stateUpdateAvailable = false; 982 while (!mPendingStates.empty()) { 983 if (mPendingStates[0].handle != nullptr) { 984 if (mRemoteSyncPoints.empty()) { 985 // If we don't have a sync point for this, apply it anyway. It 986 // will be visually wrong, but it should keep us from getting 987 // into too much trouble. 988 ALOGE("[%s] No local sync point found", mName.string()); 989 popPendingState(); 990 stateUpdateAvailable = true; 991 continue; 992 } 993 994 if (mRemoteSyncPoints.front()->frameIsAvailable()) { 995 // Apply the state update 996 popPendingState(); 997 stateUpdateAvailable = true; 998 999 // Signal our end of the sync point and then dispose of it 1000 mRemoteSyncPoints.front()->setTransactionApplied(); 1001 mRemoteSyncPoints.pop_front(); 1002 } 1003 break; 1004 } else { 1005 popPendingState(); 1006 stateUpdateAvailable = true; 1007 } 1008 } 1009 1010 // If we still have pending updates, wake SurfaceFlinger back up and point 1011 // it at this layer so we can process them 1012 if (!mPendingStates.empty()) { 1013 setTransactionFlags(eTransactionNeeded); 1014 mFlinger->setTransactionFlags(eTraversalNeeded); 1015 } 1016 1017 mCurrentState.modified = false; 1018 return stateUpdateAvailable; 1019} 1020 1021void Layer::notifyAvailableFrames() { 1022 Mutex::Autolock lock(mAvailableFrameMutex); 1023 for (auto frame : mAvailableFrames) { 1024 frame->setFrameAvailable(); 1025 } 1026} 1027 1028uint32_t Layer::doTransaction(uint32_t flags) { 1029 ATRACE_CALL(); 1030 1031 pushPendingState(); 1032 if (!applyPendingStates()) { 1033 return 0; 1034 } 1035 1036 const Layer::State& s(getDrawingState()); 1037 const Layer::State& c(getCurrentState()); 1038 1039 const bool sizeChanged = (c.requested.w != s.requested.w) || 1040 (c.requested.h != s.requested.h); 1041 1042 if (sizeChanged) { 1043 // the size changed, we need to ask our client to request a new buffer 1044 ALOGD_IF(DEBUG_RESIZE, 1045 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 1046 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1047 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n" 1048 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1049 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n", 1050 this, getName().string(), mCurrentTransform, mCurrentScalingMode, 1051 c.active.w, c.active.h, 1052 c.active.crop.left, 1053 c.active.crop.top, 1054 c.active.crop.right, 1055 c.active.crop.bottom, 1056 c.active.crop.getWidth(), 1057 c.active.crop.getHeight(), 1058 c.requested.w, c.requested.h, 1059 c.requested.crop.left, 1060 c.requested.crop.top, 1061 c.requested.crop.right, 1062 c.requested.crop.bottom, 1063 c.requested.crop.getWidth(), 1064 c.requested.crop.getHeight(), 1065 s.active.w, s.active.h, 1066 s.active.crop.left, 1067 s.active.crop.top, 1068 s.active.crop.right, 1069 s.active.crop.bottom, 1070 s.active.crop.getWidth(), 1071 s.active.crop.getHeight(), 1072 s.requested.w, s.requested.h, 1073 s.requested.crop.left, 1074 s.requested.crop.top, 1075 s.requested.crop.right, 1076 s.requested.crop.bottom, 1077 s.requested.crop.getWidth(), 1078 s.requested.crop.getHeight()); 1079 1080 // record the new size, form this point on, when the client request 1081 // a buffer, it'll get the new size. 1082 mSurfaceFlingerConsumer->setDefaultBufferSize( 1083 c.requested.w, c.requested.h); 1084 } 1085 1086 if (!isFixedSize()) { 1087 1088 const bool resizePending = (c.requested.w != c.active.w) || 1089 (c.requested.h != c.active.h); 1090 1091 if (resizePending && mSidebandStream == NULL) { 1092 // don't let Layer::doTransaction update the drawing state 1093 // if we have a pending resize, unless we are in fixed-size mode. 1094 // the drawing state will be updated only once we receive a buffer 1095 // with the correct size. 1096 // 1097 // in particular, we want to make sure the clip (which is part 1098 // of the geometry state) is latched together with the size but is 1099 // latched immediately when no resizing is involved. 1100 // 1101 // If a sideband stream is attached, however, we want to skip this 1102 // optimization so that transactions aren't missed when a buffer 1103 // never arrives 1104 1105 flags |= eDontUpdateGeometryState; 1106 } 1107 } 1108 1109 // always set active to requested, unless we're asked not to 1110 // this is used by Layer, which special cases resizes. 1111 if (flags & eDontUpdateGeometryState) { 1112 } else { 1113 Layer::State& editCurrentState(getCurrentState()); 1114 editCurrentState.active = c.requested; 1115 } 1116 1117 if (s.active != c.active) { 1118 // invalidate and recompute the visible regions if needed 1119 flags |= Layer::eVisibleRegion; 1120 } 1121 1122 if (c.sequence != s.sequence) { 1123 // invalidate and recompute the visible regions if needed 1124 flags |= eVisibleRegion; 1125 this->contentDirty = true; 1126 1127 // we may use linear filtering, if the matrix scales us 1128 const uint8_t type = c.transform.getType(); 1129 mNeedsFiltering = (!c.transform.preserveRects() || 1130 (type >= Transform::SCALE)); 1131 } 1132 1133 // Commit the transaction 1134 commitTransaction(); 1135 return flags; 1136} 1137 1138void Layer::commitTransaction() { 1139 mDrawingState = mCurrentState; 1140} 1141 1142uint32_t Layer::getTransactionFlags(uint32_t flags) { 1143 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1144} 1145 1146uint32_t Layer::setTransactionFlags(uint32_t flags) { 1147 return android_atomic_or(flags, &mTransactionFlags); 1148} 1149 1150bool Layer::setPosition(float x, float y) { 1151 if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y) 1152 return false; 1153 mCurrentState.sequence++; 1154 mCurrentState.transform.set(x, y); 1155 mCurrentState.modified = true; 1156 setTransactionFlags(eTransactionNeeded); 1157 return true; 1158} 1159bool Layer::setLayer(uint32_t z) { 1160 if (mCurrentState.z == z) 1161 return false; 1162 mCurrentState.sequence++; 1163 mCurrentState.z = z; 1164 mCurrentState.modified = true; 1165 setTransactionFlags(eTransactionNeeded); 1166 return true; 1167} 1168bool Layer::setSize(uint32_t w, uint32_t h) { 1169 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 1170 return false; 1171 mCurrentState.requested.w = w; 1172 mCurrentState.requested.h = h; 1173 mCurrentState.modified = true; 1174 setTransactionFlags(eTransactionNeeded); 1175 return true; 1176} 1177bool Layer::setAlpha(uint8_t alpha) { 1178 if (mCurrentState.alpha == alpha) 1179 return false; 1180 mCurrentState.sequence++; 1181 mCurrentState.alpha = alpha; 1182 mCurrentState.modified = true; 1183 setTransactionFlags(eTransactionNeeded); 1184 return true; 1185} 1186bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 1187 mCurrentState.sequence++; 1188 mCurrentState.transform.set( 1189 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 1190 mCurrentState.modified = true; 1191 setTransactionFlags(eTransactionNeeded); 1192 return true; 1193} 1194bool Layer::setTransparentRegionHint(const Region& transparent) { 1195 mCurrentState.requestedTransparentRegion = transparent; 1196 mCurrentState.modified = true; 1197 setTransactionFlags(eTransactionNeeded); 1198 return true; 1199} 1200bool Layer::setFlags(uint8_t flags, uint8_t mask) { 1201 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 1202 if (mCurrentState.flags == newFlags) 1203 return false; 1204 mCurrentState.sequence++; 1205 mCurrentState.flags = newFlags; 1206 mCurrentState.mask = mask; 1207 mCurrentState.modified = true; 1208 setTransactionFlags(eTransactionNeeded); 1209 return true; 1210} 1211bool Layer::setCrop(const Rect& crop) { 1212 if (mCurrentState.requested.crop == crop) 1213 return false; 1214 mCurrentState.sequence++; 1215 mCurrentState.requested.crop = crop; 1216 mCurrentState.modified = true; 1217 setTransactionFlags(eTransactionNeeded); 1218 return true; 1219} 1220 1221bool Layer::setLayerStack(uint32_t layerStack) { 1222 if (mCurrentState.layerStack == layerStack) 1223 return false; 1224 mCurrentState.sequence++; 1225 mCurrentState.layerStack = layerStack; 1226 mCurrentState.modified = true; 1227 setTransactionFlags(eTransactionNeeded); 1228 return true; 1229} 1230 1231void Layer::deferTransactionUntil(const sp<IBinder>& handle, 1232 uint64_t frameNumber) { 1233 mCurrentState.handle = handle; 1234 mCurrentState.frameNumber = frameNumber; 1235 // We don't set eTransactionNeeded, because just receiving a deferral 1236 // request without any other state updates shouldn't actually induce a delay 1237 mCurrentState.modified = true; 1238 pushPendingState(); 1239 mCurrentState.modified = false; 1240} 1241 1242void Layer::useSurfaceDamage() { 1243 if (mFlinger->mForceFullDamage) { 1244 surfaceDamageRegion = Region::INVALID_REGION; 1245 } else { 1246 surfaceDamageRegion = mSurfaceFlingerConsumer->getSurfaceDamage(); 1247 } 1248} 1249 1250void Layer::useEmptyDamage() { 1251 surfaceDamageRegion.clear(); 1252} 1253 1254// ---------------------------------------------------------------------------- 1255// pageflip handling... 1256// ---------------------------------------------------------------------------- 1257 1258bool Layer::shouldPresentNow(const DispSync& dispSync) const { 1259 if (mSidebandStreamChanged || mSingleBufferMode) { 1260 return true; 1261 } 1262 1263 Mutex::Autolock lock(mQueueItemLock); 1264 if (mQueueItems.empty()) { 1265 return false; 1266 } 1267 auto timestamp = mQueueItems[0].mTimestamp; 1268 nsecs_t expectedPresent = 1269 mSurfaceFlingerConsumer->computeExpectedPresent(dispSync); 1270 1271 // Ignore timestamps more than a second in the future 1272 bool isPlausible = timestamp < (expectedPresent + s2ns(1)); 1273 ALOGW_IF(!isPlausible, "[%s] Timestamp %" PRId64 " seems implausible " 1274 "relative to expectedPresent %" PRId64, mName.string(), timestamp, 1275 expectedPresent); 1276 1277 bool isDue = timestamp < expectedPresent; 1278 return isDue || !isPlausible; 1279} 1280 1281bool Layer::onPreComposition() { 1282 mRefreshPending = false; 1283 return mQueuedFrames > 0 || mSidebandStreamChanged || mSingleBufferMode; 1284} 1285 1286void Layer::onPostComposition() { 1287 if (mFrameLatencyNeeded) { 1288 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 1289 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 1290 1291 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 1292 if (frameReadyFence->isValid()) { 1293 mFrameTracker.setFrameReadyFence(frameReadyFence); 1294 } else { 1295 // There was no fence for this frame, so assume that it was ready 1296 // to be presented at the desired present time. 1297 mFrameTracker.setFrameReadyTime(desiredPresentTime); 1298 } 1299 1300 const HWComposer& hwc = mFlinger->getHwComposer(); 1301 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 1302 if (presentFence->isValid()) { 1303 mFrameTracker.setActualPresentFence(presentFence); 1304 } else { 1305 // The HWC doesn't support present fences, so use the refresh 1306 // timestamp instead. 1307 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 1308 mFrameTracker.setActualPresentTime(presentTime); 1309 } 1310 1311 mFrameTracker.advanceFrame(); 1312 mFrameLatencyNeeded = false; 1313 } 1314} 1315 1316bool Layer::isVisible() const { 1317 const Layer::State& s(mDrawingState); 1318 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 1319 && (mActiveBuffer != NULL || mSidebandStream != NULL); 1320} 1321 1322Region Layer::latchBuffer(bool& recomputeVisibleRegions) 1323{ 1324 ATRACE_CALL(); 1325 1326 if (android_atomic_acquire_cas(true, false, &mSidebandStreamChanged) == 0) { 1327 // mSidebandStreamChanged was true 1328 mSidebandStream = mSurfaceFlingerConsumer->getSidebandStream(); 1329 if (mSidebandStream != NULL) { 1330 setTransactionFlags(eTransactionNeeded); 1331 mFlinger->setTransactionFlags(eTraversalNeeded); 1332 } 1333 recomputeVisibleRegions = true; 1334 1335 const State& s(getDrawingState()); 1336 return s.transform.transform(Region(Rect(s.active.w, s.active.h))); 1337 } 1338 1339 Region outDirtyRegion; 1340 if (mQueuedFrames > 0 || mSingleBufferMode) { 1341 1342 // if we've already called updateTexImage() without going through 1343 // a composition step, we have to skip this layer at this point 1344 // because we cannot call updateTeximage() without a corresponding 1345 // compositionComplete() call. 1346 // we'll trigger an update in onPreComposition(). 1347 if (mRefreshPending) { 1348 return outDirtyRegion; 1349 } 1350 1351 // Capture the old state of the layer for comparisons later 1352 const State& s(getDrawingState()); 1353 const bool oldOpacity = isOpaque(s); 1354 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 1355 1356 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 1357 Layer::State& front; 1358 Layer::State& current; 1359 bool& recomputeVisibleRegions; 1360 bool stickyTransformSet; 1361 Reject(Layer::State& front, Layer::State& current, 1362 bool& recomputeVisibleRegions, bool stickySet) 1363 : front(front), current(current), 1364 recomputeVisibleRegions(recomputeVisibleRegions), 1365 stickyTransformSet(stickySet) { 1366 } 1367 1368 virtual bool reject(const sp<GraphicBuffer>& buf, 1369 const BufferItem& item) { 1370 if (buf == NULL) { 1371 return false; 1372 } 1373 1374 uint32_t bufWidth = buf->getWidth(); 1375 uint32_t bufHeight = buf->getHeight(); 1376 1377 // check that we received a buffer of the right size 1378 // (Take the buffer's orientation into account) 1379 if (item.mTransform & Transform::ROT_90) { 1380 swap(bufWidth, bufHeight); 1381 } 1382 1383 bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 1384 if (front.active != front.requested) { 1385 1386 if (isFixedSize || 1387 (bufWidth == front.requested.w && 1388 bufHeight == front.requested.h)) 1389 { 1390 // Here we pretend the transaction happened by updating the 1391 // current and drawing states. Drawing state is only accessed 1392 // in this thread, no need to have it locked 1393 front.active = front.requested; 1394 1395 // We also need to update the current state so that 1396 // we don't end-up overwriting the drawing state with 1397 // this stale current state during the next transaction 1398 // 1399 // NOTE: We don't need to hold the transaction lock here 1400 // because State::active is only accessed from this thread. 1401 current.active = front.active; 1402 1403 // recompute visible region 1404 recomputeVisibleRegions = true; 1405 } 1406 1407 ALOGD_IF(DEBUG_RESIZE, 1408 "latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n" 1409 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 1410 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n", 1411 bufWidth, bufHeight, item.mTransform, item.mScalingMode, 1412 front.active.w, front.active.h, 1413 front.active.crop.left, 1414 front.active.crop.top, 1415 front.active.crop.right, 1416 front.active.crop.bottom, 1417 front.active.crop.getWidth(), 1418 front.active.crop.getHeight(), 1419 front.requested.w, front.requested.h, 1420 front.requested.crop.left, 1421 front.requested.crop.top, 1422 front.requested.crop.right, 1423 front.requested.crop.bottom, 1424 front.requested.crop.getWidth(), 1425 front.requested.crop.getHeight()); 1426 } 1427 1428 if (!isFixedSize && !stickyTransformSet) { 1429 if (front.active.w != bufWidth || 1430 front.active.h != bufHeight) { 1431 // reject this buffer 1432 ALOGE("rejecting buffer: bufWidth=%d, bufHeight=%d, front.active.{w=%d, h=%d}", 1433 bufWidth, bufHeight, front.active.w, front.active.h); 1434 return true; 1435 } 1436 } 1437 1438 // if the transparent region has changed (this test is 1439 // conservative, but that's fine, worst case we're doing 1440 // a bit of extra work), we latch the new one and we 1441 // trigger a visible-region recompute. 1442 if (!front.activeTransparentRegion.isTriviallyEqual( 1443 front.requestedTransparentRegion)) { 1444 front.activeTransparentRegion = front.requestedTransparentRegion; 1445 1446 // We also need to update the current state so that 1447 // we don't end-up overwriting the drawing state with 1448 // this stale current state during the next transaction 1449 // 1450 // NOTE: We don't need to hold the transaction lock here 1451 // because State::active is only accessed from this thread. 1452 current.activeTransparentRegion = front.activeTransparentRegion; 1453 1454 // recompute visible region 1455 recomputeVisibleRegions = true; 1456 } 1457 1458 return false; 1459 } 1460 }; 1461 1462 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions, 1463 getProducerStickyTransform() != 0); 1464 1465 uint64_t maxFrameNumber = 0; 1466 uint64_t headFrameNumber = 0; 1467 { 1468 Mutex::Autolock lock(mQueueItemLock); 1469 maxFrameNumber = mLastFrameNumberReceived; 1470 if (!mQueueItems.empty()) { 1471 headFrameNumber = mQueueItems[0].mFrameNumber; 1472 } 1473 } 1474 1475 bool availableFramesEmpty = true; 1476 { 1477 Mutex::Autolock lock(mAvailableFrameMutex); 1478 availableFramesEmpty = mAvailableFrames.empty(); 1479 } 1480 if (!availableFramesEmpty) { 1481 Mutex::Autolock lock(mAvailableFrameMutex); 1482 bool matchingFramesFound = false; 1483 bool allTransactionsApplied = true; 1484 for (auto& frame : mAvailableFrames) { 1485 if (headFrameNumber != frame->getFrameNumber()) { 1486 break; 1487 } 1488 matchingFramesFound = true; 1489 allTransactionsApplied &= frame->transactionIsApplied(); 1490 } 1491 if (matchingFramesFound && !allTransactionsApplied) { 1492 mFlinger->signalLayerUpdate(); 1493 return outDirtyRegion; 1494 } 1495 } 1496 1497 // This boolean is used to make sure that SurfaceFlinger's shadow copy 1498 // of the buffer queue isn't modified when the buffer queue is returning 1499 // BufferItem's that weren't actually queued. This can happen in single 1500 // buffer mode. 1501 bool queuedBuffer = false; 1502 status_t updateResult = mSurfaceFlingerConsumer->updateTexImage(&r, 1503 mFlinger->mPrimaryDispSync, &mSingleBufferMode, &queuedBuffer, 1504 maxFrameNumber); 1505 if (updateResult == BufferQueue::PRESENT_LATER) { 1506 // Producer doesn't want buffer to be displayed yet. Signal a 1507 // layer update so we check again at the next opportunity. 1508 mFlinger->signalLayerUpdate(); 1509 return outDirtyRegion; 1510 } else if (updateResult == SurfaceFlingerConsumer::BUFFER_REJECTED) { 1511 // If the buffer has been rejected, remove it from the shadow queue 1512 // and return early 1513 if (queuedBuffer) { 1514 Mutex::Autolock lock(mQueueItemLock); 1515 mQueueItems.removeAt(0); 1516 android_atomic_dec(&mQueuedFrames); 1517 } 1518 return outDirtyRegion; 1519 } else if (updateResult != NO_ERROR || mUpdateTexImageFailed) { 1520 // This can occur if something goes wrong when trying to create the 1521 // EGLImage for this buffer. If this happens, the buffer has already 1522 // been released, so we need to clean up the queue and bug out 1523 // early. 1524 if (queuedBuffer) { 1525 Mutex::Autolock lock(mQueueItemLock); 1526 mQueueItems.clear(); 1527 android_atomic_and(0, &mQueuedFrames); 1528 } 1529 1530 // Once we have hit this state, the shadow queue may no longer 1531 // correctly reflect the incoming BufferQueue's contents, so even if 1532 // updateTexImage starts working, the only safe course of action is 1533 // to continue to ignore updates. 1534 mUpdateTexImageFailed = true; 1535 1536 return outDirtyRegion; 1537 } 1538 1539 if (queuedBuffer) { 1540 // Autolock scope 1541 auto currentFrameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1542 1543 Mutex::Autolock lock(mQueueItemLock); 1544 1545 // Remove any stale buffers that have been dropped during 1546 // updateTexImage 1547 while (mQueueItems[0].mFrameNumber != currentFrameNumber) { 1548 mQueueItems.removeAt(0); 1549 android_atomic_dec(&mQueuedFrames); 1550 } 1551 1552 mQueueItems.removeAt(0); 1553 } 1554 1555 1556 // Decrement the queued-frames count. Signal another event if we 1557 // have more frames pending. 1558 if ((queuedBuffer && android_atomic_dec(&mQueuedFrames) > 1) 1559 || mSingleBufferMode) { 1560 mFlinger->signalLayerUpdate(); 1561 } 1562 1563 if (!availableFramesEmpty) { 1564 Mutex::Autolock lock(mAvailableFrameMutex); 1565 auto frameNumber = mSurfaceFlingerConsumer->getFrameNumber(); 1566 while (!mAvailableFrames.empty() && 1567 frameNumber == mAvailableFrames.front()->getFrameNumber()) { 1568 mAvailableFrames.pop_front(); 1569 } 1570 } 1571 1572 if (updateResult != NO_ERROR) { 1573 // something happened! 1574 recomputeVisibleRegions = true; 1575 return outDirtyRegion; 1576 } 1577 1578 // update the active buffer 1579 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 1580 if (mActiveBuffer == NULL) { 1581 // this can only happen if the very first buffer was rejected. 1582 return outDirtyRegion; 1583 } 1584 1585 mRefreshPending = true; 1586 mFrameLatencyNeeded = true; 1587 if (oldActiveBuffer == NULL) { 1588 // the first time we receive a buffer, we need to trigger a 1589 // geometry invalidation. 1590 recomputeVisibleRegions = true; 1591 } 1592 1593 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 1594 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 1595 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 1596 if ((crop != mCurrentCrop) || 1597 (transform != mCurrentTransform) || 1598 (scalingMode != mCurrentScalingMode)) 1599 { 1600 mCurrentCrop = crop; 1601 mCurrentTransform = transform; 1602 mCurrentScalingMode = scalingMode; 1603 recomputeVisibleRegions = true; 1604 } 1605 1606 if (oldActiveBuffer != NULL) { 1607 uint32_t bufWidth = mActiveBuffer->getWidth(); 1608 uint32_t bufHeight = mActiveBuffer->getHeight(); 1609 if (bufWidth != uint32_t(oldActiveBuffer->width) || 1610 bufHeight != uint32_t(oldActiveBuffer->height)) { 1611 recomputeVisibleRegions = true; 1612 } 1613 } 1614 1615 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 1616 if (oldOpacity != isOpaque(s)) { 1617 recomputeVisibleRegions = true; 1618 } 1619 1620 // FIXME: postedRegion should be dirty & bounds 1621 Region dirtyRegion(Rect(s.active.w, s.active.h)); 1622 1623 // transform the dirty region to window-manager space 1624 outDirtyRegion = (s.transform.transform(dirtyRegion)); 1625 } 1626 return outDirtyRegion; 1627} 1628 1629uint32_t Layer::getEffectiveUsage(uint32_t usage) const 1630{ 1631 // TODO: should we do something special if mSecure is set? 1632 if (mProtectedByApp) { 1633 // need a hardware-protected path to external video sink 1634 usage |= GraphicBuffer::USAGE_PROTECTED; 1635 } 1636 if (mPotentialCursor) { 1637 usage |= GraphicBuffer::USAGE_CURSOR; 1638 } 1639 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 1640 return usage; 1641} 1642 1643void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 1644 uint32_t orientation = 0; 1645 if (!mFlinger->mDebugDisableTransformHint) { 1646 // The transform hint is used to improve performance, but we can 1647 // only have a single transform hint, it cannot 1648 // apply to all displays. 1649 const Transform& planeTransform(hw->getTransform()); 1650 orientation = planeTransform.getOrientation(); 1651 if (orientation & Transform::ROT_INVALID) { 1652 orientation = 0; 1653 } 1654 } 1655 mSurfaceFlingerConsumer->setTransformHint(orientation); 1656} 1657 1658// ---------------------------------------------------------------------------- 1659// debugging 1660// ---------------------------------------------------------------------------- 1661 1662void Layer::dump(String8& result, Colorizer& colorizer) const 1663{ 1664 const Layer::State& s(getDrawingState()); 1665 1666 colorizer.colorize(result, Colorizer::GREEN); 1667 result.appendFormat( 1668 "+ %s %p (%s)\n", 1669 getTypeId(), this, getName().string()); 1670 colorizer.reset(result); 1671 1672 s.activeTransparentRegion.dump(result, "transparentRegion"); 1673 visibleRegion.dump(result, "visibleRegion"); 1674 surfaceDamageRegion.dump(result, "surfaceDamageRegion"); 1675 sp<Client> client(mClientRef.promote()); 1676 1677 result.appendFormat( " " 1678 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), " 1679 "isOpaque=%1d, invalidate=%1d, " 1680 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 1681 " client=%p\n", 1682 s.layerStack, s.z, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h, 1683 s.active.crop.left, s.active.crop.top, 1684 s.active.crop.right, s.active.crop.bottom, 1685 isOpaque(s), contentDirty, 1686 s.alpha, s.flags, 1687 s.transform[0][0], s.transform[0][1], 1688 s.transform[1][0], s.transform[1][1], 1689 client.get()); 1690 1691 sp<const GraphicBuffer> buf0(mActiveBuffer); 1692 uint32_t w0=0, h0=0, s0=0, f0=0; 1693 if (buf0 != 0) { 1694 w0 = buf0->getWidth(); 1695 h0 = buf0->getHeight(); 1696 s0 = buf0->getStride(); 1697 f0 = buf0->format; 1698 } 1699 result.appendFormat( 1700 " " 1701 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 1702 " queued-frames=%d, mRefreshPending=%d\n", 1703 mFormat, w0, h0, s0,f0, 1704 mQueuedFrames, mRefreshPending); 1705 1706 if (mSurfaceFlingerConsumer != 0) { 1707 mSurfaceFlingerConsumer->dump(result, " "); 1708 } 1709} 1710 1711void Layer::dumpFrameStats(String8& result) const { 1712 mFrameTracker.dumpStats(result); 1713} 1714 1715void Layer::clearFrameStats() { 1716 mFrameTracker.clearStats(); 1717} 1718 1719void Layer::logFrameStats() { 1720 mFrameTracker.logAndResetStats(mName); 1721} 1722 1723void Layer::getFrameStats(FrameStats* outStats) const { 1724 mFrameTracker.getStats(outStats); 1725} 1726 1727// --------------------------------------------------------------------------- 1728 1729Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger, 1730 const sp<Layer>& layer) 1731 : mFlinger(flinger), mLayer(layer) { 1732} 1733 1734Layer::LayerCleaner::~LayerCleaner() { 1735 // destroy client resources 1736 mFlinger->onLayerDestroyed(mLayer); 1737} 1738 1739// --------------------------------------------------------------------------- 1740}; // namespace android 1741 1742#if defined(__gl_h_) 1743#error "don't include gl/gl.h in this file" 1744#endif 1745 1746#if defined(__gl2_h_) 1747#error "don't include gl2/gl2.h in this file" 1748#endif 1749