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