Layer.cpp revision a1f47b90ab53af978be45b8bda16c5d084ae66e6
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#include <stdlib.h> 18#include <stdint.h> 19#include <sys/types.h> 20 21#include <cutils/properties.h> 22#include <cutils/native_handle.h> 23 24#include <utils/Errors.h> 25#include <utils/Log.h> 26#include <utils/StopWatch.h> 27 28#include <ui/GraphicBuffer.h> 29#include <ui/PixelFormat.h> 30 31#include <surfaceflinger/Surface.h> 32 33#include "clz.h" 34#include "GLExtensions.h" 35#include "Layer.h" 36#include "SurfaceFlinger.h" 37#include "DisplayHardware/DisplayHardware.h" 38#include "DisplayHardware/HWComposer.h" 39 40 41#define DEBUG_RESIZE 0 42 43 44namespace android { 45 46template <typename T> inline T min(T a, T b) { 47 return a<b ? a : b; 48} 49 50// --------------------------------------------------------------------------- 51 52Layer::Layer(SurfaceFlinger* flinger, 53 DisplayID display, const sp<Client>& client) 54 : LayerBaseClient(flinger, display, client), 55 mGLExtensions(GLExtensions::getInstance()), 56 mNeedsBlending(true), 57 mNeedsDithering(false), 58 mSecure(false), 59 mProtectedByApp(false), 60 mProtectedByDRM(false), 61 mTextureManager(), 62 mBufferManager(mTextureManager), 63 mWidth(0), mHeight(0), mNeedsScaling(false), mFixedSize(false) 64{ 65} 66 67Layer::~Layer() 68{ 69 // FIXME: must be called from the main UI thread 70 EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); 71 mBufferManager.destroy(dpy); 72 73 // we can use getUserClientUnsafe here because we know we're 74 // single-threaded at that point. 75 sp<UserClient> ourClient(mUserClientRef.getUserClientUnsafe()); 76 if (ourClient != 0) { 77 ourClient->detachLayer(this); 78 } 79} 80 81status_t Layer::setToken(const sp<UserClient>& userClient, 82 SharedClient* sharedClient, int32_t token) 83{ 84 sp<SharedBufferServer> lcblk = new SharedBufferServer( 85 sharedClient, token, mBufferManager.getDefaultBufferCount(), 86 getIdentity()); 87 88 89 sp<UserClient> ourClient(mUserClientRef.getClient()); 90 91 /* 92 * Here it is guaranteed that userClient != ourClient 93 * (see UserClient::getTokenForSurface()). 94 * 95 * We release the token used by this surface in ourClient below. 96 * This should be safe to do so now, since this layer won't be attached 97 * to this client, it should be okay to reuse that id. 98 * 99 * If this causes problems, an other solution would be to keep a list 100 * of all the {UserClient, token} ever used and release them when the 101 * Layer is destroyed. 102 * 103 */ 104 105 if (ourClient != 0) { 106 ourClient->detachLayer(this); 107 } 108 109 status_t err = mUserClientRef.setToken(userClient, lcblk, token); 110 LOGE_IF(err != NO_ERROR, 111 "ClientRef::setToken(%p, %p, %u) failed", 112 userClient.get(), lcblk.get(), token); 113 114 if (err == NO_ERROR) { 115 // we need to free the buffers associated with this surface 116 } 117 118 return err; 119} 120 121int32_t Layer::getToken() const 122{ 123 return mUserClientRef.getToken(); 124} 125 126sp<UserClient> Layer::getClient() const 127{ 128 return mUserClientRef.getClient(); 129} 130 131// called with SurfaceFlinger::mStateLock as soon as the layer is entered 132// in the purgatory list 133void Layer::onRemoved() 134{ 135 ClientRef::Access sharedClient(mUserClientRef); 136 SharedBufferServer* lcblk(sharedClient.get()); 137 if (lcblk) { 138 // wake up the condition 139 lcblk->setStatus(NO_INIT); 140 } 141} 142 143sp<LayerBaseClient::Surface> Layer::createSurface() const 144{ 145 sp<Surface> sur(new SurfaceLayer(mFlinger, const_cast<Layer *>(this))); 146 return sur; 147} 148 149status_t Layer::ditch() 150{ 151 // NOTE: Called from the main UI thread 152 153 // the layer is not on screen anymore. free as much resources as possible 154 mFreezeLock.clear(); 155 156 Mutex::Autolock _l(mLock); 157 mWidth = mHeight = 0; 158 return NO_ERROR; 159} 160 161status_t Layer::setBuffers( uint32_t w, uint32_t h, 162 PixelFormat format, uint32_t flags) 163{ 164 // this surfaces pixel format 165 PixelFormatInfo info; 166 status_t err = getPixelFormatInfo(format, &info); 167 if (err) return err; 168 169 // the display's pixel format 170 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 171 uint32_t const maxSurfaceDims = min( 172 hw.getMaxTextureSize(), hw.getMaxViewportDims()); 173 174 // never allow a surface larger than what our underlying GL implementation 175 // can handle. 176 if ((uint32_t(w)>maxSurfaceDims) || (uint32_t(h)>maxSurfaceDims)) { 177 return BAD_VALUE; 178 } 179 180 PixelFormatInfo displayInfo; 181 getPixelFormatInfo(hw.getFormat(), &displayInfo); 182 const uint32_t hwFlags = hw.getFlags(); 183 184 mFormat = format; 185 mWidth = w; 186 mHeight = h; 187 188 mReqFormat = format; 189 mReqWidth = w; 190 mReqHeight = h; 191 192 mSecure = (flags & ISurfaceComposer::eSecure) ? true : false; 193 mProtectedByApp = (flags & ISurfaceComposer::eProtectedByApp) ? true : false; 194 mProtectedByDRM = (flags & ISurfaceComposer::eProtectedByDRM) ? true : false; 195 mNeedsBlending = (info.h_alpha - info.l_alpha) > 0 && 196 (flags & ISurfaceComposer::eOpaque) == 0; 197 198 // we use the red index 199 int displayRedSize = displayInfo.getSize(PixelFormatInfo::INDEX_RED); 200 int layerRedsize = info.getSize(PixelFormatInfo::INDEX_RED); 201 mNeedsDithering = layerRedsize > displayRedSize; 202 203 return NO_ERROR; 204} 205 206void Layer::setGeometry(hwc_layer_t* hwcl) 207{ 208 hwcl->compositionType = HWC_FRAMEBUFFER; 209 hwcl->hints = 0; 210 hwcl->flags = 0; 211 hwcl->transform = 0; 212 hwcl->blending = HWC_BLENDING_NONE; 213 214 // we can't do alpha-fade with the hwc HAL 215 const State& s(drawingState()); 216 if (s.alpha < 0xFF) { 217 hwcl->flags = HWC_SKIP_LAYER; 218 return; 219 } 220 221 // we can only handle simple transformation 222 if (mOrientation & Transform::ROT_INVALID) { 223 hwcl->flags = HWC_SKIP_LAYER; 224 return; 225 } 226 227 Transform tr(Transform(mOrientation) * Transform(mBufferTransform)); 228 hwcl->transform = tr.getOrientation(); 229 230 if (needsBlending()) { 231 hwcl->blending = mPremultipliedAlpha ? 232 HWC_BLENDING_PREMULT : HWC_BLENDING_COVERAGE; 233 } 234 235 hwcl->displayFrame.left = mTransformedBounds.left; 236 hwcl->displayFrame.top = mTransformedBounds.top; 237 hwcl->displayFrame.right = mTransformedBounds.right; 238 hwcl->displayFrame.bottom = mTransformedBounds.bottom; 239 240 hwcl->visibleRegionScreen.rects = 241 reinterpret_cast<hwc_rect_t const *>( 242 visibleRegionScreen.getArray( 243 &hwcl->visibleRegionScreen.numRects)); 244} 245 246void Layer::setPerFrameData(hwc_layer_t* hwcl) { 247 sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer()); 248 if (buffer == NULL) { 249 // this can happen if the client never drew into this layer yet, 250 // or if we ran out of memory. In that case, don't let 251 // HWC handle it. 252 hwcl->flags |= HWC_SKIP_LAYER; 253 hwcl->handle = NULL; 254 return; 255 } 256 hwcl->handle = buffer->handle; 257 258 if (!mBufferCrop.isEmpty()) { 259 hwcl->sourceCrop.left = mBufferCrop.left; 260 hwcl->sourceCrop.top = mBufferCrop.top; 261 hwcl->sourceCrop.right = mBufferCrop.right; 262 hwcl->sourceCrop.bottom = mBufferCrop.bottom; 263 } else { 264 hwcl->sourceCrop.left = 0; 265 hwcl->sourceCrop.top = 0; 266 hwcl->sourceCrop.right = buffer->width; 267 hwcl->sourceCrop.bottom = buffer->height; 268 } 269} 270 271void Layer::reloadTexture(const Region& dirty) 272{ 273 sp<GraphicBuffer> buffer(mBufferManager.getActiveBuffer()); 274 if (buffer == NULL) { 275 // this situation can happen if we ran out of memory for instance. 276 // not much we can do. continue to use whatever texture was bound 277 // to this context. 278 return; 279 } 280 281 if (mGLExtensions.haveDirectTexture()) { 282 EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); 283 if (mBufferManager.initEglImage(dpy, buffer) != NO_ERROR) { 284 // not sure what we can do here... 285 goto slowpath; 286 } 287 } else { 288slowpath: 289 GGLSurface t; 290 if (buffer->usage & GRALLOC_USAGE_SW_READ_MASK) { 291 status_t res = buffer->lock(&t, GRALLOC_USAGE_SW_READ_OFTEN); 292 LOGE_IF(res, "error %d (%s) locking buffer %p", 293 res, strerror(res), buffer.get()); 294 if (res == NO_ERROR) { 295 mBufferManager.loadTexture(dirty, t); 296 buffer->unlock(); 297 } 298 } else { 299 // we can't do anything 300 } 301 } 302} 303 304void Layer::drawForSreenShot() const 305{ 306 const bool currentFiltering = mNeedsFiltering; 307 const_cast<Layer*>(this)->mNeedsFiltering = true; 308 LayerBase::drawForSreenShot(); 309 const_cast<Layer*>(this)->mNeedsFiltering = currentFiltering; 310} 311 312void Layer::onDraw(const Region& clip) const 313{ 314 Texture tex(mBufferManager.getActiveTexture()); 315 if (tex.name == -1LU) { 316 // the texture has not been created yet, this Layer has 317 // in fact never been drawn into. This happens frequently with 318 // SurfaceView because the WindowManager can't know when the client 319 // has drawn the first time. 320 321 // If there is nothing under us, we paint the screen in black, otherwise 322 // we just skip this update. 323 324 // figure out if there is something below us 325 Region under; 326 const SurfaceFlinger::LayerVector& drawingLayers(mFlinger->mDrawingState.layersSortedByZ); 327 const size_t count = drawingLayers.size(); 328 for (size_t i=0 ; i<count ; ++i) { 329 const sp<LayerBase>& layer(drawingLayers[i]); 330 if (layer.get() == static_cast<LayerBase const*>(this)) 331 break; 332 under.orSelf(layer->visibleRegionScreen); 333 } 334 // if not everything below us is covered, we plug the holes! 335 Region holes(clip.subtract(under)); 336 if (!holes.isEmpty()) { 337 clearWithOpenGL(holes, 0, 0, 0, 1); 338 } 339 return; 340 } 341 drawWithOpenGL(clip, tex); 342} 343 344bool Layer::needsFiltering() const 345{ 346 if (!(mFlags & DisplayHardware::SLOW_CONFIG)) { 347 // if our buffer is not the same size than ourselves, 348 // we need filtering. 349 Mutex::Autolock _l(mLock); 350 if (mNeedsScaling) 351 return true; 352 } 353 return LayerBase::needsFiltering(); 354} 355 356 357status_t Layer::setBufferCount(int bufferCount) 358{ 359 ClientRef::Access sharedClient(mUserClientRef); 360 SharedBufferServer* lcblk(sharedClient.get()); 361 if (!lcblk) { 362 // oops, the client is already gone 363 return DEAD_OBJECT; 364 } 365 366 // NOTE: lcblk->resize() is protected by an internal lock 367 status_t err = lcblk->resize(bufferCount); 368 if (err == NO_ERROR) { 369 EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); 370 mBufferManager.resize(bufferCount, mFlinger, dpy); 371 } 372 373 return err; 374} 375 376sp<GraphicBuffer> Layer::requestBuffer(int index, 377 uint32_t reqWidth, uint32_t reqHeight, uint32_t reqFormat, 378 uint32_t usage) 379{ 380 sp<GraphicBuffer> buffer; 381 382 if (int32_t(reqWidth | reqHeight | reqFormat) < 0) 383 return buffer; 384 385 if ((!reqWidth && reqHeight) || (reqWidth && !reqHeight)) 386 return buffer; 387 388 // this ensures our client doesn't go away while we're accessing 389 // the shared area. 390 ClientRef::Access sharedClient(mUserClientRef); 391 SharedBufferServer* lcblk(sharedClient.get()); 392 if (!lcblk) { 393 // oops, the client is already gone 394 return buffer; 395 } 396 397 /* 398 * This is called from the client's Surface::dequeue(). This can happen 399 * at any time, especially while we're in the middle of using the 400 * buffer 'index' as our front buffer. 401 */ 402 403 status_t err = NO_ERROR; 404 uint32_t w, h, f; 405 { // scope for the lock 406 Mutex::Autolock _l(mLock); 407 408 // zero means default 409 const bool fixedSize = reqWidth && reqHeight; 410 if (!reqFormat) reqFormat = mFormat; 411 if (!reqWidth) reqWidth = mWidth; 412 if (!reqHeight) reqHeight = mHeight; 413 414 w = reqWidth; 415 h = reqHeight; 416 f = reqFormat; 417 418 if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) || 419 (reqFormat != mReqFormat)) { 420 mReqWidth = reqWidth; 421 mReqHeight = reqHeight; 422 mReqFormat = reqFormat; 423 mFixedSize = fixedSize; 424 mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; 425 426 lcblk->reallocateAllExcept(index); 427 } 428 } 429 430 // here we have to reallocate a new buffer because the buffer could be 431 // used as the front buffer, or by a client in our process 432 // (eg: status bar), and we can't release the handle under its feet. 433 const uint32_t effectiveUsage = getEffectiveUsage(usage); 434 buffer = new GraphicBuffer(w, h, f, effectiveUsage); 435 err = buffer->initCheck(); 436 437 if (err || buffer->handle == 0) { 438 GraphicBuffer::dumpAllocationsToSystemLog(); 439 LOGE_IF(err || buffer->handle == 0, 440 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)", 441 this, index, w, h, strerror(-err)); 442 } else { 443 LOGD_IF(DEBUG_RESIZE, 444 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p", 445 this, index, w, h, buffer->handle); 446 } 447 448 if (err == NO_ERROR && buffer->handle != 0) { 449 Mutex::Autolock _l(mLock); 450 mBufferManager.attachBuffer(index, buffer); 451 } 452 return buffer; 453} 454 455uint32_t Layer::getEffectiveUsage(uint32_t usage) const 456{ 457 /* 458 * buffers used for software rendering, but h/w composition 459 * are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE 460 * 461 * buffers used for h/w rendering and h/w composition 462 * are allocated with HW_RENDER | HW_TEXTURE 463 * 464 * buffers used with h/w rendering and either NPOT or no egl_image_ext 465 * are allocated with SW_READ_RARELY | HW_RENDER 466 * 467 */ 468 469 if (mSecure) { 470 // secure buffer, don't store it into the GPU 471 usage = GraphicBuffer::USAGE_SW_READ_OFTEN | 472 GraphicBuffer::USAGE_SW_WRITE_OFTEN; 473 } else { 474 // it's allowed to modify the usage flags here, but generally 475 // the requested flags should be honored. 476 // request EGLImage for all buffers 477 usage |= GraphicBuffer::USAGE_HW_TEXTURE; 478 } 479 if (mProtectedByApp || mProtectedByDRM) { 480 // need a hardware-protected path to external video sink 481 usage |= GraphicBuffer::USAGE_PROTECTED; 482 } 483 return usage; 484} 485 486uint32_t Layer::doTransaction(uint32_t flags) 487{ 488 const Layer::State& front(drawingState()); 489 const Layer::State& temp(currentState()); 490 491 const bool sizeChanged = (front.requested_w != temp.requested_w) || 492 (front.requested_h != temp.requested_h); 493 494 if (sizeChanged) { 495 // the size changed, we need to ask our client to request a new buffer 496 LOGD_IF(DEBUG_RESIZE, 497 "resize (layer=%p), requested (%dx%d), drawing (%d,%d)", 498 this, 499 int(temp.requested_w), int(temp.requested_h), 500 int(front.requested_w), int(front.requested_h)); 501 502 if (!isFixedSize()) { 503 // we're being resized and there is a freeze display request, 504 // acquire a freeze lock, so that the screen stays put 505 // until we've redrawn at the new size; this is to avoid 506 // glitches upon orientation changes. 507 if (mFlinger->hasFreezeRequest()) { 508 // if the surface is hidden, don't try to acquire the 509 // freeze lock, since hidden surfaces may never redraw 510 if (!(front.flags & ISurfaceComposer::eLayerHidden)) { 511 mFreezeLock = mFlinger->getFreezeLock(); 512 } 513 } 514 515 // this will make sure LayerBase::doTransaction doesn't update 516 // the drawing state's size 517 Layer::State& editDraw(mDrawingState); 518 editDraw.requested_w = temp.requested_w; 519 editDraw.requested_h = temp.requested_h; 520 521 // record the new size, form this point on, when the client request 522 // a buffer, it'll get the new size. 523 setBufferSize(temp.requested_w, temp.requested_h); 524 525 ClientRef::Access sharedClient(mUserClientRef); 526 SharedBufferServer* lcblk(sharedClient.get()); 527 if (lcblk) { 528 // all buffers need reallocation 529 lcblk->reallocateAll(); 530 } 531 } else { 532 // record the new size 533 setBufferSize(temp.requested_w, temp.requested_h); 534 } 535 } 536 537 if (temp.sequence != front.sequence) { 538 if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) { 539 // this surface is now hidden, so it shouldn't hold a freeze lock 540 // (it may never redraw, which is fine if it is hidden) 541 mFreezeLock.clear(); 542 } 543 } 544 545 return LayerBase::doTransaction(flags); 546} 547 548void Layer::setBufferSize(uint32_t w, uint32_t h) { 549 Mutex::Autolock _l(mLock); 550 mWidth = w; 551 mHeight = h; 552 mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; 553} 554 555bool Layer::isFixedSize() const { 556 Mutex::Autolock _l(mLock); 557 return mFixedSize; 558} 559 560// ---------------------------------------------------------------------------- 561// pageflip handling... 562// ---------------------------------------------------------------------------- 563 564void Layer::lockPageFlip(bool& recomputeVisibleRegions) 565{ 566 ClientRef::Access sharedClient(mUserClientRef); 567 SharedBufferServer* lcblk(sharedClient.get()); 568 if (!lcblk) { 569 // client died 570 recomputeVisibleRegions = true; 571 return; 572 } 573 574 ssize_t buf = lcblk->retireAndLock(); 575 if (buf == NOT_ENOUGH_DATA) { 576 // NOTE: This is not an error, it simply means there is nothing to 577 // retire. The buffer is locked because we will use it 578 // for composition later in the loop 579 return; 580 } 581 582 if (buf < NO_ERROR) { 583 LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); 584 mPostedDirtyRegion.clear(); 585 return; 586 } 587 588 // we retired a buffer, which becomes the new front buffer 589 590 const bool noActiveBuffer = !mBufferManager.hasActiveBuffer(); 591 if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) { 592 LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); 593 mPostedDirtyRegion.clear(); 594 return; 595 } 596 597 if (noActiveBuffer) { 598 // we didn't have an active buffer, we need to recompute 599 // our visible region 600 recomputeVisibleRegions = true; 601 } 602 603 sp<GraphicBuffer> newFrontBuffer(getBuffer(buf)); 604 if (newFrontBuffer != NULL) { 605 // get the dirty region 606 // compute the posted region 607 const Region dirty(lcblk->getDirtyRegion(buf)); 608 mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() ); 609 610 // update the layer size and release freeze-lock 611 const Layer::State& front(drawingState()); 612 if (newFrontBuffer->getWidth() == front.requested_w && 613 newFrontBuffer->getHeight() == front.requested_h) 614 { 615 if ((front.w != front.requested_w) || 616 (front.h != front.requested_h)) 617 { 618 // Here we pretend the transaction happened by updating the 619 // current and drawing states. Drawing state is only accessed 620 // in this thread, no need to have it locked 621 Layer::State& editDraw(mDrawingState); 622 editDraw.w = editDraw.requested_w; 623 editDraw.h = editDraw.requested_h; 624 625 // We also need to update the current state so that we don't 626 // end-up doing too much work during the next transaction. 627 // NOTE: We actually don't need hold the transaction lock here 628 // because State::w and State::h are only accessed from 629 // this thread 630 Layer::State& editTemp(currentState()); 631 editTemp.w = editDraw.w; 632 editTemp.h = editDraw.h; 633 634 // recompute visible region 635 recomputeVisibleRegions = true; 636 } 637 638 // we now have the correct size, unfreeze the screen 639 mFreezeLock.clear(); 640 } 641 642 // get the crop region 643 setBufferCrop( lcblk->getCrop(buf) ); 644 645 // get the transformation 646 setBufferTransform( lcblk->getTransform(buf) ); 647 648 } else { 649 // this should not happen unless we ran out of memory while 650 // allocating the buffer. we're hoping that things will get back 651 // to normal the next time the app tries to draw into this buffer. 652 // meanwhile, pretend the screen didn't update. 653 mPostedDirtyRegion.clear(); 654 } 655 656 if (lcblk->getQueuedCount()) { 657 // signal an event if we have more buffers waiting 658 mFlinger->signalEvent(); 659 } 660 661 /* a buffer was posted, so we need to call reloadTexture(), which 662 * will update our internal data structures (eg: EGLImageKHR or 663 * texture names). we need to do this even if mPostedDirtyRegion is 664 * empty -- it's orthogonal to the fact that a new buffer was posted, 665 * for instance, a degenerate case could be that the user did an empty 666 * update but repainted the buffer with appropriate content (after a 667 * resize for instance). 668 */ 669 reloadTexture( mPostedDirtyRegion ); 670} 671 672void Layer::unlockPageFlip( 673 const Transform& planeTransform, Region& outDirtyRegion) 674{ 675 Region dirtyRegion(mPostedDirtyRegion); 676 if (!dirtyRegion.isEmpty()) { 677 mPostedDirtyRegion.clear(); 678 // The dirty region is given in the layer's coordinate space 679 // transform the dirty region by the surface's transformation 680 // and the global transformation. 681 const Layer::State& s(drawingState()); 682 const Transform tr(planeTransform * s.transform); 683 dirtyRegion = tr.transform(dirtyRegion); 684 685 // At this point, the dirty region is in screen space. 686 // Make sure it's constrained by the visible region (which 687 // is in screen space as well). 688 dirtyRegion.andSelf(visibleRegionScreen); 689 outDirtyRegion.orSelf(dirtyRegion); 690 } 691 if (visibleRegionScreen.isEmpty()) { 692 // an invisible layer should not hold a freeze-lock 693 // (because it may never be updated and therefore never release it) 694 mFreezeLock.clear(); 695 } 696} 697 698void Layer::dump(String8& result, char* buffer, size_t SIZE) const 699{ 700 LayerBaseClient::dump(result, buffer, SIZE); 701 702 ClientRef::Access sharedClient(mUserClientRef); 703 SharedBufferServer* lcblk(sharedClient.get()); 704 uint32_t totalTime = 0; 705 if (lcblk) { 706 SharedBufferStack::Statistics stats = lcblk->getStats(); 707 totalTime= stats.totalTime; 708 result.append( lcblk->dump(" ") ); 709 } 710 711 sp<const GraphicBuffer> buf0(getBuffer(0)); 712 sp<const GraphicBuffer> buf1(getBuffer(1)); 713 uint32_t w0=0, h0=0, s0=0; 714 uint32_t w1=0, h1=0, s1=0; 715 if (buf0 != 0) { 716 w0 = buf0->getWidth(); 717 h0 = buf0->getHeight(); 718 s0 = buf0->getStride(); 719 } 720 if (buf1 != 0) { 721 w1 = buf1->getWidth(); 722 h1 = buf1->getHeight(); 723 s1 = buf1->getStride(); 724 } 725 snprintf(buffer, SIZE, 726 " " 727 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u]," 728 " freezeLock=%p, dq-q-time=%u us\n", 729 mFormat, w0, h0, s0, w1, h1, s1, 730 getFreezeLock().get(), totalTime); 731 732 result.append(buffer); 733} 734 735// --------------------------------------------------------------------------- 736 737Layer::ClientRef::ClientRef() 738 : mControlBlock(0), mToken(-1) { 739} 740 741Layer::ClientRef::~ClientRef() { 742} 743 744int32_t Layer::ClientRef::getToken() const { 745 Mutex::Autolock _l(mLock); 746 return mToken; 747} 748 749sp<UserClient> Layer::ClientRef::getClient() const { 750 Mutex::Autolock _l(mLock); 751 return mUserClient.promote(); 752} 753 754status_t Layer::ClientRef::setToken(const sp<UserClient>& uc, 755 const sp<SharedBufferServer>& sharedClient, int32_t token) { 756 Mutex::Autolock _l(mLock); 757 758 { // scope for strong mUserClient reference 759 sp<UserClient> userClient(mUserClient.promote()); 760 if (mUserClient != 0 && mControlBlock != 0) { 761 mControlBlock->setStatus(NO_INIT); 762 } 763 } 764 765 mUserClient = uc; 766 mToken = token; 767 mControlBlock = sharedClient; 768 return NO_ERROR; 769} 770 771sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const { 772 return mUserClient.promote(); 773} 774 775// this class gives us access to SharedBufferServer safely 776// it makes sure the UserClient (and its associated shared memory) 777// won't go away while we're accessing it. 778Layer::ClientRef::Access::Access(const ClientRef& ref) 779 : mControlBlock(0) 780{ 781 Mutex::Autolock _l(ref.mLock); 782 mUserClientStrongRef = ref.mUserClient.promote(); 783 if (mUserClientStrongRef != 0) 784 mControlBlock = ref.mControlBlock; 785} 786 787Layer::ClientRef::Access::~Access() 788{ 789} 790 791// --------------------------------------------------------------------------- 792 793Layer::BufferManager::BufferManager(TextureManager& tm) 794 : mNumBuffers(NUM_BUFFERS), mTextureManager(tm), 795 mActiveBufferIndex(-1), mFailover(false) 796{ 797} 798 799Layer::BufferManager::~BufferManager() 800{ 801} 802 803status_t Layer::BufferManager::resize(size_t size, 804 const sp<SurfaceFlinger>& flinger, EGLDisplay dpy) 805{ 806 Mutex::Autolock _l(mLock); 807 808 if (size < mNumBuffers) { 809 // Move the active texture into slot 0 810 BufferData activeBufferData = mBufferData[mActiveBufferIndex]; 811 mBufferData[mActiveBufferIndex] = mBufferData[0]; 812 mBufferData[0] = activeBufferData; 813 mActiveBufferIndex = 0; 814 815 // Free the buffers that are no longer needed. 816 for (size_t i = size; i < mNumBuffers; i++) { 817 mBufferData[i].buffer = 0; 818 819 // Create a message to destroy the textures on SurfaceFlinger's GL 820 // thread. 821 class MessageDestroyTexture : public MessageBase { 822 Image mTexture; 823 EGLDisplay mDpy; 824 public: 825 MessageDestroyTexture(const Image& texture, EGLDisplay dpy) 826 : mTexture(texture), mDpy(dpy) { } 827 virtual bool handler() { 828 status_t err = Layer::BufferManager::destroyTexture( 829 &mTexture, mDpy); 830 LOGE_IF(err<0, "error destroying texture: %d (%s)", 831 mTexture.name, strerror(-err)); 832 return true; // XXX: err == 0; ???? 833 } 834 }; 835 836 MessageDestroyTexture *msg = new MessageDestroyTexture( 837 mBufferData[i].texture, dpy); 838 839 // Don't allow this texture to be cleaned up by 840 // BufferManager::destroy. 841 mBufferData[i].texture.name = -1U; 842 mBufferData[i].texture.image = EGL_NO_IMAGE_KHR; 843 844 // Post the message to the SurfaceFlinger object. 845 flinger->postMessageAsync(msg); 846 } 847 } 848 849 mNumBuffers = size; 850 return NO_ERROR; 851} 852 853// only for debugging 854sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const { 855 return mBufferData[index].buffer; 856} 857 858status_t Layer::BufferManager::setActiveBufferIndex(size_t index) { 859 BufferData const * const buffers = mBufferData; 860 Mutex::Autolock _l(mLock); 861 mActiveBuffer = buffers[index].buffer; 862 mActiveBufferIndex = index; 863 return NO_ERROR; 864} 865 866size_t Layer::BufferManager::getActiveBufferIndex() const { 867 return mActiveBufferIndex; 868} 869 870Texture Layer::BufferManager::getActiveTexture() const { 871 Texture res; 872 if (mFailover || mActiveBufferIndex<0) { 873 res = mFailoverTexture; 874 } else { 875 static_cast<Image&>(res) = mBufferData[mActiveBufferIndex].texture; 876 } 877 return res; 878} 879 880sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const { 881 return mActiveBuffer; 882} 883 884bool Layer::BufferManager::hasActiveBuffer() const { 885 return mActiveBufferIndex >= 0; 886} 887 888sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index) 889{ 890 BufferData* const buffers = mBufferData; 891 sp<GraphicBuffer> buffer; 892 Mutex::Autolock _l(mLock); 893 buffer = buffers[index].buffer; 894 buffers[index].buffer = 0; 895 return buffer; 896} 897 898status_t Layer::BufferManager::attachBuffer(size_t index, 899 const sp<GraphicBuffer>& buffer) 900{ 901 BufferData* const buffers = mBufferData; 902 Mutex::Autolock _l(mLock); 903 buffers[index].buffer = buffer; 904 buffers[index].texture.dirty = true; 905 return NO_ERROR; 906} 907 908status_t Layer::BufferManager::destroy(EGLDisplay dpy) 909{ 910 BufferData* const buffers = mBufferData; 911 size_t num; 912 { // scope for the lock 913 Mutex::Autolock _l(mLock); 914 num = mNumBuffers; 915 for (size_t i=0 ; i<num ; i++) { 916 buffers[i].buffer = 0; 917 } 918 } 919 for (size_t i=0 ; i<num ; i++) { 920 destroyTexture(&buffers[i].texture, dpy); 921 } 922 destroyTexture(&mFailoverTexture, dpy); 923 return NO_ERROR; 924} 925 926status_t Layer::BufferManager::initEglImage(EGLDisplay dpy, 927 const sp<GraphicBuffer>& buffer) 928{ 929 status_t err = NO_INIT; 930 ssize_t index = mActiveBufferIndex; 931 if (index >= 0) { 932 if (!mFailover) { 933 Image& texture(mBufferData[index].texture); 934 err = mTextureManager.initEglImage(&texture, dpy, buffer); 935 // if EGLImage fails, we switch to regular texture mode, and we 936 // free all resources associated with using EGLImages. 937 if (err == NO_ERROR) { 938 mFailover = false; 939 destroyTexture(&mFailoverTexture, dpy); 940 } else { 941 mFailover = true; 942 const size_t num = mNumBuffers; 943 for (size_t i=0 ; i<num ; i++) { 944 destroyTexture(&mBufferData[i].texture, dpy); 945 } 946 } 947 } else { 948 // we failed once, don't try again 949 err = BAD_VALUE; 950 } 951 } 952 return err; 953} 954 955status_t Layer::BufferManager::loadTexture( 956 const Region& dirty, const GGLSurface& t) 957{ 958 return mTextureManager.loadTexture(&mFailoverTexture, dirty, t); 959} 960 961status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy) 962{ 963 if (tex->name != -1U) { 964 glDeleteTextures(1, &tex->name); 965 tex->name = -1U; 966 } 967 if (tex->image != EGL_NO_IMAGE_KHR) { 968 eglDestroyImageKHR(dpy, tex->image); 969 tex->image = EGL_NO_IMAGE_KHR; 970 } 971 return NO_ERROR; 972} 973 974// --------------------------------------------------------------------------- 975 976Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger, 977 const sp<Layer>& owner) 978 : Surface(flinger, owner->getIdentity(), owner) 979{ 980} 981 982Layer::SurfaceLayer::~SurfaceLayer() 983{ 984} 985 986sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, 987 uint32_t w, uint32_t h, uint32_t format, uint32_t usage) 988{ 989 sp<GraphicBuffer> buffer; 990 sp<Layer> owner(getOwner()); 991 if (owner != 0) { 992 /* 993 * requestBuffer() cannot be called from the main thread 994 * as it could cause a dead-lock, since it may have to wait 995 * on conditions updated my the main thread. 996 */ 997 buffer = owner->requestBuffer(index, w, h, format, usage); 998 } 999 return buffer; 1000} 1001 1002status_t Layer::SurfaceLayer::setBufferCount(int bufferCount) 1003{ 1004 status_t err = DEAD_OBJECT; 1005 sp<Layer> owner(getOwner()); 1006 if (owner != 0) { 1007 /* 1008 * setBufferCount() cannot be called from the main thread 1009 * as it could cause a dead-lock, since it may have to wait 1010 * on conditions updated my the main thread. 1011 */ 1012 err = owner->setBufferCount(bufferCount); 1013 } 1014 return err; 1015} 1016 1017// --------------------------------------------------------------------------- 1018 1019 1020}; // namespace android 1021