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