SurfaceFlinger.cpp revision 4b2ba53423ac2dc795a5a0bf72f6d787d9dc8950
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 /* 1017 * and then, render the layers targeted at the framebuffer 1018 */ 1019 1020 hwc_layer_t* const cur(hwc.getLayers()); 1021 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 1022 size_t count = layers.size(); 1023 1024 1025 // FIXME: workaround for b/6020860 1026 if (hw.getFlags() & DisplayHardware::BUFFER_PRESERVED) { 1027 for (size_t i=0 ; i<count ; i++) { 1028 if (cur && (cur[i].compositionType == HWC_FRAMEBUFFER)) { 1029 glEnable(GL_SCISSOR_TEST); 1030 glScissor(0,0,0,0); 1031 glClear(GL_COLOR_BUFFER_BIT); 1032 break; 1033 } 1034 } 1035 } 1036 // FIXME: bug6020860 for b/6020860 1037 1038 1039 for (size_t i=0 ; i<count ; i++) { 1040 if (cur && (cur[i].compositionType != HWC_FRAMEBUFFER)) { 1041 continue; 1042 } 1043 const sp<LayerBase>& layer(layers[i]); 1044 const Region clip(dirty.intersect(layer->visibleRegionScreen)); 1045 if (!clip.isEmpty()) { 1046 layer->draw(clip); 1047 } 1048 } 1049} 1050 1051void SurfaceFlinger::debugFlashRegions() 1052{ 1053 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1054 const uint32_t flags = hw.getFlags(); 1055 const int32_t height = hw.getHeight(); 1056 if (mSwapRegion.isEmpty()) { 1057 return; 1058 } 1059 1060 if (!((flags & DisplayHardware::SWAP_RECTANGLE) || 1061 (flags & DisplayHardware::BUFFER_PRESERVED))) { 1062 const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ? 1063 mDirtyRegion.bounds() : hw.bounds()); 1064 composeSurfaces(repaint); 1065 } 1066 1067 glDisable(GL_TEXTURE_EXTERNAL_OES); 1068 glDisable(GL_TEXTURE_2D); 1069 glDisable(GL_BLEND); 1070 glDisable(GL_SCISSOR_TEST); 1071 1072 static int toggle = 0; 1073 toggle = 1 - toggle; 1074 if (toggle) { 1075 glColor4f(1, 0, 1, 1); 1076 } else { 1077 glColor4f(1, 1, 0, 1); 1078 } 1079 1080 Region::const_iterator it = mDirtyRegion.begin(); 1081 Region::const_iterator const end = mDirtyRegion.end(); 1082 while (it != end) { 1083 const Rect& r = *it++; 1084 GLfloat vertices[][2] = { 1085 { r.left, height - r.top }, 1086 { r.left, height - r.bottom }, 1087 { r.right, height - r.bottom }, 1088 { r.right, height - r.top } 1089 }; 1090 glVertexPointer(2, GL_FLOAT, 0, vertices); 1091 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1092 } 1093 1094 hw.flip(mSwapRegion); 1095 1096 if (mDebugRegion > 1) 1097 usleep(mDebugRegion * 1000); 1098 1099 glEnable(GL_SCISSOR_TEST); 1100} 1101 1102void SurfaceFlinger::drawWormhole() const 1103{ 1104 const Region region(mWormholeRegion.intersect(mDirtyRegion)); 1105 if (region.isEmpty()) 1106 return; 1107 1108 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1109 const int32_t width = hw.getWidth(); 1110 const int32_t height = hw.getHeight(); 1111 1112 if (CC_LIKELY(!mDebugBackground)) { 1113 glClearColor(0,0,0,0); 1114 Region::const_iterator it = region.begin(); 1115 Region::const_iterator const end = region.end(); 1116 while (it != end) { 1117 const Rect& r = *it++; 1118 const GLint sy = height - (r.top + r.height()); 1119 glScissor(r.left, sy, r.width(), r.height()); 1120 glClear(GL_COLOR_BUFFER_BIT); 1121 } 1122 } else { 1123 const GLshort vertices[][2] = { { 0, 0 }, { width, 0 }, 1124 { width, height }, { 0, height } }; 1125 const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 }, { 1, 1 }, { 0, 1 } }; 1126 1127 glVertexPointer(2, GL_SHORT, 0, vertices); 1128 glTexCoordPointer(2, GL_SHORT, 0, tcoords); 1129 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1130 1131 glDisable(GL_TEXTURE_EXTERNAL_OES); 1132 glEnable(GL_TEXTURE_2D); 1133 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 1134 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 1135 glMatrixMode(GL_TEXTURE); 1136 glLoadIdentity(); 1137 1138 glDisable(GL_BLEND); 1139 1140 glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1); 1141 Region::const_iterator it = region.begin(); 1142 Region::const_iterator const end = region.end(); 1143 while (it != end) { 1144 const Rect& r = *it++; 1145 const GLint sy = height - (r.top + r.height()); 1146 glScissor(r.left, sy, r.width(), r.height()); 1147 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 1148 } 1149 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 1150 glDisable(GL_TEXTURE_2D); 1151 glLoadIdentity(); 1152 glMatrixMode(GL_MODELVIEW); 1153 } 1154} 1155 1156status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer) 1157{ 1158 Mutex::Autolock _l(mStateLock); 1159 addLayer_l(layer); 1160 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 1161 return NO_ERROR; 1162} 1163 1164status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer) 1165{ 1166 ssize_t i = mCurrentState.layersSortedByZ.add(layer); 1167 return (i < 0) ? status_t(i) : status_t(NO_ERROR); 1168} 1169 1170ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1171 const sp<LayerBaseClient>& lbc) 1172{ 1173 // attach this layer to the client 1174 size_t name = client->attachLayer(lbc); 1175 1176 Mutex::Autolock _l(mStateLock); 1177 1178 // add this layer to the current state list 1179 addLayer_l(lbc); 1180 1181 return ssize_t(name); 1182} 1183 1184status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1185{ 1186 Mutex::Autolock _l(mStateLock); 1187 status_t err = purgatorizeLayer_l(layer); 1188 if (err == NO_ERROR) 1189 setTransactionFlags(eTransactionNeeded); 1190 return err; 1191} 1192 1193status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1194{ 1195 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient()); 1196 if (lbc != 0) { 1197 mLayerMap.removeItem( lbc->getSurfaceBinder() ); 1198 } 1199 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1200 if (index >= 0) { 1201 mLayersRemoved = true; 1202 return NO_ERROR; 1203 } 1204 return status_t(index); 1205} 1206 1207status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1208{ 1209 // First add the layer to the purgatory list, which makes sure it won't 1210 // go away, then remove it from the main list (through a transaction). 1211 ssize_t err = removeLayer_l(layerBase); 1212 if (err >= 0) { 1213 mLayerPurgatory.add(layerBase); 1214 } 1215 1216 mLayersPendingRemoval.push(layerBase); 1217 1218 // it's possible that we don't find a layer, because it might 1219 // have been destroyed already -- this is not technically an error 1220 // from the user because there is a race between Client::destroySurface(), 1221 // ~Client() and ~ISurface(). 1222 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1223} 1224 1225status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer) 1226{ 1227 layer->forceVisibilityTransaction(); 1228 setTransactionFlags(eTraversalNeeded); 1229 return NO_ERROR; 1230} 1231 1232uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) 1233{ 1234 return android_atomic_release_load(&mTransactionFlags); 1235} 1236 1237uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1238{ 1239 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1240} 1241 1242uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1243{ 1244 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1245 if ((old & flags)==0) { // wake the server up 1246 signalTransaction(); 1247 } 1248 return old; 1249} 1250 1251 1252void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& state, 1253 int orientation, uint32_t flags) { 1254 Mutex::Autolock _l(mStateLock); 1255 1256 uint32_t transactionFlags = 0; 1257 if (mCurrentState.orientation != orientation) { 1258 if (uint32_t(orientation)<=eOrientation270 || orientation==42) { 1259 mCurrentState.orientation = orientation; 1260 transactionFlags |= eTransactionNeeded; 1261 } else if (orientation != eOrientationUnchanged) { 1262 ALOGW("setTransactionState: ignoring unrecognized orientation: %d", 1263 orientation); 1264 } 1265 } 1266 1267 const size_t count = state.size(); 1268 for (size_t i=0 ; i<count ; i++) { 1269 const ComposerState& s(state[i]); 1270 sp<Client> client( static_cast<Client *>(s.client.get()) ); 1271 transactionFlags |= setClientStateLocked(client, s.state); 1272 } 1273 1274 if (transactionFlags) { 1275 // this triggers the transaction 1276 setTransactionFlags(transactionFlags); 1277 1278 // if this is a synchronous transaction, wait for it to take effect 1279 // before returning. 1280 if (flags & eSynchronous) { 1281 mTransationPending = true; 1282 } 1283 while (mTransationPending) { 1284 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1285 if (CC_UNLIKELY(err != NO_ERROR)) { 1286 // just in case something goes wrong in SF, return to the 1287 // called after a few seconds. 1288 ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1289 mTransationPending = false; 1290 break; 1291 } 1292 } 1293 } 1294} 1295 1296sp<ISurface> SurfaceFlinger::createSurface( 1297 ISurfaceComposerClient::surface_data_t* params, 1298 const String8& name, 1299 const sp<Client>& client, 1300 DisplayID d, uint32_t w, uint32_t h, PixelFormat format, 1301 uint32_t flags) 1302{ 1303 sp<LayerBaseClient> layer; 1304 sp<ISurface> surfaceHandle; 1305 1306 if (int32_t(w|h) < 0) { 1307 ALOGE("createSurface() failed, w or h is negative (w=%d, h=%d)", 1308 int(w), int(h)); 1309 return surfaceHandle; 1310 } 1311 1312 //ALOGD("createSurface for (%d x %d), name=%s", w, h, name.string()); 1313 sp<Layer> normalLayer; 1314 switch (flags & eFXSurfaceMask) { 1315 case eFXSurfaceNormal: 1316 normalLayer = createNormalSurface(client, d, w, h, flags, format); 1317 layer = normalLayer; 1318 break; 1319 case eFXSurfaceBlur: 1320 // for now we treat Blur as Dim, until we can implement it 1321 // efficiently. 1322 case eFXSurfaceDim: 1323 layer = createDimSurface(client, d, w, h, flags); 1324 break; 1325 case eFXSurfaceScreenshot: 1326 layer = createScreenshotSurface(client, d, w, h, flags); 1327 break; 1328 } 1329 1330 if (layer != 0) { 1331 layer->initStates(w, h, flags); 1332 layer->setName(name); 1333 ssize_t token = addClientLayer(client, layer); 1334 1335 surfaceHandle = layer->getSurface(); 1336 if (surfaceHandle != 0) { 1337 params->token = token; 1338 params->identity = layer->getIdentity(); 1339 if (normalLayer != 0) { 1340 Mutex::Autolock _l(mStateLock); 1341 mLayerMap.add(layer->getSurfaceBinder(), normalLayer); 1342 } 1343 } 1344 1345 setTransactionFlags(eTransactionNeeded); 1346 } 1347 1348 return surfaceHandle; 1349} 1350 1351sp<Layer> SurfaceFlinger::createNormalSurface( 1352 const sp<Client>& client, DisplayID display, 1353 uint32_t w, uint32_t h, uint32_t flags, 1354 PixelFormat& format) 1355{ 1356 // initialize the surfaces 1357 switch (format) { // TODO: take h/w into account 1358 case PIXEL_FORMAT_TRANSPARENT: 1359 case PIXEL_FORMAT_TRANSLUCENT: 1360 format = PIXEL_FORMAT_RGBA_8888; 1361 break; 1362 case PIXEL_FORMAT_OPAQUE: 1363#ifdef NO_RGBX_8888 1364 format = PIXEL_FORMAT_RGB_565; 1365#else 1366 format = PIXEL_FORMAT_RGBX_8888; 1367#endif 1368 break; 1369 } 1370 1371#ifdef NO_RGBX_8888 1372 if (format == PIXEL_FORMAT_RGBX_8888) 1373 format = PIXEL_FORMAT_RGBA_8888; 1374#endif 1375 1376 sp<Layer> layer = new Layer(this, display, client); 1377 status_t err = layer->setBuffers(w, h, format, flags); 1378 if (CC_LIKELY(err != NO_ERROR)) { 1379 ALOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err)); 1380 layer.clear(); 1381 } 1382 return layer; 1383} 1384 1385sp<LayerDim> SurfaceFlinger::createDimSurface( 1386 const sp<Client>& client, DisplayID display, 1387 uint32_t w, uint32_t h, uint32_t flags) 1388{ 1389 sp<LayerDim> layer = new LayerDim(this, display, client); 1390 return layer; 1391} 1392 1393sp<LayerScreenshot> SurfaceFlinger::createScreenshotSurface( 1394 const sp<Client>& client, DisplayID display, 1395 uint32_t w, uint32_t h, uint32_t flags) 1396{ 1397 sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client); 1398 return layer; 1399} 1400 1401status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) 1402{ 1403 /* 1404 * called by the window manager, when a surface should be marked for 1405 * destruction. 1406 * 1407 * The surface is removed from the current and drawing lists, but placed 1408 * in the purgatory queue, so it's not destroyed right-away (we need 1409 * to wait for all client's references to go away first). 1410 */ 1411 1412 status_t err = NAME_NOT_FOUND; 1413 Mutex::Autolock _l(mStateLock); 1414 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1415 1416 if (layer != 0) { 1417 err = purgatorizeLayer_l(layer); 1418 if (err == NO_ERROR) { 1419 setTransactionFlags(eTransactionNeeded); 1420 } 1421 } 1422 return err; 1423} 1424 1425status_t SurfaceFlinger::destroySurface(const wp<LayerBaseClient>& layer) 1426{ 1427 // called by ~ISurface() when all references are gone 1428 status_t err = NO_ERROR; 1429 sp<LayerBaseClient> l(layer.promote()); 1430 if (l != NULL) { 1431 Mutex::Autolock _l(mStateLock); 1432 err = removeLayer_l(l); 1433 if (err == NAME_NOT_FOUND) { 1434 // The surface wasn't in the current list, which means it was 1435 // removed already, which means it is in the purgatory, 1436 // and need to be removed from there. 1437 ssize_t idx = mLayerPurgatory.remove(l); 1438 ALOGE_IF(idx < 0, 1439 "layer=%p is not in the purgatory list", l.get()); 1440 } 1441 ALOGE_IF(err<0 && err != NAME_NOT_FOUND, 1442 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1443 } 1444 return err; 1445} 1446 1447uint32_t SurfaceFlinger::setClientStateLocked( 1448 const sp<Client>& client, 1449 const layer_state_t& s) 1450{ 1451 uint32_t flags = 0; 1452 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1453 if (layer != 0) { 1454 const uint32_t what = s.what; 1455 if (what & ePositionChanged) { 1456 if (layer->setPosition(s.x, s.y)) 1457 flags |= eTraversalNeeded; 1458 } 1459 if (what & eLayerChanged) { 1460 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1461 if (layer->setLayer(s.z)) { 1462 mCurrentState.layersSortedByZ.removeAt(idx); 1463 mCurrentState.layersSortedByZ.add(layer); 1464 // we need traversal (state changed) 1465 // AND transaction (list changed) 1466 flags |= eTransactionNeeded|eTraversalNeeded; 1467 } 1468 } 1469 if (what & eSizeChanged) { 1470 if (layer->setSize(s.w, s.h)) { 1471 flags |= eTraversalNeeded; 1472 } 1473 } 1474 if (what & eAlphaChanged) { 1475 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f))) 1476 flags |= eTraversalNeeded; 1477 } 1478 if (what & eMatrixChanged) { 1479 if (layer->setMatrix(s.matrix)) 1480 flags |= eTraversalNeeded; 1481 } 1482 if (what & eTransparentRegionChanged) { 1483 if (layer->setTransparentRegionHint(s.transparentRegion)) 1484 flags |= eTraversalNeeded; 1485 } 1486 if (what & eVisibilityChanged) { 1487 if (layer->setFlags(s.flags, s.mask)) 1488 flags |= eTraversalNeeded; 1489 } 1490 } 1491 return flags; 1492} 1493 1494void SurfaceFlinger::screenReleased(int dpy) 1495{ 1496 // this may be called by a signal handler, we can't do too much in here 1497 android_atomic_or(eConsoleReleased, &mConsoleSignals); 1498 signalTransaction(); 1499} 1500 1501void SurfaceFlinger::screenAcquired(int dpy) 1502{ 1503 // this may be called by a signal handler, we can't do too much in here 1504 android_atomic_or(eConsoleAcquired, &mConsoleSignals); 1505 signalTransaction(); 1506} 1507 1508status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args) 1509{ 1510 const size_t SIZE = 4096; 1511 char buffer[SIZE]; 1512 String8 result; 1513 1514 if (!PermissionCache::checkCallingPermission(sDump)) { 1515 snprintf(buffer, SIZE, "Permission Denial: " 1516 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", 1517 IPCThreadState::self()->getCallingPid(), 1518 IPCThreadState::self()->getCallingUid()); 1519 result.append(buffer); 1520 } else { 1521 // Try to get the main lock, but don't insist if we can't 1522 // (this would indicate SF is stuck, but we want to be able to 1523 // print something in dumpsys). 1524 int retry = 3; 1525 while (mStateLock.tryLock()<0 && --retry>=0) { 1526 usleep(1000000); 1527 } 1528 const bool locked(retry >= 0); 1529 if (!locked) { 1530 snprintf(buffer, SIZE, 1531 "SurfaceFlinger appears to be unresponsive, " 1532 "dumping anyways (no locks held)\n"); 1533 result.append(buffer); 1534 } 1535 1536 bool dumpAll = true; 1537 size_t index = 0; 1538 size_t numArgs = args.size(); 1539 if (numArgs) { 1540 if ((index < numArgs) && 1541 (args[index] == String16("--list"))) { 1542 index++; 1543 listLayersLocked(args, index, result, buffer, SIZE); 1544 dumpAll = false; 1545 } 1546 1547 if ((index < numArgs) && 1548 (args[index] == String16("--latency"))) { 1549 index++; 1550 dumpStatsLocked(args, index, result, buffer, SIZE); 1551 dumpAll = false; 1552 } 1553 1554 if ((index < numArgs) && 1555 (args[index] == String16("--latency-clear"))) { 1556 index++; 1557 clearStatsLocked(args, index, result, buffer, SIZE); 1558 dumpAll = false; 1559 } 1560 } 1561 1562 if (dumpAll) { 1563 dumpAllLocked(result, buffer, SIZE); 1564 } 1565 1566 if (locked) { 1567 mStateLock.unlock(); 1568 } 1569 } 1570 write(fd, result.string(), result.size()); 1571 return NO_ERROR; 1572} 1573 1574void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index, 1575 String8& result, char* buffer, size_t SIZE) const 1576{ 1577 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1578 const size_t count = currentLayers.size(); 1579 for (size_t i=0 ; i<count ; i++) { 1580 const sp<LayerBase>& layer(currentLayers[i]); 1581 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 1582 result.append(buffer); 1583 } 1584} 1585 1586void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index, 1587 String8& result, char* buffer, size_t SIZE) const 1588{ 1589 String8 name; 1590 if (index < args.size()) { 1591 name = String8(args[index]); 1592 index++; 1593 } 1594 1595 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1596 const size_t count = currentLayers.size(); 1597 for (size_t i=0 ; i<count ; i++) { 1598 const sp<LayerBase>& layer(currentLayers[i]); 1599 if (name.isEmpty()) { 1600 snprintf(buffer, SIZE, "%s\n", layer->getName().string()); 1601 result.append(buffer); 1602 } 1603 if (name.isEmpty() || (name == layer->getName())) { 1604 layer->dumpStats(result, buffer, SIZE); 1605 } 1606 } 1607} 1608 1609void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index, 1610 String8& result, char* buffer, size_t SIZE) const 1611{ 1612 String8 name; 1613 if (index < args.size()) { 1614 name = String8(args[index]); 1615 index++; 1616 } 1617 1618 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1619 const size_t count = currentLayers.size(); 1620 for (size_t i=0 ; i<count ; i++) { 1621 const sp<LayerBase>& layer(currentLayers[i]); 1622 if (name.isEmpty() || (name == layer->getName())) { 1623 layer->clearStats(); 1624 } 1625 } 1626} 1627 1628void SurfaceFlinger::dumpAllLocked( 1629 String8& result, char* buffer, size_t SIZE) const 1630{ 1631 // figure out if we're stuck somewhere 1632 const nsecs_t now = systemTime(); 1633 const nsecs_t inSwapBuffers(mDebugInSwapBuffers); 1634 const nsecs_t inTransaction(mDebugInTransaction); 1635 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0; 1636 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0; 1637 1638 /* 1639 * Dump the visible layer list 1640 */ 1641 const LayerVector& currentLayers = mCurrentState.layersSortedByZ; 1642 const size_t count = currentLayers.size(); 1643 snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count); 1644 result.append(buffer); 1645 for (size_t i=0 ; i<count ; i++) { 1646 const sp<LayerBase>& layer(currentLayers[i]); 1647 layer->dump(result, buffer, SIZE); 1648 } 1649 1650 /* 1651 * Dump the layers in the purgatory 1652 */ 1653 1654 const size_t purgatorySize = mLayerPurgatory.size(); 1655 snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize); 1656 result.append(buffer); 1657 for (size_t i=0 ; i<purgatorySize ; i++) { 1658 const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i)); 1659 layer->shortDump(result, buffer, SIZE); 1660 } 1661 1662 /* 1663 * Dump SurfaceFlinger global state 1664 */ 1665 1666 snprintf(buffer, SIZE, "SurfaceFlinger global state:\n"); 1667 result.append(buffer); 1668 1669 const GLExtensions& extensions(GLExtensions::getInstance()); 1670 snprintf(buffer, SIZE, "GLES: %s, %s, %s\n", 1671 extensions.getVendor(), 1672 extensions.getRenderer(), 1673 extensions.getVersion()); 1674 result.append(buffer); 1675 1676 snprintf(buffer, SIZE, "EGL : %s\n", 1677 eglQueryString(graphicPlane(0).getEGLDisplay(), 1678 EGL_VERSION_HW_ANDROID)); 1679 result.append(buffer); 1680 1681 snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension()); 1682 result.append(buffer); 1683 1684 mWormholeRegion.dump(result, "WormholeRegion"); 1685 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1686 snprintf(buffer, SIZE, 1687 " orientation=%d, canDraw=%d\n", 1688 mCurrentState.orientation, hw.canDraw()); 1689 result.append(buffer); 1690 snprintf(buffer, SIZE, 1691 " last eglSwapBuffers() time: %f us\n" 1692 " last transaction time : %f us\n" 1693 " transaction-flags : %08x\n" 1694 " refresh-rate : %f fps\n" 1695 " x-dpi : %f\n" 1696 " y-dpi : %f\n" 1697 " density : %f\n", 1698 mLastSwapBufferTime/1000.0, 1699 mLastTransactionTime/1000.0, 1700 mTransactionFlags, 1701 hw.getRefreshRate(), 1702 hw.getDpiX(), 1703 hw.getDpiY(), 1704 hw.getDensity()); 1705 result.append(buffer); 1706 1707 snprintf(buffer, SIZE, " eglSwapBuffers time: %f us\n", 1708 inSwapBuffersDuration/1000.0); 1709 result.append(buffer); 1710 1711 snprintf(buffer, SIZE, " transaction time: %f us\n", 1712 inTransactionDuration/1000.0); 1713 result.append(buffer); 1714 1715 /* 1716 * VSYNC state 1717 */ 1718 mEventThread->dump(result, buffer, SIZE); 1719 1720 /* 1721 * Dump HWComposer state 1722 */ 1723 HWComposer& hwc(hw.getHwComposer()); 1724 snprintf(buffer, SIZE, "h/w composer state:\n"); 1725 result.append(buffer); 1726 snprintf(buffer, SIZE, " h/w composer %s and %s\n", 1727 hwc.initCheck()==NO_ERROR ? "present" : "not present", 1728 (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled"); 1729 result.append(buffer); 1730 hwc.dump(result, buffer, SIZE, mVisibleLayersSortedByZ); 1731 1732 /* 1733 * Dump gralloc state 1734 */ 1735 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get()); 1736 alloc.dump(result); 1737 hw.dump(result); 1738} 1739 1740status_t SurfaceFlinger::onTransact( 1741 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 1742{ 1743 switch (code) { 1744 case CREATE_CONNECTION: 1745 case SET_TRANSACTION_STATE: 1746 case SET_ORIENTATION: 1747 case BOOT_FINISHED: 1748 case TURN_ELECTRON_BEAM_OFF: 1749 case TURN_ELECTRON_BEAM_ON: 1750 { 1751 // codes that require permission check 1752 IPCThreadState* ipc = IPCThreadState::self(); 1753 const int pid = ipc->getCallingPid(); 1754 const int uid = ipc->getCallingUid(); 1755 if ((uid != AID_GRAPHICS) && 1756 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) { 1757 ALOGE("Permission Denial: " 1758 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1759 return PERMISSION_DENIED; 1760 } 1761 break; 1762 } 1763 case CAPTURE_SCREEN: 1764 { 1765 // codes that require permission check 1766 IPCThreadState* ipc = IPCThreadState::self(); 1767 const int pid = ipc->getCallingPid(); 1768 const int uid = ipc->getCallingUid(); 1769 if ((uid != AID_GRAPHICS) && 1770 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) { 1771 ALOGE("Permission Denial: " 1772 "can't read framebuffer pid=%d, uid=%d", pid, uid); 1773 return PERMISSION_DENIED; 1774 } 1775 break; 1776 } 1777 } 1778 1779 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags); 1780 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) { 1781 CHECK_INTERFACE(ISurfaceComposer, data, reply); 1782 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) { 1783 IPCThreadState* ipc = IPCThreadState::self(); 1784 const int pid = ipc->getCallingPid(); 1785 const int uid = ipc->getCallingUid(); 1786 ALOGE("Permission Denial: " 1787 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid); 1788 return PERMISSION_DENIED; 1789 } 1790 int n; 1791 switch (code) { 1792 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE 1793 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE 1794 return NO_ERROR; 1795 case 1002: // SHOW_UPDATES 1796 n = data.readInt32(); 1797 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1); 1798 invalidateHwcGeometry(); 1799 repaintEverything(); 1800 return NO_ERROR; 1801 case 1003: // SHOW_BACKGROUND 1802 n = data.readInt32(); 1803 mDebugBackground = n ? 1 : 0; 1804 return NO_ERROR; 1805 case 1004:{ // repaint everything 1806 repaintEverything(); 1807 return NO_ERROR; 1808 } 1809 case 1005:{ // force transaction 1810 setTransactionFlags(eTransactionNeeded|eTraversalNeeded); 1811 return NO_ERROR; 1812 } 1813 case 1006:{ // send empty update 1814 signalRefresh(); 1815 return NO_ERROR; 1816 } 1817 case 1008: // toggle use of hw composer 1818 n = data.readInt32(); 1819 mDebugDisableHWC = n ? 1 : 0; 1820 invalidateHwcGeometry(); 1821 repaintEverything(); 1822 return NO_ERROR; 1823 case 1009: // toggle use of transform hint 1824 n = data.readInt32(); 1825 mDebugDisableTransformHint = n ? 1 : 0; 1826 invalidateHwcGeometry(); 1827 repaintEverything(); 1828 return NO_ERROR; 1829 case 1010: // interrogate. 1830 reply->writeInt32(0); 1831 reply->writeInt32(0); 1832 reply->writeInt32(mDebugRegion); 1833 reply->writeInt32(mDebugBackground); 1834 reply->writeInt32(mDebugDisableHWC); 1835 return NO_ERROR; 1836 case 1013: { 1837 Mutex::Autolock _l(mStateLock); 1838 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1839 reply->writeInt32(hw.getPageFlipCount()); 1840 } 1841 return NO_ERROR; 1842 } 1843 } 1844 return err; 1845} 1846 1847void SurfaceFlinger::repaintEverything() { 1848 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1849 const Rect bounds(hw.getBounds()); 1850 setInvalidateRegion(Region(bounds)); 1851 signalTransaction(); 1852} 1853 1854void SurfaceFlinger::setInvalidateRegion(const Region& reg) { 1855 Mutex::Autolock _l(mInvalidateLock); 1856 mInvalidateRegion = reg; 1857} 1858 1859Region SurfaceFlinger::getAndClearInvalidateRegion() { 1860 Mutex::Autolock _l(mInvalidateLock); 1861 Region reg(mInvalidateRegion); 1862 mInvalidateRegion.clear(); 1863 return reg; 1864} 1865 1866// --------------------------------------------------------------------------- 1867 1868status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy, 1869 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 1870{ 1871 Mutex::Autolock _l(mStateLock); 1872 return renderScreenToTextureLocked(dpy, textureName, uOut, vOut); 1873} 1874 1875status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy, 1876 GLuint* textureName, GLfloat* uOut, GLfloat* vOut) 1877{ 1878 if (!GLExtensions::getInstance().haveFramebufferObject()) 1879 return INVALID_OPERATION; 1880 1881 // get screen geometry 1882 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 1883 const uint32_t hw_w = hw.getWidth(); 1884 const uint32_t hw_h = hw.getHeight(); 1885 GLfloat u = 1; 1886 GLfloat v = 1; 1887 1888 // make sure to clear all GL error flags 1889 while ( glGetError() != GL_NO_ERROR ) ; 1890 1891 // create a FBO 1892 GLuint name, tname; 1893 glGenTextures(1, &tname); 1894 glBindTexture(GL_TEXTURE_2D, tname); 1895 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1896 hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1897 if (glGetError() != GL_NO_ERROR) { 1898 while ( glGetError() != GL_NO_ERROR ) ; 1899 GLint tw = (2 << (31 - clz(hw_w))); 1900 GLint th = (2 << (31 - clz(hw_h))); 1901 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1902 tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0); 1903 u = GLfloat(hw_w) / tw; 1904 v = GLfloat(hw_h) / th; 1905 } 1906 glGenFramebuffersOES(1, &name); 1907 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 1908 glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES, 1909 GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0); 1910 1911 // redraw the screen entirely... 1912 glDisable(GL_TEXTURE_EXTERNAL_OES); 1913 glDisable(GL_TEXTURE_2D); 1914 glDisable(GL_SCISSOR_TEST); 1915 glClearColor(0,0,0,1); 1916 glClear(GL_COLOR_BUFFER_BIT); 1917 glEnable(GL_SCISSOR_TEST); 1918 glMatrixMode(GL_MODELVIEW); 1919 glLoadIdentity(); 1920 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 1921 const size_t count = layers.size(); 1922 for (size_t i=0 ; i<count ; ++i) { 1923 const sp<LayerBase>& layer(layers[i]); 1924 layer->drawForSreenShot(); 1925 } 1926 1927 hw.compositionComplete(); 1928 1929 // back to main framebuffer 1930 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 1931 glDisable(GL_SCISSOR_TEST); 1932 glDeleteFramebuffersOES(1, &name); 1933 1934 *textureName = tname; 1935 *uOut = u; 1936 *vOut = v; 1937 return NO_ERROR; 1938} 1939 1940// --------------------------------------------------------------------------- 1941 1942status_t SurfaceFlinger::electronBeamOffAnimationImplLocked() 1943{ 1944 // get screen geometry 1945 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 1946 const uint32_t hw_w = hw.getWidth(); 1947 const uint32_t hw_h = hw.getHeight(); 1948 const Region screenBounds(hw.getBounds()); 1949 1950 GLfloat u, v; 1951 GLuint tname; 1952 status_t result = renderScreenToTextureLocked(0, &tname, &u, &v); 1953 if (result != NO_ERROR) { 1954 return result; 1955 } 1956 1957 GLfloat vtx[8]; 1958 const GLfloat texCoords[4][2] = { {0,0}, {0,v}, {u,v}, {u,0} }; 1959 glBindTexture(GL_TEXTURE_2D, tname); 1960 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); 1961 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 1962 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 1963 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 1964 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 1965 glTexCoordPointer(2, GL_FLOAT, 0, texCoords); 1966 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 1967 glVertexPointer(2, GL_FLOAT, 0, vtx); 1968 1969 /* 1970 * Texture coordinate mapping 1971 * 1972 * u 1973 * 1 +----------+---+ 1974 * | | | | image is inverted 1975 * | V | | w.r.t. the texture 1976 * 1-v +----------+ | coordinates 1977 * | | 1978 * | | 1979 * | | 1980 * 0 +--------------+ 1981 * 0 1 1982 * 1983 */ 1984 1985 class s_curve_interpolator { 1986 const float nbFrames, s, v; 1987 public: 1988 s_curve_interpolator(int nbFrames, float s) 1989 : nbFrames(1.0f / (nbFrames-1)), s(s), 1990 v(1.0f + expf(-s + 0.5f*s)) { 1991 } 1992 float operator()(int f) { 1993 const float x = f * nbFrames; 1994 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; 1995 } 1996 }; 1997 1998 class v_stretch { 1999 const GLfloat hw_w, hw_h; 2000 public: 2001 v_stretch(uint32_t hw_w, uint32_t hw_h) 2002 : hw_w(hw_w), hw_h(hw_h) { 2003 } 2004 void operator()(GLfloat* vtx, float v) { 2005 const GLfloat w = hw_w + (hw_w * v); 2006 const GLfloat h = hw_h - (hw_h * v); 2007 const GLfloat x = (hw_w - w) * 0.5f; 2008 const GLfloat y = (hw_h - h) * 0.5f; 2009 vtx[0] = x; vtx[1] = y; 2010 vtx[2] = x; vtx[3] = y + h; 2011 vtx[4] = x + w; vtx[5] = y + h; 2012 vtx[6] = x + w; vtx[7] = y; 2013 } 2014 }; 2015 2016 class h_stretch { 2017 const GLfloat hw_w, hw_h; 2018 public: 2019 h_stretch(uint32_t hw_w, uint32_t hw_h) 2020 : hw_w(hw_w), hw_h(hw_h) { 2021 } 2022 void operator()(GLfloat* vtx, float v) { 2023 const GLfloat w = hw_w - (hw_w * v); 2024 const GLfloat h = 1.0f; 2025 const GLfloat x = (hw_w - w) * 0.5f; 2026 const GLfloat y = (hw_h - h) * 0.5f; 2027 vtx[0] = x; vtx[1] = y; 2028 vtx[2] = x; vtx[3] = y + h; 2029 vtx[4] = x + w; vtx[5] = y + h; 2030 vtx[6] = x + w; vtx[7] = y; 2031 } 2032 }; 2033 2034 // the full animation is 24 frames 2035 char value[PROPERTY_VALUE_MAX]; 2036 property_get("debug.sf.electron_frames", value, "24"); 2037 int nbFrames = (atoi(value) + 1) >> 1; 2038 if (nbFrames <= 0) // just in case 2039 nbFrames = 24; 2040 2041 s_curve_interpolator itr(nbFrames, 7.5f); 2042 s_curve_interpolator itg(nbFrames, 8.0f); 2043 s_curve_interpolator itb(nbFrames, 8.5f); 2044 2045 v_stretch vverts(hw_w, hw_h); 2046 2047 glMatrixMode(GL_TEXTURE); 2048 glLoadIdentity(); 2049 glMatrixMode(GL_MODELVIEW); 2050 glLoadIdentity(); 2051 2052 glEnable(GL_BLEND); 2053 glBlendFunc(GL_ONE, GL_ONE); 2054 for (int i=0 ; i<nbFrames ; i++) { 2055 float x, y, w, h; 2056 const float vr = itr(i); 2057 const float vg = itg(i); 2058 const float vb = itb(i); 2059 2060 // clear screen 2061 glColorMask(1,1,1,1); 2062 glClear(GL_COLOR_BUFFER_BIT); 2063 glEnable(GL_TEXTURE_2D); 2064 2065 // draw the red plane 2066 vverts(vtx, vr); 2067 glColorMask(1,0,0,1); 2068 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2069 2070 // draw the green plane 2071 vverts(vtx, vg); 2072 glColorMask(0,1,0,1); 2073 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2074 2075 // draw the blue plane 2076 vverts(vtx, vb); 2077 glColorMask(0,0,1,1); 2078 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2079 2080 // draw the white highlight (we use the last vertices) 2081 glDisable(GL_TEXTURE_2D); 2082 glColorMask(1,1,1,1); 2083 glColor4f(vg, vg, vg, 1); 2084 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2085 hw.flip(screenBounds); 2086 } 2087 2088 h_stretch hverts(hw_w, hw_h); 2089 glDisable(GL_BLEND); 2090 glDisable(GL_TEXTURE_2D); 2091 glColorMask(1,1,1,1); 2092 for (int i=0 ; i<nbFrames ; i++) { 2093 const float v = itg(i); 2094 hverts(vtx, v); 2095 glClear(GL_COLOR_BUFFER_BIT); 2096 glColor4f(1-v, 1-v, 1-v, 1); 2097 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2098 hw.flip(screenBounds); 2099 } 2100 2101 glColorMask(1,1,1,1); 2102 glEnable(GL_SCISSOR_TEST); 2103 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 2104 glDeleteTextures(1, &tname); 2105 glDisable(GL_TEXTURE_2D); 2106 glDisable(GL_BLEND); 2107 return NO_ERROR; 2108} 2109 2110status_t SurfaceFlinger::electronBeamOnAnimationImplLocked() 2111{ 2112 status_t result = PERMISSION_DENIED; 2113 2114 if (!GLExtensions::getInstance().haveFramebufferObject()) 2115 return INVALID_OPERATION; 2116 2117 2118 // get screen geometry 2119 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 2120 const uint32_t hw_w = hw.getWidth(); 2121 const uint32_t hw_h = hw.getHeight(); 2122 const Region screenBounds(hw.bounds()); 2123 2124 GLfloat u, v; 2125 GLuint tname; 2126 result = renderScreenToTextureLocked(0, &tname, &u, &v); 2127 if (result != NO_ERROR) { 2128 return result; 2129 } 2130 2131 GLfloat vtx[8]; 2132 const GLfloat texCoords[4][2] = { {0,v}, {0,0}, {u,0}, {u,v} }; 2133 glBindTexture(GL_TEXTURE_2D, tname); 2134 glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); 2135 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 2136 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); 2137 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); 2138 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); 2139 glTexCoordPointer(2, GL_FLOAT, 0, texCoords); 2140 glEnableClientState(GL_TEXTURE_COORD_ARRAY); 2141 glVertexPointer(2, GL_FLOAT, 0, vtx); 2142 2143 class s_curve_interpolator { 2144 const float nbFrames, s, v; 2145 public: 2146 s_curve_interpolator(int nbFrames, float s) 2147 : nbFrames(1.0f / (nbFrames-1)), s(s), 2148 v(1.0f + expf(-s + 0.5f*s)) { 2149 } 2150 float operator()(int f) { 2151 const float x = f * nbFrames; 2152 return ((1.0f/(1.0f + expf(-x*s + 0.5f*s))) - 0.5f) * v + 0.5f; 2153 } 2154 }; 2155 2156 class v_stretch { 2157 const GLfloat hw_w, hw_h; 2158 public: 2159 v_stretch(uint32_t hw_w, uint32_t hw_h) 2160 : hw_w(hw_w), hw_h(hw_h) { 2161 } 2162 void operator()(GLfloat* vtx, float v) { 2163 const GLfloat w = hw_w + (hw_w * v); 2164 const GLfloat h = hw_h - (hw_h * v); 2165 const GLfloat x = (hw_w - w) * 0.5f; 2166 const GLfloat y = (hw_h - h) * 0.5f; 2167 vtx[0] = x; vtx[1] = y; 2168 vtx[2] = x; vtx[3] = y + h; 2169 vtx[4] = x + w; vtx[5] = y + h; 2170 vtx[6] = x + w; vtx[7] = y; 2171 } 2172 }; 2173 2174 class h_stretch { 2175 const GLfloat hw_w, hw_h; 2176 public: 2177 h_stretch(uint32_t hw_w, uint32_t hw_h) 2178 : hw_w(hw_w), hw_h(hw_h) { 2179 } 2180 void operator()(GLfloat* vtx, float v) { 2181 const GLfloat w = hw_w - (hw_w * v); 2182 const GLfloat h = 1.0f; 2183 const GLfloat x = (hw_w - w) * 0.5f; 2184 const GLfloat y = (hw_h - h) * 0.5f; 2185 vtx[0] = x; vtx[1] = y; 2186 vtx[2] = x; vtx[3] = y + h; 2187 vtx[4] = x + w; vtx[5] = y + h; 2188 vtx[6] = x + w; vtx[7] = y; 2189 } 2190 }; 2191 2192 // the full animation is 12 frames 2193 int nbFrames = 8; 2194 s_curve_interpolator itr(nbFrames, 7.5f); 2195 s_curve_interpolator itg(nbFrames, 8.0f); 2196 s_curve_interpolator itb(nbFrames, 8.5f); 2197 2198 h_stretch hverts(hw_w, hw_h); 2199 glDisable(GL_BLEND); 2200 glDisable(GL_TEXTURE_2D); 2201 glColorMask(1,1,1,1); 2202 for (int i=nbFrames-1 ; i>=0 ; i--) { 2203 const float v = itg(i); 2204 hverts(vtx, v); 2205 glClear(GL_COLOR_BUFFER_BIT); 2206 glColor4f(1-v, 1-v, 1-v, 1); 2207 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2208 hw.flip(screenBounds); 2209 } 2210 2211 nbFrames = 4; 2212 v_stretch vverts(hw_w, hw_h); 2213 glEnable(GL_BLEND); 2214 glBlendFunc(GL_ONE, GL_ONE); 2215 for (int i=nbFrames-1 ; i>=0 ; i--) { 2216 float x, y, w, h; 2217 const float vr = itr(i); 2218 const float vg = itg(i); 2219 const float vb = itb(i); 2220 2221 // clear screen 2222 glColorMask(1,1,1,1); 2223 glClear(GL_COLOR_BUFFER_BIT); 2224 glEnable(GL_TEXTURE_2D); 2225 2226 // draw the red plane 2227 vverts(vtx, vr); 2228 glColorMask(1,0,0,1); 2229 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2230 2231 // draw the green plane 2232 vverts(vtx, vg); 2233 glColorMask(0,1,0,1); 2234 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2235 2236 // draw the blue plane 2237 vverts(vtx, vb); 2238 glColorMask(0,0,1,1); 2239 glDrawArrays(GL_TRIANGLE_FAN, 0, 4); 2240 2241 hw.flip(screenBounds); 2242 } 2243 2244 glColorMask(1,1,1,1); 2245 glEnable(GL_SCISSOR_TEST); 2246 glDisableClientState(GL_TEXTURE_COORD_ARRAY); 2247 glDeleteTextures(1, &tname); 2248 glDisable(GL_TEXTURE_2D); 2249 glDisable(GL_BLEND); 2250 2251 return NO_ERROR; 2252} 2253 2254// --------------------------------------------------------------------------- 2255 2256status_t SurfaceFlinger::turnElectronBeamOffImplLocked(int32_t mode) 2257{ 2258 DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); 2259 if (!hw.canDraw()) { 2260 // we're already off 2261 return NO_ERROR; 2262 } 2263 2264 // turn off hwc while we're doing the animation 2265 hw.getHwComposer().disable(); 2266 // and make sure to turn it back on (if needed) next time we compose 2267 invalidateHwcGeometry(); 2268 2269 if (mode & ISurfaceComposer::eElectronBeamAnimationOff) { 2270 electronBeamOffAnimationImplLocked(); 2271 } 2272 2273 // always clear the whole screen at the end of the animation 2274 glClearColor(0,0,0,1); 2275 glDisable(GL_SCISSOR_TEST); 2276 glClear(GL_COLOR_BUFFER_BIT); 2277 glEnable(GL_SCISSOR_TEST); 2278 hw.flip( Region(hw.bounds()) ); 2279 2280 return NO_ERROR; 2281} 2282 2283status_t SurfaceFlinger::turnElectronBeamOff(int32_t mode) 2284{ 2285 class MessageTurnElectronBeamOff : public MessageBase { 2286 SurfaceFlinger* flinger; 2287 int32_t mode; 2288 status_t result; 2289 public: 2290 MessageTurnElectronBeamOff(SurfaceFlinger* flinger, int32_t mode) 2291 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { 2292 } 2293 status_t getResult() const { 2294 return result; 2295 } 2296 virtual bool handler() { 2297 Mutex::Autolock _l(flinger->mStateLock); 2298 result = flinger->turnElectronBeamOffImplLocked(mode); 2299 return true; 2300 } 2301 }; 2302 2303 sp<MessageBase> msg = new MessageTurnElectronBeamOff(this, mode); 2304 status_t res = postMessageSync(msg); 2305 if (res == NO_ERROR) { 2306 res = static_cast<MessageTurnElectronBeamOff*>( msg.get() )->getResult(); 2307 2308 // work-around: when the power-manager calls us we activate the 2309 // animation. eventually, the "on" animation will be called 2310 // by the power-manager itself 2311 mElectronBeamAnimationMode = mode; 2312 } 2313 return res; 2314} 2315 2316// --------------------------------------------------------------------------- 2317 2318status_t SurfaceFlinger::turnElectronBeamOnImplLocked(int32_t mode) 2319{ 2320 DisplayHardware& hw(graphicPlane(0).editDisplayHardware()); 2321 if (hw.canDraw()) { 2322 // we're already on 2323 return NO_ERROR; 2324 } 2325 if (mode & ISurfaceComposer::eElectronBeamAnimationOn) { 2326 electronBeamOnAnimationImplLocked(); 2327 } 2328 2329 // make sure to redraw the whole screen when the animation is done 2330 mDirtyRegion.set(hw.bounds()); 2331 signalTransaction(); 2332 2333 return NO_ERROR; 2334} 2335 2336status_t SurfaceFlinger::turnElectronBeamOn(int32_t mode) 2337{ 2338 class MessageTurnElectronBeamOn : public MessageBase { 2339 SurfaceFlinger* flinger; 2340 int32_t mode; 2341 status_t result; 2342 public: 2343 MessageTurnElectronBeamOn(SurfaceFlinger* flinger, int32_t mode) 2344 : flinger(flinger), mode(mode), result(PERMISSION_DENIED) { 2345 } 2346 status_t getResult() const { 2347 return result; 2348 } 2349 virtual bool handler() { 2350 Mutex::Autolock _l(flinger->mStateLock); 2351 result = flinger->turnElectronBeamOnImplLocked(mode); 2352 return true; 2353 } 2354 }; 2355 2356 postMessageAsync( new MessageTurnElectronBeamOn(this, mode) ); 2357 return NO_ERROR; 2358} 2359 2360// --------------------------------------------------------------------------- 2361 2362status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy, 2363 sp<IMemoryHeap>* heap, 2364 uint32_t* w, uint32_t* h, PixelFormat* f, 2365 uint32_t sw, uint32_t sh, 2366 uint32_t minLayerZ, uint32_t maxLayerZ) 2367{ 2368 ATRACE_CALL(); 2369 2370 status_t result = PERMISSION_DENIED; 2371 2372 // only one display supported for now 2373 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 2374 return BAD_VALUE; 2375 2376 if (!GLExtensions::getInstance().haveFramebufferObject()) 2377 return INVALID_OPERATION; 2378 2379 // get screen geometry 2380 const DisplayHardware& hw(graphicPlane(dpy).displayHardware()); 2381 const uint32_t hw_w = hw.getWidth(); 2382 const uint32_t hw_h = hw.getHeight(); 2383 2384 if ((sw > hw_w) || (sh > hw_h)) 2385 return BAD_VALUE; 2386 2387 sw = (!sw) ? hw_w : sw; 2388 sh = (!sh) ? hw_h : sh; 2389 const size_t size = sw * sh * 4; 2390 2391 //ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d", 2392 // sw, sh, minLayerZ, maxLayerZ); 2393 2394 // make sure to clear all GL error flags 2395 while ( glGetError() != GL_NO_ERROR ) ; 2396 2397 // create a FBO 2398 GLuint name, tname; 2399 glGenRenderbuffersOES(1, &tname); 2400 glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname); 2401 glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh); 2402 2403 glGenFramebuffersOES(1, &name); 2404 glBindFramebufferOES(GL_FRAMEBUFFER_OES, name); 2405 glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES, 2406 GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname); 2407 2408 GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES); 2409 2410 if (status == GL_FRAMEBUFFER_COMPLETE_OES) { 2411 2412 // invert everything, b/c glReadPixel() below will invert the FB 2413 glViewport(0, 0, sw, sh); 2414 glScissor(0, 0, sw, sh); 2415 glEnable(GL_SCISSOR_TEST); 2416 glMatrixMode(GL_PROJECTION); 2417 glPushMatrix(); 2418 glLoadIdentity(); 2419 glOrthof(0, hw_w, hw_h, 0, 0, 1); 2420 glMatrixMode(GL_MODELVIEW); 2421 2422 // redraw the screen entirely... 2423 glClearColor(0,0,0,1); 2424 glClear(GL_COLOR_BUFFER_BIT); 2425 2426 const LayerVector& layers(mDrawingState.layersSortedByZ); 2427 const size_t count = layers.size(); 2428 for (size_t i=0 ; i<count ; ++i) { 2429 const sp<LayerBase>& layer(layers[i]); 2430 const uint32_t flags = layer->drawingState().flags; 2431 if (!(flags & ISurfaceComposer::eLayerHidden)) { 2432 const uint32_t z = layer->drawingState().z; 2433 if (z >= minLayerZ && z <= maxLayerZ) { 2434 layer->drawForSreenShot(); 2435 } 2436 } 2437 } 2438 2439 // XXX: this is needed on tegra 2440 glEnable(GL_SCISSOR_TEST); 2441 glScissor(0, 0, sw, sh); 2442 2443 // check for errors and return screen capture 2444 if (glGetError() != GL_NO_ERROR) { 2445 // error while rendering 2446 result = INVALID_OPERATION; 2447 } else { 2448 // allocate shared memory large enough to hold the 2449 // screen capture 2450 sp<MemoryHeapBase> base( 2451 new MemoryHeapBase(size, 0, "screen-capture") ); 2452 void* const ptr = base->getBase(); 2453 if (ptr) { 2454 // capture the screen with glReadPixels() 2455 ScopedTrace _t(ATRACE_TAG, "glReadPixels"); 2456 glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr); 2457 if (glGetError() == GL_NO_ERROR) { 2458 *heap = base; 2459 *w = sw; 2460 *h = sh; 2461 *f = PIXEL_FORMAT_RGBA_8888; 2462 result = NO_ERROR; 2463 } 2464 } else { 2465 result = NO_MEMORY; 2466 } 2467 } 2468 glEnable(GL_SCISSOR_TEST); 2469 glViewport(0, 0, hw_w, hw_h); 2470 glMatrixMode(GL_PROJECTION); 2471 glPopMatrix(); 2472 glMatrixMode(GL_MODELVIEW); 2473 } else { 2474 result = BAD_VALUE; 2475 } 2476 2477 // release FBO resources 2478 glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0); 2479 glDeleteRenderbuffersOES(1, &tname); 2480 glDeleteFramebuffersOES(1, &name); 2481 2482 hw.compositionComplete(); 2483 2484 // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK"); 2485 2486 return result; 2487} 2488 2489 2490status_t SurfaceFlinger::captureScreen(DisplayID dpy, 2491 sp<IMemoryHeap>* heap, 2492 uint32_t* width, uint32_t* height, PixelFormat* format, 2493 uint32_t sw, uint32_t sh, 2494 uint32_t minLayerZ, uint32_t maxLayerZ) 2495{ 2496 // only one display supported for now 2497 if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 2498 return BAD_VALUE; 2499 2500 if (!GLExtensions::getInstance().haveFramebufferObject()) 2501 return INVALID_OPERATION; 2502 2503 class MessageCaptureScreen : public MessageBase { 2504 SurfaceFlinger* flinger; 2505 DisplayID dpy; 2506 sp<IMemoryHeap>* heap; 2507 uint32_t* w; 2508 uint32_t* h; 2509 PixelFormat* f; 2510 uint32_t sw; 2511 uint32_t sh; 2512 uint32_t minLayerZ; 2513 uint32_t maxLayerZ; 2514 status_t result; 2515 public: 2516 MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy, 2517 sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f, 2518 uint32_t sw, uint32_t sh, 2519 uint32_t minLayerZ, uint32_t maxLayerZ) 2520 : flinger(flinger), dpy(dpy), 2521 heap(heap), w(w), h(h), f(f), sw(sw), sh(sh), 2522 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ), 2523 result(PERMISSION_DENIED) 2524 { 2525 } 2526 status_t getResult() const { 2527 return result; 2528 } 2529 virtual bool handler() { 2530 Mutex::Autolock _l(flinger->mStateLock); 2531 2532 // if we have secure windows, never allow the screen capture 2533 if (flinger->mSecureFrameBuffer) 2534 return true; 2535 2536 result = flinger->captureScreenImplLocked(dpy, 2537 heap, w, h, f, sw, sh, minLayerZ, maxLayerZ); 2538 2539 return true; 2540 } 2541 }; 2542 2543 sp<MessageBase> msg = new MessageCaptureScreen(this, 2544 dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ); 2545 status_t res = postMessageSync(msg); 2546 if (res == NO_ERROR) { 2547 res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult(); 2548 } 2549 return res; 2550} 2551 2552// --------------------------------------------------------------------------- 2553 2554sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const 2555{ 2556 sp<Layer> result; 2557 Mutex::Autolock _l(mStateLock); 2558 result = mLayerMap.valueFor( sur->asBinder() ).promote(); 2559 return result; 2560} 2561 2562// --------------------------------------------------------------------------- 2563 2564Client::Client(const sp<SurfaceFlinger>& flinger) 2565 : mFlinger(flinger), mNameGenerator(1) 2566{ 2567} 2568 2569Client::~Client() 2570{ 2571 const size_t count = mLayers.size(); 2572 for (size_t i=0 ; i<count ; i++) { 2573 sp<LayerBaseClient> layer(mLayers.valueAt(i).promote()); 2574 if (layer != 0) { 2575 mFlinger->removeLayer(layer); 2576 } 2577 } 2578} 2579 2580status_t Client::initCheck() const { 2581 return NO_ERROR; 2582} 2583 2584size_t Client::attachLayer(const sp<LayerBaseClient>& layer) 2585{ 2586 Mutex::Autolock _l(mLock); 2587 size_t name = mNameGenerator++; 2588 mLayers.add(name, layer); 2589 return name; 2590} 2591 2592void Client::detachLayer(const LayerBaseClient* layer) 2593{ 2594 Mutex::Autolock _l(mLock); 2595 // we do a linear search here, because this doesn't happen often 2596 const size_t count = mLayers.size(); 2597 for (size_t i=0 ; i<count ; i++) { 2598 if (mLayers.valueAt(i) == layer) { 2599 mLayers.removeItemsAt(i, 1); 2600 break; 2601 } 2602 } 2603} 2604sp<LayerBaseClient> Client::getLayerUser(int32_t i) const 2605{ 2606 Mutex::Autolock _l(mLock); 2607 sp<LayerBaseClient> lbc; 2608 wp<LayerBaseClient> layer(mLayers.valueFor(i)); 2609 if (layer != 0) { 2610 lbc = layer.promote(); 2611 ALOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i)); 2612 } 2613 return lbc; 2614} 2615 2616 2617status_t Client::onTransact( 2618 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) 2619{ 2620 // these must be checked 2621 IPCThreadState* ipc = IPCThreadState::self(); 2622 const int pid = ipc->getCallingPid(); 2623 const int uid = ipc->getCallingUid(); 2624 const int self_pid = getpid(); 2625 if (CC_UNLIKELY(pid != self_pid && uid != AID_GRAPHICS && uid != 0)) { 2626 // we're called from a different process, do the real check 2627 if (!PermissionCache::checkCallingPermission(sAccessSurfaceFlinger)) 2628 { 2629 ALOGE("Permission Denial: " 2630 "can't openGlobalTransaction pid=%d, uid=%d", pid, uid); 2631 return PERMISSION_DENIED; 2632 } 2633 } 2634 return BnSurfaceComposerClient::onTransact(code, data, reply, flags); 2635} 2636 2637 2638sp<ISurface> Client::createSurface( 2639 ISurfaceComposerClient::surface_data_t* params, 2640 const String8& name, 2641 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2642 uint32_t flags) 2643{ 2644 /* 2645 * createSurface must be called from the GL thread so that it can 2646 * have access to the GL context. 2647 */ 2648 2649 class MessageCreateSurface : public MessageBase { 2650 sp<ISurface> result; 2651 SurfaceFlinger* flinger; 2652 ISurfaceComposerClient::surface_data_t* params; 2653 Client* client; 2654 const String8& name; 2655 DisplayID display; 2656 uint32_t w, h; 2657 PixelFormat format; 2658 uint32_t flags; 2659 public: 2660 MessageCreateSurface(SurfaceFlinger* flinger, 2661 ISurfaceComposerClient::surface_data_t* params, 2662 const String8& name, Client* client, 2663 DisplayID display, uint32_t w, uint32_t h, PixelFormat format, 2664 uint32_t flags) 2665 : flinger(flinger), params(params), client(client), name(name), 2666 display(display), w(w), h(h), format(format), flags(flags) 2667 { 2668 } 2669 sp<ISurface> getResult() const { return result; } 2670 virtual bool handler() { 2671 result = flinger->createSurface(params, name, client, 2672 display, w, h, format, flags); 2673 return true; 2674 } 2675 }; 2676 2677 sp<MessageBase> msg = new MessageCreateSurface(mFlinger.get(), 2678 params, name, this, display, w, h, format, flags); 2679 mFlinger->postMessageSync(msg); 2680 return static_cast<MessageCreateSurface*>( msg.get() )->getResult(); 2681} 2682status_t Client::destroySurface(SurfaceID sid) { 2683 return mFlinger->removeSurface(this, sid); 2684} 2685 2686// --------------------------------------------------------------------------- 2687 2688GraphicBufferAlloc::GraphicBufferAlloc() {} 2689 2690GraphicBufferAlloc::~GraphicBufferAlloc() {} 2691 2692sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h, 2693 PixelFormat format, uint32_t usage, status_t* error) { 2694 sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage)); 2695 status_t err = graphicBuffer->initCheck(); 2696 *error = err; 2697 if (err != 0 || graphicBuffer->handle == 0) { 2698 if (err == NO_MEMORY) { 2699 GraphicBuffer::dumpAllocationsToSystemLog(); 2700 } 2701 ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) " 2702 "failed (%s), handle=%p", 2703 w, h, strerror(-err), graphicBuffer->handle); 2704 return 0; 2705 } 2706 return graphicBuffer; 2707} 2708 2709// --------------------------------------------------------------------------- 2710 2711GraphicPlane::GraphicPlane() 2712 : mHw(0) 2713{ 2714} 2715 2716GraphicPlane::~GraphicPlane() { 2717 delete mHw; 2718} 2719 2720bool GraphicPlane::initialized() const { 2721 return mHw ? true : false; 2722} 2723 2724int GraphicPlane::getWidth() const { 2725 return mWidth; 2726} 2727 2728int GraphicPlane::getHeight() const { 2729 return mHeight; 2730} 2731 2732void GraphicPlane::setDisplayHardware(DisplayHardware *hw) 2733{ 2734 mHw = hw; 2735 2736 // initialize the display orientation transform. 2737 // it's a constant that should come from the display driver. 2738 int displayOrientation = ISurfaceComposer::eOrientationDefault; 2739 char property[PROPERTY_VALUE_MAX]; 2740 if (property_get("ro.sf.hwrotation", property, NULL) > 0) { 2741 //displayOrientation 2742 switch (atoi(property)) { 2743 case 90: 2744 displayOrientation = ISurfaceComposer::eOrientation90; 2745 break; 2746 case 270: 2747 displayOrientation = ISurfaceComposer::eOrientation270; 2748 break; 2749 } 2750 } 2751 2752 const float w = hw->getWidth(); 2753 const float h = hw->getHeight(); 2754 GraphicPlane::orientationToTransfrom(displayOrientation, w, h, 2755 &mDisplayTransform); 2756 if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) { 2757 mDisplayWidth = h; 2758 mDisplayHeight = w; 2759 } else { 2760 mDisplayWidth = w; 2761 mDisplayHeight = h; 2762 } 2763 2764 setOrientation(ISurfaceComposer::eOrientationDefault); 2765} 2766 2767status_t GraphicPlane::orientationToTransfrom( 2768 int orientation, int w, int h, Transform* tr) 2769{ 2770 uint32_t flags = 0; 2771 switch (orientation) { 2772 case ISurfaceComposer::eOrientationDefault: 2773 flags = Transform::ROT_0; 2774 break; 2775 case ISurfaceComposer::eOrientation90: 2776 flags = Transform::ROT_90; 2777 break; 2778 case ISurfaceComposer::eOrientation180: 2779 flags = Transform::ROT_180; 2780 break; 2781 case ISurfaceComposer::eOrientation270: 2782 flags = Transform::ROT_270; 2783 break; 2784 default: 2785 return BAD_VALUE; 2786 } 2787 tr->set(flags, w, h); 2788 return NO_ERROR; 2789} 2790 2791status_t GraphicPlane::setOrientation(int orientation) 2792{ 2793 // If the rotation can be handled in hardware, this is where 2794 // the magic should happen. 2795 2796 const DisplayHardware& hw(displayHardware()); 2797 const float w = mDisplayWidth; 2798 const float h = mDisplayHeight; 2799 mWidth = int(w); 2800 mHeight = int(h); 2801 2802 Transform orientationTransform; 2803 GraphicPlane::orientationToTransfrom(orientation, w, h, 2804 &orientationTransform); 2805 if (orientation & ISurfaceComposer::eOrientationSwapMask) { 2806 mWidth = int(h); 2807 mHeight = int(w); 2808 } 2809 2810 mOrientation = orientation; 2811 mGlobalTransform = mDisplayTransform * orientationTransform; 2812 return NO_ERROR; 2813} 2814 2815const DisplayHardware& GraphicPlane::displayHardware() const { 2816 return *mHw; 2817} 2818 2819DisplayHardware& GraphicPlane::editDisplayHardware() { 2820 return *mHw; 2821} 2822 2823const Transform& GraphicPlane::transform() const { 2824 return mGlobalTransform; 2825} 2826 2827EGLDisplay GraphicPlane::getEGLDisplay() const { 2828 return mHw->getEGLDisplay(); 2829} 2830 2831// --------------------------------------------------------------------------- 2832 2833}; // namespace android 2834