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