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