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