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