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