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