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