Layer.cpp revision ac45e6bff1b41acd35c981291b37b23f8e083cee
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 347// As documented in libhardware header, formats in the range 348// 0x100 - 0x1FF are specific to the HAL implementation, and 349// are known to have no alpha channel 350// TODO: move definition for device-specific range into 351// hardware.h, instead of using hard-coded values here. 352#define HARDWARE_IS_DEVICE_FORMAT(f) ((f) >= 0x100 && (f) <= 0x1FF) 353 354bool Layer::needsBlending(const sp<GraphicBuffer>& buffer) const 355{ 356 // If buffers where set with eOpaque flag, all buffers are known to 357 // be opaque without having to check their actual format 358 if (mNeedsBlending && buffer != NULL) { 359 PixelFormat format = buffer->getPixelFormat(); 360 361 if (HARDWARE_IS_DEVICE_FORMAT(format)) { 362 return false; 363 } 364 365 PixelFormatInfo info; 366 status_t err = getPixelFormatInfo(format, &info); 367 if (!err && info.h_alpha <= info.l_alpha) { 368 return false; 369 } 370 } 371 372 // Return opacity as determined from flags and format options 373 // passed to setBuffers() 374 return mNeedsBlending; 375} 376 377bool Layer::needsBlending() const 378{ 379 if (mBufferManager.hasActiveBuffer()) { 380 return needsBlending(mBufferManager.getActiveBuffer()); 381 } 382 383 return mNeedsBlending; 384} 385 386bool Layer::needsFiltering() const 387{ 388 if (!(mFlags & DisplayHardware::SLOW_CONFIG)) { 389 // if our buffer is not the same size than ourselves, 390 // we need filtering. 391 Mutex::Autolock _l(mLock); 392 if (mNeedsScaling) 393 return true; 394 } 395 return LayerBase::needsFiltering(); 396} 397 398 399status_t Layer::setBufferCount(int bufferCount) 400{ 401 ClientRef::Access sharedClient(mUserClientRef); 402 SharedBufferServer* lcblk(sharedClient.get()); 403 if (!lcblk) { 404 // oops, the client is already gone 405 return DEAD_OBJECT; 406 } 407 408 // NOTE: lcblk->resize() is protected by an internal lock 409 status_t err = lcblk->resize(bufferCount); 410 if (err == NO_ERROR) { 411 EGLDisplay dpy(mFlinger->graphicPlane(0).getEGLDisplay()); 412 mBufferManager.resize(bufferCount, mFlinger, dpy); 413 } 414 415 return err; 416} 417 418sp<GraphicBuffer> Layer::requestBuffer(int index, 419 uint32_t reqWidth, uint32_t reqHeight, uint32_t reqFormat, 420 uint32_t usage) 421{ 422 sp<GraphicBuffer> buffer; 423 424 if (int32_t(reqWidth | reqHeight | reqFormat) < 0) 425 return buffer; 426 427 if ((!reqWidth && reqHeight) || (reqWidth && !reqHeight)) 428 return buffer; 429 430 // this ensures our client doesn't go away while we're accessing 431 // the shared area. 432 ClientRef::Access sharedClient(mUserClientRef); 433 SharedBufferServer* lcblk(sharedClient.get()); 434 if (!lcblk) { 435 // oops, the client is already gone 436 return buffer; 437 } 438 439 /* 440 * This is called from the client's Surface::dequeue(). This can happen 441 * at any time, especially while we're in the middle of using the 442 * buffer 'index' as our front buffer. 443 */ 444 445 status_t err = NO_ERROR; 446 uint32_t w, h, f; 447 { // scope for the lock 448 Mutex::Autolock _l(mLock); 449 450 // zero means default 451 const bool fixedSize = reqWidth && reqHeight; 452 if (!reqFormat) reqFormat = mFormat; 453 if (!reqWidth) reqWidth = mWidth; 454 if (!reqHeight) reqHeight = mHeight; 455 456 w = reqWidth; 457 h = reqHeight; 458 f = reqFormat; 459 460 if ((reqWidth != mReqWidth) || (reqHeight != mReqHeight) || 461 (reqFormat != mReqFormat)) { 462 mReqWidth = reqWidth; 463 mReqHeight = reqHeight; 464 mReqFormat = reqFormat; 465 mFixedSize = fixedSize; 466 mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; 467 468 lcblk->reallocateAllExcept(index); 469 } 470 } 471 472 // here we have to reallocate a new buffer because the buffer could be 473 // used as the front buffer, or by a client in our process 474 // (eg: status bar), and we can't release the handle under its feet. 475 const uint32_t effectiveUsage = getEffectiveUsage(usage); 476 buffer = new GraphicBuffer(w, h, f, effectiveUsage); 477 err = buffer->initCheck(); 478 479 if (err || buffer->handle == 0) { 480 GraphicBuffer::dumpAllocationsToSystemLog(); 481 LOGE_IF(err || buffer->handle == 0, 482 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d failed (%s)", 483 this, index, w, h, strerror(-err)); 484 } else { 485 LOGD_IF(DEBUG_RESIZE, 486 "Layer::requestBuffer(this=%p), index=%d, w=%d, h=%d, handle=%p", 487 this, index, w, h, buffer->handle); 488 } 489 490 if (err == NO_ERROR && buffer->handle != 0) { 491 Mutex::Autolock _l(mLock); 492 mBufferManager.attachBuffer(index, buffer); 493 } 494 return buffer; 495} 496 497uint32_t Layer::getEffectiveUsage(uint32_t usage) const 498{ 499 /* 500 * buffers used for software rendering, but h/w composition 501 * are allocated with SW_READ_OFTEN | SW_WRITE_OFTEN | HW_TEXTURE 502 * 503 * buffers used for h/w rendering and h/w composition 504 * are allocated with HW_RENDER | HW_TEXTURE 505 * 506 * buffers used with h/w rendering and either NPOT or no egl_image_ext 507 * are allocated with SW_READ_RARELY | HW_RENDER 508 * 509 */ 510 511 if (mSecure) { 512 // secure buffer, don't store it into the GPU 513 usage = GraphicBuffer::USAGE_SW_READ_OFTEN | 514 GraphicBuffer::USAGE_SW_WRITE_OFTEN; 515 } else { 516 // it's allowed to modify the usage flags here, but generally 517 // the requested flags should be honored. 518 // request EGLImage for all buffers 519 usage |= GraphicBuffer::USAGE_HW_TEXTURE; 520 } 521 if (mProtectedByApp || mProtectedByDRM) { 522 // need a hardware-protected path to external video sink 523 usage |= GraphicBuffer::USAGE_PROTECTED; 524 } 525 return usage; 526} 527 528uint32_t Layer::doTransaction(uint32_t flags) 529{ 530 const Layer::State& front(drawingState()); 531 const Layer::State& temp(currentState()); 532 533 const bool sizeChanged = (front.requested_w != temp.requested_w) || 534 (front.requested_h != temp.requested_h); 535 536 if (sizeChanged) { 537 // the size changed, we need to ask our client to request a new buffer 538 LOGD_IF(DEBUG_RESIZE, 539 "resize (layer=%p), requested (%dx%d), drawing (%d,%d)", 540 this, 541 int(temp.requested_w), int(temp.requested_h), 542 int(front.requested_w), int(front.requested_h)); 543 544 if (!isFixedSize()) { 545 // we're being resized and there is a freeze display request, 546 // acquire a freeze lock, so that the screen stays put 547 // until we've redrawn at the new size; this is to avoid 548 // glitches upon orientation changes. 549 if (mFlinger->hasFreezeRequest()) { 550 // if the surface is hidden, don't try to acquire the 551 // freeze lock, since hidden surfaces may never redraw 552 if (!(front.flags & ISurfaceComposer::eLayerHidden)) { 553 mFreezeLock = mFlinger->getFreezeLock(); 554 } 555 } 556 557 // this will make sure LayerBase::doTransaction doesn't update 558 // the drawing state's size 559 Layer::State& editDraw(mDrawingState); 560 editDraw.requested_w = temp.requested_w; 561 editDraw.requested_h = temp.requested_h; 562 563 // record the new size, form this point on, when the client request 564 // a buffer, it'll get the new size. 565 setBufferSize(temp.requested_w, temp.requested_h); 566 567 ClientRef::Access sharedClient(mUserClientRef); 568 SharedBufferServer* lcblk(sharedClient.get()); 569 if (lcblk) { 570 // all buffers need reallocation 571 lcblk->reallocateAll(); 572 } 573 } else { 574 // record the new size 575 setBufferSize(temp.requested_w, temp.requested_h); 576 } 577 } 578 579 if (temp.sequence != front.sequence) { 580 if (temp.flags & ISurfaceComposer::eLayerHidden || temp.alpha == 0) { 581 // this surface is now hidden, so it shouldn't hold a freeze lock 582 // (it may never redraw, which is fine if it is hidden) 583 mFreezeLock.clear(); 584 } 585 } 586 587 return LayerBase::doTransaction(flags); 588} 589 590void Layer::setBufferSize(uint32_t w, uint32_t h) { 591 Mutex::Autolock _l(mLock); 592 mWidth = w; 593 mHeight = h; 594 mNeedsScaling = mWidth != mReqWidth || mHeight != mReqHeight; 595} 596 597bool Layer::isFixedSize() const { 598 Mutex::Autolock _l(mLock); 599 return mFixedSize; 600} 601 602// ---------------------------------------------------------------------------- 603// pageflip handling... 604// ---------------------------------------------------------------------------- 605 606void Layer::lockPageFlip(bool& recomputeVisibleRegions) 607{ 608 ClientRef::Access sharedClient(mUserClientRef); 609 SharedBufferServer* lcblk(sharedClient.get()); 610 if (!lcblk) { 611 // client died 612 recomputeVisibleRegions = true; 613 return; 614 } 615 616 ssize_t buf = lcblk->retireAndLock(); 617 if (buf == NOT_ENOUGH_DATA) { 618 // NOTE: This is not an error, it simply means there is nothing to 619 // retire. The buffer is locked because we will use it 620 // for composition later in the loop 621 return; 622 } 623 624 if (buf < NO_ERROR) { 625 LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); 626 mPostedDirtyRegion.clear(); 627 return; 628 } 629 630 // we retired a buffer, which becomes the new front buffer 631 632 const bool noActiveBuffer = !mBufferManager.hasActiveBuffer(); 633 const bool activeBlending = 634 noActiveBuffer ? true : needsBlending(mBufferManager.getActiveBuffer()); 635 636 if (mBufferManager.setActiveBufferIndex(buf) < NO_ERROR) { 637 LOGE("retireAndLock() buffer index (%d) out of range", int(buf)); 638 mPostedDirtyRegion.clear(); 639 return; 640 } 641 642 if (noActiveBuffer) { 643 // we didn't have an active buffer, we need to recompute 644 // our visible region 645 recomputeVisibleRegions = true; 646 } 647 648 sp<GraphicBuffer> newFrontBuffer(getBuffer(buf)); 649 if (newFrontBuffer != NULL) { 650 if (!noActiveBuffer && activeBlending != needsBlending(newFrontBuffer)) { 651 // new buffer has different opacity than previous active buffer, need 652 // to recompute visible regions accordingly 653 recomputeVisibleRegions = true; 654 } 655 656 // get the dirty region 657 // compute the posted region 658 const Region dirty(lcblk->getDirtyRegion(buf)); 659 mPostedDirtyRegion = dirty.intersect( newFrontBuffer->getBounds() ); 660 661 // update the layer size and release freeze-lock 662 const Layer::State& front(drawingState()); 663 if (newFrontBuffer->getWidth() == front.requested_w && 664 newFrontBuffer->getHeight() == front.requested_h) 665 { 666 if ((front.w != front.requested_w) || 667 (front.h != front.requested_h)) 668 { 669 // Here we pretend the transaction happened by updating the 670 // current and drawing states. Drawing state is only accessed 671 // in this thread, no need to have it locked 672 Layer::State& editDraw(mDrawingState); 673 editDraw.w = editDraw.requested_w; 674 editDraw.h = editDraw.requested_h; 675 676 // We also need to update the current state so that we don't 677 // end-up doing too much work during the next transaction. 678 // NOTE: We actually don't need hold the transaction lock here 679 // because State::w and State::h are only accessed from 680 // this thread 681 Layer::State& editTemp(currentState()); 682 editTemp.w = editDraw.w; 683 editTemp.h = editDraw.h; 684 685 // recompute visible region 686 recomputeVisibleRegions = true; 687 } 688 689 // we now have the correct size, unfreeze the screen 690 mFreezeLock.clear(); 691 } 692 693 // get the crop region 694 setBufferCrop( lcblk->getCrop(buf) ); 695 696 // get the transformation 697 setBufferTransform( lcblk->getTransform(buf) ); 698 699 } else { 700 // this should not happen unless we ran out of memory while 701 // allocating the buffer. we're hoping that things will get back 702 // to normal the next time the app tries to draw into this buffer. 703 // meanwhile, pretend the screen didn't update. 704 mPostedDirtyRegion.clear(); 705 } 706 707 if (lcblk->getQueuedCount()) { 708 // signal an event if we have more buffers waiting 709 mFlinger->signalEvent(); 710 } 711 712 /* a buffer was posted, so we need to call reloadTexture(), which 713 * will update our internal data structures (eg: EGLImageKHR or 714 * texture names). we need to do this even if mPostedDirtyRegion is 715 * empty -- it's orthogonal to the fact that a new buffer was posted, 716 * for instance, a degenerate case could be that the user did an empty 717 * update but repainted the buffer with appropriate content (after a 718 * resize for instance). 719 */ 720 reloadTexture( mPostedDirtyRegion ); 721} 722 723void Layer::unlockPageFlip( 724 const Transform& planeTransform, Region& outDirtyRegion) 725{ 726 Region dirtyRegion(mPostedDirtyRegion); 727 if (!dirtyRegion.isEmpty()) { 728 mPostedDirtyRegion.clear(); 729 // The dirty region is given in the layer's coordinate space 730 // transform the dirty region by the surface's transformation 731 // and the global transformation. 732 const Layer::State& s(drawingState()); 733 const Transform tr(planeTransform * s.transform); 734 dirtyRegion = tr.transform(dirtyRegion); 735 736 // At this point, the dirty region is in screen space. 737 // Make sure it's constrained by the visible region (which 738 // is in screen space as well). 739 dirtyRegion.andSelf(visibleRegionScreen); 740 outDirtyRegion.orSelf(dirtyRegion); 741 } 742 if (visibleRegionScreen.isEmpty()) { 743 // an invisible layer should not hold a freeze-lock 744 // (because it may never be updated and therefore never release it) 745 mFreezeLock.clear(); 746 } 747} 748 749void Layer::dump(String8& result, char* buffer, size_t SIZE) const 750{ 751 LayerBaseClient::dump(result, buffer, SIZE); 752 753 ClientRef::Access sharedClient(mUserClientRef); 754 SharedBufferServer* lcblk(sharedClient.get()); 755 uint32_t totalTime = 0; 756 if (lcblk) { 757 SharedBufferStack::Statistics stats = lcblk->getStats(); 758 totalTime= stats.totalTime; 759 result.append( lcblk->dump(" ") ); 760 } 761 762 sp<const GraphicBuffer> buf0(getBuffer(0)); 763 sp<const GraphicBuffer> buf1(getBuffer(1)); 764 uint32_t w0=0, h0=0, s0=0; 765 uint32_t w1=0, h1=0, s1=0; 766 if (buf0 != 0) { 767 w0 = buf0->getWidth(); 768 h0 = buf0->getHeight(); 769 s0 = buf0->getStride(); 770 } 771 if (buf1 != 0) { 772 w1 = buf1->getWidth(); 773 h1 = buf1->getHeight(); 774 s1 = buf1->getStride(); 775 } 776 snprintf(buffer, SIZE, 777 " " 778 "format=%2d, [%3ux%3u:%3u] [%3ux%3u:%3u]," 779 " freezeLock=%p, dq-q-time=%u us\n", 780 mFormat, w0, h0, s0, w1, h1, s1, 781 getFreezeLock().get(), totalTime); 782 783 result.append(buffer); 784} 785 786// --------------------------------------------------------------------------- 787 788Layer::ClientRef::ClientRef() 789 : mControlBlock(0), mToken(-1) { 790} 791 792Layer::ClientRef::~ClientRef() { 793} 794 795int32_t Layer::ClientRef::getToken() const { 796 Mutex::Autolock _l(mLock); 797 return mToken; 798} 799 800sp<UserClient> Layer::ClientRef::getClient() const { 801 Mutex::Autolock _l(mLock); 802 return mUserClient.promote(); 803} 804 805status_t Layer::ClientRef::setToken(const sp<UserClient>& uc, 806 const sp<SharedBufferServer>& sharedClient, int32_t token) { 807 Mutex::Autolock _l(mLock); 808 809 { // scope for strong mUserClient reference 810 sp<UserClient> userClient(mUserClient.promote()); 811 if (mUserClient != 0 && mControlBlock != 0) { 812 mControlBlock->setStatus(NO_INIT); 813 } 814 } 815 816 mUserClient = uc; 817 mToken = token; 818 mControlBlock = sharedClient; 819 return NO_ERROR; 820} 821 822sp<UserClient> Layer::ClientRef::getUserClientUnsafe() const { 823 return mUserClient.promote(); 824} 825 826// this class gives us access to SharedBufferServer safely 827// it makes sure the UserClient (and its associated shared memory) 828// won't go away while we're accessing it. 829Layer::ClientRef::Access::Access(const ClientRef& ref) 830 : mControlBlock(0) 831{ 832 Mutex::Autolock _l(ref.mLock); 833 mUserClientStrongRef = ref.mUserClient.promote(); 834 if (mUserClientStrongRef != 0) 835 mControlBlock = ref.mControlBlock; 836} 837 838Layer::ClientRef::Access::~Access() 839{ 840} 841 842// --------------------------------------------------------------------------- 843 844Layer::BufferManager::BufferManager(TextureManager& tm) 845 : mNumBuffers(NUM_BUFFERS), mTextureManager(tm), 846 mActiveBufferIndex(-1), mFailover(false) 847{ 848} 849 850Layer::BufferManager::~BufferManager() 851{ 852} 853 854status_t Layer::BufferManager::resize(size_t size, 855 const sp<SurfaceFlinger>& flinger, EGLDisplay dpy) 856{ 857 Mutex::Autolock _l(mLock); 858 859 if (size < mNumBuffers) { 860 // Move the active texture into slot 0 861 BufferData activeBufferData = mBufferData[mActiveBufferIndex]; 862 mBufferData[mActiveBufferIndex] = mBufferData[0]; 863 mBufferData[0] = activeBufferData; 864 mActiveBufferIndex = 0; 865 866 // Free the buffers that are no longer needed. 867 for (size_t i = size; i < mNumBuffers; i++) { 868 mBufferData[i].buffer = 0; 869 870 // Create a message to destroy the textures on SurfaceFlinger's GL 871 // thread. 872 class MessageDestroyTexture : public MessageBase { 873 Image mTexture; 874 EGLDisplay mDpy; 875 public: 876 MessageDestroyTexture(const Image& texture, EGLDisplay dpy) 877 : mTexture(texture), mDpy(dpy) { } 878 virtual bool handler() { 879 status_t err = Layer::BufferManager::destroyTexture( 880 &mTexture, mDpy); 881 LOGE_IF(err<0, "error destroying texture: %d (%s)", 882 mTexture.name, strerror(-err)); 883 return true; // XXX: err == 0; ???? 884 } 885 }; 886 887 MessageDestroyTexture *msg = new MessageDestroyTexture( 888 mBufferData[i].texture, dpy); 889 890 // Don't allow this texture to be cleaned up by 891 // BufferManager::destroy. 892 mBufferData[i].texture.name = -1U; 893 mBufferData[i].texture.image = EGL_NO_IMAGE_KHR; 894 895 // Post the message to the SurfaceFlinger object. 896 flinger->postMessageAsync(msg); 897 } 898 } 899 900 mNumBuffers = size; 901 return NO_ERROR; 902} 903 904// only for debugging 905sp<GraphicBuffer> Layer::BufferManager::getBuffer(size_t index) const { 906 return mBufferData[index].buffer; 907} 908 909status_t Layer::BufferManager::setActiveBufferIndex(size_t index) { 910 BufferData const * const buffers = mBufferData; 911 Mutex::Autolock _l(mLock); 912 mActiveBuffer = buffers[index].buffer; 913 mActiveBufferIndex = index; 914 return NO_ERROR; 915} 916 917size_t Layer::BufferManager::getActiveBufferIndex() const { 918 return mActiveBufferIndex; 919} 920 921Texture Layer::BufferManager::getActiveTexture() const { 922 Texture res; 923 if (mFailover || mActiveBufferIndex<0) { 924 res = mFailoverTexture; 925 } else { 926 static_cast<Image&>(res) = mBufferData[mActiveBufferIndex].texture; 927 } 928 return res; 929} 930 931sp<GraphicBuffer> Layer::BufferManager::getActiveBuffer() const { 932 return mActiveBuffer; 933} 934 935bool Layer::BufferManager::hasActiveBuffer() const { 936 return mActiveBufferIndex >= 0; 937} 938 939sp<GraphicBuffer> Layer::BufferManager::detachBuffer(size_t index) 940{ 941 BufferData* const buffers = mBufferData; 942 sp<GraphicBuffer> buffer; 943 Mutex::Autolock _l(mLock); 944 buffer = buffers[index].buffer; 945 buffers[index].buffer = 0; 946 return buffer; 947} 948 949status_t Layer::BufferManager::attachBuffer(size_t index, 950 const sp<GraphicBuffer>& buffer) 951{ 952 BufferData* const buffers = mBufferData; 953 Mutex::Autolock _l(mLock); 954 buffers[index].buffer = buffer; 955 buffers[index].texture.dirty = true; 956 return NO_ERROR; 957} 958 959status_t Layer::BufferManager::destroy(EGLDisplay dpy) 960{ 961 BufferData* const buffers = mBufferData; 962 size_t num; 963 { // scope for the lock 964 Mutex::Autolock _l(mLock); 965 num = mNumBuffers; 966 for (size_t i=0 ; i<num ; i++) { 967 buffers[i].buffer = 0; 968 } 969 } 970 for (size_t i=0 ; i<num ; i++) { 971 destroyTexture(&buffers[i].texture, dpy); 972 } 973 destroyTexture(&mFailoverTexture, dpy); 974 return NO_ERROR; 975} 976 977status_t Layer::BufferManager::initEglImage(EGLDisplay dpy, 978 const sp<GraphicBuffer>& buffer) 979{ 980 status_t err = NO_INIT; 981 ssize_t index = mActiveBufferIndex; 982 if (index >= 0) { 983 if (!mFailover) { 984 Image& texture(mBufferData[index].texture); 985 err = mTextureManager.initEglImage(&texture, dpy, buffer); 986 // if EGLImage fails, we switch to regular texture mode, and we 987 // free all resources associated with using EGLImages. 988 if (err == NO_ERROR) { 989 mFailover = false; 990 destroyTexture(&mFailoverTexture, dpy); 991 } else { 992 mFailover = true; 993 const size_t num = mNumBuffers; 994 for (size_t i=0 ; i<num ; i++) { 995 destroyTexture(&mBufferData[i].texture, dpy); 996 } 997 } 998 } else { 999 // we failed once, don't try again 1000 err = BAD_VALUE; 1001 } 1002 } 1003 return err; 1004} 1005 1006status_t Layer::BufferManager::loadTexture( 1007 const Region& dirty, const GGLSurface& t) 1008{ 1009 return mTextureManager.loadTexture(&mFailoverTexture, dirty, t); 1010} 1011 1012status_t Layer::BufferManager::destroyTexture(Image* tex, EGLDisplay dpy) 1013{ 1014 if (tex->name != -1U) { 1015 glDeleteTextures(1, &tex->name); 1016 tex->name = -1U; 1017 } 1018 if (tex->image != EGL_NO_IMAGE_KHR) { 1019 eglDestroyImageKHR(dpy, tex->image); 1020 tex->image = EGL_NO_IMAGE_KHR; 1021 } 1022 return NO_ERROR; 1023} 1024 1025// --------------------------------------------------------------------------- 1026 1027Layer::SurfaceLayer::SurfaceLayer(const sp<SurfaceFlinger>& flinger, 1028 const sp<Layer>& owner) 1029 : Surface(flinger, owner->getIdentity(), owner) 1030{ 1031} 1032 1033Layer::SurfaceLayer::~SurfaceLayer() 1034{ 1035} 1036 1037sp<GraphicBuffer> Layer::SurfaceLayer::requestBuffer(int index, 1038 uint32_t w, uint32_t h, uint32_t format, uint32_t usage) 1039{ 1040 sp<GraphicBuffer> buffer; 1041 sp<Layer> owner(getOwner()); 1042 if (owner != 0) { 1043 /* 1044 * requestBuffer() cannot be called from the main thread 1045 * as it could cause a dead-lock, since it may have to wait 1046 * on conditions updated my the main thread. 1047 */ 1048 buffer = owner->requestBuffer(index, w, h, format, usage); 1049 } 1050 return buffer; 1051} 1052 1053status_t Layer::SurfaceLayer::setBufferCount(int bufferCount) 1054{ 1055 status_t err = DEAD_OBJECT; 1056 sp<Layer> owner(getOwner()); 1057 if (owner != 0) { 1058 /* 1059 * setBufferCount() cannot be called from the main thread 1060 * as it could cause a dead-lock, since it may have to wait 1061 * on conditions updated my the main thread. 1062 */ 1063 err = owner->setBufferCount(bufferCount); 1064 } 1065 return err; 1066} 1067 1068// --------------------------------------------------------------------------- 1069 1070 1071}; // namespace android 1072