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