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