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