Layer.cpp revision 6b44267a3beb457e220cad0666c039d3a765cdb2
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/StopWatch.h> 31#include <utils/Trace.h> 32 33#include <ui/GraphicBuffer.h> 34#include <ui/PixelFormat.h> 35 36#include <gui/Surface.h> 37 38#include "clz.h" 39#include "Colorizer.h" 40#include "DisplayDevice.h" 41#include "Layer.h" 42#include "SurfaceFlinger.h" 43#include "SurfaceTextureLayer.h" 44 45#include "DisplayHardware/HWComposer.h" 46 47#include "RenderEngine/RenderEngine.h" 48 49#define DEBUG_RESIZE 0 50 51namespace android { 52 53// --------------------------------------------------------------------------- 54 55int32_t Layer::sSequence = 1; 56 57Layer::Layer(SurfaceFlinger* flinger, const sp<Client>& client, 58 const String8& name, uint32_t w, uint32_t h, uint32_t flags) 59 : contentDirty(false), 60 sequence(uint32_t(android_atomic_inc(&sSequence))), 61 mFlinger(flinger), 62 mTextureName(-1U), 63 mPremultipliedAlpha(true), 64 mName("unnamed"), 65 mDebug(false), 66 mFormat(PIXEL_FORMAT_NONE), 67 mOpaqueLayer(true), 68 mTransactionFlags(0), 69 mQueuedFrames(0), 70 mCurrentTransform(0), 71 mCurrentScalingMode(NATIVE_WINDOW_SCALING_MODE_FREEZE), 72 mCurrentOpacity(true), 73 mRefreshPending(false), 74 mFrameLatencyNeeded(false), 75 mFiltering(false), 76 mNeedsFiltering(false), 77 mSecure(false), 78 mProtectedByApp(false), 79 mHasSurface(false), 80 mClientRef(client) 81{ 82 mCurrentCrop.makeInvalid(); 83 glGenTextures(1, &mTextureName); 84 85 uint32_t layerFlags = 0; 86 if (flags & ISurfaceComposerClient::eHidden) 87 layerFlags = layer_state_t::eLayerHidden; 88 89 if (flags & ISurfaceComposerClient::eNonPremultiplied) 90 mPremultipliedAlpha = false; 91 92 mName = name; 93 94 mCurrentState.active.w = w; 95 mCurrentState.active.h = h; 96 mCurrentState.active.crop.makeInvalid(); 97 mCurrentState.z = 0; 98 mCurrentState.alpha = 0xFF; 99 mCurrentState.layerStack = 0; 100 mCurrentState.flags = layerFlags; 101 mCurrentState.sequence = 0; 102 mCurrentState.transform.set(0, 0); 103 mCurrentState.requested = mCurrentState.active; 104 105 // drawing state & current state are identical 106 mDrawingState = mCurrentState; 107} 108 109void Layer::onFirstRef() 110{ 111 // Creates a custom BufferQueue for SurfaceFlingerConsumer to use 112 sp<BufferQueue> bq = new SurfaceTextureLayer(mFlinger); 113 mSurfaceFlingerConsumer = new SurfaceFlingerConsumer(mTextureName, true, 114 GL_TEXTURE_EXTERNAL_OES, false, bq); 115 116 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0)); 117 mSurfaceFlingerConsumer->setFrameAvailableListener(this); 118 mSurfaceFlingerConsumer->setSynchronousMode(true); 119 mSurfaceFlingerConsumer->setName(mName); 120 121#ifdef TARGET_DISABLE_TRIPLE_BUFFERING 122#warning "disabling triple buffering" 123 mSurfaceFlingerConsumer->setDefaultMaxBufferCount(2); 124#else 125 mSurfaceFlingerConsumer->setDefaultMaxBufferCount(3); 126#endif 127 128 const sp<const DisplayDevice> hw(mFlinger->getDefaultDisplayDevice()); 129 updateTransformHint(hw); 130} 131 132Layer::~Layer() { 133 sp<Client> c(mClientRef.promote()); 134 if (c != 0) { 135 c->detachLayer(this); 136 } 137 mFlinger->deleteTextureAsync(mTextureName); 138} 139 140// --------------------------------------------------------------------------- 141// callbacks 142// --------------------------------------------------------------------------- 143 144void Layer::onLayerDisplayed(const sp<const DisplayDevice>& hw, 145 HWComposer::HWCLayerInterface* layer) { 146 if (layer) { 147 layer->onDisplayed(); 148 mSurfaceFlingerConsumer->setReleaseFence(layer->getAndResetReleaseFence()); 149 } 150} 151 152void Layer::onFrameAvailable() { 153 android_atomic_inc(&mQueuedFrames); 154 mFlinger->signalLayerUpdate(); 155} 156 157// called with SurfaceFlinger::mStateLock from the drawing thread after 158// the layer has been remove from the current state list (and just before 159// it's removed from the drawing state list) 160void Layer::onRemoved() { 161 mSurfaceFlingerConsumer->abandon(); 162} 163 164// --------------------------------------------------------------------------- 165// set-up 166// --------------------------------------------------------------------------- 167 168const String8& Layer::getName() const { 169 return mName; 170} 171 172status_t Layer::setBuffers( uint32_t w, uint32_t h, 173 PixelFormat format, uint32_t flags) 174{ 175 // this surfaces pixel format 176 PixelFormatInfo info; 177 status_t err = getPixelFormatInfo(format, &info); 178 if (err) { 179 ALOGE("unsupported pixelformat %d", format); 180 return err; 181 } 182 183 uint32_t const maxSurfaceDims = min( 184 mFlinger->getMaxTextureSize(), mFlinger->getMaxViewportDims()); 185 186 // never allow a surface larger than what our underlying GL implementation 187 // can handle. 188 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { 189 ALOGE("dimensions too large %u x %u", uint32_t(w), uint32_t(h)); 190 return BAD_VALUE; 191 } 192 193 mFormat = format; 194 195 mSecure = (flags & ISurfaceComposerClient::eSecure) ? true : false; 196 mProtectedByApp = (flags & ISurfaceComposerClient::eProtectedByApp) ? true : false; 197 mOpaqueLayer = (flags & ISurfaceComposerClient::eOpaque); 198 mCurrentOpacity = getOpacityForFormat(format); 199 200 mSurfaceFlingerConsumer->setDefaultBufferSize(w, h); 201 mSurfaceFlingerConsumer->setDefaultBufferFormat(format); 202 mSurfaceFlingerConsumer->setConsumerUsageBits(getEffectiveUsage(0)); 203 204 return NO_ERROR; 205} 206 207sp<IBinder> Layer::getHandle() { 208 Mutex::Autolock _l(mLock); 209 210 LOG_ALWAYS_FATAL_IF(mHasSurface, 211 "Layer::getHandle() has already been called"); 212 213 mHasSurface = true; 214 215 /* 216 * The layer handle is just a BBinder object passed to the client 217 * (remote process) -- we don't keep any reference on our side such that 218 * the dtor is called when the remote side let go of its reference. 219 * 220 * LayerCleaner ensures that mFlinger->onLayerDestroyed() is called for 221 * this layer when the handle is destroyed. 222 */ 223 224 class Handle : public BBinder, public LayerCleaner { 225 wp<const Layer> mOwner; 226 public: 227 Handle(const sp<SurfaceFlinger>& flinger, const sp<Layer>& layer) 228 : LayerCleaner(flinger, layer), mOwner(layer) { 229 } 230 }; 231 232 return new Handle(mFlinger, this); 233} 234 235sp<BufferQueue> Layer::getBufferQueue() const { 236 return mSurfaceFlingerConsumer->getBufferQueue(); 237} 238 239// --------------------------------------------------------------------------- 240// h/w composer set-up 241// --------------------------------------------------------------------------- 242 243Rect Layer::getContentCrop() const { 244 // this is the crop rectangle that applies to the buffer 245 // itself (as opposed to the window) 246 Rect crop; 247 if (!mCurrentCrop.isEmpty()) { 248 // if the buffer crop is defined, we use that 249 crop = mCurrentCrop; 250 } else if (mActiveBuffer != NULL) { 251 // otherwise we use the whole buffer 252 crop = mActiveBuffer->getBounds(); 253 } else { 254 // if we don't have a buffer yet, we use an empty/invalid crop 255 crop.makeInvalid(); 256 } 257 return crop; 258} 259 260static Rect reduce(const Rect& win, const Region& exclude) { 261 if (CC_LIKELY(exclude.isEmpty())) { 262 return win; 263 } 264 if (exclude.isRect()) { 265 return win.reduce(exclude.getBounds()); 266 } 267 return Region(win).subtract(exclude).getBounds(); 268} 269 270Rect Layer::computeBounds() const { 271 const Layer::State& s(getDrawingState()); 272 Rect win(s.active.w, s.active.h); 273 if (!s.active.crop.isEmpty()) { 274 win.intersect(s.active.crop, &win); 275 } 276 // subtract the transparent region and snap to the bounds 277 return reduce(win, s.activeTransparentRegion); 278} 279 280FloatRect Layer::computeCrop(const sp<const DisplayDevice>& hw) const { 281 // the content crop is the area of the content that gets scaled to the 282 // layer's size. 283 FloatRect crop(getContentCrop()); 284 285 // the active.crop is the area of the window that gets cropped, but not 286 // scaled in any ways. 287 const State& s(getDrawingState()); 288 289 // apply the projection's clipping to the window crop in 290 // layerstack space, and convert-back to layer space. 291 // if there are no window scaling involved, this operation will map to full 292 // pixels in the buffer. 293 // FIXME: the 3 lines below can produce slightly incorrect clipping when we have 294 // a viewport clipping and a window transform. we should use floating point to fix this. 295 Rect activeCrop(s.transform.transform(s.active.crop)); 296 activeCrop.intersect(hw->getViewport(), &activeCrop); 297 activeCrop = s.transform.inverse().transform(activeCrop); 298 299 // paranoia: make sure the window-crop is constrained in the 300 // window's bounds 301 activeCrop.intersect(Rect(s.active.w, s.active.h), &activeCrop); 302 303 // subtract the transparent region and snap to the bounds 304 activeCrop = reduce(activeCrop, s.activeTransparentRegion); 305 306 if (!activeCrop.isEmpty()) { 307 // Transform the window crop to match the buffer coordinate system, 308 // which means using the inverse of the current transform set on the 309 // SurfaceFlingerConsumer. 310 uint32_t invTransform = mCurrentTransform; 311 int winWidth = s.active.w; 312 int winHeight = s.active.h; 313 if (invTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { 314 invTransform ^= NATIVE_WINDOW_TRANSFORM_FLIP_V | 315 NATIVE_WINDOW_TRANSFORM_FLIP_H; 316 winWidth = s.active.h; 317 winHeight = s.active.w; 318 } 319 const Rect winCrop = activeCrop.transform( 320 invTransform, s.active.w, s.active.h); 321 322 // below, crop is intersected with winCrop expressed in crop's coordinate space 323 float xScale = crop.getWidth() / float(winWidth); 324 float yScale = crop.getHeight() / float(winHeight); 325 326 float insetL = winCrop.left * xScale; 327 float insetT = winCrop.top * yScale; 328 float insetR = (winWidth - winCrop.right ) * xScale; 329 float insetB = (winHeight - winCrop.bottom) * yScale; 330 331 crop.left += insetL; 332 crop.top += insetT; 333 crop.right -= insetR; 334 crop.bottom -= insetB; 335 } 336 return crop; 337} 338 339void Layer::setGeometry( 340 const sp<const DisplayDevice>& hw, 341 HWComposer::HWCLayerInterface& layer) 342{ 343 layer.setDefaultState(); 344 345 // enable this layer 346 layer.setSkip(false); 347 348 if (isSecure() && !hw->isSecure()) { 349 layer.setSkip(true); 350 } 351 352 // this gives us only the "orientation" component of the transform 353 const State& s(getDrawingState()); 354 if (!isOpaque() || s.alpha != 0xFF) { 355 layer.setBlending(mPremultipliedAlpha ? 356 HWC_BLENDING_PREMULT : 357 HWC_BLENDING_COVERAGE); 358 } 359 360 // apply the layer's transform, followed by the display's global transform 361 // here we're guaranteed that the layer's transform preserves rects 362 Rect frame(s.transform.transform(computeBounds())); 363 frame.intersect(hw->getViewport(), &frame); 364 const Transform& tr(hw->getTransform()); 365 layer.setFrame(tr.transform(frame)); 366 layer.setCrop(computeCrop(hw)); 367 layer.setPlaneAlpha(s.alpha); 368 369 /* 370 * Transformations are applied in this order: 371 * 1) buffer orientation/flip/mirror 372 * 2) state transformation (window manager) 373 * 3) layer orientation (screen orientation) 374 * (NOTE: the matrices are multiplied in reverse order) 375 */ 376 377 const Transform bufferOrientation(mCurrentTransform); 378 const Transform transform(tr * s.transform * bufferOrientation); 379 380 // this gives us only the "orientation" component of the transform 381 const uint32_t orientation = transform.getOrientation(); 382 if (orientation & Transform::ROT_INVALID) { 383 // we can only handle simple transformation 384 layer.setSkip(true); 385 } else { 386 layer.setTransform(orientation); 387 } 388} 389 390void Layer::setPerFrameData(const sp<const DisplayDevice>& hw, 391 HWComposer::HWCLayerInterface& layer) { 392 // we have to set the visible region on every frame because 393 // we currently free it during onLayerDisplayed(), which is called 394 // after HWComposer::commit() -- every frame. 395 // Apply this display's projection's viewport to the visible region 396 // before giving it to the HWC HAL. 397 const Transform& tr = hw->getTransform(); 398 Region visible = tr.transform(visibleRegion.intersect(hw->getViewport())); 399 layer.setVisibleRegionScreen(visible); 400 401 // NOTE: buffer can be NULL if the client never drew into this 402 // layer yet, or if we ran out of memory 403 layer.setBuffer(mActiveBuffer); 404} 405 406void Layer::setAcquireFence(const sp<const DisplayDevice>& hw, 407 HWComposer::HWCLayerInterface& layer) { 408 int fenceFd = -1; 409 410 // TODO: there is a possible optimization here: we only need to set the 411 // acquire fence the first time a new buffer is acquired on EACH display. 412 413 if (layer.getCompositionType() == HWC_OVERLAY) { 414 sp<Fence> fence = mSurfaceFlingerConsumer->getCurrentFence(); 415 if (fence->isValid()) { 416 fenceFd = fence->dup(); 417 if (fenceFd == -1) { 418 ALOGW("failed to dup layer fence, skipping sync: %d", errno); 419 } 420 } 421 } 422 layer.setAcquireFenceFd(fenceFd); 423} 424 425// --------------------------------------------------------------------------- 426// drawing... 427// --------------------------------------------------------------------------- 428 429void Layer::draw(const sp<const DisplayDevice>& hw, const Region& clip) const { 430 onDraw(hw, clip); 431} 432 433void Layer::draw(const sp<const DisplayDevice>& hw) { 434 onDraw( hw, Region(hw->bounds()) ); 435} 436 437void Layer::onDraw(const sp<const DisplayDevice>& hw, const Region& clip) const 438{ 439 ATRACE_CALL(); 440 441 if (CC_UNLIKELY(mActiveBuffer == 0)) { 442 // the texture has not been created yet, this Layer has 443 // in fact never been drawn into. This happens frequently with 444 // SurfaceView because the WindowManager can't know when the client 445 // has drawn the first time. 446 447 // If there is nothing under us, we paint the screen in black, otherwise 448 // we just skip this update. 449 450 // figure out if there is something below us 451 Region under; 452 const SurfaceFlinger::LayerVector& drawingLayers( 453 mFlinger->mDrawingState.layersSortedByZ); 454 const size_t count = drawingLayers.size(); 455 for (size_t i=0 ; i<count ; ++i) { 456 const sp<Layer>& layer(drawingLayers[i]); 457 if (layer.get() == static_cast<Layer const*>(this)) 458 break; 459 under.orSelf( hw->getTransform().transform(layer->visibleRegion) ); 460 } 461 // if not everything below us is covered, we plug the holes! 462 Region holes(clip.subtract(under)); 463 if (!holes.isEmpty()) { 464 clearWithOpenGL(hw, holes, 0, 0, 0, 1); 465 } 466 return; 467 } 468 469 // Bind the current buffer to the GL texture, and wait for it to be 470 // ready for us to draw into. 471 status_t err = mSurfaceFlingerConsumer->bindTextureImage(); 472 if (err != NO_ERROR) { 473 ALOGW("onDraw: bindTextureImage failed (err=%d)", err); 474 // Go ahead and draw the buffer anyway; no matter what we do the screen 475 // is probably going to have something visibly wrong. 476 } 477 478 bool blackOutLayer = isProtected() || (isSecure() && !hw->isSecure()); 479 480 RenderEngine& engine(mFlinger->getRenderEngine()); 481 482 if (!blackOutLayer) { 483 // TODO: we could be more subtle with isFixedSize() 484 const bool useFiltering = getFiltering() || needsFiltering(hw) || isFixedSize(); 485 486 // Query the texture matrix given our current filtering mode. 487 float textureMatrix[16]; 488 mSurfaceFlingerConsumer->setFilteringEnabled(useFiltering); 489 mSurfaceFlingerConsumer->getTransformMatrix(textureMatrix); 490 491 // Set things up for texturing. 492 engine.setupLayerTexturing(mTextureName, useFiltering, textureMatrix); 493 } else { 494 engine.setupLayerBlackedOut(); 495 } 496 drawWithOpenGL(hw, clip); 497 engine.disableTexturing(); 498} 499 500 501void Layer::clearWithOpenGL(const sp<const DisplayDevice>& hw, const Region& clip, 502 GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha) const 503{ 504 LayerMesh mesh; 505 computeGeometry(hw, &mesh); 506 507 mFlinger->getRenderEngine().clearWithColor( 508 mesh.getVertices(), mesh.getVertexCount(), 509 red, green, blue, alpha); 510} 511 512void Layer::clearWithOpenGL( 513 const sp<const DisplayDevice>& hw, const Region& clip) const { 514 clearWithOpenGL(hw, clip, 0,0,0,0); 515} 516 517void Layer::drawWithOpenGL( 518 const sp<const DisplayDevice>& hw, const Region& clip) const { 519 const uint32_t fbHeight = hw->getHeight(); 520 const State& s(getDrawingState()); 521 522 LayerMesh mesh; 523 computeGeometry(hw, &mesh); 524 525 /* 526 * NOTE: the way we compute the texture coordinates here produces 527 * different results than when we take the HWC path -- in the later case 528 * the "source crop" is rounded to texel boundaries. 529 * This can produce significantly different results when the texture 530 * is scaled by a large amount. 531 * 532 * The GL code below is more logical (imho), and the difference with 533 * HWC is due to a limitation of the HWC API to integers -- a question 534 * is suspend is wether we should ignore this problem or revert to 535 * GL composition when a buffer scaling is applied (maybe with some 536 * minimal value)? Or, we could make GL behave like HWC -- but this feel 537 * like more of a hack. 538 */ 539 const Rect win(computeBounds()); 540 541 GLfloat left = GLfloat(win.left) / GLfloat(s.active.w); 542 GLfloat top = GLfloat(win.top) / GLfloat(s.active.h); 543 GLfloat right = GLfloat(win.right) / GLfloat(s.active.w); 544 GLfloat bottom = GLfloat(win.bottom) / GLfloat(s.active.h); 545 546 // TODO: we probably want to generate the texture coords with the mesh 547 // here we assume that we only have 4 vertices 548 float texCoords[4][2]; 549 texCoords[0][0] = left; 550 texCoords[0][1] = top; 551 texCoords[1][0] = left; 552 texCoords[1][1] = bottom; 553 texCoords[2][0] = right; 554 texCoords[2][1] = bottom; 555 texCoords[3][0] = right; 556 texCoords[3][1] = top; 557 for (int i = 0; i < 4; i++) { 558 texCoords[i][1] = 1.0f - texCoords[i][1]; 559 } 560 561 RenderEngine& engine(mFlinger->getRenderEngine()); 562 engine.setupLayerBlending(mPremultipliedAlpha, isOpaque(), s.alpha); 563 engine.drawMesh2D(mesh.getVertices(), texCoords, mesh.getVertexCount()); 564 engine.disableBlending(); 565} 566 567void Layer::setFiltering(bool filtering) { 568 mFiltering = filtering; 569} 570 571bool Layer::getFiltering() const { 572 return mFiltering; 573} 574 575// As documented in libhardware header, formats in the range 576// 0x100 - 0x1FF are specific to the HAL implementation, and 577// are known to have no alpha channel 578// TODO: move definition for device-specific range into 579// hardware.h, instead of using hard-coded values here. 580#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 581 582bool Layer::getOpacityForFormat(uint32_t format) 583{ 584 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 585 return true; 586 } 587 PixelFormatInfo info; 588 status_t err = getPixelFormatInfo(PixelFormat(format), &info); 589 // in case of error (unknown format), we assume no blending 590 return (err || info.h_alpha <= info.l_alpha); 591} 592 593// ---------------------------------------------------------------------------- 594// local state 595// ---------------------------------------------------------------------------- 596 597void Layer::computeGeometry(const sp<const DisplayDevice>& hw, LayerMesh* mesh) const 598{ 599 const Layer::State& s(getDrawingState()); 600 const Transform tr(hw->getTransform() * s.transform); 601 const uint32_t hw_h = hw->getHeight(); 602 Rect win(s.active.w, s.active.h); 603 if (!s.active.crop.isEmpty()) { 604 win.intersect(s.active.crop, &win); 605 } 606 // subtract the transparent region and snap to the bounds 607 win = reduce(win, s.activeTransparentRegion); 608 if (mesh) { 609 tr.transform(mesh->mVertices[0], win.left, win.top); 610 tr.transform(mesh->mVertices[1], win.left, win.bottom); 611 tr.transform(mesh->mVertices[2], win.right, win.bottom); 612 tr.transform(mesh->mVertices[3], win.right, win.top); 613 for (size_t i=0 ; i<4 ; i++) { 614 mesh->mVertices[i][1] = hw_h - mesh->mVertices[i][1]; 615 } 616 } 617} 618 619bool Layer::isOpaque() const 620{ 621 // if we don't have a buffer yet, we're translucent regardless of the 622 // layer's opaque flag. 623 if (mActiveBuffer == 0) { 624 return false; 625 } 626 627 // if the layer has the opaque flag, then we're always opaque, 628 // otherwise we use the current buffer's format. 629 return mOpaqueLayer || mCurrentOpacity; 630} 631 632bool Layer::isProtected() const 633{ 634 const sp<GraphicBuffer>& activeBuffer(mActiveBuffer); 635 return (activeBuffer != 0) && 636 (activeBuffer->getUsage() & GRALLOC_USAGE_PROTECTED); 637} 638 639bool Layer::isFixedSize() const { 640 return mCurrentScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 641} 642 643bool Layer::isCropped() const { 644 return !mCurrentCrop.isEmpty(); 645} 646 647bool Layer::needsFiltering(const sp<const DisplayDevice>& hw) const { 648 return mNeedsFiltering || hw->needsFiltering(); 649} 650 651void Layer::setVisibleRegion(const Region& visibleRegion) { 652 // always called from main thread 653 this->visibleRegion = visibleRegion; 654} 655 656void Layer::setCoveredRegion(const Region& coveredRegion) { 657 // always called from main thread 658 this->coveredRegion = coveredRegion; 659} 660 661void Layer::setVisibleNonTransparentRegion(const Region& 662 setVisibleNonTransparentRegion) { 663 // always called from main thread 664 this->visibleNonTransparentRegion = setVisibleNonTransparentRegion; 665} 666 667// ---------------------------------------------------------------------------- 668// transaction 669// ---------------------------------------------------------------------------- 670 671uint32_t Layer::doTransaction(uint32_t flags) { 672 ATRACE_CALL(); 673 674 const Layer::State& s(getDrawingState()); 675 const Layer::State& c(getCurrentState()); 676 677 const bool sizeChanged = (c.requested.w != s.requested.w) || 678 (c.requested.h != s.requested.h); 679 680 if (sizeChanged) { 681 // the size changed, we need to ask our client to request a new buffer 682 ALOGD_IF(DEBUG_RESIZE, 683 "doTransaction: geometry (layer=%p '%s'), tr=%02x, scalingMode=%d\n" 684 " current={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 685 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n" 686 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 687 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n", 688 this, getName().string(), mCurrentTransform, mCurrentScalingMode, 689 c.active.w, c.active.h, 690 c.active.crop.left, 691 c.active.crop.top, 692 c.active.crop.right, 693 c.active.crop.bottom, 694 c.active.crop.getWidth(), 695 c.active.crop.getHeight(), 696 c.requested.w, c.requested.h, 697 c.requested.crop.left, 698 c.requested.crop.top, 699 c.requested.crop.right, 700 c.requested.crop.bottom, 701 c.requested.crop.getWidth(), 702 c.requested.crop.getHeight(), 703 s.active.w, s.active.h, 704 s.active.crop.left, 705 s.active.crop.top, 706 s.active.crop.right, 707 s.active.crop.bottom, 708 s.active.crop.getWidth(), 709 s.active.crop.getHeight(), 710 s.requested.w, s.requested.h, 711 s.requested.crop.left, 712 s.requested.crop.top, 713 s.requested.crop.right, 714 s.requested.crop.bottom, 715 s.requested.crop.getWidth(), 716 s.requested.crop.getHeight()); 717 718 // record the new size, form this point on, when the client request 719 // a buffer, it'll get the new size. 720 mSurfaceFlingerConsumer->setDefaultBufferSize( 721 c.requested.w, c.requested.h); 722 } 723 724 if (!isFixedSize()) { 725 726 const bool resizePending = (c.requested.w != c.active.w) || 727 (c.requested.h != c.active.h); 728 729 if (resizePending) { 730 // don't let Layer::doTransaction update the drawing state 731 // if we have a pending resize, unless we are in fixed-size mode. 732 // the drawing state will be updated only once we receive a buffer 733 // with the correct size. 734 // 735 // in particular, we want to make sure the clip (which is part 736 // of the geometry state) is latched together with the size but is 737 // latched immediately when no resizing is involved. 738 739 flags |= eDontUpdateGeometryState; 740 } 741 } 742 743 // always set active to requested, unless we're asked not to 744 // this is used by Layer, which special cases resizes. 745 if (flags & eDontUpdateGeometryState) { 746 } else { 747 Layer::State& editCurrentState(getCurrentState()); 748 editCurrentState.active = c.requested; 749 } 750 751 if (s.active != c.active) { 752 // invalidate and recompute the visible regions if needed 753 flags |= Layer::eVisibleRegion; 754 } 755 756 if (c.sequence != s.sequence) { 757 // invalidate and recompute the visible regions if needed 758 flags |= eVisibleRegion; 759 this->contentDirty = true; 760 761 // we may use linear filtering, if the matrix scales us 762 const uint8_t type = c.transform.getType(); 763 mNeedsFiltering = (!c.transform.preserveRects() || 764 (type >= Transform::SCALE)); 765 } 766 767 // Commit the transaction 768 commitTransaction(); 769 return flags; 770} 771 772void Layer::commitTransaction() { 773 mDrawingState = mCurrentState; 774} 775 776uint32_t Layer::getTransactionFlags(uint32_t flags) { 777 return android_atomic_and(~flags, &mTransactionFlags) & flags; 778} 779 780uint32_t Layer::setTransactionFlags(uint32_t flags) { 781 return android_atomic_or(flags, &mTransactionFlags); 782} 783 784bool Layer::setPosition(float x, float y) { 785 if (mCurrentState.transform.tx() == x && mCurrentState.transform.ty() == y) 786 return false; 787 mCurrentState.sequence++; 788 mCurrentState.transform.set(x, y); 789 setTransactionFlags(eTransactionNeeded); 790 return true; 791} 792bool Layer::setLayer(uint32_t z) { 793 if (mCurrentState.z == z) 794 return false; 795 mCurrentState.sequence++; 796 mCurrentState.z = z; 797 setTransactionFlags(eTransactionNeeded); 798 return true; 799} 800bool Layer::setSize(uint32_t w, uint32_t h) { 801 if (mCurrentState.requested.w == w && mCurrentState.requested.h == h) 802 return false; 803 mCurrentState.requested.w = w; 804 mCurrentState.requested.h = h; 805 setTransactionFlags(eTransactionNeeded); 806 return true; 807} 808bool Layer::setAlpha(uint8_t alpha) { 809 if (mCurrentState.alpha == alpha) 810 return false; 811 mCurrentState.sequence++; 812 mCurrentState.alpha = alpha; 813 setTransactionFlags(eTransactionNeeded); 814 return true; 815} 816bool Layer::setMatrix(const layer_state_t::matrix22_t& matrix) { 817 mCurrentState.sequence++; 818 mCurrentState.transform.set( 819 matrix.dsdx, matrix.dsdy, matrix.dtdx, matrix.dtdy); 820 setTransactionFlags(eTransactionNeeded); 821 return true; 822} 823bool Layer::setTransparentRegionHint(const Region& transparent) { 824 mCurrentState.requestedTransparentRegion = transparent; 825 setTransactionFlags(eTransactionNeeded); 826 return true; 827} 828bool Layer::setFlags(uint8_t flags, uint8_t mask) { 829 const uint32_t newFlags = (mCurrentState.flags & ~mask) | (flags & mask); 830 if (mCurrentState.flags == newFlags) 831 return false; 832 mCurrentState.sequence++; 833 mCurrentState.flags = newFlags; 834 setTransactionFlags(eTransactionNeeded); 835 return true; 836} 837bool Layer::setCrop(const Rect& crop) { 838 if (mCurrentState.requested.crop == crop) 839 return false; 840 mCurrentState.sequence++; 841 mCurrentState.requested.crop = crop; 842 setTransactionFlags(eTransactionNeeded); 843 return true; 844} 845 846bool Layer::setLayerStack(uint32_t layerStack) { 847 if (mCurrentState.layerStack == layerStack) 848 return false; 849 mCurrentState.sequence++; 850 mCurrentState.layerStack = layerStack; 851 setTransactionFlags(eTransactionNeeded); 852 return true; 853} 854 855// ---------------------------------------------------------------------------- 856// pageflip handling... 857// ---------------------------------------------------------------------------- 858 859bool Layer::onPreComposition() { 860 mRefreshPending = false; 861 return mQueuedFrames > 0; 862} 863 864void Layer::onPostComposition() { 865 if (mFrameLatencyNeeded) { 866 nsecs_t desiredPresentTime = mSurfaceFlingerConsumer->getTimestamp(); 867 mFrameTracker.setDesiredPresentTime(desiredPresentTime); 868 869 sp<Fence> frameReadyFence = mSurfaceFlingerConsumer->getCurrentFence(); 870 if (frameReadyFence->isValid()) { 871 mFrameTracker.setFrameReadyFence(frameReadyFence); 872 } else { 873 // There was no fence for this frame, so assume that it was ready 874 // to be presented at the desired present time. 875 mFrameTracker.setFrameReadyTime(desiredPresentTime); 876 } 877 878 const HWComposer& hwc = mFlinger->getHwComposer(); 879 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY); 880 if (presentFence->isValid()) { 881 mFrameTracker.setActualPresentFence(presentFence); 882 } else { 883 // The HWC doesn't support present fences, so use the refresh 884 // timestamp instead. 885 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY); 886 mFrameTracker.setActualPresentTime(presentTime); 887 } 888 889 mFrameTracker.advanceFrame(); 890 mFrameLatencyNeeded = false; 891 } 892} 893 894bool Layer::isVisible() const { 895 const Layer::State& s(mDrawingState); 896 return !(s.flags & layer_state_t::eLayerHidden) && s.alpha 897 && (mActiveBuffer != NULL); 898} 899 900Region Layer::latchBuffer(bool& recomputeVisibleRegions) 901{ 902 ATRACE_CALL(); 903 904 Region outDirtyRegion; 905 if (mQueuedFrames > 0) { 906 907 // if we've already called updateTexImage() without going through 908 // a composition step, we have to skip this layer at this point 909 // because we cannot call updateTeximage() without a corresponding 910 // compositionComplete() call. 911 // we'll trigger an update in onPreComposition(). 912 if (mRefreshPending) { 913 return outDirtyRegion; 914 } 915 916 // Capture the old state of the layer for comparisons later 917 const bool oldOpacity = isOpaque(); 918 sp<GraphicBuffer> oldActiveBuffer = mActiveBuffer; 919 920 // signal another event if we have more frames pending 921 if (android_atomic_dec(&mQueuedFrames) > 1) { 922 mFlinger->signalLayerUpdate(); 923 } 924 925 struct Reject : public SurfaceFlingerConsumer::BufferRejecter { 926 Layer::State& front; 927 Layer::State& current; 928 bool& recomputeVisibleRegions; 929 Reject(Layer::State& front, Layer::State& current, 930 bool& recomputeVisibleRegions) 931 : front(front), current(current), 932 recomputeVisibleRegions(recomputeVisibleRegions) { 933 } 934 935 virtual bool reject(const sp<GraphicBuffer>& buf, 936 const BufferQueue::BufferItem& item) { 937 if (buf == NULL) { 938 return false; 939 } 940 941 uint32_t bufWidth = buf->getWidth(); 942 uint32_t bufHeight = buf->getHeight(); 943 944 // check that we received a buffer of the right size 945 // (Take the buffer's orientation into account) 946 if (item.mTransform & Transform::ROT_90) { 947 swap(bufWidth, bufHeight); 948 } 949 950 bool isFixedSize = item.mScalingMode != NATIVE_WINDOW_SCALING_MODE_FREEZE; 951 if (front.active != front.requested) { 952 953 if (isFixedSize || 954 (bufWidth == front.requested.w && 955 bufHeight == front.requested.h)) 956 { 957 // Here we pretend the transaction happened by updating the 958 // current and drawing states. Drawing state is only accessed 959 // in this thread, no need to have it locked 960 front.active = front.requested; 961 962 // We also need to update the current state so that 963 // we don't end-up overwriting the drawing state with 964 // this stale current state during the next transaction 965 // 966 // NOTE: We don't need to hold the transaction lock here 967 // because State::active is only accessed from this thread. 968 current.active = front.active; 969 970 // recompute visible region 971 recomputeVisibleRegions = true; 972 } 973 974 ALOGD_IF(DEBUG_RESIZE, 975 "latchBuffer/reject: buffer (%ux%u, tr=%02x), scalingMode=%d\n" 976 " drawing={ active ={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }\n" 977 " requested={ wh={%4u,%4u} crop={%4d,%4d,%4d,%4d} (%4d,%4d) }}\n", 978 bufWidth, bufHeight, item.mTransform, item.mScalingMode, 979 front.active.w, front.active.h, 980 front.active.crop.left, 981 front.active.crop.top, 982 front.active.crop.right, 983 front.active.crop.bottom, 984 front.active.crop.getWidth(), 985 front.active.crop.getHeight(), 986 front.requested.w, front.requested.h, 987 front.requested.crop.left, 988 front.requested.crop.top, 989 front.requested.crop.right, 990 front.requested.crop.bottom, 991 front.requested.crop.getWidth(), 992 front.requested.crop.getHeight()); 993 } 994 995 if (!isFixedSize) { 996 if (front.active.w != bufWidth || 997 front.active.h != bufHeight) { 998 // reject this buffer 999 return true; 1000 } 1001 } 1002 1003 // if the transparent region has changed (this test is 1004 // conservative, but that's fine, worst case we're doing 1005 // a bit of extra work), we latch the new one and we 1006 // trigger a visible-region recompute. 1007 if (!front.activeTransparentRegion.isTriviallyEqual( 1008 front.requestedTransparentRegion)) { 1009 front.activeTransparentRegion = front.requestedTransparentRegion; 1010 1011 // We also need to update the current state so that 1012 // we don't end-up overwriting the drawing state with 1013 // this stale current state during the next transaction 1014 // 1015 // NOTE: We don't need to hold the transaction lock here 1016 // because State::active is only accessed from this thread. 1017 current.activeTransparentRegion = front.activeTransparentRegion; 1018 1019 // recompute visible region 1020 recomputeVisibleRegions = true; 1021 } 1022 1023 return false; 1024 } 1025 }; 1026 1027 1028 Reject r(mDrawingState, getCurrentState(), recomputeVisibleRegions); 1029 1030 if (mSurfaceFlingerConsumer->updateTexImage(&r) != NO_ERROR) { 1031 // something happened! 1032 recomputeVisibleRegions = true; 1033 return outDirtyRegion; 1034 } 1035 1036 // update the active buffer 1037 mActiveBuffer = mSurfaceFlingerConsumer->getCurrentBuffer(); 1038 if (mActiveBuffer == NULL) { 1039 // this can only happen if the very first buffer was rejected. 1040 return outDirtyRegion; 1041 } 1042 1043 mRefreshPending = true; 1044 mFrameLatencyNeeded = true; 1045 if (oldActiveBuffer == NULL) { 1046 // the first time we receive a buffer, we need to trigger a 1047 // geometry invalidation. 1048 recomputeVisibleRegions = true; 1049 } 1050 1051 Rect crop(mSurfaceFlingerConsumer->getCurrentCrop()); 1052 const uint32_t transform(mSurfaceFlingerConsumer->getCurrentTransform()); 1053 const uint32_t scalingMode(mSurfaceFlingerConsumer->getCurrentScalingMode()); 1054 if ((crop != mCurrentCrop) || 1055 (transform != mCurrentTransform) || 1056 (scalingMode != mCurrentScalingMode)) 1057 { 1058 mCurrentCrop = crop; 1059 mCurrentTransform = transform; 1060 mCurrentScalingMode = scalingMode; 1061 recomputeVisibleRegions = true; 1062 } 1063 1064 if (oldActiveBuffer != NULL) { 1065 uint32_t bufWidth = mActiveBuffer->getWidth(); 1066 uint32_t bufHeight = mActiveBuffer->getHeight(); 1067 if (bufWidth != uint32_t(oldActiveBuffer->width) || 1068 bufHeight != uint32_t(oldActiveBuffer->height)) { 1069 recomputeVisibleRegions = true; 1070 } 1071 } 1072 1073 mCurrentOpacity = getOpacityForFormat(mActiveBuffer->format); 1074 if (oldOpacity != isOpaque()) { 1075 recomputeVisibleRegions = true; 1076 } 1077 1078 // FIXME: postedRegion should be dirty & bounds 1079 const Layer::State& s(getDrawingState()); 1080 Region dirtyRegion(Rect(s.active.w, s.active.h)); 1081 1082 // transform the dirty region to window-manager space 1083 outDirtyRegion = (s.transform.transform(dirtyRegion)); 1084 } 1085 return outDirtyRegion; 1086} 1087 1088uint32_t Layer::getEffectiveUsage(uint32_t usage) const 1089{ 1090 // TODO: should we do something special if mSecure is set? 1091 if (mProtectedByApp) { 1092 // need a hardware-protected path to external video sink 1093 usage |= GraphicBuffer::USAGE_PROTECTED; 1094 } 1095 usage |= GraphicBuffer::USAGE_HW_COMPOSER; 1096 return usage; 1097} 1098 1099void Layer::updateTransformHint(const sp<const DisplayDevice>& hw) const { 1100 uint32_t orientation = 0; 1101 if (!mFlinger->mDebugDisableTransformHint) { 1102 // The transform hint is used to improve performance, but we can 1103 // only have a single transform hint, it cannot 1104 // apply to all displays. 1105 const Transform& planeTransform(hw->getTransform()); 1106 orientation = planeTransform.getOrientation(); 1107 if (orientation & Transform::ROT_INVALID) { 1108 orientation = 0; 1109 } 1110 } 1111 mSurfaceFlingerConsumer->setTransformHint(orientation); 1112} 1113 1114// ---------------------------------------------------------------------------- 1115// debugging 1116// ---------------------------------------------------------------------------- 1117 1118void Layer::dump(String8& result, Colorizer& colorizer) const 1119{ 1120 const Layer::State& s(getDrawingState()); 1121 1122 colorizer.colorize(result, Colorizer::GREEN); 1123 result.appendFormat( 1124 "+ %s %p (%s)\n", 1125 getTypeId(), this, getName().string()); 1126 colorizer.reset(result); 1127 1128 s.activeTransparentRegion.dump(result, "transparentRegion"); 1129 visibleRegion.dump(result, "visibleRegion"); 1130 sp<Client> client(mClientRef.promote()); 1131 1132 result.appendFormat( " " 1133 "layerStack=%4d, z=%9d, pos=(%g,%g), size=(%4d,%4d), crop=(%4d,%4d,%4d,%4d), " 1134 "isOpaque=%1d, invalidate=%1d, " 1135 "alpha=0x%02x, flags=0x%08x, tr=[%.2f, %.2f][%.2f, %.2f]\n" 1136 " client=%p\n", 1137 s.layerStack, s.z, s.transform.tx(), s.transform.ty(), s.active.w, s.active.h, 1138 s.active.crop.left, s.active.crop.top, 1139 s.active.crop.right, s.active.crop.bottom, 1140 isOpaque(), contentDirty, 1141 s.alpha, s.flags, 1142 s.transform[0][0], s.transform[0][1], 1143 s.transform[1][0], s.transform[1][1], 1144 client.get()); 1145 1146 sp<const GraphicBuffer> buf0(mActiveBuffer); 1147 uint32_t w0=0, h0=0, s0=0, f0=0; 1148 if (buf0 != 0) { 1149 w0 = buf0->getWidth(); 1150 h0 = buf0->getHeight(); 1151 s0 = buf0->getStride(); 1152 f0 = buf0->format; 1153 } 1154 result.appendFormat( 1155 " " 1156 "format=%2d, activeBuffer=[%4ux%4u:%4u,%3X]," 1157 " queued-frames=%d, mRefreshPending=%d\n", 1158 mFormat, w0, h0, s0,f0, 1159 mQueuedFrames, mRefreshPending); 1160 1161 if (mSurfaceFlingerConsumer != 0) { 1162 mSurfaceFlingerConsumer->dump(result, " "); 1163 } 1164} 1165 1166void Layer::dumpStats(String8& result) const { 1167 mFrameTracker.dump(result); 1168} 1169 1170void Layer::clearStats() { 1171 mFrameTracker.clear(); 1172} 1173 1174// --------------------------------------------------------------------------- 1175 1176Layer::LayerCleaner::LayerCleaner(const sp<SurfaceFlinger>& flinger, 1177 const sp<Layer>& layer) 1178 : mFlinger(flinger), mLayer(layer) { 1179} 1180 1181Layer::LayerCleaner::~LayerCleaner() { 1182 // destroy client resources 1183 mFlinger->onLayerDestroyed(mLayer); 1184} 1185 1186// --------------------------------------------------------------------------- 1187 1188 1189}; // namespace android 1190