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