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