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