2 * Copyright (C) 2007 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 //#define LOG_NDEBUG 0
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
21 #include <sys/types.h>
26 #include <stdatomic.h>
30 #include <cutils/log.h>
31 #include <cutils/iosched_policy.h>
32 #include <cutils/properties.h>
34 #include <binder/IPCThreadState.h>
35 #include <binder/IServiceManager.h>
36 #include <binder/MemoryHeapBase.h>
37 #include <binder/PermissionCache.h>
39 #include <ui/DisplayInfo.h>
40 #include <ui/DisplayStatInfo.h>
42 #include <gui/BitTube.h>
43 #include <gui/BufferQueue.h>
44 #include <gui/GuiConfig.h>
45 #include <gui/IDisplayEventConnection.h>
46 #include <gui/Surface.h>
47 #include <gui/GraphicBufferAlloc.h>
49 #include <ui/GraphicBufferAllocator.h>
50 #include <ui/PixelFormat.h>
51 #include <ui/UiConfig.h>
53 #include <utils/misc.h>
54 #include <utils/String8.h>
55 #include <utils/String16.h>
56 #include <utils/StopWatch.h>
57 #include <utils/Trace.h>
59 #include <private/android_filesystem_config.h>
60 #include <private/gui/SyncFeatures.h>
64 #include "Colorizer.h"
65 #include "DdmConnection.h"
66 #include "DisplayDevice.h"
68 #include "EventControlThread.h"
69 #include "EventThread.h"
72 #include "LayerBlur.h"
73 #include "SurfaceFlinger.h"
75 #include "DisplayHardware/FramebufferSurface.h"
76 #include "DisplayHardware/HWComposer.h"
77 #include "DisplayHardware/VirtualDisplaySurface.h"
79 #include "Effects/Daltonizer.h"
81 #include "RenderEngine/RenderEngine.h"
82 #include <cutils/compiler.h>
83 #include "DisplayUtils.h"
85 #define DISPLAY_COUNT 1
88 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
91 #define DEBUG_SCREENSHOTS false
93 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
97 // This is the phase offset in nanoseconds of the software vsync event
98 // relative to the vsync event reported by HWComposer. The software vsync
99 // event is when SurfaceFlinger and Choreographer-based applications run each
102 // This phase offset allows adjustment of the minimum latency from application
103 // wake-up (by Choregographer) time to the time at which the resulting window
104 // image is displayed. This value may be either positive (after the HW vsync)
105 // or negative (before the HW vsync). Setting it to 0 will result in a
106 // minimum latency of two vsync periods because the app and SurfaceFlinger
107 // will run just after the HW vsync. Setting it to a positive number will
108 // result in the minimum latency being:
110 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
112 // Note that reducing this latency makes it more likely for the applications
113 // to not have their window content image ready in time. When this happens
114 // the latency will end up being an additional vsync period, and animations
115 // will hiccup. Therefore, this latency should be tuned somewhat
116 // conservatively (or at least with awareness of the trade-off being made).
117 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
119 // This is the phase offset at which SurfaceFlinger's composition runs.
120 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
122 // ---------------------------------------------------------------------------
124 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
125 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
126 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
127 const String16 sDump("android.permission.DUMP");
129 static sp<Layer> lastSurfaceViewLayer;
131 // ---------------------------------------------------------------------------
133 SurfaceFlinger::SurfaceFlinger()
134 : BnSurfaceComposer(),
135 mTransactionFlags(0),
136 mTransactionPending(false),
137 mAnimTransactionPending(false),
138 mLayersRemoved(false),
139 mRepaintEverything(0),
141 mBootTime(systemTime()),
142 mVisibleRegionsDirty(false),
143 mHwWorkListDirty(false),
144 mAnimCompositionPending(false),
148 mDebugDisableTransformHint(0),
149 mDebugInSwapBuffers(0),
150 mLastSwapBufferTime(0),
151 mDebugInTransaction(0),
152 mLastTransactionTime(0),
153 mBootFinished(false),
154 mForceFullDamage(false),
155 mPrimaryHWVsyncEnabled(false),
156 mHWVsyncAvailable(false),
158 mHasColorMatrix(false),
159 mHasSecondaryColorMatrix(false),
160 mHasPoweredOff(false),
164 mActiveFrameSequence(0)
166 ALOGI("SurfaceFlinger is starting");
168 // debugging stuff...
169 char value[PROPERTY_VALUE_MAX];
171 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
172 mGpuToCpuSupported = !atoi(value);
174 property_get("debug.sf.drop_missed_frames", value, "0");
175 mDropMissedFrames = atoi(value);
177 property_get("debug.sf.showupdates", value, "0");
178 mDebugRegion = atoi(value);
180 property_get("debug.sf.ddms", value, "0");
181 mDebugDDMS = atoi(value);
183 if (!startDdmConnection()) {
184 // start failed, and DDMS debugging not enabled
188 ALOGI_IF(mDebugRegion, "showupdates enabled");
189 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
192 void SurfaceFlinger::onFirstRef()
194 mEventQueue.init(this);
197 SurfaceFlinger::~SurfaceFlinger()
199 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
200 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
201 eglTerminate(display);
204 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
206 // the window manager died on us. prepare its eulogy.
208 // restore initial conditions (default device unblank, etc)
209 initializeDisplays();
211 // restart the boot-animation
215 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
217 sp<ISurfaceComposerClient> bclient;
218 sp<Client> client(new Client(this));
219 status_t err = client->initCheck();
220 if (err == NO_ERROR) {
226 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
229 class DisplayToken : public BBinder {
230 sp<SurfaceFlinger> flinger;
231 virtual ~DisplayToken() {
232 // no more references, this display must be terminated
233 Mutex::Autolock _l(flinger->mStateLock);
234 flinger->mCurrentState.displays.removeItem(this);
235 flinger->setTransactionFlags(eDisplayTransactionNeeded);
238 DisplayToken(const sp<SurfaceFlinger>& flinger)
243 sp<BBinder> token = new DisplayToken(this);
245 Mutex::Autolock _l(mStateLock);
246 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
247 info.displayName = displayName;
248 info.isSecure = secure;
249 mCurrentState.displays.add(token, info);
254 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
255 Mutex::Autolock _l(mStateLock);
257 ssize_t idx = mCurrentState.displays.indexOfKey(display);
259 ALOGW("destroyDisplay: invalid display token");
263 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
264 if (!info.isVirtualDisplay()) {
265 ALOGE("destroyDisplay called for non-virtual display");
269 mCurrentState.displays.removeItemsAt(idx);
270 setTransactionFlags(eDisplayTransactionNeeded);
273 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
274 ALOGW_IF(mBuiltinDisplays[type],
275 "Overwriting display token for display type %d", type);
276 mBuiltinDisplays[type] = new BBinder();
277 DisplayDeviceState info(type);
278 // All non-virtual displays are currently considered secure.
279 info.isSecure = true;
280 mCurrentState.displays.add(mBuiltinDisplays[type], info);
283 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
284 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
285 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
288 return mBuiltinDisplays[id];
291 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
293 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
297 void SurfaceFlinger::bootFinished()
299 const nsecs_t now = systemTime();
300 const nsecs_t duration = now - mBootTime;
301 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
302 mBootFinished = true;
304 // wait patiently for the window manager death
305 const String16 name("window");
306 sp<IBinder> window(defaultServiceManager()->getService(name));
308 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
311 // stop boot animation
312 // formerly we would just kill the process, but we now ask it to exit so it
313 // can choose where to stop the animation.
314 property_set("service.bootanim.exit", "1");
317 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
318 class MessageDestroyGLTexture : public MessageBase {
319 RenderEngine& engine;
322 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
323 : engine(engine), texture(texture) {
325 virtual bool handler() {
326 engine.deleteTextures(1, &texture);
330 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
333 class DispSyncSource : public VSyncSource, private DispSync::Callback {
335 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
338 mTraceVsync(traceVsync),
339 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
340 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
345 mPhaseOffset(phaseOffset),
348 virtual ~DispSyncSource() {}
350 virtual void setVSyncEnabled(bool enable) {
351 Mutex::Autolock lock(mVsyncMutex);
353 status_t err = mDispSync->addEventListener(mPhaseOffset,
354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error registering vsync callback: %s (%d)",
357 strerror(-err), err);
359 //ATRACE_INT(mVsyncOnLabel.string(), 1);
361 status_t err = mDispSync->removeEventListener(
362 static_cast<DispSync::Callback*>(this));
363 if (err != NO_ERROR) {
364 ALOGE("error unregistering vsync callback: %s (%d)",
365 strerror(-err), err);
367 //ATRACE_INT(mVsyncOnLabel.string(), 0);
372 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
373 Mutex::Autolock lock(mCallbackMutex);
374 mCallback = callback;
377 virtual void setPhaseOffset(nsecs_t phaseOffset) {
378 Mutex::Autolock lock(mVsyncMutex);
380 // Normalize phaseOffset to [0, period)
381 auto period = mDispSync->getPeriod();
382 phaseOffset %= period;
383 if (phaseOffset < 0) {
384 // If we're here, then phaseOffset is in (-period, 0). After this
385 // operation, it will be in (0, period)
386 phaseOffset += period;
388 mPhaseOffset = phaseOffset;
390 // If we're not enabled, we don't need to mess with the listeners
395 // Remove the listener with the old offset
396 status_t err = mDispSync->removeEventListener(
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error unregistering vsync callback: %s (%d)",
400 strerror(-err), err);
403 // Add a listener with the new offset
404 err = mDispSync->addEventListener(mPhaseOffset,
405 static_cast<DispSync::Callback*>(this));
406 if (err != NO_ERROR) {
407 ALOGE("error registering vsync callback: %s (%d)",
408 strerror(-err), err);
413 virtual void onDispSyncEvent(nsecs_t when) {
414 sp<VSyncSource::Callback> callback;
416 Mutex::Autolock lock(mCallbackMutex);
417 callback = mCallback;
420 mValue = (mValue + 1) % 2;
421 ATRACE_INT(mVsyncEventLabel.string(), mValue);
425 if (callback != NULL) {
426 callback->onVSyncEvent(when);
432 const bool mTraceVsync;
433 const String8 mVsyncOnLabel;
434 const String8 mVsyncEventLabel;
438 Mutex mCallbackMutex; // Protects the following
439 sp<VSyncSource::Callback> mCallback;
441 Mutex mVsyncMutex; // Protects the following
442 nsecs_t mPhaseOffset;
446 void SurfaceFlinger::init() {
447 ALOGI( "SurfaceFlinger's main thread ready to run. "
448 "Initializing graphics H/W...");
450 Mutex::Autolock _l(mStateLock);
452 // initialize EGL for the default display
453 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
454 eglInitialize(mEGLDisplay, NULL, NULL);
456 // start the EventThread
457 if (vsyncPhaseOffsetNs != sfVsyncPhaseOffsetNs) {
458 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
459 vsyncPhaseOffsetNs, true, "app");
460 mEventThread = new EventThread(vsyncSrc);
461 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
462 sfVsyncPhaseOffsetNs, true, "sf");
463 mSFEventThread = new EventThread(sfVsyncSrc);
464 mEventQueue.setEventThread(mSFEventThread);
466 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
467 vsyncPhaseOffsetNs, true, "sf-app");
468 mEventThread = new EventThread(vsyncSrc);
469 mEventQueue.setEventThread(mEventThread);
472 // Initialize the H/W composer object. There may or may not be an
473 // actual hardware composer underneath.
474 mHwc = DisplayUtils::getInstance()->getHWCInstance(this,
475 *static_cast<HWComposer::EventHandler *>(this));
477 // get a RenderEngine for the given display / config (can't fail)
478 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
480 // retrieve the EGL context that was selected/created
481 mEGLContext = mRenderEngine->getEGLContext();
483 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
484 "couldn't create EGLContext");
486 // initialize our non-virtual displays
487 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
488 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
489 // set-up the displays that are already connected
490 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
491 // All non-virtual displays are currently considered secure.
492 bool isSecure = true;
493 createBuiltinDisplayLocked(type);
494 wp<IBinder> token = mBuiltinDisplays[i];
496 sp<IGraphicBufferProducer> producer;
497 sp<IGraphicBufferConsumer> consumer;
498 BufferQueue::createBufferQueue(&producer, &consumer,
499 new GraphicBufferAlloc());
501 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
503 int32_t hwcId = allocateHwcDisplayId(type);
504 sp<DisplayDevice> hw = new DisplayDevice(this,
505 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
507 mRenderEngine->getEGLConfig());
508 if (i > DisplayDevice::DISPLAY_PRIMARY) {
509 // FIXME: currently we don't get blank/unblank requests
510 // for displays other than the main display, so we always
511 // assume a connected display is unblanked.
512 ALOGD("marking display %zu as acquired/unblanked", i);
513 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
515 // When a non-virtual display device is added at boot time,
516 // update the active config by querying HWC otherwise the
517 // default config (config 0) will be used.
518 int activeConfig = mHwc->getActiveConfig(hwcId);
519 if (activeConfig >= 0) {
520 hw->setActiveConfig(activeConfig);
522 mDisplays.add(token, hw);
526 // make the GLContext current so that we can create textures when creating Layers
527 // (which may happens before we render something)
528 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
530 mEventControlThread = new EventControlThread(this);
531 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
532 android_set_rt_ioprio(mEventControlThread->getTid(), 1);
534 // set a fake vsync period if there is no HWComposer
535 if (mHwc->initCheck() != NO_ERROR) {
536 mPrimaryDispSync.setPeriod(16666667);
539 // initialize our drawing state
540 mDrawingState = mCurrentState;
542 // set initial conditions (e.g. unblank default device)
543 initializeDisplays();
545 // start boot animation
549 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
550 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
551 type : mHwc->allocateDisplayId();
554 void SurfaceFlinger::startBootAnim() {
555 // start boot animation
556 property_set("service.bootanim.exit", "0");
557 property_set("ctl.start", "bootanim");
560 size_t SurfaceFlinger::getMaxTextureSize() const {
561 return mRenderEngine->getMaxTextureSize();
564 size_t SurfaceFlinger::getMaxViewportDims() const {
565 return mRenderEngine->getMaxViewportDims();
568 // ----------------------------------------------------------------------------
570 bool SurfaceFlinger::authenticateSurfaceTexture(
571 const sp<IGraphicBufferProducer>& bufferProducer) const {
572 Mutex::Autolock _l(mStateLock);
573 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
574 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
577 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
578 Vector<DisplayInfo>* configs) {
579 if ((configs == NULL) || (display.get() == NULL)) {
584 return NAME_NOT_FOUND;
586 int32_t type = NAME_NOT_FOUND;
587 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
588 if (display == mBuiltinDisplays[i]) {
598 // TODO: Not sure if display density should handled by SF any longer
600 static int getDensityFromProperty(char const* propName) {
601 char property[PROPERTY_VALUE_MAX];
603 if (property_get(propName, property, NULL) > 0) {
604 density = atoi(property);
609 static int getEmuDensity() {
610 return getDensityFromProperty("qemu.sf.lcd_density"); }
611 static int getBuildDensity() {
612 return getDensityFromProperty("ro.sf.lcd_density"); }
617 const Vector<HWComposer::DisplayConfig>& hwConfigs =
618 getHwComposer().getConfigs(type);
619 for (size_t c = 0; c < hwConfigs.size(); ++c) {
620 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
621 DisplayInfo info = DisplayInfo();
623 float xdpi = hwConfig.xdpi;
624 float ydpi = hwConfig.ydpi;
626 if (type == DisplayDevice::DISPLAY_PRIMARY) {
627 // The density of the device is provided by a build property
628 float density = Density::getBuildDensity() / 160.0f;
630 // the build doesn't provide a density -- this is wrong!
632 ALOGE("ro.sf.lcd_density must be defined as a build property");
633 density = xdpi / 160.0f;
635 if (Density::getEmuDensity()) {
636 // if "qemu.sf.lcd_density" is specified, it overrides everything
637 xdpi = ydpi = density = Density::getEmuDensity();
640 info.density = density;
642 // TODO: this needs to go away (currently needed only by webkit)
643 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
644 info.orientation = hw->getOrientation();
646 // TODO: where should this value come from?
647 static const int TV_DENSITY = 213;
648 info.density = TV_DENSITY / 160.0f;
649 info.orientation = 0;
652 char value[PROPERTY_VALUE_MAX];
653 property_get("ro.sf.hwrotation", value, "0");
654 int additionalRot = atoi(value) / 90;
655 if ((type == DisplayDevice::DISPLAY_PRIMARY) && (additionalRot & DisplayState::eOrientationSwapMask)) {
656 info.h = hwConfig.width;
657 info.w = hwConfig.height;
662 info.w = hwConfig.width;
663 info.h = hwConfig.height;
667 info.fps = float(1e9 / hwConfig.refresh);
668 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
669 info.colorTransform = hwConfig.colorTransform;
671 // This is how far in advance a buffer must be queued for
672 // presentation at a given time. If you want a buffer to appear
673 // on the screen at time N, you must submit the buffer before
674 // (N - presentationDeadline).
676 // Normally it's one full refresh period (to give SF a chance to
677 // latch the buffer), but this can be reduced by configuring a
678 // DispSync offset. Any additional delays introduced by the hardware
679 // composer or panel must be accounted for here.
681 // We add an additional 1ms to allow for processing time and
682 // differences between the ideal and actual refresh rate.
683 info.presentationDeadline =
684 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
686 // All non-virtual displays are currently considered secure.
689 configs->push_back(info);
695 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
696 DisplayStatInfo* stats) {
701 // FIXME for now we always return stats for the primary display
702 memset(stats, 0, sizeof(*stats));
703 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
704 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
708 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
709 sp<DisplayDevice> device(getDisplayDevice(display));
710 if (device != NULL) {
711 return device->getActiveConfig();
716 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
717 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
719 int32_t type = hw->getDisplayType();
720 int currentMode = hw->getActiveConfig();
722 if (mode == currentMode) {
723 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
727 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
728 ALOGW("Trying to set config for virtual display");
732 status_t status = getHwComposer().setActiveConfig(type, mode);
733 if (status == NO_ERROR) {
734 hw->setActiveConfig(mode);
738 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
739 class MessageSetActiveConfig: public MessageBase {
740 SurfaceFlinger& mFlinger;
741 sp<IBinder> mDisplay;
744 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
746 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
747 virtual bool handler() {
748 Vector<DisplayInfo> configs;
749 mFlinger.getDisplayConfigs(mDisplay, &configs);
750 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
751 ALOGE("Attempt to set active config = %d for display with %zu configs",
752 mMode, configs.size());
754 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
756 ALOGE("Attempt to set active config = %d for null display %p",
757 mMode, mDisplay.get());
758 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
759 ALOGW("Attempt to set active config = %d for virtual display",
762 mFlinger.setActiveConfigInternal(hw, mMode);
767 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
768 postMessageSync(msg);
772 status_t SurfaceFlinger::clearAnimationFrameStats() {
773 Mutex::Autolock _l(mStateLock);
774 mAnimFrameTracker.clearStats();
778 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
779 Mutex::Autolock _l(mStateLock);
780 mAnimFrameTracker.getStats(outStats);
784 // ----------------------------------------------------------------------------
786 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
787 return mEventThread->createEventConnection();
790 // ----------------------------------------------------------------------------
792 void SurfaceFlinger::waitForEvent() {
793 mEventQueue.waitMessage();
796 void SurfaceFlinger::signalTransaction() {
797 mEventQueue.invalidate();
800 void SurfaceFlinger::signalLayerUpdate() {
801 mEventQueue.invalidate();
804 void SurfaceFlinger::signalRefresh() {
805 mEventQueue.refresh();
808 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
809 nsecs_t reltime, uint32_t /* flags */) {
810 return mEventQueue.postMessage(msg, reltime);
813 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
814 nsecs_t reltime, uint32_t /* flags */) {
815 status_t res = mEventQueue.postMessage(msg, reltime);
816 if (res == NO_ERROR) {
822 void SurfaceFlinger::run() {
828 void SurfaceFlinger::enableHardwareVsync() {
829 Mutex::Autolock _l(mHWVsyncLock);
830 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
831 mPrimaryDispSync.beginResync();
832 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
833 mEventControlThread->setVsyncEnabled(true);
834 mPrimaryHWVsyncEnabled = true;
838 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
839 Mutex::Autolock _l(mHWVsyncLock);
842 mHWVsyncAvailable = true;
843 } else if (!mHWVsyncAvailable) {
844 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
848 const nsecs_t period =
849 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
851 mPrimaryDispSync.reset();
852 mPrimaryDispSync.setPeriod(period);
854 if (!mPrimaryHWVsyncEnabled) {
855 mPrimaryDispSync.beginResync();
856 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
857 mEventControlThread->setVsyncEnabled(true);
858 mPrimaryHWVsyncEnabled = true;
862 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
863 Mutex::Autolock _l(mHWVsyncLock);
864 if (mPrimaryHWVsyncEnabled) {
865 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
866 mEventControlThread->setVsyncEnabled(false);
867 mPrimaryDispSync.endResync();
868 mPrimaryHWVsyncEnabled = false;
870 if (makeUnavailable) {
871 mHWVsyncAvailable = false;
875 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
876 bool needsHwVsync = false;
878 { // Scope for the lock
879 Mutex::Autolock _l(mHWVsyncLock);
880 if (type == 0 && mPrimaryHWVsyncEnabled) {
881 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
886 enableHardwareVsync();
888 disableHardwareVsync(false);
892 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
893 if (mEventThread == NULL) {
894 // This is a temporary workaround for b/7145521. A non-null pointer
895 // does not mean EventThread has finished initializing, so this
896 // is not a correct fix.
897 ALOGW("WARNING: EventThread not started, ignoring hotplug");
901 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
902 Mutex::Autolock _l(mStateLock);
904 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
906 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
907 mBuiltinDisplays[type].clear();
908 updateVisibleRegionsDirty();
910 setTransactionFlags(eDisplayTransactionNeeded);
912 // Defer EventThread notification until SF has updated mDisplays.
916 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
918 getHwComposer().eventControl(disp, event, enabled);
921 void SurfaceFlinger::onMessageReceived(int32_t what) {
924 case MessageQueue::TRANSACTION: {
925 handleMessageTransaction();
928 case MessageQueue::INVALIDATE: {
929 bool refreshNeeded = handleMessageTransaction();
930 refreshNeeded |= handleMessageInvalidate();
931 refreshNeeded |= mRepaintEverything;
933 // Signal a refresh if a transaction modified the window state,
934 // a new buffer was latched, or if HWC has requested a full
940 case MessageQueue::REFRESH: {
941 handleMessageRefresh();
947 bool SurfaceFlinger::handleMessageTransaction() {
948 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
949 if (transactionFlags) {
950 handleTransaction(transactionFlags);
956 bool SurfaceFlinger::handleMessageInvalidate() {
958 return handlePageFlip();
961 void SurfaceFlinger::handleMessageRefresh() {
964 static nsecs_t previousExpectedPresent = 0;
965 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
966 static bool previousFrameMissed = false;
967 bool frameMissed = (expectedPresent == previousExpectedPresent);
968 if (frameMissed != previousFrameMissed) {
969 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
971 previousFrameMissed = frameMissed;
973 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
974 // Latch buffers, but don't send anything to HWC, then signal another
975 // wakeup for the next vsync
980 rebuildLayerStacks();
982 doDebugFlashRegions();
987 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
990 void SurfaceFlinger::doDebugFlashRegions()
992 // is debugging enabled
993 if (CC_LIKELY(!mDebugRegion))
996 const bool repaintEverything = mRepaintEverything;
997 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
998 const sp<DisplayDevice>& hw(mDisplays[dpy]);
999 if (hw->isDisplayOn()) {
1000 // transform the dirty region into this screen's coordinate space
1001 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1002 if (!dirtyRegion.isEmpty()) {
1003 // redraw the whole screen
1004 doComposeSurfaces(hw, Region(hw->bounds()));
1006 // and draw the dirty region
1007 const int32_t height = hw->getHeight();
1008 RenderEngine& engine(getRenderEngine());
1009 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1011 hw->compositionComplete();
1012 hw->swapBuffers(getHwComposer());
1019 if (mDebugRegion > 1) {
1020 usleep(mDebugRegion * 1000);
1023 HWComposer& hwc(getHwComposer());
1024 if (hwc.initCheck() == NO_ERROR) {
1025 status_t err = hwc.prepare();
1026 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1030 void SurfaceFlinger::preComposition()
1032 bool needExtraInvalidate = false;
1033 const LayerVector& layers(mDrawingState.layersSortedByZ);
1034 const size_t count = layers.size();
1035 for (size_t i=0 ; i<count ; i++) {
1036 if (layers[i]->onPreComposition()) {
1037 needExtraInvalidate = true;
1040 if (needExtraInvalidate) {
1041 signalLayerUpdate();
1045 void SurfaceFlinger::postComposition()
1047 const LayerVector& layers(mDrawingState.layersSortedByZ);
1048 const size_t count = layers.size();
1049 for (size_t i=0 ; i<count ; i++) {
1050 layers[i]->onPostComposition();
1053 const HWComposer& hwc = getHwComposer();
1054 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1056 if (presentFence->isValid()) {
1057 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1058 enableHardwareVsync();
1060 disableHardwareVsync(false);
1064 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1065 if (kIgnorePresentFences) {
1066 if (hw->isDisplayOn()) {
1067 enableHardwareVsync();
1071 if (mAnimCompositionPending) {
1072 mAnimCompositionPending = false;
1074 if (presentFence->isValid()) {
1075 mAnimFrameTracker.setActualPresentFence(presentFence);
1077 // The HWC doesn't support present fences, so use the refresh
1078 // timestamp instead.
1079 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1080 mAnimFrameTracker.setActualPresentTime(presentTime);
1082 mAnimFrameTracker.advanceFrame();
1085 dumpDrawCycle(false);
1087 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1091 nsecs_t currentTime = systemTime();
1092 if (mHasPoweredOff) {
1093 mHasPoweredOff = false;
1095 nsecs_t period = mPrimaryDispSync.getPeriod();
1096 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1097 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1098 if (numPeriods < NUM_BUCKETS - 1) {
1099 mFrameBuckets[numPeriods] += elapsedTime;
1101 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1103 mTotalTime += elapsedTime;
1105 mLastSwapTime = currentTime;
1108 void SurfaceFlinger::rebuildLayerStacks() {
1109 updateExtendedMode();
1110 // rebuild the visible layer list per screen
1111 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1113 mVisibleRegionsDirty = false;
1114 invalidateHwcGeometry();
1116 const LayerVector& layers(mDrawingState.layersSortedByZ);
1117 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1118 Region opaqueRegion;
1120 Vector< sp<Layer> > layersSortedByZ;
1121 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1122 const Transform& tr(hw->getTransform());
1123 const Rect bounds(hw->getBounds());
1124 if (hw->isDisplayOn()) {
1125 computeVisibleRegions(hw->getHwcDisplayId(), layers,
1126 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1128 const size_t count = layers.size();
1129 for (size_t i=0 ; i<count ; i++) {
1130 const sp<Layer>& layer(layers[i]);
1132 Region drawRegion(tr.transform(
1133 layer->visibleNonTransparentRegion));
1134 drawRegion.andSelf(bounds);
1135 if (!drawRegion.isEmpty()) {
1136 layersSortedByZ.add(layer);
1141 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1142 hw->undefinedRegion.set(bounds);
1143 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1144 hw->dirtyRegion.orSelf(dirtyRegion);
1149 void SurfaceFlinger::setUpHWComposer() {
1150 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1151 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1152 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1153 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1155 // If nothing has changed (!dirty), don't recompose.
1156 // If something changed, but we don't currently have any visible layers,
1157 // and didn't when we last did a composition, then skip it this time.
1158 // The second rule does two things:
1159 // - When all layers are removed from a display, we'll emit one black
1160 // frame, then nothing more until we get new layers.
1161 // - When a display is created with a private layer stack, we won't
1162 // emit any black frames until a layer is added to the layer stack.
1163 bool mustRecompose = dirty && !(empty && wasEmpty);
1165 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1166 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1167 mustRecompose ? "doing" : "skipping",
1170 wasEmpty ? "+" : "-");
1172 mDisplays[dpy]->beginFrame(mustRecompose);
1174 if (mustRecompose) {
1175 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1179 HWComposer& hwc(getHwComposer());
1180 if (hwc.initCheck() == NO_ERROR) {
1181 // build the h/w work list
1182 if (CC_UNLIKELY(mHwWorkListDirty)) {
1183 mHwWorkListDirty = false;
1184 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1185 sp<const DisplayDevice> hw(mDisplays[dpy]);
1186 const int32_t id = hw->getHwcDisplayId();
1188 const Vector< sp<Layer> >& currentLayers(
1189 hw->getVisibleLayersSortedByZ());
1190 const size_t count = currentLayers.size();
1191 if (hwc.createWorkList(id, count) == NO_ERROR) {
1192 HWComposer::LayerListIterator cur = hwc.begin(id);
1193 const HWComposer::LayerListIterator end = hwc.end(id);
1194 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1195 const sp<Layer>& layer(currentLayers[i]);
1196 layer->setGeometry(hw, *cur);
1197 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix || mHasSecondaryColorMatrix) {
1206 // set the per-frame data
1207 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1208 sp<const DisplayDevice> hw(mDisplays[dpy]);
1209 const int32_t id = hw->getHwcDisplayId();
1211 bool freezeSurfacePresent = false;
1212 isfreezeSurfacePresent(freezeSurfacePresent, hw, id);
1213 const Vector< sp<Layer> >& currentLayers(
1214 hw->getVisibleLayersSortedByZ());
1215 const size_t count = currentLayers.size();
1216 HWComposer::LayerListIterator cur = hwc.begin(id);
1217 const HWComposer::LayerListIterator end = hwc.end(id);
1218 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1220 * update the per-frame h/w composer data for each layer
1221 * and build the transparent region of the FB
1223 const sp<Layer>& layer(currentLayers[i]);
1224 layer->setPerFrameData(hw, *cur);
1225 setOrientationEventControl(freezeSurfacePresent,id);
1226 if(!strncmp(layer->getName(), "SurfaceView",
1228 lastSurfaceViewLayer = layer;
1234 // If possible, attempt to use the cursor overlay on each display.
1235 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1236 sp<const DisplayDevice> hw(mDisplays[dpy]);
1237 const int32_t id = hw->getHwcDisplayId();
1239 const Vector< sp<Layer> >& currentLayers(
1240 hw->getVisibleLayersSortedByZ());
1241 const size_t count = currentLayers.size();
1242 HWComposer::LayerListIterator cur = hwc.begin(id);
1243 const HWComposer::LayerListIterator end = hwc.end(id);
1244 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1245 const sp<Layer>& layer(currentLayers[i]);
1246 if (layer->isPotentialCursor()) {
1247 cur->setIsCursorLayerHint();
1254 dumpDrawCycle(true);
1256 status_t err = hwc.prepare();
1257 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1259 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1260 sp<const DisplayDevice> hw(mDisplays[dpy]);
1261 hw->prepareFrame(hwc);
1266 void SurfaceFlinger::doComposition() {
1268 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1269 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1270 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1271 if (hw->isDisplayOn()) {
1272 // transform the dirty region into this screen's coordinate space
1273 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1275 // repaint the framebuffer (if needed)
1276 doDisplayComposition(hw, dirtyRegion);
1278 ++mActiveFrameSequence;
1280 hw->dirtyRegion.clear();
1281 hw->flip(hw->swapRegion);
1282 hw->swapRegion.clear();
1284 // inform the h/w that we're done compositing
1285 hw->compositionComplete();
1290 void SurfaceFlinger::postFramebuffer()
1294 const nsecs_t now = systemTime();
1295 mDebugInSwapBuffers = now;
1297 HWComposer& hwc(getHwComposer());
1298 if (hwc.initCheck() == NO_ERROR) {
1299 if (!hwc.supportsFramebufferTarget()) {
1301 // "surface must be bound to the calling thread's current context,
1302 // for the current rendering API."
1303 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1308 // make the default display current because the VirtualDisplayDevice code cannot
1309 // deal with dequeueBuffer() being called outside of the composition loop; however
1310 // the code below can call glFlush() which is allowed (and does in some case) call
1312 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1314 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1315 sp<const DisplayDevice> hw(mDisplays[dpy]);
1316 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1317 hw->onSwapBuffersCompleted(hwc);
1318 const size_t count = currentLayers.size();
1319 int32_t id = hw->getHwcDisplayId();
1320 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1321 HWComposer::LayerListIterator cur = hwc.begin(id);
1322 const HWComposer::LayerListIterator end = hwc.end(id);
1323 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1324 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1327 for (size_t i = 0; i < count; i++) {
1328 currentLayers[i]->onLayerDisplayed(hw, NULL);
1333 mLastSwapBufferTime = systemTime() - now;
1334 mDebugInSwapBuffers = 0;
1336 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1337 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1340 ALOGV_IF(mFrameRateHelper.update(), "FPS: %d", mFrameRateHelper.get());
1343 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1347 // here we keep a copy of the drawing state (that is the state that's
1348 // going to be overwritten by handleTransactionLocked()) outside of
1349 // mStateLock so that the side-effects of the State assignment
1350 // don't happen with mStateLock held (which can cause deadlocks).
1351 State drawingState(mDrawingState);
1353 Mutex::Autolock _l(mStateLock);
1354 const nsecs_t now = systemTime();
1355 mDebugInTransaction = now;
1357 // Here we're guaranteed that some transaction flags are set
1358 // so we can call handleTransactionLocked() unconditionally.
1359 // We call getTransactionFlags(), which will also clear the flags,
1360 // with mStateLock held to guarantee that mCurrentState won't change
1361 // until the transaction is committed.
1363 transactionFlags = getTransactionFlags(eTransactionMask);
1364 handleTransactionLocked(transactionFlags);
1366 mLastTransactionTime = systemTime() - now;
1367 mDebugInTransaction = 0;
1368 invalidateHwcGeometry();
1369 // here the transaction has been committed
1372 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1374 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1375 const size_t count = currentLayers.size();
1378 * Traversal of the children
1379 * (perform the transaction for each of them if needed)
1382 if (transactionFlags & eTraversalNeeded) {
1383 for (size_t i=0 ; i<count ; i++) {
1384 const sp<Layer>& layer(currentLayers[i]);
1385 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1386 if (!trFlags) continue;
1388 const uint32_t flags = layer->doTransaction(0);
1389 if (flags & Layer::eVisibleRegion)
1390 mVisibleRegionsDirty = true;
1395 * Perform display own transactions if needed
1398 if (transactionFlags & eDisplayTransactionNeeded) {
1399 // here we take advantage of Vector's copy-on-write semantics to
1400 // improve performance by skipping the transaction entirely when
1401 // know that the lists are identical
1402 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1403 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1404 if (!curr.isIdenticalTo(draw)) {
1405 mVisibleRegionsDirty = true;
1406 const size_t cc = curr.size();
1407 size_t dc = draw.size();
1409 // find the displays that were removed
1410 // (ie: in drawing state but not in current state)
1411 // also handle displays that changed
1412 // (ie: displays that are in both lists)
1413 for (size_t i=0 ; i<dc ; i++) {
1414 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1416 // in drawing state but not in current state
1417 if (!draw[i].isMainDisplay()) {
1418 // Call makeCurrent() on the primary display so we can
1419 // be sure that nothing associated with this display
1421 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1422 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1423 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1425 hw->disconnect(getHwComposer());
1426 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1427 mEventThread->onHotplugReceived(draw[i].type, false);
1428 mDisplays.removeItem(draw.keyAt(i));
1430 ALOGW("trying to remove the main display");
1433 // this display is in both lists. see if something changed.
1434 const DisplayDeviceState& state(curr[j]);
1435 const wp<IBinder>& display(curr.keyAt(j));
1436 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1437 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1438 if (state_binder != draw_binder) {
1439 // changing the surface is like destroying and
1440 // recreating the DisplayDevice, so we just remove it
1441 // from the drawing state, so that it get re-added
1443 sp<DisplayDevice> hw(getDisplayDevice(display));
1445 hw->disconnect(getHwComposer());
1446 mDisplays.removeItem(display);
1447 mDrawingState.displays.removeItemsAt(i);
1449 // at this point we must loop to the next item
1453 const sp<DisplayDevice> disp(getDisplayDevice(display));
1455 if (state.layerStack != draw[i].layerStack) {
1456 disp->setLayerStack(state.layerStack);
1458 if ((state.orientation != draw[i].orientation)
1459 || (state.viewport != draw[i].viewport)
1460 || (state.frame != draw[i].frame))
1462 disp->setProjection(state.orientation,
1463 state.viewport, state.frame);
1465 if (state.width != draw[i].width || state.height != draw[i].height) {
1466 disp->setDisplaySize(state.width, state.height);
1472 // find displays that were added
1473 // (ie: in current state but not in drawing state)
1474 for (size_t i=0 ; i<cc ; i++) {
1475 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1476 const DisplayDeviceState& state(curr[i]);
1478 sp<DisplaySurface> dispSurface;
1479 sp<IGraphicBufferProducer> producer;
1480 sp<IGraphicBufferProducer> bqProducer;
1481 sp<IGraphicBufferConsumer> bqConsumer;
1482 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1483 new GraphicBufferAlloc());
1485 int32_t hwcDisplayId = -1;
1486 if (state.isVirtualDisplay()) {
1487 // Virtual displays without a surface are dormant:
1488 // they have external state (layer stack, projection,
1489 // etc.) but no internal state (i.e. a DisplayDevice).
1490 if (state.surface != NULL) {
1493 DisplayUtils* displayUtils = DisplayUtils::getInstance();
1494 int status = state.surface->query(
1495 NATIVE_WINDOW_WIDTH, &width);
1496 ALOGE_IF(status != NO_ERROR,
1497 "Unable to query width (%d)", status);
1499 status = state.surface->query(
1500 NATIVE_WINDOW_HEIGHT, &height);
1501 ALOGE_IF(status != NO_ERROR,
1502 "Unable to query height (%d)", status);
1503 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1504 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1505 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1507 status = state.surface->query(
1508 NATIVE_WINDOW_CONSUMER_USAGE_BITS, &usage);
1509 ALOGW_IF(status != NO_ERROR,
1510 "Unable to query usage (%d)", status);
1511 if ( (status == NO_ERROR) &&
1512 displayUtils->canAllocateHwcDisplayIdForVDS(usage)) {
1513 hwcDisplayId = allocateHwcDisplayId(state.type);
1517 displayUtils->initVDSInstance(mHwc, hwcDisplayId, state.surface,
1518 dispSurface, producer, bqProducer, bqConsumer,
1519 state.displayName, state.isSecure, state.type);
1523 ALOGE_IF(state.surface!=NULL,
1524 "adding a supported display, but rendering "
1525 "surface is provided (%p), ignoring it",
1526 state.surface.get());
1527 hwcDisplayId = allocateHwcDisplayId(state.type);
1528 // for supported (by hwc) displays we provide our
1529 // own rendering surface
1530 dispSurface = new FramebufferSurface(*mHwc, state.type,
1532 producer = bqProducer;
1535 const wp<IBinder>& display(curr.keyAt(i));
1536 if (dispSurface != NULL && producer != NULL) {
1537 sp<DisplayDevice> hw = new DisplayDevice(this,
1538 state.type, hwcDisplayId,
1539 mHwc->getFormat(hwcDisplayId), state.isSecure,
1540 display, dispSurface, producer,
1541 mRenderEngine->getEGLConfig());
1542 hw->setLayerStack(state.layerStack);
1543 hw->setProjection(state.orientation,
1544 state.viewport, state.frame);
1545 hw->setDisplayName(state.displayName);
1546 // When a new display device is added update the active
1547 // config by querying HWC otherwise the default config
1548 // (config 0) will be used.
1549 if (hwcDisplayId >= DisplayDevice::DISPLAY_PRIMARY &&
1550 hwcDisplayId < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1551 int activeConfig = mHwc->getActiveConfig(hwcDisplayId);
1552 if (activeConfig >= 0) {
1553 hw->setActiveConfig(activeConfig);
1556 mDisplays.add(display, hw);
1557 if (state.isVirtualDisplay()) {
1558 if (hwcDisplayId >= 0) {
1559 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1560 hw->getWidth(), hw->getHeight(),
1564 mEventThread->onHotplugReceived(state.type, true);
1572 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1573 // The transform hint might have changed for some layers
1574 // (either because a display has changed, or because a layer
1577 // Walk through all the layers in currentLayers,
1578 // and update their transform hint.
1580 // If a layer is visible only on a single display, then that
1581 // display is used to calculate the hint, otherwise we use the
1584 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1585 // the hint is set before we acquire a buffer from the surface texture.
1587 // NOTE: layer transactions have taken place already, so we use their
1588 // drawing state. However, SurfaceFlinger's own transaction has not
1589 // happened yet, so we must use the current state layer list
1590 // (soon to become the drawing state list).
1592 sp<const DisplayDevice> disp;
1593 uint32_t currentlayerStack = 0;
1594 for (size_t i=0; i<count; i++) {
1595 // NOTE: we rely on the fact that layers are sorted by
1596 // layerStack first (so we don't have to traverse the list
1597 // of displays for every layer).
1598 const sp<Layer>& layer(currentLayers[i]);
1599 uint32_t layerStack = layer->getDrawingState().layerStack;
1600 if (i==0 || currentlayerStack != layerStack) {
1601 currentlayerStack = layerStack;
1602 // figure out if this layerstack is mirrored
1603 // (more than one display) if so, pick the default display,
1604 // if not, pick the only display it's on.
1606 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1607 sp<const DisplayDevice> hw(mDisplays[dpy]);
1608 if (hw->getLayerStack() == currentlayerStack) {
1619 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1620 // redraw after transform hint changes. See bug 8508397.
1622 // could be null when this layer is using a layerStack
1623 // that is not visible on any display. Also can occur at
1624 // screen off/on times.
1625 disp = getDefaultDisplayDevice();
1627 layer->updateTransformHint(disp);
1633 * Perform our own transaction if needed
1636 const LayerVector& layers(mDrawingState.layersSortedByZ);
1637 if (currentLayers.size() > layers.size()) {
1638 // layers have been added
1639 mVisibleRegionsDirty = true;
1642 // some layers might have been removed, so
1643 // we need to update the regions they're exposing.
1644 if (mLayersRemoved) {
1645 mLayersRemoved = false;
1646 mVisibleRegionsDirty = true;
1647 const size_t count = layers.size();
1648 for (size_t i=0 ; i<count ; i++) {
1649 const sp<Layer>& layer(layers[i]);
1650 if (currentLayers.indexOf(layer) < 0) {
1651 // this layer is not visible anymore
1652 // TODO: we could traverse the tree from front to back and
1653 // compute the actual visible region
1654 // TODO: we could cache the transformed region
1655 const Layer::State& s(layer->getDrawingState());
1656 Region visibleReg = s.transform.transform(
1657 Region(Rect(s.active.w, s.active.h)));
1658 invalidateLayerStack(s.layerStack, visibleReg);
1663 commitTransaction();
1665 updateCursorAsync();
1668 void SurfaceFlinger::updateCursorAsync()
1670 HWComposer& hwc(getHwComposer());
1671 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1672 sp<const DisplayDevice> hw(mDisplays[dpy]);
1673 const int32_t id = hw->getHwcDisplayId();
1677 const Vector< sp<Layer> >& currentLayers(
1678 hw->getVisibleLayersSortedByZ());
1679 const size_t count = currentLayers.size();
1680 HWComposer::LayerListIterator cur = hwc.begin(id);
1681 const HWComposer::LayerListIterator end = hwc.end(id);
1682 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1683 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1686 const sp<Layer>& layer(currentLayers[i]);
1687 Rect cursorPos = layer->getPosition(hw);
1688 hwc.setCursorPositionAsync(id, cursorPos);
1694 void SurfaceFlinger::commitTransaction()
1696 if (!mLayersPendingRemoval.isEmpty()) {
1697 // Notify removed layers now that they can't be drawn from
1698 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1699 mLayersPendingRemoval[i]->onRemoved();
1701 mLayersPendingRemoval.clear();
1704 // If this transaction is part of a window animation then the next frame
1705 // we composite should be considered an animation as well.
1706 mAnimCompositionPending = mAnimTransactionPending;
1708 mDrawingState = mCurrentState;
1709 mTransactionPending = false;
1710 mAnimTransactionPending = false;
1711 mTransactionCV.broadcast();
1714 void SurfaceFlinger::computeVisibleRegions(size_t dpy,
1715 const LayerVector& currentLayers, uint32_t layerStack,
1716 Region& outDirtyRegion, Region& outOpaqueRegion)
1720 Region aboveOpaqueLayers;
1721 Region aboveCoveredLayers;
1724 outDirtyRegion.clear();
1725 bool bIgnoreLayers = false;
1727 getIndexLOI(dpy, currentLayers, bIgnoreLayers, indexLOI);
1729 size_t i = currentLayers.size();
1731 const sp<Layer>& layer = currentLayers[i];
1733 // start with the whole surface at its current location
1734 const Layer::State& s(layer->getDrawingState());
1736 if(updateLayerVisibleNonTransparentRegion(dpy, layer,
1737 bIgnoreLayers, indexLOI,
1742 * opaqueRegion: area of a surface that is fully opaque.
1744 Region opaqueRegion;
1747 * visibleRegion: area of a surface that is visible on screen
1748 * and not fully transparent. This is essentially the layer's
1749 * footprint minus the opaque regions above it.
1750 * Areas covered by a translucent surface are considered visible.
1752 Region visibleRegion;
1755 * coveredRegion: area of a surface that is covered by all
1756 * visible regions above it (which includes the translucent areas).
1758 Region coveredRegion;
1761 * transparentRegion: area of a surface that is hinted to be completely
1762 * transparent. This is only used to tell when the layer has no visible
1763 * non-transparent regions and can be removed from the layer list. It
1764 * does not affect the visibleRegion of this layer or any layers
1765 * beneath it. The hint may not be correct if apps don't respect the
1766 * SurfaceView restrictions (which, sadly, some don't).
1768 Region transparentRegion;
1771 // handle hidden surfaces by setting the visible region to empty
1772 if (CC_LIKELY(layer->isVisible())) {
1773 const bool translucent = !layer->isOpaque(s);
1774 Rect bounds(s.transform.transform(layer->computeBounds()));
1775 visibleRegion.set(bounds);
1776 if (!visibleRegion.isEmpty()) {
1777 // Remove the transparent area from the visible region
1779 const Transform tr(s.transform);
1780 if (tr.transformed()) {
1781 if (tr.preserveRects()) {
1782 // transform the transparent region
1783 transparentRegion = tr.transform(s.activeTransparentRegion);
1785 // transformation too complex, can't do the
1786 // transparent region optimization.
1787 transparentRegion.clear();
1790 transparentRegion = s.activeTransparentRegion;
1794 // compute the opaque region
1795 const int32_t layerOrientation = s.transform.getOrientation();
1796 if (s.alpha==255 && !translucent &&
1797 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1798 // the opaque region is the layer's footprint
1799 opaqueRegion = visibleRegion;
1804 // Clip the covered region to the visible region
1805 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1807 // Update aboveCoveredLayers for next (lower) layer
1808 aboveCoveredLayers.orSelf(visibleRegion);
1810 // subtract the opaque region covered by the layers above us
1811 visibleRegion.subtractSelf(aboveOpaqueLayers);
1813 // compute this layer's dirty region
1814 if (layer->contentDirty) {
1815 // we need to invalidate the whole region
1816 dirty = visibleRegion;
1817 // as well, as the old visible region
1818 dirty.orSelf(layer->visibleRegion);
1819 layer->contentDirty = false;
1821 /* compute the exposed region:
1822 * the exposed region consists of two components:
1823 * 1) what's VISIBLE now and was COVERED before
1824 * 2) what's EXPOSED now less what was EXPOSED before
1826 * note that (1) is conservative, we start with the whole
1827 * visible region but only keep what used to be covered by
1828 * something -- which mean it may have been exposed.
1830 * (2) handles areas that were not covered by anything but got
1831 * exposed because of a resize.
1833 const Region newExposed = visibleRegion - coveredRegion;
1834 const Region oldVisibleRegion = layer->visibleRegion;
1835 const Region oldCoveredRegion = layer->coveredRegion;
1836 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1837 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1839 dirty.subtractSelf(aboveOpaqueLayers);
1841 // accumulate to the screen dirty region
1842 outDirtyRegion.orSelf(dirty);
1844 // Update aboveOpaqueLayers for next (lower) layer
1845 aboveOpaqueLayers.orSelf(opaqueRegion);
1847 // Store the visible region in screen space
1848 layer->setVisibleRegion(visibleRegion);
1849 layer->setCoveredRegion(coveredRegion);
1850 layer->setVisibleNonTransparentRegion(
1851 visibleRegion.subtract(transparentRegion));
1854 outOpaqueRegion = aboveOpaqueLayers;
1857 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1858 const Region& dirty) {
1859 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1860 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1861 if (hw->getLayerStack() == layerStack) {
1862 hw->dirtyRegion.orSelf(dirty);
1867 bool SurfaceFlinger::handlePageFlip()
1871 bool visibleRegions = false;
1872 const LayerVector& layers(mDrawingState.layersSortedByZ);
1873 bool frameQueued = false;
1875 // Store the set of layers that need updates. This set must not change as
1876 // buffers are being latched, as this could result in a deadlock.
1877 // Example: Two producers share the same command stream and:
1878 // 1.) Layer 0 is latched
1879 // 2.) Layer 0 gets a new frame
1880 // 2.) Layer 1 gets a new frame
1881 // 3.) Layer 1 is latched.
1882 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1883 // second frame. But layer 0's second frame could be waiting on display.
1884 Vector<Layer*> layersWithQueuedFrames;
1885 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1886 const sp<Layer>& layer(layers[i]);
1887 if (layer->hasQueuedFrame()) {
1889 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1890 layersWithQueuedFrames.push_back(layer.get());
1892 layer->useEmptyDamage();
1895 layer->useEmptyDamage();
1898 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1899 Layer* layer = layersWithQueuedFrames[i];
1900 const Region dirty(layer->latchBuffer(visibleRegions));
1901 layer->useSurfaceDamage();
1902 const Layer::State& s(layer->getDrawingState());
1903 invalidateLayerStack(s.layerStack, dirty);
1906 mVisibleRegionsDirty |= visibleRegions;
1908 // If we will need to wake up at some time in the future to deal with a
1909 // queued frame that shouldn't be displayed during this vsync period, wake
1910 // up during the next vsync period to check again.
1911 if (frameQueued && layersWithQueuedFrames.empty()) {
1912 signalLayerUpdate();
1915 // Only continue with the refresh if there is actually new work to do
1916 return !layersWithQueuedFrames.empty();
1919 void SurfaceFlinger::invalidateHwcGeometry()
1921 mHwWorkListDirty = true;
1925 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1926 const Region& inDirtyRegion)
1928 // We only need to actually compose the display if:
1929 // 1) It is being handled by hardware composer, which may need this to
1930 // keep its virtual display state machine in sync, or
1931 // 2) There is work to be done (the dirty region isn't empty)
1932 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1933 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1937 Region dirtyRegion(inDirtyRegion);
1939 // compute the invalid region
1940 hw->swapRegion.orSelf(dirtyRegion);
1942 uint32_t flags = hw->getFlags();
1943 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1944 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1945 // takes a rectangle, we must make sure to update that whole
1946 // rectangle in that case
1947 dirtyRegion.set(hw->swapRegion.bounds());
1949 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1950 // We need to redraw the rectangle that will be updated
1951 // (pushed to the framebuffer).
1952 // This is needed because PARTIAL_UPDATES only takes one
1953 // rectangle instead of a region (see DisplayDevice::flip())
1954 dirtyRegion.set(hw->swapRegion.bounds());
1956 // we need to redraw everything (the whole screen)
1957 dirtyRegion.set(hw->bounds());
1958 hw->swapRegion = dirtyRegion;
1962 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix && !mHasSecondaryColorMatrix)) {
1963 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1965 RenderEngine& engine(getRenderEngine());
1966 mat4 colorMatrix = mColorMatrix;
1967 if (mHasSecondaryColorMatrix) {
1968 colorMatrix = mHasColorMatrix ? (colorMatrix * mSecondaryColorMatrix) : mSecondaryColorMatrix;
1971 colorMatrix = colorMatrix * mDaltonizer();
1973 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1974 doComposeSurfaces(hw, dirtyRegion);
1975 engine.setupColorTransform(oldMatrix);
1978 // update the swap region and clear the dirty region
1979 hw->swapRegion.orSelf(dirtyRegion);
1981 // swap buffers (presentation)
1982 hw->swapBuffers(getHwComposer());
1985 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1987 RenderEngine& engine(getRenderEngine());
1988 const int32_t id = hw->getHwcDisplayId();
1989 HWComposer& hwc(getHwComposer());
1990 HWComposer::LayerListIterator cur = hwc.begin(id);
1991 const HWComposer::LayerListIterator end = hwc.end(id);
1993 bool hasGlesComposition = hwc.hasGlesComposition(id);
1994 if (hasGlesComposition) {
1995 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1996 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1997 hw->getDisplayName().string());
1998 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1999 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
2000 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2005 // Never touch the framebuffer if we don't have any framebuffer layers
2006 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2007 if (hasHwcComposition) {
2008 // when using overlays, we assume a fully transparent framebuffer
2009 // NOTE: we could reduce how much we need to clear, for instance
2010 // remove where there are opaque FB layers. however, on some
2011 // GPUs doing a "clean slate" clear might be more efficient.
2012 // We'll revisit later if needed.
2013 engine.clearWithColor(0, 0, 0, 0);
2015 // we start with the whole screen area
2016 const Region bounds(hw->getBounds());
2018 // we remove the scissor part
2019 // we're left with the letterbox region
2020 // (common case is that letterbox ends-up being empty)
2021 const Region letterbox(bounds.subtract(hw->getScissor()));
2023 // compute the area to clear
2024 Region region(hw->undefinedRegion.merge(letterbox));
2026 // but limit it to the dirty region
2027 region.andSelf(dirty);
2029 // screen is already cleared here
2030 if (!region.isEmpty()) {
2031 // can happen with SurfaceView
2032 drawWormHoleIfRequired(cur, end, hw, region);
2036 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2037 // just to be on the safe side, we don't set the
2038 // scissor on the main display. It should never be needed
2039 // anyways (though in theory it could since the API allows it).
2040 const Rect& bounds(hw->getBounds());
2041 const Rect& scissor(hw->getScissor());
2042 if (scissor != bounds) {
2043 // scissor doesn't match the screen's dimensions, so we
2044 // need to clear everything outside of it and enable
2045 // the GL scissor so we don't draw anything where we shouldn't
2047 // enable scissor for this frame
2048 const uint32_t height = hw->getHeight();
2049 engine.setScissor(scissor.left, height - scissor.bottom,
2050 scissor.getWidth(), scissor.getHeight());
2056 * and then, render the layers targeted at the framebuffer
2059 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2060 const size_t count = layers.size();
2061 const Transform& tr = hw->getTransform();
2063 // we're using h/w composer
2064 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2065 const sp<Layer>& layer(layers[i]);
2066 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2067 if (!clip.isEmpty()) {
2068 switch (cur->getCompositionType()) {
2069 case HWC_CURSOR_OVERLAY:
2071 const Layer::State& state(layer->getDrawingState());
2072 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2074 && layer->isOpaque(state) && (state.alpha == 0xFF)
2075 && hasGlesComposition) {
2076 // never clear the very first layer since we're
2077 // guaranteed the FB is already cleared
2078 layer->clearWithOpenGL(hw, clip);
2082 case HWC_FRAMEBUFFER: {
2083 layer->draw(hw, clip);
2086 case HWC_FRAMEBUFFER_TARGET: {
2087 // this should not happen as the iterator shouldn't
2088 // let us get there.
2089 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2094 layer->setAcquireFence(hw, *cur);
2097 // we're not using h/w composer
2098 for (size_t i=0 ; i<count ; ++i) {
2099 const sp<Layer>& layer(layers[i]);
2100 const Region clip(dirty.intersect(
2101 tr.transform(layer->visibleRegion)));
2102 if (!clip.isEmpty()) {
2103 layer->draw(hw, clip);
2108 // disable scissor at the end of the frame
2109 engine.disableScissor();
2113 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2114 const int32_t height = hw->getHeight();
2115 RenderEngine& engine(getRenderEngine());
2116 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2119 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2120 const sp<IBinder>& handle,
2121 const sp<IGraphicBufferProducer>& gbc,
2122 const sp<Layer>& lbc)
2124 // add this layer to the current state list
2126 Mutex::Autolock _l(mStateLock);
2127 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2130 mCurrentState.layersSortedByZ.add(lbc);
2131 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2134 // attach this layer to the client
2135 client->attachLayer(handle, lbc);
2140 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2141 Mutex::Autolock _l(mStateLock);
2142 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2144 mLayersPendingRemoval.push(layer);
2145 mLayersRemoved = true;
2146 setTransactionFlags(eTransactionNeeded);
2149 return status_t(index);
2152 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2153 return android_atomic_release_load(&mTransactionFlags);
2156 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2157 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2160 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2161 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2162 if ((old & flags)==0) { // wake the server up
2163 signalTransaction();
2168 void SurfaceFlinger::setTransactionState(
2169 const Vector<ComposerState>& state,
2170 const Vector<DisplayState>& displays,
2175 delayDPTransactionIfNeeded(displays);
2176 Mutex::Autolock _l(mStateLock);
2177 uint32_t transactionFlags = 0;
2179 if (flags & eAnimation) {
2180 // For window updates that are part of an animation we must wait for
2181 // previous animation "frames" to be handled.
2182 while (mAnimTransactionPending) {
2183 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2184 if (CC_UNLIKELY(err != NO_ERROR)) {
2185 // just in case something goes wrong in SF, return to the
2186 // caller after a few seconds.
2187 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2188 "waiting for previous animation frame");
2189 mAnimTransactionPending = false;
2195 size_t count = displays.size();
2196 for (size_t i=0 ; i<count ; i++) {
2197 const DisplayState& s(displays[i]);
2198 transactionFlags |= setDisplayStateLocked(s);
2201 count = state.size();
2202 for (size_t i=0 ; i<count ; i++) {
2203 const ComposerState& s(state[i]);
2204 // Here we need to check that the interface we're given is indeed
2205 // one of our own. A malicious client could give us a NULL
2206 // IInterface, or one of its own or even one of our own but a
2207 // different type. All these situations would cause us to crash.
2209 // NOTE: it would be better to use RTTI as we could directly check
2210 // that we have a Client*. however, RTTI is disabled in Android.
2211 if (s.client != NULL) {
2212 sp<IBinder> binder = IInterface::asBinder(s.client);
2213 if (binder != NULL) {
2214 String16 desc(binder->getInterfaceDescriptor());
2215 if (desc == ISurfaceComposerClient::descriptor) {
2216 sp<Client> client( static_cast<Client *>(s.client.get()) );
2217 transactionFlags |= setClientStateLocked(client, s.state);
2223 if (transactionFlags) {
2224 // this triggers the transaction
2225 setTransactionFlags(transactionFlags);
2227 // if this is a synchronous transaction, wait for it to take effect
2228 // before returning.
2229 if (flags & eSynchronous) {
2230 mTransactionPending = true;
2232 if (flags & eAnimation) {
2233 mAnimTransactionPending = true;
2235 while (mTransactionPending) {
2236 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2237 if (CC_UNLIKELY(err != NO_ERROR)) {
2238 // just in case something goes wrong in SF, return to the
2239 // called after a few seconds.
2240 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2241 mTransactionPending = false;
2248 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2250 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2255 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2256 if (disp.isValid()) {
2257 const uint32_t what = s.what;
2258 if (what & DisplayState::eSurfaceChanged) {
2259 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2260 disp.surface = s.surface;
2261 flags |= eDisplayTransactionNeeded;
2264 if (what & DisplayState::eLayerStackChanged) {
2265 if (disp.layerStack != s.layerStack) {
2266 disp.layerStack = s.layerStack;
2267 flags |= eDisplayTransactionNeeded;
2270 if (what & DisplayState::eDisplayProjectionChanged) {
2271 if (disp.orientation != s.orientation) {
2272 disp.orientation = s.orientation;
2273 flags |= eDisplayTransactionNeeded;
2275 if (disp.frame != s.frame) {
2276 disp.frame = s.frame;
2277 flags |= eDisplayTransactionNeeded;
2279 if (disp.viewport != s.viewport) {
2280 disp.viewport = s.viewport;
2281 flags |= eDisplayTransactionNeeded;
2284 if (what & DisplayState::eDisplaySizeChanged) {
2285 if (disp.width != s.width) {
2286 disp.width = s.width;
2287 flags |= eDisplayTransactionNeeded;
2289 if (disp.height != s.height) {
2290 disp.height = s.height;
2291 flags |= eDisplayTransactionNeeded;
2298 uint32_t SurfaceFlinger::setClientStateLocked(
2299 const sp<Client>& client,
2300 const layer_state_t& s)
2303 sp<Layer> layer(client->getLayerUser(s.surface));
2305 const uint32_t what = s.what;
2306 if (what & layer_state_t::ePositionChanged) {
2307 if (layer->setPosition(s.x, s.y))
2308 flags |= eTraversalNeeded;
2310 if (what & layer_state_t::eLayerChanged) {
2311 // NOTE: index needs to be calculated before we update the state
2312 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2313 if (layer->setLayer(s.z)) {
2314 mCurrentState.layersSortedByZ.removeAt(idx);
2315 mCurrentState.layersSortedByZ.add(layer);
2316 // we need traversal (state changed)
2317 // AND transaction (list changed)
2318 flags |= eTransactionNeeded|eTraversalNeeded;
2321 if (what & layer_state_t::eBlurChanged) {
2322 ALOGV("eBlurChanged");
2323 if (layer->setBlur(uint8_t(255.0f*s.blur+0.5f))) {
2324 flags |= eTraversalNeeded;
2327 if (what & layer_state_t::eBlurMaskSurfaceChanged) {
2328 ALOGV("eBlurMaskSurfaceChanged");
2329 sp<Layer> maskLayer = 0;
2330 if (s.blurMaskSurface != 0) {
2331 maskLayer = client->getLayerUser(s.blurMaskSurface);
2333 if (maskLayer == 0) {
2334 ALOGV("eBlurMaskSurfaceChanged. maskLayer == 0");
2336 ALOGV("eBlurMaskSurfaceChagned. maskLayer.z == %d", maskLayer->getCurrentState().z);
2337 if (maskLayer->isBlurLayer()) {
2338 ALOGE("Blur layer can not be used as blur mask surface");
2342 if (layer->setBlurMaskLayer(maskLayer)) {
2343 flags |= eTraversalNeeded;
2346 if (what & layer_state_t::eBlurMaskSamplingChanged) {
2347 if (layer->setBlurMaskSampling(s.blurMaskSampling)) {
2348 flags |= eTraversalNeeded;
2351 if (what & layer_state_t::eBlurMaskAlphaThresholdChanged) {
2352 if (layer->setBlurMaskAlphaThreshold(s.blurMaskAlphaThreshold)) {
2353 flags |= eTraversalNeeded;
2356 if (what & layer_state_t::eSizeChanged) {
2357 if (layer->setSize(s.w, s.h)) {
2358 flags |= eTraversalNeeded;
2361 if (what & layer_state_t::eAlphaChanged) {
2362 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2363 flags |= eTraversalNeeded;
2365 if (what & layer_state_t::eMatrixChanged) {
2366 if (layer->setMatrix(s.matrix))
2367 flags |= eTraversalNeeded;
2369 if (what & layer_state_t::eTransparentRegionChanged) {
2370 if (layer->setTransparentRegionHint(s.transparentRegion))
2371 flags |= eTraversalNeeded;
2373 if (what & layer_state_t::eFlagsChanged) {
2374 if (layer->setFlags(s.flags, s.mask))
2375 flags |= eTraversalNeeded;
2377 if (what & layer_state_t::eCropChanged) {
2378 if (layer->setCrop(s.crop))
2379 flags |= eTraversalNeeded;
2381 if (what & layer_state_t::eLayerStackChanged) {
2382 // NOTE: index needs to be calculated before we update the state
2383 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2384 if (layer->setLayerStack(s.layerStack)) {
2385 mCurrentState.layersSortedByZ.removeAt(idx);
2386 mCurrentState.layersSortedByZ.add(layer);
2387 // we need traversal (state changed)
2388 // AND transaction (list changed)
2389 flags |= eTransactionNeeded|eTraversalNeeded;
2396 status_t SurfaceFlinger::createLayer(
2397 const String8& name,
2398 const sp<Client>& client,
2399 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2400 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2402 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2403 if (int32_t(w|h) < 0) {
2404 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2409 status_t result = NO_ERROR;
2413 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2414 case ISurfaceComposerClient::eFXSurfaceNormal:
2415 result = createNormalLayer(client,
2416 name, w, h, flags, format,
2417 handle, gbp, &layer);
2419 case ISurfaceComposerClient::eFXSurfaceDim:
2420 result = createDimLayer(client,
2422 handle, gbp, &layer);
2424 case ISurfaceComposerClient::eFXSurfaceBlur:
2425 result = createBlurLayer(client,
2427 handle, gbp, &layer);
2434 if (result != NO_ERROR) {
2438 result = addClientLayer(client, *handle, *gbp, layer);
2439 if (result != NO_ERROR) {
2443 setTransactionFlags(eTransactionNeeded);
2447 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2448 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2449 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2451 // initialize the surfaces
2453 case PIXEL_FORMAT_TRANSPARENT:
2454 case PIXEL_FORMAT_TRANSLUCENT:
2455 format = PIXEL_FORMAT_RGBA_8888;
2457 case PIXEL_FORMAT_OPAQUE:
2458 format = PIXEL_FORMAT_RGBX_8888;
2462 *outLayer = DisplayUtils::getInstance()->getLayerInstance(this, client, name, w, h, flags);
2463 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2464 if (err == NO_ERROR) {
2465 *handle = (*outLayer)->getHandle();
2466 *gbp = (*outLayer)->getProducer();
2469 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2473 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2474 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2475 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2477 *outLayer = new LayerDim(this, client, name, w, h, flags);
2478 *handle = (*outLayer)->getHandle();
2479 *gbp = (*outLayer)->getProducer();
2483 status_t SurfaceFlinger::createBlurLayer(const sp<Client>& client,
2484 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2485 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2487 *outLayer = new LayerBlur(this, client, name, w, h, flags);
2488 *handle = (*outLayer)->getHandle();
2489 *gbp = (*outLayer)->getProducer();
2493 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2495 // called by the window manager when it wants to remove a Layer
2496 status_t err = NO_ERROR;
2497 sp<Layer> l(client->getLayerUser(handle));
2499 err = removeLayer(l);
2500 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2501 "error removing layer=%p (%s)", l.get(), strerror(-err));
2506 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2508 // called by ~LayerCleaner() when all references to the IBinder (handle)
2510 status_t err = NO_ERROR;
2511 sp<Layer> l(layer.promote());
2513 err = removeLayer(l);
2514 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2515 "error removing layer=%p (%s)", l.get(), strerror(-err));
2520 // ---------------------------------------------------------------------------
2522 void SurfaceFlinger::onInitializeDisplays() {
2523 // reset screen orientation and use primary layer stack
2524 Vector<ComposerState> state;
2525 Vector<DisplayState> displays;
2527 d.what = DisplayState::eDisplayProjectionChanged |
2528 DisplayState::eLayerStackChanged;
2529 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2531 d.orientation = DisplayState::eOrientationDefault;
2532 d.frame.makeInvalid();
2533 d.viewport.makeInvalid();
2537 setTransactionState(state, displays, 0);
2538 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2540 const nsecs_t period =
2541 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2542 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2545 void SurfaceFlinger::initializeDisplays() {
2546 class MessageScreenInitialized : public MessageBase {
2547 SurfaceFlinger* flinger;
2549 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2550 virtual bool handler() {
2551 flinger->onInitializeDisplays();
2555 sp<MessageBase> msg = new MessageScreenInitialized(this);
2556 postMessageAsync(msg); // we may be called from main thread, use async message
2559 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2561 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2563 int32_t type = hw->getDisplayType();
2564 int currentMode = hw->getPowerMode();
2566 if (mode == currentMode) {
2567 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2571 hw->setPowerMode(mode);
2572 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2573 ALOGW("Trying to set power mode for virtual display");
2577 if (currentMode == HWC_POWER_MODE_OFF) {
2578 getHwComposer().setPowerMode(type, mode);
2579 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2580 // FIXME: eventthread only knows about the main display right now
2581 mEventThread->onScreenAcquired();
2582 resyncToHardwareVsync(true);
2585 mVisibleRegionsDirty = true;
2586 mHasPoweredOff = true;
2587 repaintEverything();
2588 } else if (mode == HWC_POWER_MODE_OFF) {
2589 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2590 disableHardwareVsync(true); // also cancels any in-progress resync
2592 // FIXME: eventthread only knows about the main display right now
2593 mEventThread->onScreenReleased();
2596 getHwComposer().setPowerMode(type, mode);
2597 mVisibleRegionsDirty = true;
2598 // from this point on, SF will stop drawing on this display
2600 getHwComposer().setPowerMode(type, mode);
2604 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2605 class MessageSetPowerMode: public MessageBase {
2606 SurfaceFlinger& mFlinger;
2607 sp<IBinder> mDisplay;
2610 MessageSetPowerMode(SurfaceFlinger& flinger,
2611 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2612 mDisplay(disp) { mMode = mode; }
2613 virtual bool handler() {
2614 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2616 ALOGE("Attempt to set power mode = %d for null display %p",
2617 mMode, mDisplay.get());
2618 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2619 ALOGW("Attempt to set power mode = %d for virtual display",
2622 mFlinger.setPowerModeInternal(hw, mMode);
2627 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2628 postMessageSync(msg);
2631 // ---------------------------------------------------------------------------
2633 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2637 IPCThreadState* ipc = IPCThreadState::self();
2638 const int pid = ipc->getCallingPid();
2639 const int uid = ipc->getCallingUid();
2640 if ((uid != AID_SHELL) &&
2641 !PermissionCache::checkPermission(sDump, pid, uid)) {
2642 result.appendFormat("Permission Denial: "
2643 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2645 // Try to get the main lock, but give up after one second
2646 // (this would indicate SF is stuck, but we want to be able to
2647 // print something in dumpsys).
2648 status_t err = mStateLock.timedLock(s2ns(1));
2649 bool locked = (err == NO_ERROR);
2651 result.appendFormat(
2652 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2653 "dumping anyways (no locks held)\n", strerror(-err), err);
2656 bool dumpAll = true;
2658 size_t numArgs = args.size();
2660 if ((index < numArgs) &&
2661 (args[index] == String16("--list"))) {
2663 listLayersLocked(args, index, result);
2667 if ((index < numArgs) &&
2668 (args[index] == String16("--latency"))) {
2670 dumpStatsLocked(args, index, result);
2674 if ((index < numArgs) &&
2675 (args[index] == String16("--latency-clear"))) {
2677 clearStatsLocked(args, index, result);
2681 if ((index < numArgs) &&
2682 (args[index] == String16("--dispsync"))) {
2684 mPrimaryDispSync.dump(result);
2688 if ((index < numArgs) &&
2689 (args[index] == String16("--static-screen"))) {
2691 dumpStaticScreenStats(result);
2697 dumpAllLocked(args, index, result);
2701 mStateLock.unlock();
2704 write(fd, result.string(), result.size());
2708 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2709 size_t& /* index */, String8& result) const
2711 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2712 const size_t count = currentLayers.size();
2713 for (size_t i=0 ; i<count ; i++) {
2714 const sp<Layer>& layer(currentLayers[i]);
2715 result.appendFormat("%s\n", layer->getName().string());
2719 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2720 String8& result) const
2723 if (index < args.size()) {
2724 name = String8(args[index]);
2728 const nsecs_t period =
2729 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2730 result.appendFormat("%" PRId64 "\n", period);
2732 if (name.isEmpty()) {
2733 mAnimFrameTracker.dumpStats(result);
2736 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2737 const size_t count = currentLayers.size();
2738 for (size_t i=0 ; i<count ; i++) {
2739 const sp<Layer>& layer(currentLayers[i]);
2740 if (name == layer->getName()) {
2742 layer->dumpFrameStats(result);
2745 if (!found && !strncmp(name.string(), "SurfaceView", 11)) {
2746 lastSurfaceViewLayer->dumpFrameStats(result);
2751 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2752 String8& /* result */)
2755 if (index < args.size()) {
2756 name = String8(args[index]);
2760 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2761 const size_t count = currentLayers.size();
2762 for (size_t i=0 ; i<count ; i++) {
2763 const sp<Layer>& layer(currentLayers[i]);
2764 if (name.isEmpty() || (name == layer->getName())) {
2765 layer->clearFrameStats();
2769 mAnimFrameTracker.clearStats();
2772 // This should only be called from the main thread. Otherwise it would need
2773 // the lock and should use mCurrentState rather than mDrawingState.
2774 void SurfaceFlinger::logFrameStats() {
2775 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2776 const size_t count = drawingLayers.size();
2777 for (size_t i=0 ; i<count ; i++) {
2778 const sp<Layer>& layer(drawingLayers[i]);
2779 layer->logFrameStats();
2782 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2785 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2787 static const char* config =
2789 #ifdef HAS_CONTEXT_PRIORITY
2790 " HAS_CONTEXT_PRIORITY"
2792 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2793 " NEVER_DEFAULT_TO_ASYNC_MODE"
2795 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2796 " TARGET_DISABLE_TRIPLE_BUFFERING"
2799 result.append(config);
2802 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2804 result.appendFormat("Static screen stats:\n");
2805 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2806 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2807 float percent = 100.0f *
2808 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2809 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2810 b + 1, bucketTimeSec, percent);
2812 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2813 float percent = 100.0f *
2814 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2815 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2816 NUM_BUCKETS - 1, bucketTimeSec, percent);
2819 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2820 String8& result) const
2822 bool colorize = false;
2823 if (index < args.size()
2824 && (args[index] == String16("--color"))) {
2829 Colorizer colorizer(colorize);
2831 // figure out if we're stuck somewhere
2832 const nsecs_t now = systemTime();
2833 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2834 const nsecs_t inTransaction(mDebugInTransaction);
2835 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2836 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2839 * Dump library configuration.
2842 colorizer.bold(result);
2843 result.append("Build configuration:");
2844 colorizer.reset(result);
2845 appendSfConfigString(result);
2846 appendUiConfigString(result);
2847 appendGuiConfigString(result);
2848 result.append("\n");
2850 colorizer.bold(result);
2851 result.append("Sync configuration: ");
2852 colorizer.reset(result);
2853 result.append(SyncFeatures::getInstance().toString());
2854 result.append("\n");
2856 colorizer.bold(result);
2857 result.append("DispSync configuration: ");
2858 colorizer.reset(result);
2859 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2860 "present offset %d ns (refresh %" PRId64 " ns)",
2861 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2862 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2863 result.append("\n");
2865 // Dump static screen stats
2866 result.append("\n");
2867 dumpStaticScreenStats(result);
2868 result.append("\n");
2871 * Dump the visible layer list
2873 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2874 const size_t count = currentLayers.size();
2875 colorizer.bold(result);
2876 result.appendFormat("Visible layers (count = %zu)\n", count);
2877 colorizer.reset(result);
2878 for (size_t i=0 ; i<count ; i++) {
2879 const sp<Layer>& layer(currentLayers[i]);
2880 layer->dump(result, colorizer);
2884 * Dump Display state
2887 colorizer.bold(result);
2888 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2889 colorizer.reset(result);
2890 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2891 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2896 * Dump SurfaceFlinger global state
2899 colorizer.bold(result);
2900 result.append("SurfaceFlinger global state:\n");
2901 colorizer.reset(result);
2903 HWComposer& hwc(getHwComposer());
2904 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2906 colorizer.bold(result);
2907 result.appendFormat("EGL implementation : %s\n",
2908 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2909 colorizer.reset(result);
2910 result.appendFormat("%s\n",
2911 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2913 mRenderEngine->dump(result);
2915 hw->undefinedRegion.dump(result, "undefinedRegion");
2916 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2917 hw->getOrientation(), hw->isDisplayOn());
2918 result.appendFormat(
2919 " last eglSwapBuffers() time: %f us\n"
2920 " last transaction time : %f us\n"
2921 " transaction-flags : %08x\n"
2922 " refresh-rate : %f fps\n"
2925 " gpu_to_cpu_unsupported : %d\n"
2927 mLastSwapBufferTime/1000.0,
2928 mLastTransactionTime/1000.0,
2930 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2931 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2932 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2933 !mGpuToCpuSupported);
2935 result.appendFormat(" eglSwapBuffers time: %f us\n",
2936 inSwapBuffersDuration/1000.0);
2938 result.appendFormat(" transaction time: %f us\n",
2939 inTransactionDuration/1000.0);
2944 mEventThread->dump(result);
2947 * Dump HWComposer state
2949 colorizer.bold(result);
2950 result.append("h/w composer state:\n");
2951 colorizer.reset(result);
2952 result.appendFormat(" h/w composer %s and %s\n",
2953 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2954 (mDebugDisableHWC || mDebugRegion || mDaltonize
2956 || mHasSecondaryColorMatrix) ? "disabled" : "enabled");
2960 * Dump gralloc state
2962 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2966 const Vector< sp<Layer> >&
2967 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2968 // Note: mStateLock is held here
2970 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2971 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2972 dpy = mDisplays.keyAt(i);
2977 ALOGW("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2978 // Just use the primary display so we have something to return
2979 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2981 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2984 bool SurfaceFlinger::startDdmConnection()
2986 void* libddmconnection_dso =
2987 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2988 if (!libddmconnection_dso) {
2991 void (*DdmConnection_start)(const char* name);
2992 DdmConnection_start =
2993 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2994 if (!DdmConnection_start) {
2995 dlclose(libddmconnection_dso);
2998 (*DdmConnection_start)(getServiceName());
3002 status_t SurfaceFlinger::onTransact(
3003 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3006 case CREATE_CONNECTION:
3007 case CREATE_DISPLAY:
3008 case SET_TRANSACTION_STATE:
3010 case CLEAR_ANIMATION_FRAME_STATS:
3011 case GET_ANIMATION_FRAME_STATS:
3012 case SET_POWER_MODE:
3014 // codes that require permission check
3015 IPCThreadState* ipc = IPCThreadState::self();
3016 const int pid = ipc->getCallingPid();
3017 const int uid = ipc->getCallingUid();
3018 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3019 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3020 ALOGE("Permission Denial: "
3021 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3022 return PERMISSION_DENIED;
3026 case CAPTURE_SCREEN:
3028 // codes that require permission check
3029 IPCThreadState* ipc = IPCThreadState::self();
3030 const int pid = ipc->getCallingPid();
3031 const int uid = ipc->getCallingUid();
3032 if ((uid != AID_GRAPHICS) &&
3033 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3034 ALOGE("Permission Denial: "
3035 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3036 return PERMISSION_DENIED;
3042 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3043 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3044 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3045 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3046 IPCThreadState* ipc = IPCThreadState::self();
3047 const int pid = ipc->getCallingPid();
3048 const int uid = ipc->getCallingUid();
3049 ALOGE("Permission Denial: "
3050 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3051 return PERMISSION_DENIED;
3055 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3056 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3058 case 1002: // SHOW_UPDATES
3059 n = data.readInt32();
3060 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3061 invalidateHwcGeometry();
3062 repaintEverything();
3064 case 1004:{ // repaint everything
3065 repaintEverything();
3068 case 1005:{ // force transaction
3069 setTransactionFlags(
3071 eDisplayTransactionNeeded|
3075 case 1006:{ // send empty update
3079 case 1008: // toggle use of hw composer
3080 n = data.readInt32();
3081 mDebugDisableHWC = n ? 1 : 0;
3082 invalidateHwcGeometry();
3083 repaintEverything();
3085 case 1009: // toggle use of transform hint
3086 n = data.readInt32();
3087 mDebugDisableTransformHint = n ? 1 : 0;
3088 invalidateHwcGeometry();
3089 repaintEverything();
3091 case 1010: // interrogate.
3092 reply->writeInt32(0);
3093 reply->writeInt32(0);
3094 reply->writeInt32(mDebugRegion);
3095 reply->writeInt32(0);
3096 reply->writeInt32(mDebugDisableHWC);
3099 Mutex::Autolock _l(mStateLock);
3100 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3101 reply->writeInt32(hw->getPageFlipCount());
3106 n = data.readInt32();
3108 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3109 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3110 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3113 mDaltonizer.setMode(Daltonizer::correction);
3115 mDaltonizer.setMode(Daltonizer::simulation);
3118 invalidateHwcGeometry();
3119 repaintEverything();
3123 // apply a color matrix
3124 n = data.readInt32();
3125 mHasColorMatrix = n ? 1 : 0;
3127 // color matrix is sent as mat3 matrix followed by vec3
3128 // offset, then packed into a mat4 where the last row is
3129 // the offset and extra values are 0
3130 for (size_t i = 0 ; i < 4; i++) {
3131 for (size_t j = 0; j < 4; j++) {
3132 mColorMatrix[i][j] = data.readFloat();
3136 mColorMatrix = mat4();
3138 invalidateHwcGeometry();
3139 repaintEverything();
3142 // This is an experimental interface
3143 // Needs to be shifted to proper binder interface when we productize
3145 n = data.readInt32();
3146 mPrimaryDispSync.setRefreshSkipCount(n);
3150 n = data.readInt32();
3151 mForceFullDamage = static_cast<bool>(n);
3154 case 1018: { // Modify Choreographer's phase offset
3155 n = data.readInt32();
3156 if (mEventThread != NULL)
3157 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3160 case 1019: { // Modify SurfaceFlinger's phase offset
3161 n = data.readInt32();
3162 if (mSFEventThread != NULL)
3163 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3167 // apply a secondary color matrix
3168 // this will be combined with any other transformations
3169 n = data.readInt32();
3170 mHasSecondaryColorMatrix = n ? 1 : 0;
3172 // color matrix is sent as mat3 matrix followed by vec3
3173 // offset, then packed into a mat4 where the last row is
3174 // the offset and extra values are 0
3175 for (size_t i = 0 ; i < 4; i++) {
3176 for (size_t j = 0; j < 4; j++) {
3177 mSecondaryColorMatrix[i][j] = data.readFloat();
3181 mSecondaryColorMatrix = mat4();
3183 invalidateHwcGeometry();
3184 repaintEverything();
3193 void SurfaceFlinger::repaintEverything() {
3194 android_atomic_or(1, &mRepaintEverything);
3195 signalTransaction();
3198 // ---------------------------------------------------------------------------
3199 // Capture screen into an IGraphiBufferProducer
3200 // ---------------------------------------------------------------------------
3202 /* The code below is here to handle b/8734824
3204 * We create a IGraphicBufferProducer wrapper that forwards all calls
3205 * from the surfaceflinger thread to the calling binder thread, where they
3206 * are executed. This allows the calling thread in the calling process to be
3207 * reused and not depend on having "enough" binder threads to handle the
3210 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3211 /* Parts of GraphicProducerWrapper are run on two different threads,
3212 * communicating by sending messages via Looper but also by shared member
3213 * data. Coherence maintenance is subtle and in places implicit (ugh).
3215 * Don't rely on Looper's sendMessage/handleMessage providing
3216 * release/acquire semantics for any data not actually in the Message.
3217 * Data going from surfaceflinger to binder threads needs to be
3218 * synchronized explicitly.
3220 * Barrier open/wait do provide release/acquire semantics. This provides
3221 * implicit synchronization for data coming back from binder to
3222 * surfaceflinger threads.
3225 sp<IGraphicBufferProducer> impl;
3241 * Called on surfaceflinger thread. This is called by our "fake"
3242 * BpGraphicBufferProducer. We package the data and reply Parcel and
3243 * forward them to the binder thread.
3245 virtual status_t transact(uint32_t code,
3246 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3249 this->reply = reply;
3251 // if we've exited, we run the message synchronously right here.
3252 // note (JH): as far as I can tell from looking at the code, this
3253 // never actually happens. if it does, i'm not sure if it happens
3254 // on the surfaceflinger or binder thread.
3255 handleMessage(Message(MSG_API_CALL));
3258 // Prevent stores to this->{code, data, reply} from being
3259 // reordered later than the construction of Message.
3260 atomic_thread_fence(memory_order_release);
3261 looper->sendMessage(this, Message(MSG_API_CALL));
3268 * here we run on the binder thread. All we've got to do is
3269 * call the real BpGraphicBufferProducer.
3271 virtual void handleMessage(const Message& message) {
3272 int what = message.what;
3273 // Prevent reads below from happening before the read from Message
3274 atomic_thread_fence(memory_order_acquire);
3275 if (what == MSG_API_CALL) {
3276 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3278 } else if (what == MSG_EXIT) {
3279 exitRequested = true;
3284 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3286 looper(new Looper(true)),
3288 exitRequested(false)
3292 status_t waitForResponse() {
3294 looper->pollOnce(-1);
3295 } while (!exitRequested);
3300 void exit(status_t result) {
3301 this->result = result;
3303 // Ensure this->result is visible to the binder thread before it
3304 // handles the message.
3305 atomic_thread_fence(memory_order_release);
3306 looper->sendMessage(this, Message(MSG_EXIT));
3311 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3312 const sp<IGraphicBufferProducer>& producer,
3313 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3314 uint32_t minLayerZ, uint32_t maxLayerZ,
3315 bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
3316 bool useReadPixels) {
3318 if (CC_UNLIKELY(display == 0))
3321 if (CC_UNLIKELY(producer == 0))
3324 // if we have secure windows on this display, never allow the screen capture
3325 // unless the producer interface is local (i.e.: we can take a screenshot for
3327 if (!IInterface::asBinder(producer)->localBinder()) {
3328 Mutex::Autolock _l(mStateLock);
3329 sp<const DisplayDevice> hw(getDisplayDevice(display));
3330 if (hw->getSecureLayerVisible()) {
3331 ALOGW("FB is protected: PERMISSION_DENIED");
3332 return PERMISSION_DENIED;
3336 // Convert to surfaceflinger's internal rotation type.
3337 Transform::orientation_flags rotationFlags;
3339 case ISurfaceComposer::eRotateNone:
3340 rotationFlags = Transform::ROT_0;
3342 case ISurfaceComposer::eRotate90:
3343 rotationFlags = Transform::ROT_90;
3345 case ISurfaceComposer::eRotate180:
3346 rotationFlags = Transform::ROT_180;
3348 case ISurfaceComposer::eRotate270:
3349 rotationFlags = Transform::ROT_270;
3352 rotationFlags = Transform::ROT_0;
3353 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3357 class MessageCaptureScreen : public MessageBase {
3358 SurfaceFlinger* flinger;
3359 sp<IBinder> display;
3360 sp<IGraphicBufferProducer> producer;
3362 uint32_t reqWidth, reqHeight;
3363 uint32_t minLayerZ,maxLayerZ;
3364 bool useIdentityTransform;
3365 Transform::orientation_flags rotation;
3369 MessageCaptureScreen(SurfaceFlinger* flinger,
3370 const sp<IBinder>& display,
3371 const sp<IGraphicBufferProducer>& producer,
3372 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3373 uint32_t minLayerZ, uint32_t maxLayerZ,
3374 bool useIdentityTransform, Transform::orientation_flags rotation,
3376 : flinger(flinger), display(display), producer(producer),
3377 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3378 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3379 useIdentityTransform(useIdentityTransform),
3381 useReadPixels(useReadPixels),
3382 result(PERMISSION_DENIED)
3385 status_t getResult() const {
3388 virtual bool handler() {
3389 Mutex::Autolock _l(flinger->mStateLock);
3390 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3391 bool useReadPixels = this->useReadPixels && !flinger->mGpuToCpuSupported;
3392 result = flinger->captureScreenImplLocked(hw, producer,
3393 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3394 useIdentityTransform, rotation, useReadPixels);
3395 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3400 // make sure to process transactions before screenshots -- a transaction
3401 // might already be pending but scheduled for VSYNC; this guarantees we
3402 // will handle it before the screenshot. When VSYNC finally arrives
3403 // the scheduled transaction will be a no-op. If no transactions are
3404 // scheduled at this time, this will end-up being a no-op as well.
3405 mEventQueue.invalidateTransactionNow();
3407 // this creates a "fake" BBinder which will serve as a "fake" remote
3408 // binder to receive the marshaled calls and forward them to the
3409 // real remote (a BpGraphicBufferProducer)
3410 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3412 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3413 // which does the marshaling work forwards to our "fake remote" above.
3414 sp<MessageBase> msg = new MessageCaptureScreen(this,
3415 display, IGraphicBufferProducer::asInterface( wrapper ),
3416 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3417 useIdentityTransform, rotationFlags, useReadPixels);
3419 status_t res = postMessageAsync(msg);
3420 if (res == NO_ERROR) {
3421 res = wrapper->waitForResponse();
3427 void SurfaceFlinger::renderScreenImplLocked(
3428 const sp<const DisplayDevice>& hw,
3429 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3430 uint32_t minLayerZ, uint32_t maxLayerZ,
3431 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3434 RenderEngine& engine(getRenderEngine());
3436 // get screen geometry
3437 const int32_t hw_w = hw->getWidth();
3438 const int32_t hw_h = hw->getHeight();
3439 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3440 static_cast<int32_t>(reqHeight) != hw_h;
3442 // if a default or invalid sourceCrop is passed in, set reasonable values
3443 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3444 !sourceCrop.isValid()) {
3445 sourceCrop.setLeftTop(Point(0, 0));
3446 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3449 // ensure that sourceCrop is inside screen
3450 if (sourceCrop.left < 0) {
3451 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3453 if (sourceCrop.right > hw_w) {
3454 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3456 if (sourceCrop.top < 0) {
3457 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3459 if (sourceCrop.bottom > hw_h) {
3460 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3463 // make sure to clear all GL error flags
3464 engine.checkErrors();
3466 if (DisplayDevice::DISPLAY_PRIMARY == hw->getDisplayType() &&
3467 hw->isPanelInverseMounted()) {
3468 rotation = (Transform::orientation_flags)
3469 (rotation ^ Transform::ROT_180);
3472 // set-up our viewport
3473 engine.setViewportAndProjection(
3474 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3475 engine.disableTexturing();
3477 // redraw the screen entirely...
3478 engine.clearWithColor(0, 0, 0, 1);
3480 const LayerVector& layers( mDrawingState.layersSortedByZ );
3481 const size_t count = layers.size();
3482 for (size_t i=0 ; i<count ; ++i) {
3483 const sp<Layer>& layer(layers[i]);
3484 const Layer::State& state(layer->getDrawingState());
3485 if (state.layerStack == hw->getLayerStack()) {
3486 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3487 if (canDrawLayerinScreenShot(hw,layer)) {
3488 if (filtering) layer->setFiltering(true);
3489 layer->draw(hw, useIdentityTransform);
3490 if (filtering) layer->setFiltering(false);
3496 // compositionComplete is needed for older driver
3497 hw->compositionComplete();
3498 hw->setViewportAndProjection();
3502 status_t SurfaceFlinger::captureScreenImplLocked(
3503 const sp<const DisplayDevice>& hw,
3504 const sp<IGraphicBufferProducer>& producer,
3505 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3506 uint32_t minLayerZ, uint32_t maxLayerZ,
3507 bool useIdentityTransform, Transform::orientation_flags rotation,
3512 // get screen geometry
3513 uint32_t hw_w = hw->getWidth();
3514 uint32_t hw_h = hw->getHeight();
3516 if (rotation & Transform::ROT_90) {
3517 std::swap(hw_w, hw_h);
3520 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3521 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3522 reqWidth, reqHeight, hw_w, hw_h);
3526 ++mActiveFrameSequence;
3528 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3529 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3531 // create a surface (because we're a producer, and we need to
3532 // dequeue/queue a buffer)
3533 sp<Surface> sur = new Surface(producer, false);
3534 ANativeWindow* window = sur.get();
3536 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3537 if (result == NO_ERROR) {
3538 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3539 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3542 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3543 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3544 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3545 err |= native_window_set_usage(window, usage);
3547 if (err == NO_ERROR) {
3548 ANativeWindowBuffer* buffer;
3549 /* TODO: Once we have the sync framework everywhere this can use
3550 * server-side waits on the fence that dequeueBuffer returns.
3552 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3553 if (result == NO_ERROR) {
3555 // create an EGLImage from the buffer so we can later
3556 // turn it into a texture
3557 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3558 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3559 if (image != EGL_NO_IMAGE_KHR) {
3560 // this binds the given EGLImage as a framebuffer for the
3561 // duration of this scope.
3562 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image,
3563 useReadPixels, reqWidth, reqHeight);
3564 if (imageBond.getStatus() == NO_ERROR) {
3565 // this will in fact render into our dequeued buffer
3566 // via an FBO, which means we didn't have to create
3567 // an EGLSurface and therefore we're not
3568 // dependent on the context's EGLConfig.
3569 renderScreenImplLocked(
3570 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3571 useIdentityTransform, rotation);
3573 // Attempt to create a sync khr object that can produce a sync point. If that
3574 // isn't available, create a non-dupable sync object in the fallback path and
3575 // wait on it directly.
3577 if (!DEBUG_SCREENSHOTS) {
3578 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3579 // native fence fd will not be populated until flush() is done.
3580 getRenderEngine().flush();
3582 sync = EGL_NO_SYNC_KHR;
3584 if (sync != EGL_NO_SYNC_KHR) {
3586 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3587 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3588 ALOGW("captureScreen: failed to dup sync khr object");
3591 eglDestroySyncKHR(mEGLDisplay, sync);
3594 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3595 if (sync != EGL_NO_SYNC_KHR) {
3596 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3597 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3598 EGLint eglErr = eglGetError();
3599 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3600 ALOGW("captureScreen: fence wait timed out");
3602 ALOGW_IF(eglErr != EGL_SUCCESS,
3603 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3605 eglDestroySyncKHR(mEGLDisplay, sync);
3607 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3610 if (useReadPixels) {
3611 sp<GraphicBuffer> buf = static_cast<GraphicBuffer*>(buffer);
3613 if (buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, &vaddr) == NO_ERROR) {
3614 getRenderEngine().readPixels(0, 0, buffer->stride, reqHeight,
3619 if (DEBUG_SCREENSHOTS) {
3620 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3621 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3622 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3623 hw, minLayerZ, maxLayerZ);
3628 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3629 result = INVALID_OPERATION;
3631 // destroy our image
3632 eglDestroyImageKHR(mEGLDisplay, image);
3636 // queueBuffer takes ownership of syncFd
3637 result = window->queueBuffer(window, buffer, syncFd);
3642 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3648 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3649 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3650 if (DEBUG_SCREENSHOTS) {
3651 for (size_t y=0 ; y<h ; y++) {
3652 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3653 for (size_t x=0 ; x<w ; x++) {
3654 if (p[x] != 0xFF000000) return;
3657 ALOGE("*** we just took a black screenshot ***\n"
3658 "requested minz=%d, maxz=%d, layerStack=%d",
3659 minLayerZ, maxLayerZ, hw->getLayerStack());
3660 const LayerVector& layers( mDrawingState.layersSortedByZ );
3661 const size_t count = layers.size();
3662 for (size_t i=0 ; i<count ; ++i) {
3663 const sp<Layer>& layer(layers[i]);
3664 const Layer::State& state(layer->getDrawingState());
3665 const bool visible = (state.layerStack == hw->getLayerStack())
3666 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3667 && (layer->isVisible());
3668 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3669 visible ? '+' : '-',
3670 i, layer->getName().string(), state.layerStack, state.z,
3671 layer->isVisible(), state.flags, state.alpha);
3676 /* ------------------------------------------------------------------------
3680 bool SurfaceFlinger::updateLayerVisibleNonTransparentRegion(const int& /*dpy*/,
3681 const sp<Layer>& layer, bool& /*bIgnoreLayers*/, int& /*indexLOI*/,
3682 uint32_t layerStack, const int& /*i*/) {
3684 const Layer::State& s(layer->getDrawingState());
3686 // only consider the layers on the given layer stack
3687 if (s.layerStack != layerStack) {
3688 /* set the visible region as empty since we have removed the
3689 * layerstack check in rebuildLayerStack() function
3691 Region visibleNonTransRegion;
3692 visibleNonTransRegion.set(Rect(0,0));
3693 layer->setVisibleNonTransparentRegion(visibleNonTransRegion);
3701 bool SurfaceFlinger::canDrawLayerinScreenShot(
3702 const sp<const DisplayDevice>& /*hw*/,
3703 const sp<Layer>& layer) {
3704 return layer->isVisible();
3707 void SurfaceFlinger::drawWormHoleIfRequired(HWComposer::LayerListIterator& /*cur*/,
3708 const HWComposer::LayerListIterator& /*end*/,
3709 const sp<const DisplayDevice>& hw,
3710 const Region& region) {
3711 drawWormhole(hw, region);
3714 // ---------------------------------------------------------------------------
3716 SurfaceFlinger::LayerVector::LayerVector() {
3719 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3720 : SortedVector<sp<Layer> >(rhs) {
3723 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3724 const void* rhs) const
3726 // sort layers per layer-stack, then by z-order and finally by sequence
3727 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3728 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3730 uint32_t ls = l->getCurrentState().layerStack;
3731 uint32_t rs = r->getCurrentState().layerStack;
3735 uint32_t lz = l->getCurrentState().z;
3736 uint32_t rz = r->getCurrentState().z;
3740 return l->sequence - r->sequence;
3743 // ---------------------------------------------------------------------------
3745 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3746 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3749 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3750 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3751 viewport.makeInvalid();
3752 frame.makeInvalid();
3755 // ---------------------------------------------------------------------------
3757 }; // namespace android
3760 #if defined(__gl_h_)
3761 #error "don't include gl/gl.h in this file"
3764 #if defined(__gl2_h_)
3765 #error "don't include gl2/gl2.h in this file"