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