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