Layer.cpp revision ca4d3602c07837d0b2ac6878685a8e327b5f30f0
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 { 661 if ((front.w != front.requested_w) || 662 (front.h != front.requested_h)) 663 { 664 // Here we pretend the transaction happened by updating the 665 // current and drawing states. Drawing state is only accessed 666 // in this thread, no need to have it locked 667 Layer::State& editDraw(mDrawingState); 668 editDraw.w = editDraw.requested_w; 669 editDraw.h = editDraw.requested_h; 670 671 // We also need to update the current state so that we don't 672 // end-up doing too much work during the next transaction. 673 // NOTE: We actually don't need hold the transaction lock here 674 // because State::w and State::h are only accessed from 675 // this thread 676 Layer::State& editTemp(currentState()); 677 editTemp.w = editDraw.w; 678 editTemp.h = editDraw.h; 679 680 // recompute visible region 681 recomputeVisibleRegions = true; 682 } 683 684 // we now have the correct size, unfreeze the screen 685 mFreezeLock.clear(); 686 } 687 688 // get the crop region 689 setBufferCrop( lcblk->getCrop(buf) ); 690 691 // get the transformation 692 setBufferTransform( lcblk->getTransform(buf) ); 693 694 } else { 695 // this should not happen unless we ran out of memory while 696 // allocating the buffer. we're hoping that things will get back 697 // to normal the next time the app tries to draw into this buffer. 698 // meanwhile, pretend the screen didn't update. 699 mPostedDirtyRegion.clear(); 700 } 701 702 if (lcblk->getQueuedCount()) { 703 // signal an event if we have more buffers waiting 704 mFlinger->signalEvent(); 705 } 706 707 /* a buffer was posted, so we need to call reloadTexture(), which 708 * will update our internal data structures (eg: EGLImageKHR or 709 * texture names). we need to do this even if mPostedDirtyRegion is 710 * empty -- it's orthogonal to the fact that a new buffer was posted, 711 * for instance, a degenerate case could be that the user did an empty 712 * update but repainted the buffer with appropriate content (after a 713 * resize for instance). 714 */ 715 reloadTexture( mPostedDirtyRegion ); 716} 717 718void Layer::unlockPageFlip( 719 const Transform& planeTransform, Region& outDirtyRegion) 720{ 721 Region dirtyRegion(mPostedDirtyRegion); 722 if (!dirtyRegion.isEmpty()) { 723 mPostedDirtyRegion.clear(); 724 // The dirty region is given in the layer's coordinate space 725 // transform the dirty region by the surface's transformation 726 // and the global transformation. 727 const Layer::State& s(drawingState()); 728 const Transform tr(planeTransform * s.transform); 729 dirtyRegion = tr.transform(dirtyRegion); 730 731 // At this point, the dirty region is in screen space. 732 // Make sure it's constrained by the visible region (which 733 // is in screen space as well). 734 dirtyRegion.andSelf(visibleRegionScreen); 735 outDirtyRegion.orSelf(dirtyRegion); 736 } 737 if (visibleRegionScreen.isEmpty()) { 738 // an invisible layer should not hold a freeze-lock 739 // (because it may never be updated and therefore never release it) 740 mFreezeLock.clear(); 741 } 742} 743 744void Layer::dump(String8& result, char* buffer, size_t SIZE) const 745{ 746 LayerBaseClient::dump(result, buffer, SIZE); 747 748 ClientRef::Access sharedClient(mUserClientRef); 749 SharedBufferServer* lcblk(sharedClient.get()); 750 uint32_t totalTime = 0; 751 if (lcblk) { 752 SharedBufferStack::Statistics stats = lcblk->getStats(); 753 totalTime= stats.totalTime; 754 result.append( lcblk->dump(" ") ); 755 } 756 757 sp<const GraphicBuffer> buf0(getBuffer(0)); 758 sp<const GraphicBuffer> buf1(getBuffer(1)); 759 uint32_t w0=0, h0=0, s0=0; 760 uint32_t w1=0, h1=0, s1=0; 761 if (buf0 != 0) { 762 w0 = buf0->getWidth(); 763 h0 = buf0->getHeight(); 764 s0 = buf0->getStride(); 765 } 766 if (buf1 != 0) { 767 w1 = buf1->getWidth(); 768 h1 = buf1->getHeight(); 769 s1 = buf1->getStride(); 770 } 771 snprintf(buffer, SIZE, 772 " " 773 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u]," 774 " freezeLock=%p, dq-q-time=%u us\n", 775 mFormat, w0, h0, s0, w1, h1, s1, 776 getFreezeLock().get(), totalTime); 777 778 result.append(buffer); 779} 780 781// --------------------------------------------------------------------------- 782 783Layer::ClientRef::ClientRef() 784 : mControlBlock(0), mToken(-1) { 785} 786 787Layer::ClientRef::~ClientRef() { 788} 789 790int32_t Layer::ClientRef::getToken() const { 791 Mutex::Autolock _l(mLock); 792 return mToken; 793} 794 795sp<UserClient> Layer::ClientRef::getClient() const { 796 Mutex::Autolock _l(mLock); 797 return mUserClient.promote(); 798} 799 800status_t Layer::ClientRef::setToken(const sp<UserClient>& uc, 801 const sp<SharedBufferServer>& sharedClient, int32_t token) { 802 Mutex::Autolock _l(mLock); 803 804 { // scope for strong mUserClient reference 805 sp<UserClient> userClient(mUserClient.promote()); 806 if (userClient != 0 && mControlBlock != 0) { 807 mControlBlock->setStatus(NO_INIT); 808 } 809 } 810 811 mUserClient = uc; 812 mToken = token; 813 mControlBlock = sharedClient; 814 return NO_ERROR; 815} 816 817sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const { 818 return mUserClient.promote(); 819} 820 821// this class gives us access to SharedBufferServer safely 822// it makes sure the UserClient (and its associated shared memory) 823// won't go away while we're accessing it. 824Layer::ClientRef::Access::Access(const ClientRef& ref) 825 : mControlBlock(0) 826{ 827 Mutex::Autolock _l(ref.mLock); 828 mUserClientStrongRef = ref.mUserClient.promote(); 829 if (mUserClientStrongRef != 0) 830 mControlBlock = ref.mControlBlock; 831} 832 833Layer::ClientRef::Access::~Access() 834{ 835} 836 837// --------------------------------------------------------------------------- 838 839Layer::BufferManager::BufferManager(TextureManager& tm) 840 : mNumBuffers(NUM_BUFFERS), mTextureManager(tm), 841 mActiveBufferIndex(-1), mFailover(false) 842{ 843} 844 845Layer::BufferManager::~BufferManager() 846{ 847} 848 849status_t Layer::BufferManager::resize(size_t size, 850 const sp<SurfaceFlinger>& flinger, EGLDisplay dpy) 851{ 852 Mutex::Autolock _l(mLock); 853 854 if (size < mNumBuffers) { 855 // If there is an active texture, move it into slot 0 if needed 856 if (mActiveBufferIndex > 0) { 857 BufferData activeBufferData = mBufferData[mActiveBufferIndex]; 858 mBufferData[mActiveBufferIndex] = mBufferData[0]; 859 mBufferData[0] = activeBufferData; 860 mActiveBufferIndex = 0; 861 } 862 863 // Free the buffers that are no longer needed. 864 for (size_t i = size; i < mNumBuffers; i++) { 865 mBufferData[i].buffer = 0; 866 867 // Create a message to destroy the textures on SurfaceFlinger's GL 868 // thread. 869 class MessageDestroyTexture : public MessageBase { 870 Image mTexture; 871 EGLDisplay mDpy; 872 public: 873 MessageDestroyTexture(const Image& texture, EGLDisplay dpy) 874 : mTexture(texture), mDpy(dpy) { } 875 virtual bool handler() { 876 status_t err = Layer::BufferManager::destroyTexture( 877 &mTexture, mDpy); 878 LOGE_IF(err<0, "error destroying texture: %d (%s)", 879 mTexture.name, strerror(-err)); 880 return true; // XXX: err == 0; ???? 881 } 882 }; 883 884 MessageDestroyTexture *msg = new MessageDestroyTexture( 885 mBufferData[i].texture, dpy); 886 887 // Don't allow this texture to be cleaned up by 888 // BufferManager::destroy. 889 mBufferData[i].texture.name = -1U; 890 mBufferData[i].texture.image = EGL_NO_IMAGE_KHR; 891 892 // Post the message to the SurfaceFlinger object. 893 flinger->postMessageAsync(msg); 894 } 895 } 896 897 mNumBuffers = size; 898 return NO_ERROR; 899} 900 901// only for debugging 902sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const { 903 return mBufferData[index].buffer; 904} 905 906status_t Layer::BufferManager::setActiveBufferIndex(size_t index) { 907 BufferData const * const buffers = mBufferData; 908 Mutex::Autolock _l(mLock); 909 mActiveBuffer = buffers[index].buffer; 910 mActiveBufferIndex = index; 911 return NO_ERROR; 912} 913 914size_t Layer::BufferManager::getActiveBufferIndex() const { 915 return mActiveBufferIndex; 916} 917 918Texture Layer::BufferManager::getActiveTexture() const { 919 Texture res; 920 if (mFailover || mActiveBufferIndex<0) { 921 res = mFailoverTexture; 922 } else { 923 static_cast<Image&>(res) = mBufferData[mActiveBufferIndex].texture; 924 } 925 return res; 926} 927 928sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const { 929 return mActiveBuffer; 930} 931 932bool Layer::BufferManager::hasActiveBuffer() const { 933 return mActiveBufferIndex >= 0; 934} 935 936sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index) 937{ 938 BufferData* const buffers = mBufferData; 939 sp<GraphicBuffer> buffer; 940 Mutex::Autolock _l(mLock); 941 buffer = buffers[index].buffer; 942 buffers[index].buffer = 0; 943 return buffer; 944} 945 946status_t Layer::BufferManager::attachBuffer(size_t index, 947 const sp<GraphicBuffer>& buffer) 948{ 949 BufferData* const buffers = mBufferData; 950 Mutex::Autolock _l(mLock); 951 buffers[index].buffer = buffer; 952 buffers[index].texture.dirty = true; 953 return NO_ERROR; 954} 955 956status_t Layer::BufferManager::destroy(EGLDisplay dpy) 957{ 958 BufferData* const buffers = mBufferData; 959 size_t num; 960 { // scope for the lock 961 Mutex::Autolock _l(mLock); 962 num = mNumBuffers; 963 for (size_t i=0 ; i<num ; i++) { 964 buffers[i].buffer = 0; 965 } 966 } 967 for (size_t i=0 ; i<num ; i++) { 968 destroyTexture(&buffers[i].texture, dpy); 969 } 970 destroyTexture(&mFailoverTexture, dpy); 971 return NO_ERROR; 972} 973 974status_t Layer::BufferManager::initEglImage(EGLDisplay dpy, 975 const sp<GraphicBuffer>& buffer) 976{ 977 status_t err = NO_INIT; 978 ssize_t index = mActiveBufferIndex; 979 if (index >= 0) { 980 if (!mFailover) { 981 { 982 // Without that lock, there is a chance of race condition 983 // where while composing a specific index, requestBuf 984 // with the same index can be executed and touch the same data 985 // that is being used in initEglImage. 986 // (e.g. dirty flag in texture) 987 Mutex::Autolock _l(mLock); 988 Image& texture(mBufferData[index].texture); 989 err = mTextureManager.initEglImage(&texture, dpy, buffer); 990 } 991 // if EGLImage fails, we switch to regular texture mode, and we 992 // free all resources associated with using EGLImages. 993 if (err == NO_ERROR) { 994 mFailover = false; 995 destroyTexture(&mFailoverTexture, dpy); 996 } else { 997 mFailover = true; 998 const size_t num = mNumBuffers; 999 for (size_t i=0 ; i<num ; i++) { 1000 destroyTexture(&mBufferData[i].texture, dpy); 1001 } 1002 } 1003 } else { 1004 // we failed once, don't try again 1005 err = BAD_VALUE; 1006 } 1007 } 1008 return err; 1009} 1010 1011status_t Layer::BufferManager::loadTexture( 1012 const Region& dirty, const GGLSurface& t) 1013{ 1014 return mTextureManager.loadTexture(&mFailoverTexture, dirty, t); 1015} 1016 1017status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy) 1018{ 1019 if (tex->name != -1U) { 1020 glDeleteTextures(1, &tex->name); 1021 tex->name = -1U; 1022 } 1023 if (tex->image != EGL_NO_IMAGE_KHR) { 1024 eglDestroyImageKHR(dpy, tex->image); 1025 tex->image = EGL_NO_IMAGE_KHR; 1026 } 1027 return NO_ERROR; 1028} 1029 1030// --------------------------------------------------------------------------- 1031 1032Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger, 1033 const sp<Layer>& owner) 1034 : Surface(flinger, owner->getIdentity(), owner) 1035{ 1036} 1037 1038Layer::SurfaceLayer::~SurfaceLayer() 1039{ 1040} 1041 1042sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, 1043 uint32_t w, uint32_t h, uint32_t format, uint32_t usage) 1044{ 1045 sp<GraphicBuffer> buffer; 1046 sp<Layer> owner(getOwner()); 1047 if (owner != 0) { 1048 /* 1049 * requestBuffer() cannot be called from the main thread 1050 * as it could cause a dead-lock, since it may have to wait 1051 * on conditions updated my the main thread. 1052 */ 1053 buffer = owner->requestBuffer(index, w, h, format, usage); 1054 } 1055 return buffer; 1056} 1057 1058status_t Layer::SurfaceLayer::setBufferCount(int bufferCount) 1059{ 1060 status_t err = DEAD_OBJECT; 1061 sp<Layer> owner(getOwner()); 1062 if (owner != 0) { 1063 /* 1064 * setBufferCount() cannot be called from the main thread 1065 * as it could cause a dead-lock, since it may have to wait 1066 * on conditions updated my the main thread. 1067 */ 1068 err = owner->setBufferCount(bufferCount); 1069 } 1070 return err; 1071} 1072 1073// --------------------------------------------------------------------------- 1074 1075 1076}; // namespace android 1077