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