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