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