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