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