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