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