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