SurfaceFlinger.cpp revision 48b888aab9fdcfba250722dffbdffe61f11c64f3
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 <stdio.h> 19#include <stdint.h> 20#include <unistd.h> 21#include <fcntl.h> 22#include <errno.h> 23#include <math.h> 24#include <limits.h> 25#include <sys/types.h> 26#include <sys/stat.h> 27#include <sys/ioctl.h> 28 29#include <cutils/log.h> 30#include <cutils/properties.h> 31 32#include <binder/IPCThreadState.h> 33#include <binder/IServiceManager.h> 34#include <binder/MemoryHeapBase.h> 35 36#include <utils/String8.h> 37#include <utils/String16.h> 38#include <utils/StopWatch.h> 39 40#include <ui/GraphicBufferAllocator.h> 41#include <ui/GraphicLog.h> 42#include <ui/PixelFormat.h> 43 44#include <pixelflinger/pixelflinger.h> 45#include <GLES/gl.h> 46 47#include "clz.h" 48#include "GLExtensions.h" 49#include "Layer.h" 50#include "LayerDim.h" 51#include "SurfaceFlinger.h" 52 53#include "DisplayHardware/DisplayHardware.h" 54#include "DisplayHardware/HWComposer.h" 55 56/* ideally AID_GRAPHICS would be in a semi-public header 57 * or there would be a way to map a user/group name to its id 58 */ 59#ifndef AID_GRAPHICS 60#define AID_GRAPHICS 1003 61#endif 62 63#define DISPLAY_COUNT 1 64 65namespace android { 66// --------------------------------------------------------------------------- 67 68SurfaceFlinger::SurfaceFlinger() 69 : BnSurfaceComposer(), Thread(false), 70 mTransactionFlags(0), 71 mTransactionCount(0), 72 mResizeTransationPending(false), 73 mLayersRemoved(false), 74 mBootTime(systemTime()), 75 mHardwareTest("android.permission.HARDWARE_TEST"), 76 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"), 77 mReadFramebuffer("android.permission.READ_FRAME_BUFFER"), 78 mDump("android.permission.DUMP"), 79 mVisibleRegionsDirty(false), 80 mHwWorkListDirty(false), 81 mDeferReleaseConsole(false), 82 mFreezeDisplay(false), 83 mElectronBeamAnimationMode(0), 84 mFreezeCount(0), 85 mFreezeDisplayTime(0), 86 mDebugRegion(0), 87 mDebugBackground(0), 88 mDebugDisableHWC(0), 89 mDebugInSwapBuffers(0), 90 mLastSwapBufferTime(0), 91 mDebugInTransaction(0), 92 mLastTransactionTime(0), 93 mBootFinished(false), 94 mConsoleSignals(0), 95 mSecureFrameBuffer(0) 96{ 97 init(); 98} 99 100void SurfaceFlinger::init() 101{ 102 LOGI("SurfaceFlinger is starting"); 103 104 // debugging stuff... 105 char value[PROPERTY_VALUE_MAX]; 106 property_get("debug.sf.showupdates", value, "0"); 107 mDebugRegion = atoi(value); 108 property_get("debug.sf.showbackground", value, "0"); 109 mDebugBackground = atoi(value); 110 111 LOGI_IF(mDebugRegion, "showupdates enabled"); 112 LOGI_IF(mDebugBackground, "showbackground enabled"); 113} 114 115SurfaceFlinger::~SurfaceFlinger() 116{ 117 glDeleteTextures(1, &mWormholeTexName); 118} 119 120sp<IMemoryHeap> SurfaceFlinger::getCblk() const 121{ 122 return mServerHeap; 123} 124 125sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 126{ 127 sp<ISurfaceComposerClient> bclient; 128 sp<Client> client(new Client(this)); 129 status_t err = client->initCheck(); 130 if (err == NO_ERROR) { 131 bclient = client; 132 } 133 return bclient; 134} 135 136sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection() 137{ 138 sp<ISurfaceComposerClient> bclient; 139 sp<UserClient> client(new UserClient(this)); 140 status_t err = client->initCheck(); 141 if (err == NO_ERROR) { 142 bclient = client; 143 } 144 return bclient; 145} 146 147sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc() 148{ 149 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc()); 150 return gba; 151} 152 153const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const 154{ 155 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy); 156 const GraphicPlane& plane(mGraphicPlanes[dpy]); 157 return plane; 158} 159 160GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) 161{ 162 return const_cast<GraphicPlane&>( 163 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy)); 164} 165 166void SurfaceFlinger::bootFinished() 167{ 168 const nsecs_t now = systemTime(); 169 const nsecs_t duration = now - mBootTime; 170 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 171 mBootFinished = true; 172 property_set("ctl.stop", "bootanim"); 173} 174 175void SurfaceFlinger::onFirstRef() 176{ 177 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY); 178 179 // Wait for the main thread to be done with its initialization 180 mReadyToRunBarrier.wait(); 181} 182 183static inline uint16_t pack565(int r, int g, int b) { 184 return (r<<11)|(g<<5)|b; 185} 186 187status_t SurfaceFlinger::readyToRun() 188{ 189 LOGI( "SurfaceFlinger's main thread ready to run. " 190 "Initializing graphics H/W..."); 191 192 // we only support one display currently 193 int dpy = 0; 194 195 { 196 // initialize the main display 197 GraphicPlane& plane(graphicPlane(dpy)); 198 DisplayHardware* const hw = new DisplayHardware(this, dpy); 199 plane.setDisplayHardware(hw); 200 } 201 202 // create the shared control-block 203 mServerHeap = new MemoryHeapBase(4096, 204 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap"); 205 LOGE_IF(mServerHeap==0, "can't create shared memory dealer"); 206 207 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase()); 208 LOGE_IF(mServerCblk==0, "can't get to shared control block's address"); 209 210 new(mServerCblk) surface_flinger_cblk_t; 211 212 // initialize primary screen 213 // (other display should be initialized in the same manner, but 214 // asynchronously, as they could come and go. None of this is supported 215 // yet). 216 const GraphicPlane& plane(graphicPlane(dpy)); 217 const DisplayHardware& hw = plane.displayHardware(); 218 const uint32_t w = hw.getWidth(); 219 const uint32_t h = hw.getHeight(); 220 const uint32_t f = hw.getFormat(); 221 hw.makeCurrent(); 222 223 // initialize the shared control block 224 mServerCblk->connected |= 1<<dpy; 225 display_cblk_t* dcblk = mServerCblk->displays + dpy; 226 memset(dcblk, 0, sizeof(display_cblk_t)); 227 dcblk->w = plane.getWidth(); 228 dcblk->h = plane.getHeight(); 229 dcblk->format = f; 230 dcblk->orientation = ISurfaceComposer::eOrientationDefault; 231 dcblk->xdpi = hw.getDpiX(); 232 dcblk->ydpi = hw.getDpiY(); 233 dcblk->fps = hw.getRefreshRate(); 234 dcblk->density = hw.getDensity(); 235 236 // Initialize OpenGL|ES 237 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 238 glPixelStorei(GL_PACK_ALIGNMENT, 4); 239 glEnableClientState(GL_VERTEX_ARRAY); 240 glEnable(GL_SCISSOR_TEST); 241 glShadeModel(GL_FLAT); 242 glDisable(GL_DITHER); 243 glDisable(GL_CULL_FACE); 244 245 const uint16_t g0 = pack565(0x0F,0x1F,0x0F); 246 const uint16_t g1 = pack565(0x17,0x2f,0x17); 247 const uint16_t textureData[4] = { g0, g1, g1, g0 }; 248 glGenTextures(1, &mWormholeTexName); 249 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 250 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 251 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 252 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 253 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 254 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, 255 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData); 256 257 glViewport(0, 0, w, h); 258 glMatrixMode(GL_PROJECTION); 259 glLoadIdentity(); 260 glOrthof(0, w, h, 0, 0, 1); 261 262 LayerDim::initDimmer(this, w, h); 263 264 mReadyToRunBarrier.open(); 265 266 /* 267 * We're now ready to accept clients... 268 */ 269 270 // start boot animation 271 property_set("ctl.start", "bootanim"); 272 273 return NO_ERROR; 274} 275 276// ---------------------------------------------------------------------------- 277#if 0 278#pragma mark - 279#pragma mark Events Handler 280#endif 281 282void SurfaceFlinger::waitForEvent() 283{ 284 while (true) { 285 nsecs_t timeout = -1; 286 const nsecs_t freezeDisplayTimeout = ms2ns(5000); 287 if (UNLIKELY(isFrozen())) { 288 // wait 5 seconds 289 const nsecs_t now = systemTime(); 290 if (mFreezeDisplayTime == 0) { 291 mFreezeDisplayTime = now; 292 } 293 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime); 294 timeout = waitTime>0 ? waitTime : 0; 295 } 296 297 sp<MessageBase> msg = mEventQueue.waitMessage(timeout); 298 299 // see if we timed out 300 if (isFrozen()) { 301 const nsecs_t now = systemTime(); 302 nsecs_t frozenTime = (now - mFreezeDisplayTime); 303 if (frozenTime >= freezeDisplayTimeout) { 304 // we timed out and are still frozen 305 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d", 306 mFreezeDisplay, mFreezeCount); 307 mFreezeDisplayTime = 0; 308 mFreezeCount = 0; 309 mFreezeDisplay = false; 310 } 311 } 312 313 if (msg != 0) { 314 switch (msg->what) { 315 case MessageQueue::INVALIDATE: 316 // invalidate message, just return to the main loop 317 return; 318 } 319 } 320 } 321} 322 323void SurfaceFlinger::signalEvent() { 324 mEventQueue.invalidate(); 325} 326 327void SurfaceFlinger::signal() const { 328 // this is the IPC call 329 const_cast<SurfaceFlinger*>(this)->signalEvent(); 330} 331 332status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 333 nsecs_t reltime, uint32_t flags) 334{ 335 return mEventQueue.postMessage(msg, reltime, flags); 336} 337 338status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 339 nsecs_t reltime, uint32_t flags) 340{ 341 status_t res = mEventQueue.postMessage(msg, reltime, flags); 342 if (res == NO_ERROR) { 343 msg->wait(); 344 } 345 return res; 346} 347 348// ---------------------------------------------------------------------------- 349#if 0 350#pragma mark - 351#pragma mark Main loop 352#endif 353 354bool SurfaceFlinger::threadLoop() 355{ 356 waitForEvent(); 357 358 // check for transactions 359 if (UNLIKELY(mConsoleSignals)) { 360 handleConsoleEvents(); 361 } 362 363 if (LIKELY(mTransactionCount == 0)) { 364 // if we're in a global transaction, don't do anything. 365 const uint32_t mask = eTransactionNeeded | eTraversalNeeded; 366 uint32_t transactionFlags = getTransactionFlags(mask); 367 if (LIKELY(transactionFlags)) { 368 handleTransaction(transactionFlags); 369 } 370 } 371 372 // post surfaces (if needed) 373 handlePageFlip(); 374 375 if (UNLIKELY(mHwWorkListDirty)) { 376 // build the h/w work list 377 handleWorkList(); 378 } 379 380 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 381 if (LIKELY(hw.canDraw() && !isFrozen())) { 382 // repaint the framebuffer (if needed) 383 384 const int index = hw.getCurrentBufferIndex(); 385 GraphicLog& logger(GraphicLog::getInstance()); 386 387 logger.log(GraphicLog::SF_REPAINT, index); 388 handleRepaint(); 389 390 // inform the h/w that we're done compositing 391 logger.log(GraphicLog::SF_COMPOSITION_COMPLETE, index); 392 hw.compositionComplete(); 393 394 logger.log(GraphicLog::SF_SWAP_BUFFERS, index); 395 postFramebuffer(); 396 397 logger.log(GraphicLog::SF_UNLOCK_CLIENTS, index); 398 unlockClients(); 399 400 logger.log(GraphicLog::SF_REPAINT_DONE, index); 401 } else { 402 // pretend we did the post 403 hw.compositionComplete(); 404 unlockClients(); 405 usleep(16667); // 60 fps period 406 } 407 return true; 408} 409 410void SurfaceFlinger::postFramebuffer() 411{ 412 if (!mInvalidRegion.isEmpty()) { 413 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 414 const nsecs_t now = systemTime(); 415 mDebugInSwapBuffers = now; 416 hw.flip(mInvalidRegion); 417 mLastSwapBufferTime = systemTime() - now; 418 mDebugInSwapBuffers = 0; 419 mInvalidRegion.clear(); 420 } 421} 422 423void SurfaceFlinger::handleConsoleEvents() 424{ 425 // something to do with the console 426 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 427 428 int what = android_atomic_and(0, &mConsoleSignals); 429 if (what & eConsoleAcquired) { 430 hw.acquireScreen(); 431 // this is a temporary work-around, eventually this should be called 432 // by the power-manager 433 SurfaceFlinger::turnElectronBeamOn(mElectronBeamAnimationMode); 434 } 435 436 if (mDeferReleaseConsole && hw.isScreenAcquired()) { 437 // We got the release signal before the acquire signal 438 mDeferReleaseConsole = false; 439 hw.releaseScreen(); 440 } 441 442 if (what & eConsoleReleased) { 443 if (hw.isScreenAcquired()) { 444 hw.releaseScreen(); 445 } else { 446 mDeferReleaseConsole = true; 447 } 448 } 449 450 mDirtyRegion.set(hw.bounds()); 451} 452 453void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 454{ 455 Vector< sp<LayerBase> > ditchedLayers; 456 457 /* 458 * Perform and commit the transaction 459 */ 460 461 { // scope for the lock 462 Mutex::Autolock _l(mStateLock); 463 const nsecs_t now = systemTime(); 464 mDebugInTransaction = now; 465 handleTransactionLocked(transactionFlags, ditchedLayers); 466 mLastTransactionTime = systemTime() - now; 467 mDebugInTransaction = 0; 468 invalidateHwcGeometry(); 469 // here the transaction has been committed 470 } 471 472 /* 473 * Clean-up all layers that went away 474 * (do this without the lock held) 475 */ 476 477 const size_t count = ditchedLayers.size(); 478 for (size_t i=0 ; i<count ; i++) { 479 if (ditchedLayers[i] != 0) { 480 //LOGD("ditching layer %p", ditchedLayers[i].get()); 481 ditchedLayers[i]->ditch(); 482 } 483 } 484} 485 486void SurfaceFlinger::handleTransactionLocked( 487 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers) 488{ 489 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 490 const size_t count = currentLayers.size(); 491 492 /* 493 * Traversal of the children 494 * (perform the transaction for each of them if needed) 495 */ 496 497 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded; 498 if (layersNeedTransaction) { 499 for (size_t i=0 ; i<count ; i++) { 500 const sp<LayerBase>& layer = currentLayers[i]; 501 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 502 if (!trFlags) continue; 503 504 const uint32_t flags = layer->doTransaction(0); 505 if (flags & Layer::eVisibleRegion) 506 mVisibleRegionsDirty = true; 507 } 508 } 509 510 /* 511 * Perform our own transaction if needed 512 */ 513 514 if (transactionFlags & eTransactionNeeded) { 515 if (mCurrentState.orientation != mDrawingState.orientation) { 516 // the orientation has changed, recompute all visible regions 517 // and invalidate everything. 518 519 const int dpy = 0; 520 const int orientation = mCurrentState.orientation; 521 const uint32_t type = mCurrentState.orientationType; 522 GraphicPlane& plane(graphicPlane(dpy)); 523 plane.setOrientation(orientation); 524 525 // update the shared control block 526 const DisplayHardware& hw(plane.displayHardware()); 527 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy; 528 dcblk->orientation = orientation; 529 dcblk->w = plane.getWidth(); 530 dcblk->h = plane.getHeight(); 531 532 mVisibleRegionsDirty = true; 533 mDirtyRegion.set(hw.bounds()); 534 } 535 536 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) { 537 // freezing or unfreezing the display -> trigger animation if needed 538 mFreezeDisplay = mCurrentState.freezeDisplay; 539 if (mFreezeDisplay) 540 mFreezeDisplayTime = 0; 541 } 542 543 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) { 544 // layers have been added 545 mVisibleRegionsDirty = true; 546 } 547 548 // some layers might have been removed, so 549 // we need to update the regions they're exposing. 550 if (mLayersRemoved) { 551 mLayersRemoved = false; 552 mVisibleRegionsDirty = true; 553 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 554 const size_t count = previousLayers.size(); 555 for (size_t i=0 ; i<count ; i++) { 556 const sp<LayerBase>& layer(previousLayers[i]); 557 if (currentLayers.indexOf( layer ) < 0) { 558 // this layer is not visible anymore 559 ditchedLayers.add(layer); 560 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen); 561 } 562 } 563 } 564 } 565 566 commitTransaction(); 567} 568 569sp<FreezeLock> SurfaceFlinger::getFreezeLock() const 570{ 571 return new FreezeLock(const_cast<SurfaceFlinger *>(this)); 572} 573 574void SurfaceFlinger::computeVisibleRegions( 575 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion) 576{ 577 const GraphicPlane& plane(graphicPlane(0)); 578 const Transform& planeTransform(plane.transform()); 579 const DisplayHardware& hw(plane.displayHardware()); 580 const Region screenRegion(hw.bounds()); 581 582 Region aboveOpaqueLayers; 583 Region aboveCoveredLayers; 584 Region dirty; 585 586 bool secureFrameBuffer = false; 587 588 size_t i = currentLayers.size(); 589 while (i--) { 590 const sp<LayerBase>& layer = currentLayers[i]; 591 layer->validateVisibility(planeTransform); 592 593 // start with the whole surface at its current location 594 const Layer::State& s(layer->drawingState()); 595 596 /* 597 * opaqueRegion: area of a surface that is fully opaque. 598 */ 599 Region opaqueRegion; 600 601 /* 602 * visibleRegion: area of a surface that is visible on screen 603 * and not fully transparent. This is essentially the layer's 604 * footprint minus the opaque regions above it. 605 * Areas covered by a translucent surface are considered visible. 606 */ 607 Region visibleRegion; 608 609 /* 610 * coveredRegion: area of a surface that is covered by all 611 * visible regions above it (which includes the translucent areas). 612 */ 613 Region coveredRegion; 614 615 616 // handle hidden surfaces by setting the visible region to empty 617 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) { 618 const bool translucent = layer->needsBlending(); 619 const Rect bounds(layer->visibleBounds()); 620 visibleRegion.set(bounds); 621 visibleRegion.andSelf(screenRegion); 622 if (!visibleRegion.isEmpty()) { 623 // Remove the transparent area from the visible region 624 if (translucent) { 625 visibleRegion.subtractSelf(layer->transparentRegionScreen); 626 } 627 628 // compute the opaque region 629 const int32_t layerOrientation = layer->getOrientation(); 630 if (s.alpha==255 && !translucent && 631 ((layerOrientation & Transform::ROT_INVALID) == false)) { 632 // the opaque region is the layer's footprint 633 opaqueRegion = visibleRegion; 634 } 635 } 636 } 637 638 // Clip the covered region to the visible region 639 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 640 641 // Update aboveCoveredLayers for next (lower) layer 642 aboveCoveredLayers.orSelf(visibleRegion); 643 644 // subtract the opaque region covered by the layers above us 645 visibleRegion.subtractSelf(aboveOpaqueLayers); 646 647 // compute this layer's dirty region 648 if (layer->contentDirty) { 649 // we need to invalidate the whole region 650 dirty = visibleRegion; 651 // as well, as the old visible region 652 dirty.orSelf(layer->visibleRegionScreen); 653 layer->contentDirty = false; 654 } else { 655 /* compute the exposed region: 656 * the exposed region consists of two components: 657 * 1) what's VISIBLE now and was COVERED before 658 * 2) what's EXPOSED now less what was EXPOSED before 659 * 660 * note that (1) is conservative, we start with the whole 661 * visible region but only keep what used to be covered by 662 * something -- which mean it may have been exposed. 663 * 664 * (2) handles areas that were not covered by anything but got 665 * exposed because of a resize. 666 */ 667 const Region newExposed = visibleRegion - coveredRegion; 668 const Region oldVisibleRegion = layer->visibleRegionScreen; 669 const Region oldCoveredRegion = layer->coveredRegionScreen; 670 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 671 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 672 } 673 dirty.subtractSelf(aboveOpaqueLayers); 674 675 // accumulate to the screen dirty region 676 dirtyRegion.orSelf(dirty); 677 678 // Update aboveOpaqueLayers for next (lower) layer 679 aboveOpaqueLayers.orSelf(opaqueRegion); 680 681 // Store the visible region is screen space 682 layer->setVisibleRegion(visibleRegion); 683 layer->setCoveredRegion(coveredRegion); 684 685 // If a secure layer is partially visible, lock-down the screen! 686 if (layer->isSecure() && !visibleRegion.isEmpty()) { 687 secureFrameBuffer = true; 688 } 689 } 690 691 // invalidate the areas where a layer was removed 692 dirtyRegion.orSelf(mDirtyRegionRemovedLayer); 693 mDirtyRegionRemovedLayer.clear(); 694 695 mSecureFrameBuffer = secureFrameBuffer; 696 opaqueRegion = aboveOpaqueLayers; 697} 698 699 700void SurfaceFlinger::commitTransaction() 701{ 702 mDrawingState = mCurrentState; 703 mResizeTransationPending = false; 704 mTransactionCV.broadcast(); 705} 706 707void SurfaceFlinger::handlePageFlip() 708{ 709 bool visibleRegions = mVisibleRegionsDirty; 710 LayerVector& currentLayers( 711 const_cast<LayerVector&>(mDrawingState.layersSortedByZ)); 712 visibleRegions |= lockPageFlip(currentLayers); 713 714 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 715 const Region screenRegion(hw.bounds()); 716 if (visibleRegions) { 717 Region opaqueRegion; 718 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion); 719 720 /* 721 * rebuild the visible layer list 722 */ 723 mVisibleLayersSortedByZ.clear(); 724 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 725 size_t count = currentLayers.size(); 726 mVisibleLayersSortedByZ.setCapacity(count); 727 for (size_t i=0 ; i<count ; i++) { 728 if (!currentLayers[i]->visibleRegionScreen.isEmpty()) 729 mVisibleLayersSortedByZ.add(currentLayers[i]); 730 } 731 732 mWormholeRegion = screenRegion.subtract(opaqueRegion); 733 mVisibleRegionsDirty = false; 734 invalidateHwcGeometry(); 735 } 736 737 unlockPageFlip(currentLayers); 738 mDirtyRegion.andSelf(screenRegion); 739} 740 741void SurfaceFlinger::invalidateHwcGeometry() 742{ 743 mHwWorkListDirty = true; 744} 745 746bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers) 747{ 748 bool recomputeVisibleRegions = false; 749 size_t count = currentLayers.size(); 750 sp<LayerBase> const* layers = currentLayers.array(); 751 for (size_t i=0 ; i<count ; i++) { 752 const sp<LayerBase>& layer(layers[i]); 753 layer->lockPageFlip(recomputeVisibleRegions); 754 } 755 return recomputeVisibleRegions; 756} 757 758void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers) 759{ 760 const GraphicPlane& plane(graphicPlane(0)); 761 const Transform& planeTransform(plane.transform()); 762 size_t count = currentLayers.size(); 763 sp<LayerBase> const* layers = currentLayers.array(); 764 for (size_t i=0 ; i<count ; i++) { 765 const sp<LayerBase>& layer(layers[i]); 766 layer->unlockPageFlip(planeTransform, mDirtyRegion); 767 } 768} 769 770void SurfaceFlinger::handleWorkList() 771{ 772 mHwWorkListDirty = false; 773 HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer()); 774 if (hwc.initCheck() == NO_ERROR) { 775 const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ); 776 const size_t count = currentLayers.size(); 777 hwc.createWorkList(count); 778 hwc_layer_t* const cur(hwc.getLayers()); 779 for (size_t i=0 ; cur && i<count ; i++) { 780 currentLayers[i]->setGeometry(&cur[i]); 781 if (mDebugDisableHWC) { 782 cur[i].compositionType = HWC_FRAMEBUFFER; 783 cur[i].flags |= HWC_SKIP_LAYER; 784 } 785 } 786 } 787} 788 789void SurfaceFlinger::handleRepaint() 790{ 791 // compute the invalid region 792 mInvalidRegion.orSelf(mDirtyRegion); 793 794 if (UNLIKELY(mDebugRegion)) { 795 debugFlashRegions(); 796 } 797 798 // set the frame buffer 799 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 800 glMatrixMode(GL_MODELVIEW); 801 glLoadIdentity(); 802 803 uint32_t flags = hw.getFlags(); 804 if ((flags & DisplayHardware::SWAP_RECTANGLE) || 805 (flags & DisplayHardware::BUFFER_PRESERVED)) 806 { 807 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 808 // takes a rectangle, we must make sure to update that whole 809 // rectangle in that case 810 if (flags & DisplayHardware::SWAP_RECTANGLE) { 811 // TODO: we really should be able to pass a region to 812 // SWAP_RECTANGLE so that we don't have to redraw all this. 813 mDirtyRegion.set(mInvalidRegion.bounds()); 814 } else { 815 // in the BUFFER_PRESERVED case, obviously, we can update only 816 // what's needed and nothing more. 817 // NOTE: this is NOT a common case, as preserving the backbuffer 818 // is costly and usually involves copying the whole update back. 819 } 820 } else { 821 if (flags & DisplayHardware::PARTIAL_UPDATES) { 822 // We need to redraw the rectangle that will be updated 823 // (pushed to the framebuffer). 824 // This is needed because PARTIAL_UPDATES only takes one 825 // rectangle instead of a region (see DisplayHardware::flip()) 826 mDirtyRegion.set(mInvalidRegion.bounds()); 827 } else { 828 // we need to redraw everything (the whole screen) 829 mDirtyRegion.set(hw.bounds()); 830 mInvalidRegion = mDirtyRegion; 831 } 832 } 833 834 // compose all surfaces 835 composeSurfaces(mDirtyRegion); 836 837 // clear the dirty regions 838 mDirtyRegion.clear(); 839} 840 841void SurfaceFlinger::composeSurfaces(const Region& dirty) 842{ 843 if (UNLIKELY(!mWormholeRegion.isEmpty())) { 844 // should never happen unless the window manager has a bug 845 // draw something... 846 drawWormhole(); 847 } 848 849 status_t err = NO_ERROR; 850 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 851 size_t count = layers.size(); 852 853 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 854 HWComposer& hwc(hw.getHwComposer()); 855 hwc_layer_t* const cur(hwc.getLayers()); 856 857 LOGE_IF(cur && hwc.getNumLayers() != count, 858 "HAL number of layers (%d) doesn't match surfaceflinger (%d)", 859 hwc.getNumLayers(), count); 860 861 // just to be extra-safe, use the smallest count 862 if (hwc.initCheck() == NO_ERROR) { 863 count = count < hwc.getNumLayers() ? count : hwc.getNumLayers(); 864 } 865 866 /* 867 * update the per-frame h/w composer data for each layer 868 * and build the transparent region of the FB 869 */ 870 Region transparent; 871 if (cur) { 872 for (size_t i=0 ; i<count ; i++) { 873 const sp<LayerBase>& layer(layers[i]); 874 layer->setPerFrameData(&cur[i]); 875 if (cur[i].hints & HWC_HINT_CLEAR_FB) { 876 if (!(layer->needsBlending())) { 877 transparent.orSelf(layer->visibleRegionScreen); 878 } 879 } 880 } 881 err = hwc.prepare(); 882 LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 883 } 884 885 /* 886 * clear the area of the FB that need to be transparent 887 */ 888 transparent.andSelf(dirty); 889 if (!transparent.isEmpty()) { 890 glClearColor(0,0,0,0); 891 Region::const_iterator it = transparent.begin(); 892 Region::const_iterator const end = transparent.end(); 893 const int32_t height = hw.getHeight(); 894 while (it != end) { 895 const Rect& r(*it++); 896 const GLint sy = height - (r.top + r.height()); 897 glScissor(r.left, sy, r.width(), r.height()); 898 glClear(GL_COLOR_BUFFER_BIT); 899 } 900 } 901 902 903 /* 904 * and then, render the layers targeted at the framebuffer 905 */ 906 for (size_t i=0 ; i<count ; i++) { 907 if (cur) { 908 if ((cur[i].compositionType != HWC_FRAMEBUFFER) && 909 !(cur[i].flags & HWC_SKIP_LAYER)) { 910 // skip layers handled by the HAL 911 continue; 912 } 913 } 914 915 const sp<LayerBase>& layer(layers[i]); 916 const Region clip(dirty.intersect(layer->visibleRegionScreen)); 917 if (!clip.isEmpty()) { 918 layer->draw(clip); 919 } 920 } 921} 922 923void SurfaceFlinger::unlockClients() 924{ 925 const LayerVector& drawingLayers(mDrawingState.layersSortedByZ); 926 const size_t count = drawingLayers.size(); 927 sp<LayerBase> const* const layers = drawingLayers.array(); 928 for (size_t i=0 ; i<count ; ++i) { 929 const sp<LayerBase>& layer = layers[i]; 930 layer->finishPageFlip(); 931 } 932} 933 934void SurfaceFlinger::debugFlashRegions() 935{ 936 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 937 const uint32_t flags = hw.getFlags(); 938 939 if (!((flags & DisplayHardware::SWAP_RECTANGLE) || 940 (flags & DisplayHardware::BUFFER_PRESERVED))) { 941 const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ? 942 mDirtyRegion.bounds() : hw.bounds()); 943 composeSurfaces(repaint); 944 } 945 946 TextureManager::deactivateTextures(); 947 948 glDisable(GL_BLEND); 949 glDisable(GL_DITHER); 950 glDisable(GL_SCISSOR_TEST); 951 952 static int toggle = 0; 953 toggle = 1 - toggle; 954 if (toggle) { 955 glColor4f(1, 0, 1, 1); 956 } else { 957 glColor4f(1, 1, 0, 1); 958 } 959 960 Region::const_iterator it = mDirtyRegion.begin(); 961 Region::const_iterator const end = mDirtyRegion.end(); 962 while (it != end) { 963 const Rect& r = *it++; 964 GLfloat vertices[][2] = { 965 { r.left, r.top }, 966 { r.left, r.bottom }, 967 { r.right, r.bottom }, 968 { r.right, r.top } 969 }; 970 glVertexPointer(2, GL_FLOAT, 0, vertices); 971 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 972 } 973 974 if (mInvalidRegion.isEmpty()) { 975 mDirtyRegion.dump("mDirtyRegion"); 976 mInvalidRegion.dump("mInvalidRegion"); 977 } 978 hw.flip(mInvalidRegion); 979 980 if (mDebugRegion > 1) 981 usleep(mDebugRegion * 1000); 982 983 glEnable(GL_SCISSOR_TEST); 984 //mDirtyRegion.dump("mDirtyRegion"); 985} 986 987void SurfaceFlinger::drawWormhole() const 988{ 989 const Region region(mWormholeRegion.intersect(mDirtyRegion)); 990 if (region.isEmpty()) 991 return; 992 993 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 994 const int32_t width = hw.getWidth(); 995 const int32_t height = hw.getHeight(); 996 997 glDisable(GL_BLEND); 998 glDisable(GL_DITHER); 999 1000 if (LIKELY(!mDebugBackground)) { 1001 glClearColor(0,0,0,0); 1002 Region::const_iterator it = region.begin(); 1003 Region::const_iterator const end = region.end(); 1004 while (it != end) { 1005 const Rect& r = *it++; 1006 const GLint sy = height - (r.top + r.height()); 1007 glScissor(r.left, sy, r.width(), r.height()); 1008 glClear(GL_COLOR_BUFFER_BIT); 1009 } 1010 } else { 1011 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 }, 1012 { width, height }, { 0, height } }; 1013 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; 1014 glVertexPointer(2, GL_SHORT, 0, vertices); 1015 glTexCoordPointer(2, GL_SHORT, 0, tcoords); 1016 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1017#if defined(GL_OES_EGL_image_external) 1018 if (GLExtensions::getInstance().haveTextureExternal()) { 1019 glDisable(GL_TEXTURE_EXTERNAL_OES); 1020 } 1021#endif 1022 glEnable(GL_TEXTURE_2D); 1023 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 1024 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 1025 glMatrixMode(GL_TEXTURE); 1026 glLoadIdentity(); 1027 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1); 1028 Region::const_iterator it = region.begin(); 1029 Region::const_iterator const end = region.end(); 1030 while (it != end) { 1031 const Rect& r = *it++; 1032 const GLint sy = height - (r.top + r.height()); 1033 glScissor(r.left, sy, r.width(), r.height()); 1034 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1035 } 1036 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 1037 glLoadIdentity(); 1038 glMatrixMode(GL_MODELVIEW); 1039 } 1040} 1041 1042void SurfaceFlinger::debugShowFPS() const 1043{ 1044 static int mFrameCount; 1045 static int mLastFrameCount = 0; 1046 static nsecs_t mLastFpsTime = 0; 1047 static float mFps = 0; 1048 mFrameCount++; 1049 nsecs_t now = systemTime(); 1050 nsecs_t diff = now - mLastFpsTime; 1051 if (diff > ms2ns(250)) { 1052 mFps = ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff; 1053 mLastFpsTime = now; 1054 mLastFrameCount = mFrameCount; 1055 } 1056 // XXX: mFPS has the value we want 1057 } 1058 1059status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer) 1060{ 1061 Mutex::Autolock _l(mStateLock); 1062 addLayer_l(layer); 1063 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 1064 return NO_ERROR; 1065} 1066 1067status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer) 1068{ 1069 ssize_t i = mCurrentState.layersSortedByZ.add(layer); 1070 return (i < 0) ? status_t(i) : status_t(NO_ERROR); 1071} 1072 1073ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1074 const sp<LayerBaseClient>& lbc) 1075{ 1076 Mutex::Autolock _l(mStateLock); 1077 1078 // attach this layer to the client 1079 ssize_t name = client->attachLayer(lbc); 1080 1081 // add this layer to the current state list 1082 addLayer_l(lbc); 1083 1084 return name; 1085} 1086 1087status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1088{ 1089 Mutex::Autolock _l(mStateLock); 1090 status_t err = purgatorizeLayer_l(layer); 1091 if (err == NO_ERROR) 1092 setTransactionFlags(eTransactionNeeded); 1093 return err; 1094} 1095 1096status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1097{ 1098 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient()); 1099 if (lbc != 0) { 1100 mLayerMap.removeItem( lbc->getSurface()->asBinder() ); 1101 } 1102 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1103 if (index >= 0) { 1104 mLayersRemoved = true; 1105 return NO_ERROR; 1106 } 1107 return status_t(index); 1108} 1109 1110status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1111{ 1112 // First add the layer to the purgatory list, which makes sure it won't 1113 // go away, then remove it from the main list (through a transaction). 1114 ssize_t err = removeLayer_l(layerBase); 1115 if (err >= 0) { 1116 mLayerPurgatory.add(layerBase); 1117 } 1118 1119 layerBase->onRemoved(); 1120 1121 // it's possible that we don't find a layer, because it might 1122 // have been destroyed already -- this is not technically an error 1123 // from the user because there is a race between Client::destroySurface(), 1124 // ~Client() and ~ISurface(). 1125 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1126} 1127 1128status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer) 1129{ 1130 layer->forceVisibilityTransaction(); 1131 setTransactionFlags(eTraversalNeeded); 1132 return NO_ERROR; 1133} 1134 1135uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1136{ 1137 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1138} 1139 1140uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1141{ 1142 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1143 if ((old & flags)==0) { // wake the server up 1144 signalEvent(); 1145 } 1146 return old; 1147} 1148 1149void SurfaceFlinger::openGlobalTransaction() 1150{ 1151 android_atomic_inc(&mTransactionCount); 1152} 1153 1154void SurfaceFlinger::closeGlobalTransaction() 1155{ 1156 if (android_atomic_dec(&mTransactionCount) == 1) { 1157 signalEvent(); 1158 1159 // if there is a transaction with a resize, wait for it to 1160 // take effect before returning. 1161 Mutex::Autolock _l(mStateLock); 1162 while (mResizeTransationPending) { 1163 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1164 if (CC_UNLIKELY(err != NO_ERROR)) { 1165 // just in case something goes wrong in SF, return to the 1166 // called after a few seconds. 1167 LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1168 mResizeTransationPending = false; 1169 break; 1170 } 1171 } 1172 } 1173} 1174 1175status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags) 1176{ 1177 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1178 return BAD_VALUE; 1179 1180 Mutex::Autolock _l(mStateLock); 1181 mCurrentState.freezeDisplay = 1; 1182 setTransactionFlags(eTransactionNeeded); 1183 1184 // flags is intended to communicate some sort of animation behavior 1185 // (for instance fading) 1186 return NO_ERROR; 1187} 1188 1189status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags) 1190{ 1191 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1192 return BAD_VALUE; 1193 1194 Mutex::Autolock _l(mStateLock); 1195 mCurrentState.freezeDisplay = 0; 1196 setTransactionFlags(eTransactionNeeded); 1197 1198 // flags is intended to communicate some sort of animation behavior 1199 // (for instance fading) 1200 return NO_ERROR; 1201} 1202 1203int SurfaceFlinger::setOrientation(DisplayID dpy, 1204 int orientation, uint32_t flags) 1205{ 1206 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1207 return BAD_VALUE; 1208 1209 Mutex::Autolock _l(mStateLock); 1210 if (mCurrentState.orientation != orientation) { 1211 if (uint32_t(orientation)<=eOrientation270 || orientation==42) { 1212 mCurrentState.orientationType = flags; 1213 mCurrentState.orientation = orientation; 1214 setTransactionFlags(eTransactionNeeded); 1215 mTransactionCV.wait(mStateLock); 1216 } else { 1217 orientation = BAD_VALUE; 1218 } 1219 } 1220 return orientation; 1221} 1222 1223sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid, 1224 const String8& name, ISurfaceComposerClient::surface_data_t* params, 1225 DisplayID d, uint32_t w, uint32_t h, PixelFormat format, 1226 uint32_t flags) 1227{ 1228 sp<LayerBaseClient> layer; 1229 sp<LayerBaseClient::Surface> surfaceHandle; 1230 1231 if (int32_t(w|h) < 0) { 1232 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)", 1233 int(w), int(h)); 1234 return surfaceHandle; 1235 } 1236 1237 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h); 1238 sp<Layer> normalLayer; 1239 switch (flags & eFXSurfaceMask) { 1240 case eFXSurfaceNormal: 1241 normalLayer = createNormalSurface(client, d, w, h, flags, format); 1242 layer = normalLayer; 1243 break; 1244 case eFXSurfaceBlur: 1245 // for now we treat Blur as Dim, until we can implement it 1246 // efficiently. 1247 case eFXSurfaceDim: 1248 layer = createDimSurface(client, d, w, h, flags); 1249 break; 1250 } 1251 1252 if (layer != 0) { 1253 layer->initStates(w, h, flags); 1254 layer->setName(name); 1255 ssize_t token = addClientLayer(client, layer); 1256 1257 surfaceHandle = layer->getSurface(); 1258 if (surfaceHandle != 0) { 1259 params->token = token; 1260 params->identity = surfaceHandle->getIdentity(); 1261 params->width = w; 1262 params->height = h; 1263 params->format = format; 1264 if (normalLayer != 0) { 1265 Mutex::Autolock _l(mStateLock); 1266 mLayerMap.add(surfaceHandle->asBinder(), normalLayer); 1267 } 1268 } 1269 1270 setTransactionFlags(eTransactionNeeded); 1271 } 1272 1273 return surfaceHandle; 1274} 1275 1276sp<Layer> SurfaceFlinger::createNormalSurface( 1277 const sp<Client>& client, DisplayID display, 1278 uint32_t w, uint32_t h, uint32_t flags, 1279 PixelFormat& format) 1280{ 1281 // initialize the surfaces 1282 switch (format) { // TODO: take h/w into account 1283 case PIXEL_FORMAT_TRANSPARENT: 1284 case PIXEL_FORMAT_TRANSLUCENT: 1285 format = PIXEL_FORMAT_RGBA_8888; 1286 break; 1287 case PIXEL_FORMAT_OPAQUE: 1288#ifdef NO_RGBX_8888 1289 format = PIXEL_FORMAT_RGB_565; 1290#else 1291 format = PIXEL_FORMAT_RGBX_8888; 1292#endif 1293 break; 1294 } 1295 1296#ifdef NO_RGBX_8888 1297 if (format == PIXEL_FORMAT_RGBX_8888) 1298 format = PIXEL_FORMAT_RGBA_8888; 1299#endif 1300 1301 sp<Layer> layer = new Layer(this, display, client); 1302 status_t err = layer->setBuffers(w, h, format, flags); 1303 if (LIKELY(err != NO_ERROR)) { 1304 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err)); 1305 layer.clear(); 1306 } 1307 return layer; 1308} 1309 1310sp<LayerDim> SurfaceFlinger::createDimSurface( 1311 const sp<Client>& client, DisplayID display, 1312 uint32_t w, uint32_t h, uint32_t flags) 1313{ 1314 sp<LayerDim> layer = new LayerDim(this, display, client); 1315 layer->initStates(w, h, flags); 1316 return layer; 1317} 1318 1319status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) 1320{ 1321 /* 1322 * called by the window manager, when a surface should be marked for 1323 * destruction. 1324 * 1325 * The surface is removed from the current and drawing lists, but placed 1326 * in the purgatory queue, so it's not destroyed right-away (we need 1327 * to wait for all client's references to go away first). 1328 */ 1329 1330 status_t err = NAME_NOT_FOUND; 1331 Mutex::Autolock _l(mStateLock); 1332 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1333 if (layer != 0) { 1334 err = purgatorizeLayer_l(layer); 1335 if (err == NO_ERROR) { 1336 setTransactionFlags(eTransactionNeeded); 1337 } 1338 } 1339 return err; 1340} 1341 1342status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer) 1343{ 1344 // called by ~ISurface() when all references are gone 1345 1346 class MessageDestroySurface : public MessageBase { 1347 SurfaceFlinger* flinger; 1348 sp<LayerBaseClient> layer; 1349 public: 1350 MessageDestroySurface( 1351 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer) 1352 : flinger(flinger), layer(layer) { } 1353 virtual bool handler() { 1354 sp<LayerBaseClient> l(layer); 1355 layer.clear(); // clear it outside of the lock; 1356 Mutex::Autolock _l(flinger->mStateLock); 1357 /* 1358 * remove the layer from the current list -- chances are that it's 1359 * not in the list anyway, because it should have been removed 1360 * already upon request of the client (eg: window manager). 1361 * However, a buggy client could have not done that. 1362 * Since we know we don't have any more clients, we don't need 1363 * to use the purgatory. 1364 */ 1365 status_t err = flinger->removeLayer_l(l); 1366 if (err == NAME_NOT_FOUND) { 1367 // The surface wasn't in the current list, which means it was 1368 // removed already, which means it is in the purgatory, 1369 // and need to be removed from there. 1370 // This needs to happen from the main thread since its dtor 1371 // must run from there (b/c of OpenGL ES). Additionally, we 1372 // can't really acquire our internal lock from 1373 // destroySurface() -- see postMessage() below. 1374 ssize_t idx = flinger->mLayerPurgatory.remove(l); 1375 LOGE_IF(idx < 0, 1376 "layer=%p is not in the purgatory list", l.get()); 1377 } 1378 1379 LOGE_IF(err<0 && err != NAME_NOT_FOUND, 1380 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1381 return true; 1382 } 1383 }; 1384 1385 postMessageAsync( new MessageDestroySurface(this, layer) ); 1386 return NO_ERROR; 1387} 1388 1389status_t SurfaceFlinger::setClientState( 1390 const sp<Client>& client, 1391 int32_t count, 1392 const layer_state_t* states) 1393{ 1394 Mutex::Autolock _l(mStateLock); 1395 uint32_t flags = 0; 1396 for (int i=0 ; i<count ; i++) { 1397 const layer_state_t& s(states[i]); 1398 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1399 if (layer != 0) { 1400 const uint32_t what = s.what; 1401 if (what & ePositionChanged) { 1402 if (layer->setPosition(s.x, s.y)) 1403 flags |= eTraversalNeeded; 1404 } 1405 if (what & eLayerChanged) { 1406 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1407 if (layer->setLayer(s.z)) { 1408 mCurrentState.layersSortedByZ.removeAt(idx); 1409 mCurrentState.layersSortedByZ.add(layer); 1410 // we need traversal (state changed) 1411 // AND transaction (list changed) 1412 flags |= eTransactionNeeded|eTraversalNeeded; 1413 } 1414 } 1415 if (what & eSizeChanged) { 1416 if (layer->setSize(s.w, s.h)) { 1417 flags |= eTraversalNeeded; 1418 mResizeTransationPending = true; 1419 } 1420 } 1421 if (what & eAlphaChanged) { 1422 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1423 flags |= eTraversalNeeded; 1424 } 1425 if (what & eMatrixChanged) { 1426 if (layer->setMatrix(s.matrix)) 1427 flags |= eTraversalNeeded; 1428 } 1429 if (what & eTransparentRegionChanged) { 1430 if (layer->setTransparentRegionHint(s.transparentRegion)) 1431 flags |= eTraversalNeeded; 1432 } 1433 if (what & eVisibilityChanged) { 1434 if (layer->setFlags(s.flags, s.mask)) 1435 flags |= eTraversalNeeded; 1436 } 1437 } 1438 } 1439 if (flags) { 1440 setTransactionFlags(flags); 1441 } 1442 return NO_ERROR; 1443} 1444 1445void SurfaceFlinger::screenReleased(int dpy) 1446{ 1447 // this may be called by a signal handler, we can't do too much in here 1448 android_atomic_or(eConsoleReleased, &mConsoleSignals); 1449 signalEvent(); 1450} 1451 1452void SurfaceFlinger::screenAcquired(int dpy) 1453{ 1454 // this may be called by a signal handler, we can't do too much in here 1455 android_atomic_or(eConsoleAcquired, &mConsoleSignals); 1456 signalEvent(); 1457} 1458 1459status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 1460{ 1461 const size_t SIZE = 4096; 1462 char buffer[SIZE]; 1463 String8 result; 1464 if (!mDump.checkCalling()) { 1465 snprintf(buffer, SIZE, "Permission Denial: " 1466 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 1467 IPCThreadState::self()->getCallingPid(), 1468 IPCThreadState::self()->getCallingUid()); 1469 result.append(buffer); 1470 } else { 1471 1472 // figure out if we're stuck somewhere 1473 const nsecs_t now = systemTime(); 1474 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 1475 const nsecs_t inTransaction(mDebugInTransaction); 1476 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 1477 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 1478 1479 // Try to get the main lock, but don't insist if we can't 1480 // (this would indicate SF is stuck, but we want to be able to 1481 // print something in dumpsys). 1482 int retry = 3; 1483 while (mStateLock.tryLock()<0 && --retry>=0) { 1484 usleep(1000000); 1485 } 1486 const bool locked(retry >= 0); 1487 if (!locked) { 1488 snprintf(buffer, SIZE, 1489 "SurfaceFlinger appears to be unresponsive, " 1490 "dumping anyways (no locks held)\n"); 1491 result.append(buffer); 1492 } 1493 1494 /* 1495 * Dump the visible layer list 1496 */ 1497 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1498 const size_t count = currentLayers.size(); 1499 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 1500 result.append(buffer); 1501 for (size_t i=0 ; i<count ; i++) { 1502 const sp<LayerBase>& layer(currentLayers[i]); 1503 layer->dump(result, buffer, SIZE); 1504 const Layer::State& s(layer->drawingState()); 1505 s.transparentRegion.dump(result, "transparentRegion"); 1506 layer->transparentRegionScreen.dump(result, "transparentRegionScreen"); 1507 layer->visibleRegionScreen.dump(result, "visibleRegionScreen"); 1508 } 1509 1510 /* 1511 * Dump the layers in the purgatory 1512 */ 1513 1514 const size_t purgatorySize = mLayerPurgatory.size(); 1515 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 1516 result.append(buffer); 1517 for (size_t i=0 ; i<purgatorySize ; i++) { 1518 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 1519 layer->shortDump(result, buffer, SIZE); 1520 } 1521 1522 /* 1523 * Dump SurfaceFlinger global state 1524 */ 1525 1526 snprintf(buffer, SIZE, "SurfaceFlinger global state\n"); 1527 result.append(buffer); 1528 mWormholeRegion.dump(result, "WormholeRegion"); 1529 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1530 snprintf(buffer, SIZE, 1531 " display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n", 1532 mFreezeDisplay?"yes":"no", mFreezeCount, 1533 mCurrentState.orientation, hw.canDraw()); 1534 result.append(buffer); 1535 snprintf(buffer, SIZE, 1536 " last eglSwapBuffers() time: %f us\n" 1537 " last transaction time : %f us\n", 1538 mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0); 1539 result.append(buffer); 1540 1541 if (inSwapBuffersDuration || !locked) { 1542 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 1543 inSwapBuffersDuration/1000.0); 1544 result.append(buffer); 1545 } 1546 1547 if (inTransactionDuration || !locked) { 1548 snprintf(buffer, SIZE, " transaction time: %f us\n", 1549 inTransactionDuration/1000.0); 1550 result.append(buffer); 1551 } 1552 1553 /* 1554 * Dump HWComposer state 1555 */ 1556 HWComposer& hwc(hw.getHwComposer()); 1557 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 1558 hwc.initCheck()==NO_ERROR ? "present" : "not present", 1559 mDebugDisableHWC ? "disabled" : "enabled"); 1560 result.append(buffer); 1561 hwc.dump(result, buffer, SIZE); 1562 1563 /* 1564 * Dump gralloc state 1565 */ 1566 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 1567 alloc.dump(result); 1568 hw.dump(result); 1569 1570 if (locked) { 1571 mStateLock.unlock(); 1572 } 1573 } 1574 write(fd, result.string(), result.size()); 1575 return NO_ERROR; 1576} 1577 1578status_t SurfaceFlinger::onTransact( 1579 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 1580{ 1581 switch (code) { 1582 case CREATE_CONNECTION: 1583 case OPEN_GLOBAL_TRANSACTION: 1584 case CLOSE_GLOBAL_TRANSACTION: 1585 case SET_ORIENTATION: 1586 case FREEZE_DISPLAY: 1587 case UNFREEZE_DISPLAY: 1588 case BOOT_FINISHED: 1589 case TURN_ELECTRON_BEAM_OFF: 1590 case TURN_ELECTRON_BEAM_ON: 1591 { 1592 // codes that require permission check 1593 IPCThreadState* ipc = IPCThreadState::self(); 1594 const int pid = ipc->getCallingPid(); 1595 const int uid = ipc->getCallingUid(); 1596 if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) { 1597 LOGE("Permission Denial: " 1598 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1599 return PERMISSION_DENIED; 1600 } 1601 break; 1602 } 1603 case CAPTURE_SCREEN: 1604 { 1605 // codes that require permission check 1606 IPCThreadState* ipc = IPCThreadState::self(); 1607 const int pid = ipc->getCallingPid(); 1608 const int uid = ipc->getCallingUid(); 1609 if ((uid != AID_GRAPHICS) && !mReadFramebuffer.check(pid, uid)) { 1610 LOGE("Permission Denial: " 1611 "can't read framebuffer pid=%d, uid=%d", pid, uid); 1612 return PERMISSION_DENIED; 1613 } 1614 break; 1615 } 1616 } 1617 1618 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 1619 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 1620 CHECK_INTERFACE(ISurfaceComposer, data, reply); 1621 if (UNLIKELY(!mHardwareTest.checkCalling())) { 1622 IPCThreadState* ipc = IPCThreadState::self(); 1623 const int pid = ipc->getCallingPid(); 1624 const int uid = ipc->getCallingUid(); 1625 LOGE("Permission Denial: " 1626 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1627 return PERMISSION_DENIED; 1628 } 1629 int n; 1630 switch (code) { 1631 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 1632 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 1633 return NO_ERROR; 1634 case 1002: // SHOW_UPDATES 1635 n = data.readInt32(); 1636 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 1637 return NO_ERROR; 1638 case 1003: // SHOW_BACKGROUND 1639 n = data.readInt32(); 1640 mDebugBackground = n ? 1 : 0; 1641 return NO_ERROR; 1642 case 1008: // toggle use of hw composer 1643 n = data.readInt32(); 1644 mDebugDisableHWC = n ? 1 : 0; 1645 invalidateHwcGeometry(); 1646 // fall-through... 1647 case 1004:{ // repaint everything 1648 Mutex::Autolock _l(mStateLock); 1649 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1650 mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe 1651 signalEvent(); 1652 return NO_ERROR; 1653 } 1654 case 1005:{ // force transaction 1655 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 1656 return NO_ERROR; 1657 } 1658 case 1006:{ // enable/disable GraphicLog 1659 int enabled = data.readInt32(); 1660 GraphicLog::getInstance().setEnabled(enabled); 1661 return NO_ERROR; 1662 } 1663 case 1007: // set mFreezeCount 1664 mFreezeCount = data.readInt32(); 1665 mFreezeDisplayTime = 0; 1666 return NO_ERROR; 1667 case 1010: // interrogate. 1668 reply->writeInt32(0); 1669 reply->writeInt32(0); 1670 reply->writeInt32(mDebugRegion); 1671 reply->writeInt32(mDebugBackground); 1672 return NO_ERROR; 1673 case 1013: { 1674 Mutex::Autolock _l(mStateLock); 1675 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1676 reply->writeInt32(hw.getPageFlipCount()); 1677 } 1678 return NO_ERROR; 1679 } 1680 } 1681 return err; 1682} 1683 1684// --------------------------------------------------------------------------- 1685 1686status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, 1687 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 1688{ 1689 if (!GLExtensions::getInstance().haveFramebufferObject()) 1690 return INVALID_OPERATION; 1691 1692 // get screen geometry 1693 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 1694 const uint32_t hw_w = hw.getWidth(); 1695 const uint32_t hw_h = hw.getHeight(); 1696 GLfloat u = 1; 1697 GLfloat v = 1; 1698 1699 // make sure to clear all GL error flags 1700 while ( glGetError() != GL_NO_ERROR ) ; 1701 1702 // create a FBO 1703 GLuint name, tname; 1704 glGenTextures(1, &tname); 1705 glBindTexture(GL_TEXTURE_2D, tname); 1706 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1707 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1708 if (glGetError() != GL_NO_ERROR) { 1709 while ( glGetError() != GL_NO_ERROR ) ; 1710 GLint tw = (2 << (31 - clz(hw_w))); 1711 GLint th = (2 << (31 - clz(hw_h))); 1712 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1713 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1714 u = GLfloat(hw_w) / tw; 1715 v = GLfloat(hw_h) / th; 1716 } 1717 glGenFramebuffersOES(1, &name); 1718 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 1719 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 1720 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 1721 1722 // redraw the screen entirely... 1723 glClearColor(0,0,0,1); 1724 glClear(GL_COLOR_BUFFER_BIT); 1725 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 1726 const size_t count = layers.size(); 1727 for (size_t i=0 ; i<count ; ++i) { 1728 const sp<LayerBase>& layer(layers[i]); 1729 layer->drawForSreenShot(); 1730 } 1731 1732 // back to main framebuffer 1733 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1734 glDisable(GL_SCISSOR_TEST); 1735 glDeleteFramebuffersOES(1, &name); 1736 1737 *textureName = tname; 1738 *uOut = u; 1739 *vOut = v; 1740 return NO_ERROR; 1741} 1742 1743// --------------------------------------------------------------------------- 1744 1745status_t SurfaceFlinger::electronBeamOffAnimationImplLocked() 1746{ 1747 status_t result = PERMISSION_DENIED; 1748 1749 if (!GLExtensions::getInstance().haveFramebufferObject()) 1750 return INVALID_OPERATION; 1751 1752 // get screen geometry 1753 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1754 const uint32_t hw_w = hw.getWidth(); 1755 const uint32_t hw_h = hw.getHeight(); 1756 const Region screenBounds(hw.bounds()); 1757 1758 GLfloat u, v; 1759 GLuint tname; 1760 result = renderScreenToTextureLocked(0, &tname, &u, &v); 1761 if (result != NO_ERROR) { 1762 return result; 1763 } 1764 1765 GLfloat vtx[8]; 1766 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} }; 1767 glEnable(GL_TEXTURE_2D); 1768 glBindTexture(GL_TEXTURE_2D, tname); 1769 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 1770 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 1771 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1772 glTexCoordPointer(2, GL_FLOAT, 0, texCoords); 1773 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1774 glVertexPointer(2, GL_FLOAT, 0, vtx); 1775 1776 class s_curve_interpolator { 1777 const float nbFrames, s, v; 1778 public: 1779 s_curve_interpolator(int nbFrames, float s) 1780 : nbFrames(1.0f / (nbFrames-1)), s(s), 1781 v(1.0f + expf(-s + 0.5f*s)) { 1782 } 1783 float operator()(int f) { 1784 const float x = f * nbFrames; 1785 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; 1786 } 1787 }; 1788 1789 class v_stretch { 1790 const GLfloat hw_w, hw_h; 1791 public: 1792 v_stretch(uint32_t hw_w, uint32_t hw_h) 1793 : hw_w(hw_w), hw_h(hw_h) { 1794 } 1795 void operator()(GLfloat* vtx, float v) { 1796 const GLfloat w = hw_w + (hw_w * v); 1797 const GLfloat h = hw_h - (hw_h * v); 1798 const GLfloat x = (hw_w - w) * 0.5f; 1799 const GLfloat y = (hw_h - h) * 0.5f; 1800 vtx[0] = x; vtx[1] = y; 1801 vtx[2] = x; vtx[3] = y + h; 1802 vtx[4] = x + w; vtx[5] = y + h; 1803 vtx[6] = x + w; vtx[7] = y; 1804 } 1805 }; 1806 1807 class h_stretch { 1808 const GLfloat hw_w, hw_h; 1809 public: 1810 h_stretch(uint32_t hw_w, uint32_t hw_h) 1811 : hw_w(hw_w), hw_h(hw_h) { 1812 } 1813 void operator()(GLfloat* vtx, float v) { 1814 const GLfloat w = hw_w - (hw_w * v); 1815 const GLfloat h = 1.0f; 1816 const GLfloat x = (hw_w - w) * 0.5f; 1817 const GLfloat y = (hw_h - h) * 0.5f; 1818 vtx[0] = x; vtx[1] = y; 1819 vtx[2] = x; vtx[3] = y + h; 1820 vtx[4] = x + w; vtx[5] = y + h; 1821 vtx[6] = x + w; vtx[7] = y; 1822 } 1823 }; 1824 1825 // the full animation is 24 frames 1826 const int nbFrames = 12; 1827 s_curve_interpolator itr(nbFrames, 7.5f); 1828 s_curve_interpolator itg(nbFrames, 8.0f); 1829 s_curve_interpolator itb(nbFrames, 8.5f); 1830 1831 v_stretch vverts(hw_w, hw_h); 1832 glEnable(GL_BLEND); 1833 glBlendFunc(GL_ONE, GL_ONE); 1834 for (int i=0 ; i<nbFrames ; i++) { 1835 float x, y, w, h; 1836 const float vr = itr(i); 1837 const float vg = itg(i); 1838 const float vb = itb(i); 1839 1840 // clear screen 1841 glColorMask(1,1,1,1); 1842 glClear(GL_COLOR_BUFFER_BIT); 1843 glEnable(GL_TEXTURE_2D); 1844 1845 // draw the red plane 1846 vverts(vtx, vr); 1847 glColorMask(1,0,0,1); 1848 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1849 1850 // draw the green plane 1851 vverts(vtx, vg); 1852 glColorMask(0,1,0,1); 1853 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1854 1855 // draw the blue plane 1856 vverts(vtx, vb); 1857 glColorMask(0,0,1,1); 1858 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1859 1860 // draw the white highlight (we use the last vertices) 1861 glDisable(GL_TEXTURE_2D); 1862 glColorMask(1,1,1,1); 1863 glColor4f(vg, vg, vg, 1); 1864 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1865 hw.flip(screenBounds); 1866 } 1867 1868 h_stretch hverts(hw_w, hw_h); 1869 glDisable(GL_BLEND); 1870 glDisable(GL_TEXTURE_2D); 1871 glColorMask(1,1,1,1); 1872 for (int i=0 ; i<nbFrames ; i++) { 1873 const float v = itg(i); 1874 hverts(vtx, v); 1875 glClear(GL_COLOR_BUFFER_BIT); 1876 glColor4f(1-v, 1-v, 1-v, 1); 1877 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1878 hw.flip(screenBounds); 1879 } 1880 1881 glColorMask(1,1,1,1); 1882 glEnable(GL_SCISSOR_TEST); 1883 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 1884 glDeleteTextures(1, &tname); 1885 return NO_ERROR; 1886} 1887 1888status_t SurfaceFlinger::electronBeamOnAnimationImplLocked() 1889{ 1890 status_t result = PERMISSION_DENIED; 1891 1892 if (!GLExtensions::getInstance().haveFramebufferObject()) 1893 return INVALID_OPERATION; 1894 1895 1896 // get screen geometry 1897 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1898 const uint32_t hw_w = hw.getWidth(); 1899 const uint32_t hw_h = hw.getHeight(); 1900 const Region screenBounds(hw.bounds()); 1901 1902 GLfloat u, v; 1903 GLuint tname; 1904 result = renderScreenToTextureLocked(0, &tname, &u, &v); 1905 if (result != NO_ERROR) { 1906 return result; 1907 } 1908 1909 // back to main framebuffer 1910 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1911 glDisable(GL_SCISSOR_TEST); 1912 1913 GLfloat vtx[8]; 1914 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} }; 1915 glEnable(GL_TEXTURE_2D); 1916 glBindTexture(GL_TEXTURE_2D, tname); 1917 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); 1918 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 1919 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1920 glTexCoordPointer(2, GL_FLOAT, 0, texCoords); 1921 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1922 glVertexPointer(2, GL_FLOAT, 0, vtx); 1923 1924 class s_curve_interpolator { 1925 const float nbFrames, s, v; 1926 public: 1927 s_curve_interpolator(int nbFrames, float s) 1928 : nbFrames(1.0f / (nbFrames-1)), s(s), 1929 v(1.0f + expf(-s + 0.5f*s)) { 1930 } 1931 float operator()(int f) { 1932 const float x = f * nbFrames; 1933 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; 1934 } 1935 }; 1936 1937 class v_stretch { 1938 const GLfloat hw_w, hw_h; 1939 public: 1940 v_stretch(uint32_t hw_w, uint32_t hw_h) 1941 : hw_w(hw_w), hw_h(hw_h) { 1942 } 1943 void operator()(GLfloat* vtx, float v) { 1944 const GLfloat w = hw_w + (hw_w * v); 1945 const GLfloat h = hw_h - (hw_h * v); 1946 const GLfloat x = (hw_w - w) * 0.5f; 1947 const GLfloat y = (hw_h - h) * 0.5f; 1948 vtx[0] = x; vtx[1] = y; 1949 vtx[2] = x; vtx[3] = y + h; 1950 vtx[4] = x + w; vtx[5] = y + h; 1951 vtx[6] = x + w; vtx[7] = y; 1952 } 1953 }; 1954 1955 class h_stretch { 1956 const GLfloat hw_w, hw_h; 1957 public: 1958 h_stretch(uint32_t hw_w, uint32_t hw_h) 1959 : hw_w(hw_w), hw_h(hw_h) { 1960 } 1961 void operator()(GLfloat* vtx, float v) { 1962 const GLfloat w = hw_w - (hw_w * v); 1963 const GLfloat h = 1.0f; 1964 const GLfloat x = (hw_w - w) * 0.5f; 1965 const GLfloat y = (hw_h - h) * 0.5f; 1966 vtx[0] = x; vtx[1] = y; 1967 vtx[2] = x; vtx[3] = y + h; 1968 vtx[4] = x + w; vtx[5] = y + h; 1969 vtx[6] = x + w; vtx[7] = y; 1970 } 1971 }; 1972 1973 // the full animation is 12 frames 1974 int nbFrames = 8; 1975 s_curve_interpolator itr(nbFrames, 7.5f); 1976 s_curve_interpolator itg(nbFrames, 8.0f); 1977 s_curve_interpolator itb(nbFrames, 8.5f); 1978 1979 h_stretch hverts(hw_w, hw_h); 1980 glDisable(GL_BLEND); 1981 glDisable(GL_TEXTURE_2D); 1982 glColorMask(1,1,1,1); 1983 for (int i=nbFrames-1 ; i>=0 ; i--) { 1984 const float v = itg(i); 1985 hverts(vtx, v); 1986 glClear(GL_COLOR_BUFFER_BIT); 1987 glColor4f(1-v, 1-v, 1-v, 1); 1988 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1989 hw.flip(screenBounds); 1990 } 1991 1992 nbFrames = 4; 1993 v_stretch vverts(hw_w, hw_h); 1994 glEnable(GL_BLEND); 1995 glBlendFunc(GL_ONE, GL_ONE); 1996 for (int i=nbFrames-1 ; i>=0 ; i--) { 1997 float x, y, w, h; 1998 const float vr = itr(i); 1999 const float vg = itg(i); 2000 const float vb = itb(i); 2001 2002 // clear screen 2003 glColorMask(1,1,1,1); 2004 glClear(GL_COLOR_BUFFER_BIT); 2005 glEnable(GL_TEXTURE_2D); 2006 2007 // draw the red plane 2008 vverts(vtx, vr); 2009 glColorMask(1,0,0,1); 2010 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2011 2012 // draw the green plane 2013 vverts(vtx, vg); 2014 glColorMask(0,1,0,1); 2015 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2016 2017 // draw the blue plane 2018 vverts(vtx, vb); 2019 glColorMask(0,0,1,1); 2020 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2021 2022 hw.flip(screenBounds); 2023 } 2024 2025 glColorMask(1,1,1,1); 2026 glEnable(GL_SCISSOR_TEST); 2027 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 2028 glDeleteTextures(1, &tname); 2029 2030 return NO_ERROR; 2031} 2032 2033// --------------------------------------------------------------------------- 2034 2035status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode) 2036{ 2037 DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); 2038 if (!hw.canDraw()) { 2039 // we're already off 2040 return NO_ERROR; 2041 } 2042 if (mode & ISurfaceComposer::eElectronBeamAnimationOff) { 2043 electronBeamOffAnimationImplLocked(); 2044 } 2045 2046 // always clear the whole screen at the end of the animation 2047 glClearColor(0,0,0,1); 2048 glDisable(GL_SCISSOR_TEST); 2049 glClear(GL_COLOR_BUFFER_BIT); 2050 glEnable(GL_SCISSOR_TEST); 2051 hw.flip( Region(hw.bounds()) ); 2052 2053 hw.setCanDraw(false); 2054 return NO_ERROR; 2055} 2056 2057status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode) 2058{ 2059 class MessageTurnElectronBeamOff : public MessageBase { 2060 SurfaceFlinger* flinger; 2061 int32_t mode; 2062 status_t result; 2063 public: 2064 MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode) 2065 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { 2066 } 2067 status_t getResult() const { 2068 return result; 2069 } 2070 virtual bool handler() { 2071 Mutex::Autolock _l(flinger->mStateLock); 2072 result = flinger->turnElectronBeamOffImplLocked(mode); 2073 return true; 2074 } 2075 }; 2076 2077 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode); 2078 status_t res = postMessageSync(msg); 2079 if (res == NO_ERROR) { 2080 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult(); 2081 2082 // work-around: when the power-manager calls us we activate the 2083 // animation. eventually, the "on" animation will be called 2084 // by the power-manager itself 2085 mElectronBeamAnimationMode = mode; 2086 } 2087 return res; 2088} 2089 2090// --------------------------------------------------------------------------- 2091 2092status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode) 2093{ 2094 DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); 2095 if (hw.canDraw()) { 2096 // we're already on 2097 return NO_ERROR; 2098 } 2099 if (mode & ISurfaceComposer::eElectronBeamAnimationOn) { 2100 electronBeamOnAnimationImplLocked(); 2101 } 2102 hw.setCanDraw(true); 2103 2104 // make sure to redraw the whole screen when the animation is done 2105 mDirtyRegion.set(hw.bounds()); 2106 signalEvent(); 2107 2108 return NO_ERROR; 2109} 2110 2111status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode) 2112{ 2113 class MessageTurnElectronBeamOn : public MessageBase { 2114 SurfaceFlinger* flinger; 2115 int32_t mode; 2116 status_t result; 2117 public: 2118 MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode) 2119 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { 2120 } 2121 status_t getResult() const { 2122 return result; 2123 } 2124 virtual bool handler() { 2125 Mutex::Autolock _l(flinger->mStateLock); 2126 result = flinger->turnElectronBeamOnImplLocked(mode); 2127 return true; 2128 } 2129 }; 2130 2131 postMessageAsync( new MessageTurnElectronBeamOn(this, mode) ); 2132 return NO_ERROR; 2133} 2134 2135// --------------------------------------------------------------------------- 2136 2137status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, 2138 sp<IMemoryHeap>* heap, 2139 uint32_t* w, uint32_t* h, PixelFormat* f, 2140 uint32_t sw, uint32_t sh, 2141 uint32_t minLayerZ, uint32_t maxLayerZ) 2142{ 2143 status_t result = PERMISSION_DENIED; 2144 2145 // only one display supported for now 2146 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 2147 return BAD_VALUE; 2148 2149 if (!GLExtensions::getInstance().haveFramebufferObject()) 2150 return INVALID_OPERATION; 2151 2152 // get screen geometry 2153 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 2154 const uint32_t hw_w = hw.getWidth(); 2155 const uint32_t hw_h = hw.getHeight(); 2156 2157 if ((sw > hw_w) || (sh > hw_h)) 2158 return BAD_VALUE; 2159 2160 sw = (!sw) ? hw_w : sw; 2161 sh = (!sh) ? hw_h : sh; 2162 const size_t size = sw * sh * 4; 2163 2164 LOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2165 sw, sh, minLayerZ, maxLayerZ); 2166 2167 // make sure to clear all GL error flags 2168 while ( glGetError() != GL_NO_ERROR ) ; 2169 2170 // create a FBO 2171 GLuint name, tname; 2172 glGenRenderbuffersOES(1, &tname); 2173 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2174 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2175 glGenFramebuffersOES(1, &name); 2176 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2177 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2178 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2179 2180 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2181 2182 LOGD("screenshot: FBO created, status=0x%x", status); 2183 2184 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2185 2186 // invert everything, b/c glReadPixel() below will invert the FB 2187 glViewport(0, 0, sw, sh); 2188 glScissor(0, 0, sw, sh); 2189 glMatrixMode(GL_PROJECTION); 2190 glPushMatrix(); 2191 glLoadIdentity(); 2192 glOrthof(0, hw_w, 0, hw_h, 0, 1); 2193 glMatrixMode(GL_MODELVIEW); 2194 2195 // redraw the screen entirely... 2196 glClearColor(0,0,0,1); 2197 glClear(GL_COLOR_BUFFER_BIT); 2198 2199 LOGD("screenshot: glClear() issued"); 2200 2201 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 2202 const size_t count = layers.size(); 2203 for (size_t i=0 ; i<count ; ++i) { 2204 const sp<LayerBase>& layer(layers[i]); 2205 const uint32_t z = layer->drawingState().z; 2206 if (z >= minLayerZ && z <= maxLayerZ) { 2207 layer->drawForSreenShot(); 2208 } 2209 } 2210 2211 LOGD("screenshot: All layers rendered"); 2212 2213 // XXX: this is needed on tegra 2214 glScissor(0, 0, sw, sh); 2215 2216 // check for errors and return screen capture 2217 if (glGetError() != GL_NO_ERROR) { 2218 // error while rendering 2219 result = INVALID_OPERATION; 2220 } else { 2221 // allocate shared memory large enough to hold the 2222 // screen capture 2223 sp<MemoryHeapBase> base( 2224 new MemoryHeapBase(size, 0, "screen-capture") ); 2225 void* const ptr = base->getBase(); 2226 if (ptr) { 2227 2228 LOGD("screenshot: about to call glReadPixels(0,0,%d,%d,...,%p)", 2229 sw, sh, ptr); 2230 2231 // capture the screen with glReadPixels() 2232 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2233 if (glGetError() == GL_NO_ERROR) { 2234 *heap = base; 2235 *w = sw; 2236 *h = sh; 2237 *f = PIXEL_FORMAT_RGBA_8888; 2238 result = NO_ERROR; 2239 } 2240 } else { 2241 result = NO_MEMORY; 2242 } 2243 2244 LOGD("screenshot: glReadPixels() returned %s", strerror(result)); 2245 2246 } 2247 glEnable(GL_SCISSOR_TEST); 2248 glViewport(0, 0, hw_w, hw_h); 2249 glMatrixMode(GL_PROJECTION); 2250 glPopMatrix(); 2251 glMatrixMode(GL_MODELVIEW); 2252 } else { 2253 result = BAD_VALUE; 2254 } 2255 2256 LOGD("screenshot: about to release FBO resources"); 2257 2258 // release FBO resources 2259 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2260 glDeleteRenderbuffersOES(1, &tname); 2261 glDeleteFramebuffersOES(1, &name); 2262 2263 LOGD("screenshot: about to call compositionComplete()"); 2264 2265 hw.compositionComplete(); 2266 2267 LOGD("screenshot: result = %s", strerror(result)); 2268 2269 return result; 2270} 2271 2272 2273status_t SurfaceFlinger::captureScreen(DisplayID dpy, 2274 sp<IMemoryHeap>* heap, 2275 uint32_t* width, uint32_t* height, PixelFormat* format, 2276 uint32_t sw, uint32_t sh, 2277 uint32_t minLayerZ, uint32_t maxLayerZ) 2278{ 2279 // only one display supported for now 2280 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 2281 return BAD_VALUE; 2282 2283 if (!GLExtensions::getInstance().haveFramebufferObject()) 2284 return INVALID_OPERATION; 2285 2286 class MessageCaptureScreen : public MessageBase { 2287 SurfaceFlinger* flinger; 2288 DisplayID dpy; 2289 sp<IMemoryHeap>* heap; 2290 uint32_t* w; 2291 uint32_t* h; 2292 PixelFormat* f; 2293 uint32_t sw; 2294 uint32_t sh; 2295 uint32_t minLayerZ; 2296 uint32_t maxLayerZ; 2297 status_t result; 2298 public: 2299 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy, 2300 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2301 uint32_t sw, uint32_t sh, 2302 uint32_t minLayerZ, uint32_t maxLayerZ) 2303 : flinger(flinger), dpy(dpy), 2304 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2305 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2306 result(PERMISSION_DENIED) 2307 { 2308 } 2309 status_t getResult() const { 2310 return result; 2311 } 2312 virtual bool handler() { 2313 Mutex::Autolock _l(flinger->mStateLock); 2314 2315 // if we have secure windows, never allow the screen capture 2316 if (flinger->mSecureFrameBuffer) 2317 return true; 2318 2319 result = flinger->captureScreenImplLocked(dpy, 2320 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2321 2322 return true; 2323 } 2324 }; 2325 2326 sp<MessageBase> msg = new MessageCaptureScreen(this, 2327 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2328 status_t res = postMessageSync(msg); 2329 if (res == NO_ERROR) { 2330 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2331 } 2332 return res; 2333} 2334 2335// --------------------------------------------------------------------------- 2336 2337sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const 2338{ 2339 sp<Layer> result; 2340 Mutex::Autolock _l(mStateLock); 2341 result = mLayerMap.valueFor( sur->asBinder() ).promote(); 2342 return result; 2343} 2344 2345// --------------------------------------------------------------------------- 2346 2347Client::Client(const sp<SurfaceFlinger>& flinger) 2348 : mFlinger(flinger), mNameGenerator(1) 2349{ 2350} 2351 2352Client::~Client() 2353{ 2354 const size_t count = mLayers.size(); 2355 for (size_t i=0 ; i<count ; i++) { 2356 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote()); 2357 if (layer != 0) { 2358 mFlinger->removeLayer(layer); 2359 } 2360 } 2361} 2362 2363status_t Client::initCheck() const { 2364 return NO_ERROR; 2365} 2366 2367ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer) 2368{ 2369 int32_t name = android_atomic_inc(&mNameGenerator); 2370 mLayers.add(name, layer); 2371 return name; 2372} 2373 2374void Client::detachLayer(const LayerBaseClient* layer) 2375{ 2376 // we do a linear search here, because this doesn't happen often 2377 const size_t count = mLayers.size(); 2378 for (size_t i=0 ; i<count ; i++) { 2379 if (mLayers.valueAt(i) == layer) { 2380 mLayers.removeItemsAt(i, 1); 2381 break; 2382 } 2383 } 2384} 2385sp<LayerBaseClient> Client::getLayerUser(int32_t i) const { 2386 sp<LayerBaseClient> lbc; 2387 const wp<LayerBaseClient>& layer(mLayers.valueFor(i)); 2388 if (layer != 0) { 2389 lbc = layer.promote(); 2390 LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i)); 2391 } 2392 return lbc; 2393} 2394 2395sp<IMemoryHeap> Client::getControlBlock() const { 2396 return 0; 2397} 2398ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const { 2399 return -1; 2400} 2401sp<ISurface> Client::createSurface( 2402 ISurfaceComposerClient::surface_data_t* params, int pid, 2403 const String8& name, 2404 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2405 uint32_t flags) 2406{ 2407 return mFlinger->createSurface(this, pid, name, params, 2408 display, w, h, format, flags); 2409} 2410status_t Client::destroySurface(SurfaceID sid) { 2411 return mFlinger->removeSurface(this, sid); 2412} 2413status_t Client::setState(int32_t count, const layer_state_t* states) { 2414 return mFlinger->setClientState(this, count, states); 2415} 2416 2417// --------------------------------------------------------------------------- 2418 2419UserClient::UserClient(const sp<SurfaceFlinger>& flinger) 2420 : ctrlblk(0), mBitmap(0), mFlinger(flinger) 2421{ 2422 const int pgsize = getpagesize(); 2423 const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1)); 2424 2425 mCblkHeap = new MemoryHeapBase(cblksize, 0, 2426 "SurfaceFlinger Client control-block"); 2427 2428 ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase()); 2429 if (ctrlblk) { // construct the shared structure in-place. 2430 new(ctrlblk) SharedClient; 2431 } 2432} 2433 2434UserClient::~UserClient() 2435{ 2436 if (ctrlblk) { 2437 ctrlblk->~SharedClient(); // destroy our shared-structure. 2438 } 2439 2440 /* 2441 * When a UserClient dies, it's unclear what to do exactly. 2442 * We could go ahead and destroy all surfaces linked to that client 2443 * however, it wouldn't be fair to the main Client 2444 * (usually the the window-manager), which might want to re-target 2445 * the layer to another UserClient. 2446 * I think the best is to do nothing, or not much; in most cases the 2447 * WM itself will go ahead and clean things up when it detects a client of 2448 * his has died. 2449 * The remaining question is what to display? currently we keep 2450 * just keep the current buffer. 2451 */ 2452} 2453 2454status_t UserClient::initCheck() const { 2455 return ctrlblk == 0 ? NO_INIT : NO_ERROR; 2456} 2457 2458void UserClient::detachLayer(const Layer* layer) 2459{ 2460 int32_t name = layer->getToken(); 2461 if (name >= 0) { 2462 int32_t mask = 1LU<<name; 2463 if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) { 2464 LOGW("token %d wasn't marked as used %08x", name, int(mBitmap)); 2465 } 2466 } 2467} 2468 2469sp<IMemoryHeap> UserClient::getControlBlock() const { 2470 return mCblkHeap; 2471} 2472 2473ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const 2474{ 2475 int32_t name = NAME_NOT_FOUND; 2476 sp<Layer> layer(mFlinger->getLayer(sur)); 2477 if (layer == 0) { 2478 return name; 2479 } 2480 2481 // if this layer already has a token, just return it 2482 name = layer->getToken(); 2483 if ((name >= 0) && (layer->getClient() == this)) { 2484 return name; 2485 } 2486 2487 name = 0; 2488 do { 2489 int32_t mask = 1LU<<name; 2490 if ((android_atomic_or(mask, &mBitmap) & mask) == 0) { 2491 // we found and locked that name 2492 status_t err = layer->setToken( 2493 const_cast<UserClient*>(this), ctrlblk, name); 2494 if (err != NO_ERROR) { 2495 // free the name 2496 android_atomic_and(~mask, &mBitmap); 2497 name = err; 2498 } 2499 break; 2500 } 2501 if (++name > 31) 2502 name = NO_MEMORY; 2503 } while(name >= 0); 2504 2505 //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)", 2506 // sur->asBinder().get(), name, this, mBitmap); 2507 return name; 2508} 2509 2510sp<ISurface> UserClient::createSurface( 2511 ISurfaceComposerClient::surface_data_t* params, int pid, 2512 const String8& name, 2513 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2514 uint32_t flags) { 2515 return 0; 2516} 2517status_t UserClient::destroySurface(SurfaceID sid) { 2518 return INVALID_OPERATION; 2519} 2520status_t UserClient::setState(int32_t count, const layer_state_t* states) { 2521 return INVALID_OPERATION; 2522} 2523 2524// --------------------------------------------------------------------------- 2525 2526GraphicBufferAlloc::GraphicBufferAlloc() {} 2527 2528GraphicBufferAlloc::~GraphicBufferAlloc() {} 2529 2530sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h, 2531 PixelFormat format, uint32_t usage) { 2532 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage)); 2533 status_t err = graphicBuffer->initCheck(); 2534 if (err != 0) { 2535 LOGE("createGraphicBuffer: init check failed: %d", err); 2536 return 0; 2537 } else if (graphicBuffer->handle == 0) { 2538 LOGE("createGraphicBuffer: unable to create GraphicBuffer"); 2539 return 0; 2540 } 2541 Mutex::Autolock _l(mLock); 2542 mBuffers.add(graphicBuffer); 2543 return graphicBuffer; 2544} 2545 2546void GraphicBufferAlloc::freeAllGraphicBuffersExcept(int bufIdx) { 2547 Mutex::Autolock _l(mLock); 2548 if (0 <= bufIdx && bufIdx < mBuffers.size()) { 2549 sp<GraphicBuffer> b(mBuffers[bufIdx]); 2550 mBuffers.clear(); 2551 mBuffers.add(b); 2552 } else { 2553 mBuffers.clear(); 2554 } 2555} 2556 2557// --------------------------------------------------------------------------- 2558 2559GraphicPlane::GraphicPlane() 2560 : mHw(0) 2561{ 2562} 2563 2564GraphicPlane::~GraphicPlane() { 2565 delete mHw; 2566} 2567 2568bool GraphicPlane::initialized() const { 2569 return mHw ? true : false; 2570} 2571 2572int GraphicPlane::getWidth() const { 2573 return mWidth; 2574} 2575 2576int GraphicPlane::getHeight() const { 2577 return mHeight; 2578} 2579 2580void GraphicPlane::setDisplayHardware(DisplayHardware *hw) 2581{ 2582 mHw = hw; 2583 2584 // initialize the display orientation transform. 2585 // it's a constant that should come from the display driver. 2586 int displayOrientation = ISurfaceComposer::eOrientationDefault; 2587 char property[PROPERTY_VALUE_MAX]; 2588 if (property_get("ro.sf.hwrotation", property, NULL) > 0) { 2589 //displayOrientation 2590 switch (atoi(property)) { 2591 case 90: 2592 displayOrientation = ISurfaceComposer::eOrientation90; 2593 break; 2594 case 270: 2595 displayOrientation = ISurfaceComposer::eOrientation270; 2596 break; 2597 } 2598 } 2599 2600 const float w = hw->getWidth(); 2601 const float h = hw->getHeight(); 2602 GraphicPlane::orientationToTransfrom(displayOrientation, w, h, 2603 &mDisplayTransform); 2604 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) { 2605 mDisplayWidth = h; 2606 mDisplayHeight = w; 2607 } else { 2608 mDisplayWidth = w; 2609 mDisplayHeight = h; 2610 } 2611 2612 setOrientation(ISurfaceComposer::eOrientationDefault); 2613} 2614 2615status_t GraphicPlane::orientationToTransfrom( 2616 int orientation, int w, int h, Transform* tr) 2617{ 2618 uint32_t flags = 0; 2619 switch (orientation) { 2620 case ISurfaceComposer::eOrientationDefault: 2621 flags = Transform::ROT_0; 2622 break; 2623 case ISurfaceComposer::eOrientation90: 2624 flags = Transform::ROT_90; 2625 break; 2626 case ISurfaceComposer::eOrientation180: 2627 flags = Transform::ROT_180; 2628 break; 2629 case ISurfaceComposer::eOrientation270: 2630 flags = Transform::ROT_270; 2631 break; 2632 default: 2633 return BAD_VALUE; 2634 } 2635 tr->set(flags, w, h); 2636 return NO_ERROR; 2637} 2638 2639status_t GraphicPlane::setOrientation(int orientation) 2640{ 2641 // If the rotation can be handled in hardware, this is where 2642 // the magic should happen. 2643 2644 const DisplayHardware& hw(displayHardware()); 2645 const float w = mDisplayWidth; 2646 const float h = mDisplayHeight; 2647 mWidth = int(w); 2648 mHeight = int(h); 2649 2650 Transform orientationTransform; 2651 GraphicPlane::orientationToTransfrom(orientation, w, h, 2652 &orientationTransform); 2653 if (orientation & ISurfaceComposer::eOrientationSwapMask) { 2654 mWidth = int(h); 2655 mHeight = int(w); 2656 } 2657 2658 mOrientation = orientation; 2659 mGlobalTransform = mDisplayTransform * orientationTransform; 2660 return NO_ERROR; 2661} 2662 2663const DisplayHardware& GraphicPlane::displayHardware() const { 2664 return *mHw; 2665} 2666 2667DisplayHardware& GraphicPlane::editDisplayHardware() { 2668 return *mHw; 2669} 2670 2671const Transform& GraphicPlane::transform() const { 2672 return mGlobalTransform; 2673} 2674 2675EGLDisplay GraphicPlane::getEGLDisplay() const { 2676 return mHw->getEGLDisplay(); 2677} 2678 2679// --------------------------------------------------------------------------- 2680 2681}; // namespace android 2682