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