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