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