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