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