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 mHasPoweredOff(false),
163 mActiveFrameSequence(0)
165 ALOGI("SurfaceFlinger is starting");
167 // debugging stuff...
168 char value[PROPERTY_VALUE_MAX];
170 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
171 mGpuToCpuSupported = !atoi(value);
173 property_get("debug.sf.drop_missed_frames", value, "0");
174 mDropMissedFrames = atoi(value);
176 property_get("debug.sf.showupdates", value, "0");
177 mDebugRegion = atoi(value);
179 property_get("debug.sf.ddms", value, "0");
180 mDebugDDMS = atoi(value);
182 if (!startDdmConnection()) {
183 // start failed, and DDMS debugging not enabled
187 ALOGI_IF(mDebugRegion, "showupdates enabled");
188 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
191 void SurfaceFlinger::onFirstRef()
193 mEventQueue.init(this);
196 SurfaceFlinger::~SurfaceFlinger()
198 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
199 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
200 eglTerminate(display);
203 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
205 // the window manager died on us. prepare its eulogy.
207 // restore initial conditions (default device unblank, etc)
208 initializeDisplays();
210 // restart the boot-animation
214 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
216 sp<ISurfaceComposerClient> bclient;
217 sp<Client> client(new Client(this));
218 status_t err = client->initCheck();
219 if (err == NO_ERROR) {
225 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
228 class DisplayToken : public BBinder {
229 sp<SurfaceFlinger> flinger;
230 virtual ~DisplayToken() {
231 // no more references, this display must be terminated
232 Mutex::Autolock _l(flinger->mStateLock);
233 flinger->mCurrentState.displays.removeItem(this);
234 flinger->setTransactionFlags(eDisplayTransactionNeeded);
237 DisplayToken(const sp<SurfaceFlinger>& flinger)
242 sp<BBinder> token = new DisplayToken(this);
244 Mutex::Autolock _l(mStateLock);
245 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
246 info.displayName = displayName;
247 info.isSecure = secure;
248 mCurrentState.displays.add(token, info);
253 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
254 Mutex::Autolock _l(mStateLock);
256 ssize_t idx = mCurrentState.displays.indexOfKey(display);
258 ALOGW("destroyDisplay: invalid display token");
262 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
263 if (!info.isVirtualDisplay()) {
264 ALOGE("destroyDisplay called for non-virtual display");
268 mCurrentState.displays.removeItemsAt(idx);
269 setTransactionFlags(eDisplayTransactionNeeded);
272 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
273 ALOGW_IF(mBuiltinDisplays[type],
274 "Overwriting display token for display type %d", type);
275 mBuiltinDisplays[type] = new BBinder();
276 DisplayDeviceState info(type);
277 // All non-virtual displays are currently considered secure.
278 info.isSecure = true;
279 mCurrentState.displays.add(mBuiltinDisplays[type], info);
282 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
283 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
284 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
287 return mBuiltinDisplays[id];
290 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
292 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
296 void SurfaceFlinger::bootFinished()
298 const nsecs_t now = systemTime();
299 const nsecs_t duration = now - mBootTime;
300 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
301 mBootFinished = true;
303 // wait patiently for the window manager death
304 const String16 name("window");
305 sp<IBinder> window(defaultServiceManager()->getService(name));
307 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
310 // stop boot animation
311 // formerly we would just kill the process, but we now ask it to exit so it
312 // can choose where to stop the animation.
313 property_set("service.bootanim.exit", "1");
316 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
317 class MessageDestroyGLTexture : public MessageBase {
318 RenderEngine& engine;
321 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
322 : engine(engine), texture(texture) {
324 virtual bool handler() {
325 engine.deleteTextures(1, &texture);
329 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
332 class DispSyncSource : public VSyncSource, private DispSync::Callback {
334 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
337 mTraceVsync(traceVsync),
338 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
339 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
344 mPhaseOffset(phaseOffset),
347 virtual ~DispSyncSource() {}
349 virtual void setVSyncEnabled(bool enable) {
350 Mutex::Autolock lock(mVsyncMutex);
352 status_t err = mDispSync->addEventListener(mPhaseOffset,
353 static_cast<DispSync::Callback*>(this));
354 if (err != NO_ERROR) {
355 ALOGE("error registering vsync callback: %s (%d)",
356 strerror(-err), err);
358 //ATRACE_INT(mVsyncOnLabel.string(), 1);
360 status_t err = mDispSync->removeEventListener(
361 static_cast<DispSync::Callback*>(this));
362 if (err != NO_ERROR) {
363 ALOGE("error unregistering vsync callback: %s (%d)",
364 strerror(-err), err);
366 //ATRACE_INT(mVsyncOnLabel.string(), 0);
371 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
372 Mutex::Autolock lock(mCallbackMutex);
373 mCallback = callback;
376 virtual void setPhaseOffset(nsecs_t phaseOffset) {
377 Mutex::Autolock lock(mVsyncMutex);
379 // Normalize phaseOffset to [0, period)
380 auto period = mDispSync->getPeriod();
381 phaseOffset %= period;
382 if (phaseOffset < 0) {
383 // If we're here, then phaseOffset is in (-period, 0). After this
384 // operation, it will be in (0, period)
385 phaseOffset += period;
387 mPhaseOffset = phaseOffset;
389 // If we're not enabled, we don't need to mess with the listeners
394 // Remove the listener with the old offset
395 status_t err = mDispSync->removeEventListener(
396 static_cast<DispSync::Callback*>(this));
397 if (err != NO_ERROR) {
398 ALOGE("error unregistering vsync callback: %s (%d)",
399 strerror(-err), err);
402 // Add a listener with the new offset
403 err = mDispSync->addEventListener(mPhaseOffset,
404 static_cast<DispSync::Callback*>(this));
405 if (err != NO_ERROR) {
406 ALOGE("error registering vsync callback: %s (%d)",
407 strerror(-err), err);
412 virtual void onDispSyncEvent(nsecs_t when) {
413 sp<VSyncSource::Callback> callback;
415 Mutex::Autolock lock(mCallbackMutex);
416 callback = mCallback;
419 mValue = (mValue + 1) % 2;
420 ATRACE_INT(mVsyncEventLabel.string(), mValue);
424 if (callback != NULL) {
425 callback->onVSyncEvent(when);
431 const bool mTraceVsync;
432 const String8 mVsyncOnLabel;
433 const String8 mVsyncEventLabel;
437 Mutex mCallbackMutex; // Protects the following
438 sp<VSyncSource::Callback> mCallback;
440 Mutex mVsyncMutex; // Protects the following
441 nsecs_t mPhaseOffset;
445 void SurfaceFlinger::init() {
446 ALOGI( "SurfaceFlinger's main thread ready to run. "
447 "Initializing graphics H/W...");
449 Mutex::Autolock _l(mStateLock);
451 // initialize EGL for the default display
452 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
453 eglInitialize(mEGLDisplay, NULL, NULL);
455 // start the EventThread
456 if (vsyncPhaseOffsetNs != sfVsyncPhaseOffsetNs) {
457 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
458 vsyncPhaseOffsetNs, true, "app");
459 mEventThread = new EventThread(vsyncSrc);
460 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
461 sfVsyncPhaseOffsetNs, true, "sf");
462 mSFEventThread = new EventThread(sfVsyncSrc);
463 mEventQueue.setEventThread(mSFEventThread);
465 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
466 vsyncPhaseOffsetNs, true, "sf-app");
467 mEventThread = new EventThread(vsyncSrc);
468 mEventQueue.setEventThread(mEventThread);
471 // Initialize the H/W composer object. There may or may not be an
472 // actual hardware composer underneath.
473 mHwc = DisplayUtils::getInstance()->getHWCInstance(this,
474 *static_cast<HWComposer::EventHandler *>(this));
476 // get a RenderEngine for the given display / config (can't fail)
477 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
479 // retrieve the EGL context that was selected/created
480 mEGLContext = mRenderEngine->getEGLContext();
482 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
483 "couldn't create EGLContext");
485 // initialize our non-virtual displays
486 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
487 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
488 // set-up the displays that are already connected
489 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
490 // All non-virtual displays are currently considered secure.
491 bool isSecure = true;
492 createBuiltinDisplayLocked(type);
493 wp<IBinder> token = mBuiltinDisplays[i];
495 sp<IGraphicBufferProducer> producer;
496 sp<IGraphicBufferConsumer> consumer;
497 BufferQueue::createBufferQueue(&producer, &consumer,
498 new GraphicBufferAlloc());
500 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
502 int32_t hwcId = allocateHwcDisplayId(type);
503 sp<DisplayDevice> hw = new DisplayDevice(this,
504 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
506 mRenderEngine->getEGLConfig());
507 if (i > DisplayDevice::DISPLAY_PRIMARY) {
508 // FIXME: currently we don't get blank/unblank requests
509 // for displays other than the main display, so we always
510 // assume a connected display is unblanked.
511 ALOGD("marking display %zu as acquired/unblanked", i);
512 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
514 // When a non-virtual display device is added at boot time,
515 // update the active config by querying HWC otherwise the
516 // default config (config 0) will be used.
517 int activeConfig = mHwc->getActiveConfig(hwcId);
518 if (activeConfig >= 0) {
519 hw->setActiveConfig(activeConfig);
521 mDisplays.add(token, hw);
525 // make the GLContext current so that we can create textures when creating Layers
526 // (which may happens before we render something)
527 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
529 mEventControlThread = new EventControlThread(this);
530 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
531 android_set_rt_ioprio(mEventControlThread->getTid(), 1);
533 // set a fake vsync period if there is no HWComposer
534 if (mHwc->initCheck() != NO_ERROR) {
535 mPrimaryDispSync.setPeriod(16666667);
538 // initialize our drawing state
539 mDrawingState = mCurrentState;
541 // set initial conditions (e.g. unblank default device)
542 initializeDisplays();
544 // start boot animation
548 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
549 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
550 type : mHwc->allocateDisplayId();
553 void SurfaceFlinger::startBootAnim() {
554 // start boot animation
555 property_set("service.bootanim.exit", "0");
556 property_set("ctl.start", "bootanim");
559 size_t SurfaceFlinger::getMaxTextureSize() const {
560 return mRenderEngine->getMaxTextureSize();
563 size_t SurfaceFlinger::getMaxViewportDims() const {
564 return mRenderEngine->getMaxViewportDims();
567 // ----------------------------------------------------------------------------
569 bool SurfaceFlinger::authenticateSurfaceTexture(
570 const sp<IGraphicBufferProducer>& bufferProducer) const {
571 Mutex::Autolock _l(mStateLock);
572 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
573 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
576 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
577 Vector<DisplayInfo>* configs) {
578 if ((configs == NULL) || (display.get() == NULL)) {
583 return NAME_NOT_FOUND;
585 int32_t type = NAME_NOT_FOUND;
586 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
587 if (display == mBuiltinDisplays[i]) {
597 // TODO: Not sure if display density should handled by SF any longer
599 static int getDensityFromProperty(char const* propName) {
600 char property[PROPERTY_VALUE_MAX];
602 if (property_get(propName, property, NULL) > 0) {
603 density = atoi(property);
608 static int getEmuDensity() {
609 return getDensityFromProperty("qemu.sf.lcd_density"); }
610 static int getBuildDensity() {
611 return getDensityFromProperty("ro.sf.lcd_density"); }
616 const Vector<HWComposer::DisplayConfig>& hwConfigs =
617 getHwComposer().getConfigs(type);
618 for (size_t c = 0; c < hwConfigs.size(); ++c) {
619 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
620 DisplayInfo info = DisplayInfo();
622 float xdpi = hwConfig.xdpi;
623 float ydpi = hwConfig.ydpi;
625 if (type == DisplayDevice::DISPLAY_PRIMARY) {
626 // The density of the device is provided by a build property
627 float density = Density::getBuildDensity() / 160.0f;
629 // the build doesn't provide a density -- this is wrong!
631 ALOGE("ro.sf.lcd_density must be defined as a build property");
632 density = xdpi / 160.0f;
634 if (Density::getEmuDensity()) {
635 // if "qemu.sf.lcd_density" is specified, it overrides everything
636 xdpi = ydpi = density = Density::getEmuDensity();
639 info.density = density;
641 // TODO: this needs to go away (currently needed only by webkit)
642 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
643 info.orientation = hw->getOrientation();
645 // TODO: where should this value come from?
646 static const int TV_DENSITY = 213;
647 info.density = TV_DENSITY / 160.0f;
648 info.orientation = 0;
651 char value[PROPERTY_VALUE_MAX];
652 property_get("ro.sf.hwrotation", value, "0");
653 int additionalRot = atoi(value) / 90;
654 if ((type == DisplayDevice::DISPLAY_PRIMARY) && (additionalRot & DisplayState::eOrientationSwapMask)) {
655 info.h = hwConfig.width;
656 info.w = hwConfig.height;
661 info.w = hwConfig.width;
662 info.h = hwConfig.height;
666 info.fps = float(1e9 / hwConfig.refresh);
667 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
668 info.colorTransform = hwConfig.colorTransform;
670 // This is how far in advance a buffer must be queued for
671 // presentation at a given time. If you want a buffer to appear
672 // on the screen at time N, you must submit the buffer before
673 // (N - presentationDeadline).
675 // Normally it's one full refresh period (to give SF a chance to
676 // latch the buffer), but this can be reduced by configuring a
677 // DispSync offset. Any additional delays introduced by the hardware
678 // composer or panel must be accounted for here.
680 // We add an additional 1ms to allow for processing time and
681 // differences between the ideal and actual refresh rate.
682 info.presentationDeadline =
683 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
685 // All non-virtual displays are currently considered secure.
688 configs->push_back(info);
694 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
695 DisplayStatInfo* stats) {
700 // FIXME for now we always return stats for the primary display
701 memset(stats, 0, sizeof(*stats));
702 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
703 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
707 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
708 sp<DisplayDevice> device(getDisplayDevice(display));
709 if (device != NULL) {
710 return device->getActiveConfig();
715 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
716 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
718 int32_t type = hw->getDisplayType();
719 int currentMode = hw->getActiveConfig();
721 if (mode == currentMode) {
722 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
726 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
727 ALOGW("Trying to set config for virtual display");
731 status_t status = getHwComposer().setActiveConfig(type, mode);
732 if (status == NO_ERROR) {
733 hw->setActiveConfig(mode);
737 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
738 class MessageSetActiveConfig: public MessageBase {
739 SurfaceFlinger& mFlinger;
740 sp<IBinder> mDisplay;
743 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
745 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
746 virtual bool handler() {
747 Vector<DisplayInfo> configs;
748 mFlinger.getDisplayConfigs(mDisplay, &configs);
749 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
750 ALOGE("Attempt to set active config = %d for display with %zu configs",
751 mMode, configs.size());
753 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
755 ALOGE("Attempt to set active config = %d for null display %p",
756 mMode, mDisplay.get());
757 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
758 ALOGW("Attempt to set active config = %d for virtual display",
761 mFlinger.setActiveConfigInternal(hw, mMode);
766 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
767 postMessageSync(msg);
771 status_t SurfaceFlinger::clearAnimationFrameStats() {
772 Mutex::Autolock _l(mStateLock);
773 mAnimFrameTracker.clearStats();
777 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
778 Mutex::Autolock _l(mStateLock);
779 mAnimFrameTracker.getStats(outStats);
783 // ----------------------------------------------------------------------------
785 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
786 return mEventThread->createEventConnection();
789 // ----------------------------------------------------------------------------
791 void SurfaceFlinger::waitForEvent() {
792 mEventQueue.waitMessage();
795 void SurfaceFlinger::signalTransaction() {
796 mEventQueue.invalidate();
799 void SurfaceFlinger::signalLayerUpdate() {
800 mEventQueue.invalidate();
803 void SurfaceFlinger::signalRefresh() {
804 mEventQueue.refresh();
807 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
808 nsecs_t reltime, uint32_t /* flags */) {
809 return mEventQueue.postMessage(msg, reltime);
812 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
813 nsecs_t reltime, uint32_t /* flags */) {
814 status_t res = mEventQueue.postMessage(msg, reltime);
815 if (res == NO_ERROR) {
821 void SurfaceFlinger::run() {
827 void SurfaceFlinger::enableHardwareVsync() {
828 Mutex::Autolock _l(mHWVsyncLock);
829 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
830 mPrimaryDispSync.beginResync();
831 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
832 mEventControlThread->setVsyncEnabled(true);
833 mPrimaryHWVsyncEnabled = true;
837 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
838 Mutex::Autolock _l(mHWVsyncLock);
841 mHWVsyncAvailable = true;
842 } else if (!mHWVsyncAvailable) {
843 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
847 const nsecs_t period =
848 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
850 mPrimaryDispSync.reset();
851 mPrimaryDispSync.setPeriod(period);
853 if (!mPrimaryHWVsyncEnabled) {
854 mPrimaryDispSync.beginResync();
855 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
856 mEventControlThread->setVsyncEnabled(true);
857 mPrimaryHWVsyncEnabled = true;
861 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
862 Mutex::Autolock _l(mHWVsyncLock);
863 if (mPrimaryHWVsyncEnabled) {
864 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
865 mEventControlThread->setVsyncEnabled(false);
866 mPrimaryDispSync.endResync();
867 mPrimaryHWVsyncEnabled = false;
869 if (makeUnavailable) {
870 mHWVsyncAvailable = false;
874 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
875 bool needsHwVsync = false;
877 { // Scope for the lock
878 Mutex::Autolock _l(mHWVsyncLock);
879 if (type == 0 && mPrimaryHWVsyncEnabled) {
880 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
885 enableHardwareVsync();
887 disableHardwareVsync(false);
891 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
892 if (mEventThread == NULL) {
893 // This is a temporary workaround for b/7145521. A non-null pointer
894 // does not mean EventThread has finished initializing, so this
895 // is not a correct fix.
896 ALOGW("WARNING: EventThread not started, ignoring hotplug");
900 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
901 Mutex::Autolock _l(mStateLock);
903 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
905 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
906 mBuiltinDisplays[type].clear();
907 updateVisibleRegionsDirty();
909 setTransactionFlags(eDisplayTransactionNeeded);
911 // Defer EventThread notification until SF has updated mDisplays.
915 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
917 getHwComposer().eventControl(disp, event, enabled);
920 void SurfaceFlinger::onMessageReceived(int32_t what) {
923 case MessageQueue::TRANSACTION: {
924 handleMessageTransaction();
927 case MessageQueue::INVALIDATE: {
928 bool refreshNeeded = handleMessageTransaction();
929 refreshNeeded |= handleMessageInvalidate();
930 refreshNeeded |= mRepaintEverything;
932 // Signal a refresh if a transaction modified the window state,
933 // a new buffer was latched, or if HWC has requested a full
939 case MessageQueue::REFRESH: {
940 handleMessageRefresh();
946 bool SurfaceFlinger::handleMessageTransaction() {
947 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
948 if (transactionFlags) {
949 handleTransaction(transactionFlags);
955 bool SurfaceFlinger::handleMessageInvalidate() {
957 return handlePageFlip();
960 void SurfaceFlinger::handleMessageRefresh() {
963 static nsecs_t previousExpectedPresent = 0;
964 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
965 static bool previousFrameMissed = false;
966 bool frameMissed = (expectedPresent == previousExpectedPresent);
967 if (frameMissed != previousFrameMissed) {
968 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
970 previousFrameMissed = frameMissed;
972 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
973 // Latch buffers, but don't send anything to HWC, then signal another
974 // wakeup for the next vsync
979 rebuildLayerStacks();
981 doDebugFlashRegions();
986 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
989 void SurfaceFlinger::doDebugFlashRegions()
991 // is debugging enabled
992 if (CC_LIKELY(!mDebugRegion))
995 const bool repaintEverything = mRepaintEverything;
996 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
997 const sp<DisplayDevice>& hw(mDisplays[dpy]);
998 if (hw->isDisplayOn()) {
999 // transform the dirty region into this screen's coordinate space
1000 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1001 if (!dirtyRegion.isEmpty()) {
1002 // redraw the whole screen
1003 doComposeSurfaces(hw, Region(hw->bounds()));
1005 // and draw the dirty region
1006 const int32_t height = hw->getHeight();
1007 RenderEngine& engine(getRenderEngine());
1008 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1010 hw->compositionComplete();
1011 hw->swapBuffers(getHwComposer());
1018 if (mDebugRegion > 1) {
1019 usleep(mDebugRegion * 1000);
1022 HWComposer& hwc(getHwComposer());
1023 if (hwc.initCheck() == NO_ERROR) {
1024 status_t err = hwc.prepare();
1025 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1029 void SurfaceFlinger::preComposition()
1031 bool needExtraInvalidate = false;
1032 const LayerVector& layers(mDrawingState.layersSortedByZ);
1033 const size_t count = layers.size();
1034 for (size_t i=0 ; i<count ; i++) {
1035 if (layers[i]->onPreComposition()) {
1036 needExtraInvalidate = true;
1039 if (needExtraInvalidate) {
1040 signalLayerUpdate();
1044 void SurfaceFlinger::postComposition()
1046 const LayerVector& layers(mDrawingState.layersSortedByZ);
1047 const size_t count = layers.size();
1048 for (size_t i=0 ; i<count ; i++) {
1049 layers[i]->onPostComposition();
1052 const HWComposer& hwc = getHwComposer();
1053 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1055 if (presentFence->isValid()) {
1056 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1057 enableHardwareVsync();
1059 disableHardwareVsync(false);
1063 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1064 if (kIgnorePresentFences) {
1065 if (hw->isDisplayOn()) {
1066 enableHardwareVsync();
1070 if (mAnimCompositionPending) {
1071 mAnimCompositionPending = false;
1073 if (presentFence->isValid()) {
1074 mAnimFrameTracker.setActualPresentFence(presentFence);
1076 // The HWC doesn't support present fences, so use the refresh
1077 // timestamp instead.
1078 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1079 mAnimFrameTracker.setActualPresentTime(presentTime);
1081 mAnimFrameTracker.advanceFrame();
1084 dumpDrawCycle(false);
1086 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1090 nsecs_t currentTime = systemTime();
1091 if (mHasPoweredOff) {
1092 mHasPoweredOff = false;
1094 nsecs_t period = mPrimaryDispSync.getPeriod();
1095 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1096 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1097 if (numPeriods < NUM_BUCKETS - 1) {
1098 mFrameBuckets[numPeriods] += elapsedTime;
1100 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1102 mTotalTime += elapsedTime;
1104 mLastSwapTime = currentTime;
1107 void SurfaceFlinger::rebuildLayerStacks() {
1108 updateExtendedMode();
1109 // rebuild the visible layer list per screen
1110 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1112 mVisibleRegionsDirty = false;
1113 invalidateHwcGeometry();
1115 const LayerVector& layers(mDrawingState.layersSortedByZ);
1116 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1117 Region opaqueRegion;
1119 Vector< sp<Layer> > layersSortedByZ;
1120 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1121 const Transform& tr(hw->getTransform());
1122 const Rect bounds(hw->getBounds());
1123 if (hw->isDisplayOn()) {
1124 computeVisibleRegions(hw->getHwcDisplayId(), layers,
1125 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1127 const size_t count = layers.size();
1128 for (size_t i=0 ; i<count ; i++) {
1129 const sp<Layer>& layer(layers[i]);
1131 Region drawRegion(tr.transform(
1132 layer->visibleNonTransparentRegion));
1133 drawRegion.andSelf(bounds);
1134 if (!drawRegion.isEmpty()) {
1135 layersSortedByZ.add(layer);
1140 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1141 hw->undefinedRegion.set(bounds);
1142 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1143 hw->dirtyRegion.orSelf(dirtyRegion);
1148 void SurfaceFlinger::setUpHWComposer() {
1149 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1150 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1151 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1152 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1154 // If nothing has changed (!dirty), don't recompose.
1155 // If something changed, but we don't currently have any visible layers,
1156 // and didn't when we last did a composition, then skip it this time.
1157 // The second rule does two things:
1158 // - When all layers are removed from a display, we'll emit one black
1159 // frame, then nothing more until we get new layers.
1160 // - When a display is created with a private layer stack, we won't
1161 // emit any black frames until a layer is added to the layer stack.
1162 bool mustRecompose = dirty && !(empty && wasEmpty);
1164 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1165 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1166 mustRecompose ? "doing" : "skipping",
1169 wasEmpty ? "+" : "-");
1171 mDisplays[dpy]->beginFrame(mustRecompose);
1173 if (mustRecompose) {
1174 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1178 HWComposer& hwc(getHwComposer());
1179 if (hwc.initCheck() == NO_ERROR) {
1180 // build the h/w work list
1181 if (CC_UNLIKELY(mHwWorkListDirty)) {
1182 mHwWorkListDirty = false;
1183 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1184 sp<const DisplayDevice> hw(mDisplays[dpy]);
1185 const int32_t id = hw->getHwcDisplayId();
1187 const Vector< sp<Layer> >& currentLayers(
1188 hw->getVisibleLayersSortedByZ());
1189 const size_t count = currentLayers.size();
1190 if (hwc.createWorkList(id, count) == NO_ERROR) {
1191 HWComposer::LayerListIterator cur = hwc.begin(id);
1192 const HWComposer::LayerListIterator end = hwc.end(id);
1193 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1194 const sp<Layer>& layer(currentLayers[i]);
1195 layer->setGeometry(hw, *cur);
1196 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1205 // set the per-frame data
1206 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1207 sp<const DisplayDevice> hw(mDisplays[dpy]);
1208 const int32_t id = hw->getHwcDisplayId();
1210 bool freezeSurfacePresent = false;
1211 isfreezeSurfacePresent(freezeSurfacePresent, hw, id);
1212 const Vector< sp<Layer> >& currentLayers(
1213 hw->getVisibleLayersSortedByZ());
1214 const size_t count = currentLayers.size();
1215 HWComposer::LayerListIterator cur = hwc.begin(id);
1216 const HWComposer::LayerListIterator end = hwc.end(id);
1217 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1219 * update the per-frame h/w composer data for each layer
1220 * and build the transparent region of the FB
1222 const sp<Layer>& layer(currentLayers[i]);
1223 layer->setPerFrameData(hw, *cur);
1224 setOrientationEventControl(freezeSurfacePresent,id);
1225 if(!strncmp(layer->getName(), "SurfaceView",
1227 lastSurfaceViewLayer = layer;
1233 // If possible, attempt to use the cursor overlay on each display.
1234 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1235 sp<const DisplayDevice> hw(mDisplays[dpy]);
1236 const int32_t id = hw->getHwcDisplayId();
1238 const Vector< sp<Layer> >& currentLayers(
1239 hw->getVisibleLayersSortedByZ());
1240 const size_t count = currentLayers.size();
1241 HWComposer::LayerListIterator cur = hwc.begin(id);
1242 const HWComposer::LayerListIterator end = hwc.end(id);
1243 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1244 const sp<Layer>& layer(currentLayers[i]);
1245 if (layer->isPotentialCursor()) {
1246 cur->setIsCursorLayerHint();
1253 dumpDrawCycle(true);
1255 status_t err = hwc.prepare();
1256 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1258 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1259 sp<const DisplayDevice> hw(mDisplays[dpy]);
1260 hw->prepareFrame(hwc);
1265 void SurfaceFlinger::doComposition() {
1267 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1268 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1269 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1270 if (hw->isDisplayOn()) {
1271 // transform the dirty region into this screen's coordinate space
1272 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1274 // repaint the framebuffer (if needed)
1275 doDisplayComposition(hw, dirtyRegion);
1277 ++mActiveFrameSequence;
1279 hw->dirtyRegion.clear();
1280 hw->flip(hw->swapRegion);
1281 hw->swapRegion.clear();
1283 // inform the h/w that we're done compositing
1284 hw->compositionComplete();
1289 void SurfaceFlinger::postFramebuffer()
1293 const nsecs_t now = systemTime();
1294 mDebugInSwapBuffers = now;
1296 HWComposer& hwc(getHwComposer());
1297 if (hwc.initCheck() == NO_ERROR) {
1298 if (!hwc.supportsFramebufferTarget()) {
1300 // "surface must be bound to the calling thread's current context,
1301 // for the current rendering API."
1302 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1307 // make the default display current because the VirtualDisplayDevice code cannot
1308 // deal with dequeueBuffer() being called outside of the composition loop; however
1309 // the code below can call glFlush() which is allowed (and does in some case) call
1311 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1313 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1314 sp<const DisplayDevice> hw(mDisplays[dpy]);
1315 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1316 hw->onSwapBuffersCompleted(hwc);
1317 const size_t count = currentLayers.size();
1318 int32_t id = hw->getHwcDisplayId();
1319 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1320 HWComposer::LayerListIterator cur = hwc.begin(id);
1321 const HWComposer::LayerListIterator end = hwc.end(id);
1322 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1323 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1326 for (size_t i = 0; i < count; i++) {
1327 currentLayers[i]->onLayerDisplayed(hw, NULL);
1332 mLastSwapBufferTime = systemTime() - now;
1333 mDebugInSwapBuffers = 0;
1335 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1336 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1339 ALOGV_IF(mFrameRateHelper.update(), "FPS: %d", mFrameRateHelper.get());
1342 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1346 // here we keep a copy of the drawing state (that is the state that's
1347 // going to be overwritten by handleTransactionLocked()) outside of
1348 // mStateLock so that the side-effects of the State assignment
1349 // don't happen with mStateLock held (which can cause deadlocks).
1350 State drawingState(mDrawingState);
1352 Mutex::Autolock _l(mStateLock);
1353 const nsecs_t now = systemTime();
1354 mDebugInTransaction = now;
1356 // Here we're guaranteed that some transaction flags are set
1357 // so we can call handleTransactionLocked() unconditionally.
1358 // We call getTransactionFlags(), which will also clear the flags,
1359 // with mStateLock held to guarantee that mCurrentState won't change
1360 // until the transaction is committed.
1362 transactionFlags = getTransactionFlags(eTransactionMask);
1363 handleTransactionLocked(transactionFlags);
1365 mLastTransactionTime = systemTime() - now;
1366 mDebugInTransaction = 0;
1367 invalidateHwcGeometry();
1368 // here the transaction has been committed
1371 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1373 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1374 const size_t count = currentLayers.size();
1377 * Traversal of the children
1378 * (perform the transaction for each of them if needed)
1381 if (transactionFlags & eTraversalNeeded) {
1382 for (size_t i=0 ; i<count ; i++) {
1383 const sp<Layer>& layer(currentLayers[i]);
1384 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1385 if (!trFlags) continue;
1387 const uint32_t flags = layer->doTransaction(0);
1388 if (flags & Layer::eVisibleRegion)
1389 mVisibleRegionsDirty = true;
1394 * Perform display own transactions if needed
1397 if (transactionFlags & eDisplayTransactionNeeded) {
1398 // here we take advantage of Vector's copy-on-write semantics to
1399 // improve performance by skipping the transaction entirely when
1400 // know that the lists are identical
1401 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1402 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1403 if (!curr.isIdenticalTo(draw)) {
1404 mVisibleRegionsDirty = true;
1405 const size_t cc = curr.size();
1406 size_t dc = draw.size();
1408 // find the displays that were removed
1409 // (ie: in drawing state but not in current state)
1410 // also handle displays that changed
1411 // (ie: displays that are in both lists)
1412 for (size_t i=0 ; i<dc ; i++) {
1413 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1415 // in drawing state but not in current state
1416 if (!draw[i].isMainDisplay()) {
1417 // Call makeCurrent() on the primary display so we can
1418 // be sure that nothing associated with this display
1420 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1421 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1422 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1424 hw->disconnect(getHwComposer());
1425 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1426 mEventThread->onHotplugReceived(draw[i].type, false);
1427 mDisplays.removeItem(draw.keyAt(i));
1429 ALOGW("trying to remove the main display");
1432 // this display is in both lists. see if something changed.
1433 const DisplayDeviceState& state(curr[j]);
1434 const wp<IBinder>& display(curr.keyAt(j));
1435 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1436 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1437 if (state_binder != draw_binder) {
1438 // changing the surface is like destroying and
1439 // recreating the DisplayDevice, so we just remove it
1440 // from the drawing state, so that it get re-added
1442 sp<DisplayDevice> hw(getDisplayDevice(display));
1444 hw->disconnect(getHwComposer());
1445 mDisplays.removeItem(display);
1446 mDrawingState.displays.removeItemsAt(i);
1448 // at this point we must loop to the next item
1452 const sp<DisplayDevice> disp(getDisplayDevice(display));
1454 if (state.layerStack != draw[i].layerStack) {
1455 disp->setLayerStack(state.layerStack);
1457 if ((state.orientation != draw[i].orientation)
1458 || (state.viewport != draw[i].viewport)
1459 || (state.frame != draw[i].frame))
1461 disp->setProjection(state.orientation,
1462 state.viewport, state.frame);
1464 if (state.width != draw[i].width || state.height != draw[i].height) {
1465 disp->setDisplaySize(state.width, state.height);
1471 // find displays that were added
1472 // (ie: in current state but not in drawing state)
1473 for (size_t i=0 ; i<cc ; i++) {
1474 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1475 const DisplayDeviceState& state(curr[i]);
1477 sp<DisplaySurface> dispSurface;
1478 sp<IGraphicBufferProducer> producer;
1479 sp<IGraphicBufferProducer> bqProducer;
1480 sp<IGraphicBufferConsumer> bqConsumer;
1481 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1482 new GraphicBufferAlloc());
1484 int32_t hwcDisplayId = -1;
1485 if (state.isVirtualDisplay()) {
1486 // Virtual displays without a surface are dormant:
1487 // they have external state (layer stack, projection,
1488 // etc.) but no internal state (i.e. a DisplayDevice).
1489 if (state.surface != NULL) {
1492 DisplayUtils* displayUtils = DisplayUtils::getInstance();
1493 int status = state.surface->query(
1494 NATIVE_WINDOW_WIDTH, &width);
1495 ALOGE_IF(status != NO_ERROR,
1496 "Unable to query width (%d)", status);
1498 status = state.surface->query(
1499 NATIVE_WINDOW_HEIGHT, &height);
1500 ALOGE_IF(status != NO_ERROR,
1501 "Unable to query height (%d)", status);
1502 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1503 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1504 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1506 status = state.surface->query(
1507 NATIVE_WINDOW_CONSUMER_USAGE_BITS, &usage);
1508 ALOGW_IF(status != NO_ERROR,
1509 "Unable to query usage (%d)", status);
1510 if ( (status == NO_ERROR) &&
1511 displayUtils->canAllocateHwcDisplayIdForVDS(usage)) {
1512 hwcDisplayId = allocateHwcDisplayId(state.type);
1516 displayUtils->initVDSInstance(mHwc, hwcDisplayId, state.surface,
1517 dispSurface, producer, bqProducer, bqConsumer,
1518 state.displayName, state.isSecure, state.type);
1522 ALOGE_IF(state.surface!=NULL,
1523 "adding a supported display, but rendering "
1524 "surface is provided (%p), ignoring it",
1525 state.surface.get());
1526 hwcDisplayId = allocateHwcDisplayId(state.type);
1527 // for supported (by hwc) displays we provide our
1528 // own rendering surface
1529 dispSurface = new FramebufferSurface(*mHwc, state.type,
1531 producer = bqProducer;
1534 const wp<IBinder>& display(curr.keyAt(i));
1535 if (dispSurface != NULL && producer != NULL) {
1536 sp<DisplayDevice> hw = new DisplayDevice(this,
1537 state.type, hwcDisplayId,
1538 mHwc->getFormat(hwcDisplayId), state.isSecure,
1539 display, dispSurface, producer,
1540 mRenderEngine->getEGLConfig());
1541 hw->setLayerStack(state.layerStack);
1542 hw->setProjection(state.orientation,
1543 state.viewport, state.frame);
1544 hw->setDisplayName(state.displayName);
1545 // When a new display device is added update the active
1546 // config by querying HWC otherwise the default config
1547 // (config 0) will be used.
1548 if (hwcDisplayId >= DisplayDevice::DISPLAY_PRIMARY &&
1549 hwcDisplayId < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
1550 int activeConfig = mHwc->getActiveConfig(hwcDisplayId);
1551 if (activeConfig >= 0) {
1552 hw->setActiveConfig(activeConfig);
1555 mDisplays.add(display, hw);
1556 if (state.isVirtualDisplay()) {
1557 if (hwcDisplayId >= 0) {
1558 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1559 hw->getWidth(), hw->getHeight(),
1563 mEventThread->onHotplugReceived(state.type, true);
1571 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1572 // The transform hint might have changed for some layers
1573 // (either because a display has changed, or because a layer
1576 // Walk through all the layers in currentLayers,
1577 // and update their transform hint.
1579 // If a layer is visible only on a single display, then that
1580 // display is used to calculate the hint, otherwise we use the
1583 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1584 // the hint is set before we acquire a buffer from the surface texture.
1586 // NOTE: layer transactions have taken place already, so we use their
1587 // drawing state. However, SurfaceFlinger's own transaction has not
1588 // happened yet, so we must use the current state layer list
1589 // (soon to become the drawing state list).
1591 sp<const DisplayDevice> disp;
1592 uint32_t currentlayerStack = 0;
1593 for (size_t i=0; i<count; i++) {
1594 // NOTE: we rely on the fact that layers are sorted by
1595 // layerStack first (so we don't have to traverse the list
1596 // of displays for every layer).
1597 const sp<Layer>& layer(currentLayers[i]);
1598 uint32_t layerStack = layer->getDrawingState().layerStack;
1599 if (i==0 || currentlayerStack != layerStack) {
1600 currentlayerStack = layerStack;
1601 // figure out if this layerstack is mirrored
1602 // (more than one display) if so, pick the default display,
1603 // if not, pick the only display it's on.
1605 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1606 sp<const DisplayDevice> hw(mDisplays[dpy]);
1607 if (hw->getLayerStack() == currentlayerStack) {
1618 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1619 // redraw after transform hint changes. See bug 8508397.
1621 // could be null when this layer is using a layerStack
1622 // that is not visible on any display. Also can occur at
1623 // screen off/on times.
1624 disp = getDefaultDisplayDevice();
1626 layer->updateTransformHint(disp);
1632 * Perform our own transaction if needed
1635 const LayerVector& layers(mDrawingState.layersSortedByZ);
1636 if (currentLayers.size() > layers.size()) {
1637 // layers have been added
1638 mVisibleRegionsDirty = true;
1641 // some layers might have been removed, so
1642 // we need to update the regions they're exposing.
1643 if (mLayersRemoved) {
1644 mLayersRemoved = false;
1645 mVisibleRegionsDirty = true;
1646 const size_t count = layers.size();
1647 for (size_t i=0 ; i<count ; i++) {
1648 const sp<Layer>& layer(layers[i]);
1649 if (currentLayers.indexOf(layer) < 0) {
1650 // this layer is not visible anymore
1651 // TODO: we could traverse the tree from front to back and
1652 // compute the actual visible region
1653 // TODO: we could cache the transformed region
1654 const Layer::State& s(layer->getDrawingState());
1655 Region visibleReg = s.transform.transform(
1656 Region(Rect(s.active.w, s.active.h)));
1657 invalidateLayerStack(s.layerStack, visibleReg);
1662 commitTransaction();
1664 updateCursorAsync();
1667 void SurfaceFlinger::updateCursorAsync()
1669 HWComposer& hwc(getHwComposer());
1670 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1671 sp<const DisplayDevice> hw(mDisplays[dpy]);
1672 const int32_t id = hw->getHwcDisplayId();
1676 const Vector< sp<Layer> >& currentLayers(
1677 hw->getVisibleLayersSortedByZ());
1678 const size_t count = currentLayers.size();
1679 HWComposer::LayerListIterator cur = hwc.begin(id);
1680 const HWComposer::LayerListIterator end = hwc.end(id);
1681 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1682 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1685 const sp<Layer>& layer(currentLayers[i]);
1686 Rect cursorPos = layer->getPosition(hw);
1687 hwc.setCursorPositionAsync(id, cursorPos);
1693 void SurfaceFlinger::commitTransaction()
1695 if (!mLayersPendingRemoval.isEmpty()) {
1696 // Notify removed layers now that they can't be drawn from
1697 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1698 mLayersPendingRemoval[i]->onRemoved();
1700 mLayersPendingRemoval.clear();
1703 // If this transaction is part of a window animation then the next frame
1704 // we composite should be considered an animation as well.
1705 mAnimCompositionPending = mAnimTransactionPending;
1707 mDrawingState = mCurrentState;
1708 mTransactionPending = false;
1709 mAnimTransactionPending = false;
1710 mTransactionCV.broadcast();
1713 void SurfaceFlinger::computeVisibleRegions(size_t dpy,
1714 const LayerVector& currentLayers, uint32_t layerStack,
1715 Region& outDirtyRegion, Region& outOpaqueRegion)
1719 Region aboveOpaqueLayers;
1720 Region aboveCoveredLayers;
1723 outDirtyRegion.clear();
1724 bool bIgnoreLayers = false;
1726 getIndexLOI(dpy, currentLayers, bIgnoreLayers, indexLOI);
1728 size_t i = currentLayers.size();
1730 const sp<Layer>& layer = currentLayers[i];
1732 // start with the whole surface at its current location
1733 const Layer::State& s(layer->getDrawingState());
1735 if(updateLayerVisibleNonTransparentRegion(dpy, layer,
1736 bIgnoreLayers, indexLOI,
1741 * opaqueRegion: area of a surface that is fully opaque.
1743 Region opaqueRegion;
1746 * visibleRegion: area of a surface that is visible on screen
1747 * and not fully transparent. This is essentially the layer's
1748 * footprint minus the opaque regions above it.
1749 * Areas covered by a translucent surface are considered visible.
1751 Region visibleRegion;
1754 * coveredRegion: area of a surface that is covered by all
1755 * visible regions above it (which includes the translucent areas).
1757 Region coveredRegion;
1760 * transparentRegion: area of a surface that is hinted to be completely
1761 * transparent. This is only used to tell when the layer has no visible
1762 * non-transparent regions and can be removed from the layer list. It
1763 * does not affect the visibleRegion of this layer or any layers
1764 * beneath it. The hint may not be correct if apps don't respect the
1765 * SurfaceView restrictions (which, sadly, some don't).
1767 Region transparentRegion;
1770 // handle hidden surfaces by setting the visible region to empty
1771 if (CC_LIKELY(layer->isVisible())) {
1772 const bool translucent = !layer->isOpaque(s);
1773 Rect bounds(s.transform.transform(layer->computeBounds()));
1774 visibleRegion.set(bounds);
1775 if (!visibleRegion.isEmpty()) {
1776 // Remove the transparent area from the visible region
1778 const Transform tr(s.transform);
1779 if (tr.transformed()) {
1780 if (tr.preserveRects()) {
1781 // transform the transparent region
1782 transparentRegion = tr.transform(s.activeTransparentRegion);
1784 // transformation too complex, can't do the
1785 // transparent region optimization.
1786 transparentRegion.clear();
1789 transparentRegion = s.activeTransparentRegion;
1793 // compute the opaque region
1794 const int32_t layerOrientation = s.transform.getOrientation();
1795 if (s.alpha==255 && !translucent &&
1796 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1797 // the opaque region is the layer's footprint
1798 opaqueRegion = visibleRegion;
1803 // Clip the covered region to the visible region
1804 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1806 // Update aboveCoveredLayers for next (lower) layer
1807 aboveCoveredLayers.orSelf(visibleRegion);
1809 // subtract the opaque region covered by the layers above us
1810 visibleRegion.subtractSelf(aboveOpaqueLayers);
1812 // compute this layer's dirty region
1813 if (layer->contentDirty) {
1814 // we need to invalidate the whole region
1815 dirty = visibleRegion;
1816 // as well, as the old visible region
1817 dirty.orSelf(layer->visibleRegion);
1818 layer->contentDirty = false;
1820 /* compute the exposed region:
1821 * the exposed region consists of two components:
1822 * 1) what's VISIBLE now and was COVERED before
1823 * 2) what's EXPOSED now less what was EXPOSED before
1825 * note that (1) is conservative, we start with the whole
1826 * visible region but only keep what used to be covered by
1827 * something -- which mean it may have been exposed.
1829 * (2) handles areas that were not covered by anything but got
1830 * exposed because of a resize.
1832 const Region newExposed = visibleRegion - coveredRegion;
1833 const Region oldVisibleRegion = layer->visibleRegion;
1834 const Region oldCoveredRegion = layer->coveredRegion;
1835 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1836 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1838 dirty.subtractSelf(aboveOpaqueLayers);
1840 // accumulate to the screen dirty region
1841 outDirtyRegion.orSelf(dirty);
1843 // Update aboveOpaqueLayers for next (lower) layer
1844 aboveOpaqueLayers.orSelf(opaqueRegion);
1846 // Store the visible region in screen space
1847 layer->setVisibleRegion(visibleRegion);
1848 layer->setCoveredRegion(coveredRegion);
1849 layer->setVisibleNonTransparentRegion(
1850 visibleRegion.subtract(transparentRegion));
1853 outOpaqueRegion = aboveOpaqueLayers;
1856 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1857 const Region& dirty) {
1858 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1859 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1860 if (hw->getLayerStack() == layerStack) {
1861 hw->dirtyRegion.orSelf(dirty);
1866 bool SurfaceFlinger::handlePageFlip()
1870 bool visibleRegions = false;
1871 const LayerVector& layers(mDrawingState.layersSortedByZ);
1872 bool frameQueued = false;
1874 // Store the set of layers that need updates. This set must not change as
1875 // buffers are being latched, as this could result in a deadlock.
1876 // Example: Two producers share the same command stream and:
1877 // 1.) Layer 0 is latched
1878 // 2.) Layer 0 gets a new frame
1879 // 2.) Layer 1 gets a new frame
1880 // 3.) Layer 1 is latched.
1881 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1882 // second frame. But layer 0's second frame could be waiting on display.
1883 Vector<Layer*> layersWithQueuedFrames;
1884 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1885 const sp<Layer>& layer(layers[i]);
1886 if (layer->hasQueuedFrame()) {
1888 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1889 layersWithQueuedFrames.push_back(layer.get());
1891 layer->useEmptyDamage();
1894 layer->useEmptyDamage();
1897 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1898 Layer* layer = layersWithQueuedFrames[i];
1899 const Region dirty(layer->latchBuffer(visibleRegions));
1900 layer->useSurfaceDamage();
1901 const Layer::State& s(layer->getDrawingState());
1902 invalidateLayerStack(s.layerStack, dirty);
1905 mVisibleRegionsDirty |= visibleRegions;
1907 // If we will need to wake up at some time in the future to deal with a
1908 // queued frame that shouldn't be displayed during this vsync period, wake
1909 // up during the next vsync period to check again.
1910 if (frameQueued && layersWithQueuedFrames.empty()) {
1911 signalLayerUpdate();
1914 // Only continue with the refresh if there is actually new work to do
1915 return !layersWithQueuedFrames.empty();
1918 void SurfaceFlinger::invalidateHwcGeometry()
1920 mHwWorkListDirty = true;
1924 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1925 const Region& inDirtyRegion)
1927 // We only need to actually compose the display if:
1928 // 1) It is being handled by hardware composer, which may need this to
1929 // keep its virtual display state machine in sync, or
1930 // 2) There is work to be done (the dirty region isn't empty)
1931 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1932 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1936 Region dirtyRegion(inDirtyRegion);
1938 // compute the invalid region
1939 hw->swapRegion.orSelf(dirtyRegion);
1941 uint32_t flags = hw->getFlags();
1942 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1943 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1944 // takes a rectangle, we must make sure to update that whole
1945 // rectangle in that case
1946 dirtyRegion.set(hw->swapRegion.bounds());
1948 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1949 // We need to redraw the rectangle that will be updated
1950 // (pushed to the framebuffer).
1951 // This is needed because PARTIAL_UPDATES only takes one
1952 // rectangle instead of a region (see DisplayDevice::flip())
1953 dirtyRegion.set(hw->swapRegion.bounds());
1955 // we need to redraw everything (the whole screen)
1956 dirtyRegion.set(hw->bounds());
1957 hw->swapRegion = dirtyRegion;
1961 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1962 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1964 RenderEngine& engine(getRenderEngine());
1965 mat4 colorMatrix = mColorMatrix;
1967 colorMatrix = colorMatrix * mDaltonizer();
1969 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1970 doComposeSurfaces(hw, dirtyRegion);
1971 engine.setupColorTransform(oldMatrix);
1974 // update the swap region and clear the dirty region
1975 hw->swapRegion.orSelf(dirtyRegion);
1977 // swap buffers (presentation)
1978 hw->swapBuffers(getHwComposer());
1981 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1983 RenderEngine& engine(getRenderEngine());
1984 const int32_t id = hw->getHwcDisplayId();
1985 HWComposer& hwc(getHwComposer());
1986 HWComposer::LayerListIterator cur = hwc.begin(id);
1987 const HWComposer::LayerListIterator end = hwc.end(id);
1989 bool hasGlesComposition = hwc.hasGlesComposition(id);
1990 if (hasGlesComposition) {
1991 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1992 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1993 hw->getDisplayName().string());
1994 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1995 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1996 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
2001 // Never touch the framebuffer if we don't have any framebuffer layers
2002 const bool hasHwcComposition = hwc.hasHwcComposition(id);
2003 if (hasHwcComposition) {
2004 // when using overlays, we assume a fully transparent framebuffer
2005 // NOTE: we could reduce how much we need to clear, for instance
2006 // remove where there are opaque FB layers. however, on some
2007 // GPUs doing a "clean slate" clear might be more efficient.
2008 // We'll revisit later if needed.
2009 engine.clearWithColor(0, 0, 0, 0);
2011 // we start with the whole screen area
2012 const Region bounds(hw->getBounds());
2014 // we remove the scissor part
2015 // we're left with the letterbox region
2016 // (common case is that letterbox ends-up being empty)
2017 const Region letterbox(bounds.subtract(hw->getScissor()));
2019 // compute the area to clear
2020 Region region(hw->undefinedRegion.merge(letterbox));
2022 // but limit it to the dirty region
2023 region.andSelf(dirty);
2025 // screen is already cleared here
2026 if (!region.isEmpty()) {
2027 // can happen with SurfaceView
2028 drawWormHoleIfRequired(cur, end, hw, region);
2032 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
2033 // just to be on the safe side, we don't set the
2034 // scissor on the main display. It should never be needed
2035 // anyways (though in theory it could since the API allows it).
2036 const Rect& bounds(hw->getBounds());
2037 const Rect& scissor(hw->getScissor());
2038 if (scissor != bounds) {
2039 // scissor doesn't match the screen's dimensions, so we
2040 // need to clear everything outside of it and enable
2041 // the GL scissor so we don't draw anything where we shouldn't
2043 // enable scissor for this frame
2044 const uint32_t height = hw->getHeight();
2045 engine.setScissor(scissor.left, height - scissor.bottom,
2046 scissor.getWidth(), scissor.getHeight());
2052 * and then, render the layers targeted at the framebuffer
2055 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
2056 const size_t count = layers.size();
2057 const Transform& tr = hw->getTransform();
2059 // we're using h/w composer
2060 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
2061 const sp<Layer>& layer(layers[i]);
2062 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
2063 if (!clip.isEmpty()) {
2064 switch (cur->getCompositionType()) {
2065 case HWC_CURSOR_OVERLAY:
2067 const Layer::State& state(layer->getDrawingState());
2068 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
2070 && layer->isOpaque(state) && (state.alpha == 0xFF)
2071 && hasGlesComposition) {
2072 // never clear the very first layer since we're
2073 // guaranteed the FB is already cleared
2074 layer->clearWithOpenGL(hw, clip);
2078 case HWC_FRAMEBUFFER: {
2079 layer->draw(hw, clip);
2082 case HWC_FRAMEBUFFER_TARGET: {
2083 // this should not happen as the iterator shouldn't
2084 // let us get there.
2085 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2090 layer->setAcquireFence(hw, *cur);
2093 // we're not using h/w composer
2094 for (size_t i=0 ; i<count ; ++i) {
2095 const sp<Layer>& layer(layers[i]);
2096 const Region clip(dirty.intersect(
2097 tr.transform(layer->visibleRegion)));
2098 if (!clip.isEmpty()) {
2099 layer->draw(hw, clip);
2104 // disable scissor at the end of the frame
2105 engine.disableScissor();
2109 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2110 const int32_t height = hw->getHeight();
2111 RenderEngine& engine(getRenderEngine());
2112 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2115 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2116 const sp<IBinder>& handle,
2117 const sp<IGraphicBufferProducer>& gbc,
2118 const sp<Layer>& lbc)
2120 // add this layer to the current state list
2122 Mutex::Autolock _l(mStateLock);
2123 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2126 mCurrentState.layersSortedByZ.add(lbc);
2127 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2130 // attach this layer to the client
2131 client->attachLayer(handle, lbc);
2136 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2137 Mutex::Autolock _l(mStateLock);
2138 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2140 mLayersPendingRemoval.push(layer);
2141 mLayersRemoved = true;
2142 setTransactionFlags(eTransactionNeeded);
2145 return status_t(index);
2148 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2149 return android_atomic_release_load(&mTransactionFlags);
2152 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2153 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2156 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2157 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2158 if ((old & flags)==0) { // wake the server up
2159 signalTransaction();
2164 void SurfaceFlinger::setTransactionState(
2165 const Vector<ComposerState>& state,
2166 const Vector<DisplayState>& displays,
2171 delayDPTransactionIfNeeded(displays);
2172 Mutex::Autolock _l(mStateLock);
2173 uint32_t transactionFlags = 0;
2175 if (flags & eAnimation) {
2176 // For window updates that are part of an animation we must wait for
2177 // previous animation "frames" to be handled.
2178 while (mAnimTransactionPending) {
2179 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2180 if (CC_UNLIKELY(err != NO_ERROR)) {
2181 // just in case something goes wrong in SF, return to the
2182 // caller after a few seconds.
2183 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2184 "waiting for previous animation frame");
2185 mAnimTransactionPending = false;
2191 size_t count = displays.size();
2192 for (size_t i=0 ; i<count ; i++) {
2193 const DisplayState& s(displays[i]);
2194 transactionFlags |= setDisplayStateLocked(s);
2197 count = state.size();
2198 for (size_t i=0 ; i<count ; i++) {
2199 const ComposerState& s(state[i]);
2200 // Here we need to check that the interface we're given is indeed
2201 // one of our own. A malicious client could give us a NULL
2202 // IInterface, or one of its own or even one of our own but a
2203 // different type. All these situations would cause us to crash.
2205 // NOTE: it would be better to use RTTI as we could directly check
2206 // that we have a Client*. however, RTTI is disabled in Android.
2207 if (s.client != NULL) {
2208 sp<IBinder> binder = IInterface::asBinder(s.client);
2209 if (binder != NULL) {
2210 String16 desc(binder->getInterfaceDescriptor());
2211 if (desc == ISurfaceComposerClient::descriptor) {
2212 sp<Client> client( static_cast<Client *>(s.client.get()) );
2213 transactionFlags |= setClientStateLocked(client, s.state);
2219 if (transactionFlags) {
2220 // this triggers the transaction
2221 setTransactionFlags(transactionFlags);
2223 // if this is a synchronous transaction, wait for it to take effect
2224 // before returning.
2225 if (flags & eSynchronous) {
2226 mTransactionPending = true;
2228 if (flags & eAnimation) {
2229 mAnimTransactionPending = true;
2231 while (mTransactionPending) {
2232 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2233 if (CC_UNLIKELY(err != NO_ERROR)) {
2234 // just in case something goes wrong in SF, return to the
2235 // called after a few seconds.
2236 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2237 mTransactionPending = false;
2244 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2246 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2251 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2252 if (disp.isValid()) {
2253 const uint32_t what = s.what;
2254 if (what & DisplayState::eSurfaceChanged) {
2255 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2256 disp.surface = s.surface;
2257 flags |= eDisplayTransactionNeeded;
2260 if (what & DisplayState::eLayerStackChanged) {
2261 if (disp.layerStack != s.layerStack) {
2262 disp.layerStack = s.layerStack;
2263 flags |= eDisplayTransactionNeeded;
2266 if (what & DisplayState::eDisplayProjectionChanged) {
2267 if (disp.orientation != s.orientation) {
2268 disp.orientation = s.orientation;
2269 flags |= eDisplayTransactionNeeded;
2271 if (disp.frame != s.frame) {
2272 disp.frame = s.frame;
2273 flags |= eDisplayTransactionNeeded;
2275 if (disp.viewport != s.viewport) {
2276 disp.viewport = s.viewport;
2277 flags |= eDisplayTransactionNeeded;
2280 if (what & DisplayState::eDisplaySizeChanged) {
2281 if (disp.width != s.width) {
2282 disp.width = s.width;
2283 flags |= eDisplayTransactionNeeded;
2285 if (disp.height != s.height) {
2286 disp.height = s.height;
2287 flags |= eDisplayTransactionNeeded;
2294 uint32_t SurfaceFlinger::setClientStateLocked(
2295 const sp<Client>& client,
2296 const layer_state_t& s)
2299 sp<Layer> layer(client->getLayerUser(s.surface));
2301 const uint32_t what = s.what;
2302 if (what & layer_state_t::ePositionChanged) {
2303 if (layer->setPosition(s.x, s.y))
2304 flags |= eTraversalNeeded;
2306 if (what & layer_state_t::eLayerChanged) {
2307 // NOTE: index needs to be calculated before we update the state
2308 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2309 if (layer->setLayer(s.z)) {
2310 mCurrentState.layersSortedByZ.removeAt(idx);
2311 mCurrentState.layersSortedByZ.add(layer);
2312 // we need traversal (state changed)
2313 // AND transaction (list changed)
2314 flags |= eTransactionNeeded|eTraversalNeeded;
2317 if (what & layer_state_t::eBlurChanged) {
2318 ALOGV("eBlurChanged");
2319 if (layer->setBlur(uint8_t(255.0f*s.blur+0.5f))) {
2320 flags |= eTraversalNeeded;
2323 if (what & layer_state_t::eBlurMaskSurfaceChanged) {
2324 ALOGV("eBlurMaskSurfaceChanged");
2325 sp<Layer> maskLayer = 0;
2326 if (s.blurMaskSurface != 0) {
2327 maskLayer = client->getLayerUser(s.blurMaskSurface);
2329 if (maskLayer == 0) {
2330 ALOGV("eBlurMaskSurfaceChanged. maskLayer == 0");
2332 ALOGV("eBlurMaskSurfaceChagned. maskLayer.z == %d", maskLayer->getCurrentState().z);
2333 if (maskLayer->isBlurLayer()) {
2334 ALOGE("Blur layer can not be used as blur mask surface");
2338 if (layer->setBlurMaskLayer(maskLayer)) {
2339 flags |= eTraversalNeeded;
2342 if (what & layer_state_t::eBlurMaskSamplingChanged) {
2343 if (layer->setBlurMaskSampling(s.blurMaskSampling)) {
2344 flags |= eTraversalNeeded;
2347 if (what & layer_state_t::eBlurMaskAlphaThresholdChanged) {
2348 if (layer->setBlurMaskAlphaThreshold(s.blurMaskAlphaThreshold)) {
2349 flags |= eTraversalNeeded;
2352 if (what & layer_state_t::eSizeChanged) {
2353 if (layer->setSize(s.w, s.h)) {
2354 flags |= eTraversalNeeded;
2357 if (what & layer_state_t::eAlphaChanged) {
2358 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2359 flags |= eTraversalNeeded;
2361 if (what & layer_state_t::eMatrixChanged) {
2362 if (layer->setMatrix(s.matrix))
2363 flags |= eTraversalNeeded;
2365 if (what & layer_state_t::eTransparentRegionChanged) {
2366 if (layer->setTransparentRegionHint(s.transparentRegion))
2367 flags |= eTraversalNeeded;
2369 if (what & layer_state_t::eFlagsChanged) {
2370 if (layer->setFlags(s.flags, s.mask))
2371 flags |= eTraversalNeeded;
2373 if (what & layer_state_t::eCropChanged) {
2374 if (layer->setCrop(s.crop))
2375 flags |= eTraversalNeeded;
2377 if (what & layer_state_t::eLayerStackChanged) {
2378 // NOTE: index needs to be calculated before we update the state
2379 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2380 if (layer->setLayerStack(s.layerStack)) {
2381 mCurrentState.layersSortedByZ.removeAt(idx);
2382 mCurrentState.layersSortedByZ.add(layer);
2383 // we need traversal (state changed)
2384 // AND transaction (list changed)
2385 flags |= eTransactionNeeded|eTraversalNeeded;
2392 status_t SurfaceFlinger::createLayer(
2393 const String8& name,
2394 const sp<Client>& client,
2395 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2396 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2398 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2399 if (int32_t(w|h) < 0) {
2400 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2405 status_t result = NO_ERROR;
2409 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2410 case ISurfaceComposerClient::eFXSurfaceNormal:
2411 result = createNormalLayer(client,
2412 name, w, h, flags, format,
2413 handle, gbp, &layer);
2415 case ISurfaceComposerClient::eFXSurfaceDim:
2416 result = createDimLayer(client,
2418 handle, gbp, &layer);
2420 case ISurfaceComposerClient::eFXSurfaceBlur:
2421 result = createBlurLayer(client,
2423 handle, gbp, &layer);
2430 if (result != NO_ERROR) {
2434 result = addClientLayer(client, *handle, *gbp, layer);
2435 if (result != NO_ERROR) {
2439 setTransactionFlags(eTransactionNeeded);
2443 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2444 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2445 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2447 // initialize the surfaces
2449 case PIXEL_FORMAT_TRANSPARENT:
2450 case PIXEL_FORMAT_TRANSLUCENT:
2451 format = PIXEL_FORMAT_RGBA_8888;
2453 case PIXEL_FORMAT_OPAQUE:
2454 format = PIXEL_FORMAT_RGBX_8888;
2458 *outLayer = DisplayUtils::getInstance()->getLayerInstance(this, client, name, w, h, flags);
2459 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2460 if (err == NO_ERROR) {
2461 *handle = (*outLayer)->getHandle();
2462 *gbp = (*outLayer)->getProducer();
2465 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2469 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2470 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2471 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2473 *outLayer = new LayerDim(this, client, name, w, h, flags);
2474 *handle = (*outLayer)->getHandle();
2475 *gbp = (*outLayer)->getProducer();
2479 status_t SurfaceFlinger::createBlurLayer(const sp<Client>& client,
2480 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2481 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2483 *outLayer = new LayerBlur(this, client, name, w, h, flags);
2484 *handle = (*outLayer)->getHandle();
2485 *gbp = (*outLayer)->getProducer();
2489 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2491 // called by the window manager when it wants to remove a Layer
2492 status_t err = NO_ERROR;
2493 sp<Layer> l(client->getLayerUser(handle));
2495 err = removeLayer(l);
2496 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2497 "error removing layer=%p (%s)", l.get(), strerror(-err));
2502 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2504 // called by ~LayerCleaner() when all references to the IBinder (handle)
2506 status_t err = NO_ERROR;
2507 sp<Layer> l(layer.promote());
2509 err = removeLayer(l);
2510 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2511 "error removing layer=%p (%s)", l.get(), strerror(-err));
2516 // ---------------------------------------------------------------------------
2518 void SurfaceFlinger::onInitializeDisplays() {
2519 // reset screen orientation and use primary layer stack
2520 Vector<ComposerState> state;
2521 Vector<DisplayState> displays;
2523 d.what = DisplayState::eDisplayProjectionChanged |
2524 DisplayState::eLayerStackChanged;
2525 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2527 d.orientation = DisplayState::eOrientationDefault;
2528 d.frame.makeInvalid();
2529 d.viewport.makeInvalid();
2533 setTransactionState(state, displays, 0);
2534 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2536 const nsecs_t period =
2537 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2538 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2541 void SurfaceFlinger::initializeDisplays() {
2542 class MessageScreenInitialized : public MessageBase {
2543 SurfaceFlinger* flinger;
2545 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2546 virtual bool handler() {
2547 flinger->onInitializeDisplays();
2551 sp<MessageBase> msg = new MessageScreenInitialized(this);
2552 postMessageAsync(msg); // we may be called from main thread, use async message
2555 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2557 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2559 int32_t type = hw->getDisplayType();
2560 int currentMode = hw->getPowerMode();
2562 if (mode == currentMode) {
2563 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2567 hw->setPowerMode(mode);
2568 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2569 ALOGW("Trying to set power mode for virtual display");
2573 if (currentMode == HWC_POWER_MODE_OFF) {
2574 getHwComposer().setPowerMode(type, mode);
2575 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2576 // FIXME: eventthread only knows about the main display right now
2577 mEventThread->onScreenAcquired();
2578 resyncToHardwareVsync(true);
2581 mVisibleRegionsDirty = true;
2582 mHasPoweredOff = true;
2583 repaintEverything();
2584 } else if (mode == HWC_POWER_MODE_OFF) {
2585 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2586 disableHardwareVsync(true); // also cancels any in-progress resync
2588 // FIXME: eventthread only knows about the main display right now
2589 mEventThread->onScreenReleased();
2592 getHwComposer().setPowerMode(type, mode);
2593 mVisibleRegionsDirty = true;
2594 // from this point on, SF will stop drawing on this display
2596 getHwComposer().setPowerMode(type, mode);
2600 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2601 class MessageSetPowerMode: public MessageBase {
2602 SurfaceFlinger& mFlinger;
2603 sp<IBinder> mDisplay;
2606 MessageSetPowerMode(SurfaceFlinger& flinger,
2607 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2608 mDisplay(disp) { mMode = mode; }
2609 virtual bool handler() {
2610 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2612 ALOGE("Attempt to set power mode = %d for null display %p",
2613 mMode, mDisplay.get());
2614 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2615 ALOGW("Attempt to set power mode = %d for virtual display",
2618 mFlinger.setPowerModeInternal(hw, mMode);
2623 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2624 postMessageSync(msg);
2627 // ---------------------------------------------------------------------------
2629 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2633 IPCThreadState* ipc = IPCThreadState::self();
2634 const int pid = ipc->getCallingPid();
2635 const int uid = ipc->getCallingUid();
2636 if ((uid != AID_SHELL) &&
2637 !PermissionCache::checkPermission(sDump, pid, uid)) {
2638 result.appendFormat("Permission Denial: "
2639 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2641 // Try to get the main lock, but give up after one second
2642 // (this would indicate SF is stuck, but we want to be able to
2643 // print something in dumpsys).
2644 status_t err = mStateLock.timedLock(s2ns(1));
2645 bool locked = (err == NO_ERROR);
2647 result.appendFormat(
2648 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2649 "dumping anyways (no locks held)\n", strerror(-err), err);
2652 bool dumpAll = true;
2654 size_t numArgs = args.size();
2656 if ((index < numArgs) &&
2657 (args[index] == String16("--list"))) {
2659 listLayersLocked(args, index, result);
2663 if ((index < numArgs) &&
2664 (args[index] == String16("--latency"))) {
2666 dumpStatsLocked(args, index, result);
2670 if ((index < numArgs) &&
2671 (args[index] == String16("--latency-clear"))) {
2673 clearStatsLocked(args, index, result);
2677 if ((index < numArgs) &&
2678 (args[index] == String16("--dispsync"))) {
2680 mPrimaryDispSync.dump(result);
2684 if ((index < numArgs) &&
2685 (args[index] == String16("--static-screen"))) {
2687 dumpStaticScreenStats(result);
2693 dumpAllLocked(args, index, result);
2697 mStateLock.unlock();
2700 write(fd, result.string(), result.size());
2704 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2705 size_t& /* index */, String8& result) const
2707 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2708 const size_t count = currentLayers.size();
2709 for (size_t i=0 ; i<count ; i++) {
2710 const sp<Layer>& layer(currentLayers[i]);
2711 result.appendFormat("%s\n", layer->getName().string());
2715 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2716 String8& result) const
2719 if (index < args.size()) {
2720 name = String8(args[index]);
2724 const nsecs_t period =
2725 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2726 result.appendFormat("%" PRId64 "\n", period);
2728 if (name.isEmpty()) {
2729 mAnimFrameTracker.dumpStats(result);
2732 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2733 const size_t count = currentLayers.size();
2734 for (size_t i=0 ; i<count ; i++) {
2735 const sp<Layer>& layer(currentLayers[i]);
2736 if (name == layer->getName()) {
2738 layer->dumpFrameStats(result);
2741 if (!found && !strncmp(name.string(), "SurfaceView", 11)) {
2742 lastSurfaceViewLayer->dumpFrameStats(result);
2747 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2748 String8& /* result */)
2751 if (index < args.size()) {
2752 name = String8(args[index]);
2756 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2757 const size_t count = currentLayers.size();
2758 for (size_t i=0 ; i<count ; i++) {
2759 const sp<Layer>& layer(currentLayers[i]);
2760 if (name.isEmpty() || (name == layer->getName())) {
2761 layer->clearFrameStats();
2765 mAnimFrameTracker.clearStats();
2768 // This should only be called from the main thread. Otherwise it would need
2769 // the lock and should use mCurrentState rather than mDrawingState.
2770 void SurfaceFlinger::logFrameStats() {
2771 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2772 const size_t count = drawingLayers.size();
2773 for (size_t i=0 ; i<count ; i++) {
2774 const sp<Layer>& layer(drawingLayers[i]);
2775 layer->logFrameStats();
2778 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2781 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2783 static const char* config =
2785 #ifdef HAS_CONTEXT_PRIORITY
2786 " HAS_CONTEXT_PRIORITY"
2788 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2789 " NEVER_DEFAULT_TO_ASYNC_MODE"
2791 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2792 " TARGET_DISABLE_TRIPLE_BUFFERING"
2795 result.append(config);
2798 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2800 result.appendFormat("Static screen stats:\n");
2801 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2802 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2803 float percent = 100.0f *
2804 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2805 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2806 b + 1, bucketTimeSec, percent);
2808 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2809 float percent = 100.0f *
2810 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2811 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2812 NUM_BUCKETS - 1, bucketTimeSec, percent);
2815 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2816 String8& result) const
2818 bool colorize = false;
2819 if (index < args.size()
2820 && (args[index] == String16("--color"))) {
2825 Colorizer colorizer(colorize);
2827 // figure out if we're stuck somewhere
2828 const nsecs_t now = systemTime();
2829 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2830 const nsecs_t inTransaction(mDebugInTransaction);
2831 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2832 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2835 * Dump library configuration.
2838 colorizer.bold(result);
2839 result.append("Build configuration:");
2840 colorizer.reset(result);
2841 appendSfConfigString(result);
2842 appendUiConfigString(result);
2843 appendGuiConfigString(result);
2844 result.append("\n");
2846 colorizer.bold(result);
2847 result.append("Sync configuration: ");
2848 colorizer.reset(result);
2849 result.append(SyncFeatures::getInstance().toString());
2850 result.append("\n");
2852 colorizer.bold(result);
2853 result.append("DispSync configuration: ");
2854 colorizer.reset(result);
2855 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2856 "present offset %d ns (refresh %" PRId64 " ns)",
2857 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2858 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2859 result.append("\n");
2861 // Dump static screen stats
2862 result.append("\n");
2863 dumpStaticScreenStats(result);
2864 result.append("\n");
2867 * Dump the visible layer list
2869 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2870 const size_t count = currentLayers.size();
2871 colorizer.bold(result);
2872 result.appendFormat("Visible layers (count = %zu)\n", count);
2873 colorizer.reset(result);
2874 for (size_t i=0 ; i<count ; i++) {
2875 const sp<Layer>& layer(currentLayers[i]);
2876 layer->dump(result, colorizer);
2880 * Dump Display state
2883 colorizer.bold(result);
2884 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2885 colorizer.reset(result);
2886 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2887 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2892 * Dump SurfaceFlinger global state
2895 colorizer.bold(result);
2896 result.append("SurfaceFlinger global state:\n");
2897 colorizer.reset(result);
2899 HWComposer& hwc(getHwComposer());
2900 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2902 colorizer.bold(result);
2903 result.appendFormat("EGL implementation : %s\n",
2904 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2905 colorizer.reset(result);
2906 result.appendFormat("%s\n",
2907 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2909 mRenderEngine->dump(result);
2911 hw->undefinedRegion.dump(result, "undefinedRegion");
2912 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2913 hw->getOrientation(), hw->isDisplayOn());
2914 result.appendFormat(
2915 " last eglSwapBuffers() time: %f us\n"
2916 " last transaction time : %f us\n"
2917 " transaction-flags : %08x\n"
2918 " refresh-rate : %f fps\n"
2921 " gpu_to_cpu_unsupported : %d\n"
2923 mLastSwapBufferTime/1000.0,
2924 mLastTransactionTime/1000.0,
2926 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2927 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2928 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2929 !mGpuToCpuSupported);
2931 result.appendFormat(" eglSwapBuffers time: %f us\n",
2932 inSwapBuffersDuration/1000.0);
2934 result.appendFormat(" transaction time: %f us\n",
2935 inTransactionDuration/1000.0);
2940 mEventThread->dump(result);
2943 * Dump HWComposer state
2945 colorizer.bold(result);
2946 result.append("h/w composer state:\n");
2947 colorizer.reset(result);
2948 result.appendFormat(" h/w composer %s and %s\n",
2949 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2950 (mDebugDisableHWC || mDebugRegion || mDaltonize
2951 || mHasColorMatrix) ? "disabled" : "enabled");
2955 * Dump gralloc state
2957 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2961 const Vector< sp<Layer> >&
2962 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2963 // Note: mStateLock is held here
2965 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2966 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2967 dpy = mDisplays.keyAt(i);
2972 ALOGW("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2973 // Just use the primary display so we have something to return
2974 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2976 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2979 bool SurfaceFlinger::startDdmConnection()
2981 void* libddmconnection_dso =
2982 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2983 if (!libddmconnection_dso) {
2986 void (*DdmConnection_start)(const char* name);
2987 DdmConnection_start =
2988 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2989 if (!DdmConnection_start) {
2990 dlclose(libddmconnection_dso);
2993 (*DdmConnection_start)(getServiceName());
2997 status_t SurfaceFlinger::onTransact(
2998 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
3001 case CREATE_CONNECTION:
3002 case CREATE_DISPLAY:
3003 case SET_TRANSACTION_STATE:
3005 case CLEAR_ANIMATION_FRAME_STATS:
3006 case GET_ANIMATION_FRAME_STATS:
3007 case SET_POWER_MODE:
3009 // codes that require permission check
3010 IPCThreadState* ipc = IPCThreadState::self();
3011 const int pid = ipc->getCallingPid();
3012 const int uid = ipc->getCallingUid();
3013 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
3014 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
3015 ALOGE("Permission Denial: "
3016 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3017 return PERMISSION_DENIED;
3021 case CAPTURE_SCREEN:
3023 // codes that require permission check
3024 IPCThreadState* ipc = IPCThreadState::self();
3025 const int pid = ipc->getCallingPid();
3026 const int uid = ipc->getCallingUid();
3027 if ((uid != AID_GRAPHICS) &&
3028 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
3029 ALOGE("Permission Denial: "
3030 "can't read framebuffer pid=%d, uid=%d", pid, uid);
3031 return PERMISSION_DENIED;
3037 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
3038 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
3039 CHECK_INTERFACE(ISurfaceComposer, data, reply);
3040 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
3041 IPCThreadState* ipc = IPCThreadState::self();
3042 const int pid = ipc->getCallingPid();
3043 const int uid = ipc->getCallingUid();
3044 ALOGE("Permission Denial: "
3045 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
3046 return PERMISSION_DENIED;
3050 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
3051 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
3053 case 1002: // SHOW_UPDATES
3054 n = data.readInt32();
3055 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
3056 invalidateHwcGeometry();
3057 repaintEverything();
3059 case 1004:{ // repaint everything
3060 repaintEverything();
3063 case 1005:{ // force transaction
3064 setTransactionFlags(
3066 eDisplayTransactionNeeded|
3070 case 1006:{ // send empty update
3074 case 1008: // toggle use of hw composer
3075 n = data.readInt32();
3076 mDebugDisableHWC = n ? 1 : 0;
3077 invalidateHwcGeometry();
3078 repaintEverything();
3080 case 1009: // toggle use of transform hint
3081 n = data.readInt32();
3082 mDebugDisableTransformHint = n ? 1 : 0;
3083 invalidateHwcGeometry();
3084 repaintEverything();
3086 case 1010: // interrogate.
3087 reply->writeInt32(0);
3088 reply->writeInt32(0);
3089 reply->writeInt32(mDebugRegion);
3090 reply->writeInt32(0);
3091 reply->writeInt32(mDebugDisableHWC);
3094 Mutex::Autolock _l(mStateLock);
3095 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
3096 reply->writeInt32(hw->getPageFlipCount());
3101 n = data.readInt32();
3103 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
3104 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
3105 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
3108 mDaltonizer.setMode(Daltonizer::correction);
3110 mDaltonizer.setMode(Daltonizer::simulation);
3113 invalidateHwcGeometry();
3114 repaintEverything();
3118 // apply a color matrix
3119 n = data.readInt32();
3120 mHasColorMatrix = n ? 1 : 0;
3122 // color matrix is sent as mat3 matrix followed by vec3
3123 // offset, then packed into a mat4 where the last row is
3124 // the offset and extra values are 0
3125 for (size_t i = 0 ; i < 4; i++) {
3126 for (size_t j = 0; j < 4; j++) {
3127 mColorMatrix[i][j] = data.readFloat();
3131 mColorMatrix = mat4();
3133 invalidateHwcGeometry();
3134 repaintEverything();
3137 // This is an experimental interface
3138 // Needs to be shifted to proper binder interface when we productize
3140 n = data.readInt32();
3141 mPrimaryDispSync.setRefreshSkipCount(n);
3145 n = data.readInt32();
3146 mForceFullDamage = static_cast<bool>(n);
3149 case 1018: { // Modify Choreographer's phase offset
3150 n = data.readInt32();
3151 if (mEventThread != NULL)
3152 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3155 case 1019: { // Modify SurfaceFlinger's phase offset
3156 n = data.readInt32();
3157 if (mSFEventThread != NULL)
3158 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3166 void SurfaceFlinger::repaintEverything() {
3167 android_atomic_or(1, &mRepaintEverything);
3168 signalTransaction();
3171 // ---------------------------------------------------------------------------
3172 // Capture screen into an IGraphiBufferProducer
3173 // ---------------------------------------------------------------------------
3175 /* The code below is here to handle b/8734824
3177 * We create a IGraphicBufferProducer wrapper that forwards all calls
3178 * from the surfaceflinger thread to the calling binder thread, where they
3179 * are executed. This allows the calling thread in the calling process to be
3180 * reused and not depend on having "enough" binder threads to handle the
3183 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3184 /* Parts of GraphicProducerWrapper are run on two different threads,
3185 * communicating by sending messages via Looper but also by shared member
3186 * data. Coherence maintenance is subtle and in places implicit (ugh).
3188 * Don't rely on Looper's sendMessage/handleMessage providing
3189 * release/acquire semantics for any data not actually in the Message.
3190 * Data going from surfaceflinger to binder threads needs to be
3191 * synchronized explicitly.
3193 * Barrier open/wait do provide release/acquire semantics. This provides
3194 * implicit synchronization for data coming back from binder to
3195 * surfaceflinger threads.
3198 sp<IGraphicBufferProducer> impl;
3214 * Called on surfaceflinger thread. This is called by our "fake"
3215 * BpGraphicBufferProducer. We package the data and reply Parcel and
3216 * forward them to the binder thread.
3218 virtual status_t transact(uint32_t code,
3219 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3222 this->reply = reply;
3224 // if we've exited, we run the message synchronously right here.
3225 // note (JH): as far as I can tell from looking at the code, this
3226 // never actually happens. if it does, i'm not sure if it happens
3227 // on the surfaceflinger or binder thread.
3228 handleMessage(Message(MSG_API_CALL));
3231 // Prevent stores to this->{code, data, reply} from being
3232 // reordered later than the construction of Message.
3233 atomic_thread_fence(memory_order_release);
3234 looper->sendMessage(this, Message(MSG_API_CALL));
3241 * here we run on the binder thread. All we've got to do is
3242 * call the real BpGraphicBufferProducer.
3244 virtual void handleMessage(const Message& message) {
3245 int what = message.what;
3246 // Prevent reads below from happening before the read from Message
3247 atomic_thread_fence(memory_order_acquire);
3248 if (what == MSG_API_CALL) {
3249 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3251 } else if (what == MSG_EXIT) {
3252 exitRequested = true;
3257 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3259 looper(new Looper(true)),
3261 exitRequested(false)
3265 status_t waitForResponse() {
3267 looper->pollOnce(-1);
3268 } while (!exitRequested);
3273 void exit(status_t result) {
3274 this->result = result;
3276 // Ensure this->result is visible to the binder thread before it
3277 // handles the message.
3278 atomic_thread_fence(memory_order_release);
3279 looper->sendMessage(this, Message(MSG_EXIT));
3284 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3285 const sp<IGraphicBufferProducer>& producer,
3286 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3287 uint32_t minLayerZ, uint32_t maxLayerZ,
3288 bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
3289 bool useReadPixels) {
3291 if (CC_UNLIKELY(display == 0))
3294 if (CC_UNLIKELY(producer == 0))
3297 // if we have secure windows on this display, never allow the screen capture
3298 // unless the producer interface is local (i.e.: we can take a screenshot for
3300 if (!IInterface::asBinder(producer)->localBinder()) {
3301 Mutex::Autolock _l(mStateLock);
3302 sp<const DisplayDevice> hw(getDisplayDevice(display));
3303 if (hw->getSecureLayerVisible()) {
3304 ALOGW("FB is protected: PERMISSION_DENIED");
3305 return PERMISSION_DENIED;
3309 // Convert to surfaceflinger's internal rotation type.
3310 Transform::orientation_flags rotationFlags;
3312 case ISurfaceComposer::eRotateNone:
3313 rotationFlags = Transform::ROT_0;
3315 case ISurfaceComposer::eRotate90:
3316 rotationFlags = Transform::ROT_90;
3318 case ISurfaceComposer::eRotate180:
3319 rotationFlags = Transform::ROT_180;
3321 case ISurfaceComposer::eRotate270:
3322 rotationFlags = Transform::ROT_270;
3325 rotationFlags = Transform::ROT_0;
3326 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3330 class MessageCaptureScreen : public MessageBase {
3331 SurfaceFlinger* flinger;
3332 sp<IBinder> display;
3333 sp<IGraphicBufferProducer> producer;
3335 uint32_t reqWidth, reqHeight;
3336 uint32_t minLayerZ,maxLayerZ;
3337 bool useIdentityTransform;
3338 Transform::orientation_flags rotation;
3342 MessageCaptureScreen(SurfaceFlinger* flinger,
3343 const sp<IBinder>& display,
3344 const sp<IGraphicBufferProducer>& producer,
3345 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3346 uint32_t minLayerZ, uint32_t maxLayerZ,
3347 bool useIdentityTransform, Transform::orientation_flags rotation,
3349 : flinger(flinger), display(display), producer(producer),
3350 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3351 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3352 useIdentityTransform(useIdentityTransform),
3354 useReadPixels(useReadPixels),
3355 result(PERMISSION_DENIED)
3358 status_t getResult() const {
3361 virtual bool handler() {
3362 Mutex::Autolock _l(flinger->mStateLock);
3363 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3364 bool useReadPixels = this->useReadPixels && !flinger->mGpuToCpuSupported;
3365 result = flinger->captureScreenImplLocked(hw, producer,
3366 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3367 useIdentityTransform, rotation, useReadPixels);
3368 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3373 // make sure to process transactions before screenshots -- a transaction
3374 // might already be pending but scheduled for VSYNC; this guarantees we
3375 // will handle it before the screenshot. When VSYNC finally arrives
3376 // the scheduled transaction will be a no-op. If no transactions are
3377 // scheduled at this time, this will end-up being a no-op as well.
3378 mEventQueue.invalidateTransactionNow();
3380 // this creates a "fake" BBinder which will serve as a "fake" remote
3381 // binder to receive the marshaled calls and forward them to the
3382 // real remote (a BpGraphicBufferProducer)
3383 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3385 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3386 // which does the marshaling work forwards to our "fake remote" above.
3387 sp<MessageBase> msg = new MessageCaptureScreen(this,
3388 display, IGraphicBufferProducer::asInterface( wrapper ),
3389 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3390 useIdentityTransform, rotationFlags, useReadPixels);
3392 status_t res = postMessageAsync(msg);
3393 if (res == NO_ERROR) {
3394 res = wrapper->waitForResponse();
3400 void SurfaceFlinger::renderScreenImplLocked(
3401 const sp<const DisplayDevice>& hw,
3402 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3403 uint32_t minLayerZ, uint32_t maxLayerZ,
3404 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3407 RenderEngine& engine(getRenderEngine());
3409 // get screen geometry
3410 const int32_t hw_w = hw->getWidth();
3411 const int32_t hw_h = hw->getHeight();
3412 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3413 static_cast<int32_t>(reqHeight) != hw_h;
3415 // if a default or invalid sourceCrop is passed in, set reasonable values
3416 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3417 !sourceCrop.isValid()) {
3418 sourceCrop.setLeftTop(Point(0, 0));
3419 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3422 // ensure that sourceCrop is inside screen
3423 if (sourceCrop.left < 0) {
3424 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3426 if (sourceCrop.right > hw_w) {
3427 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3429 if (sourceCrop.top < 0) {
3430 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3432 if (sourceCrop.bottom > hw_h) {
3433 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3436 // make sure to clear all GL error flags
3437 engine.checkErrors();
3439 if (DisplayDevice::DISPLAY_PRIMARY == hw->getDisplayType() &&
3440 hw->isPanelInverseMounted()) {
3441 rotation = (Transform::orientation_flags)
3442 (rotation ^ Transform::ROT_180);
3445 // set-up our viewport
3446 engine.setViewportAndProjection(
3447 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3448 engine.disableTexturing();
3450 // redraw the screen entirely...
3451 engine.clearWithColor(0, 0, 0, 1);
3453 const LayerVector& layers( mDrawingState.layersSortedByZ );
3454 const size_t count = layers.size();
3455 for (size_t i=0 ; i<count ; ++i) {
3456 const sp<Layer>& layer(layers[i]);
3457 const Layer::State& state(layer->getDrawingState());
3458 if (state.layerStack == hw->getLayerStack()) {
3459 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3460 if (canDrawLayerinScreenShot(hw,layer)) {
3461 if (filtering) layer->setFiltering(true);
3462 layer->draw(hw, useIdentityTransform);
3463 if (filtering) layer->setFiltering(false);
3469 // compositionComplete is needed for older driver
3470 hw->compositionComplete();
3471 hw->setViewportAndProjection();
3475 status_t SurfaceFlinger::captureScreenImplLocked(
3476 const sp<const DisplayDevice>& hw,
3477 const sp<IGraphicBufferProducer>& producer,
3478 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3479 uint32_t minLayerZ, uint32_t maxLayerZ,
3480 bool useIdentityTransform, Transform::orientation_flags rotation,
3485 // get screen geometry
3486 uint32_t hw_w = hw->getWidth();
3487 uint32_t hw_h = hw->getHeight();
3489 if (rotation & Transform::ROT_90) {
3490 std::swap(hw_w, hw_h);
3493 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3494 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3495 reqWidth, reqHeight, hw_w, hw_h);
3499 ++mActiveFrameSequence;
3501 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3502 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3504 // create a surface (because we're a producer, and we need to
3505 // dequeue/queue a buffer)
3506 sp<Surface> sur = new Surface(producer, false);
3507 ANativeWindow* window = sur.get();
3509 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3510 if (result == NO_ERROR) {
3511 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3512 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3515 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3516 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3517 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3518 err |= native_window_set_usage(window, usage);
3520 if (err == NO_ERROR) {
3521 ANativeWindowBuffer* buffer;
3522 /* TODO: Once we have the sync framework everywhere this can use
3523 * server-side waits on the fence that dequeueBuffer returns.
3525 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3526 if (result == NO_ERROR) {
3528 // create an EGLImage from the buffer so we can later
3529 // turn it into a texture
3530 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3531 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3532 if (image != EGL_NO_IMAGE_KHR) {
3533 // this binds the given EGLImage as a framebuffer for the
3534 // duration of this scope.
3535 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image,
3536 useReadPixels, reqWidth, reqHeight);
3537 if (imageBond.getStatus() == NO_ERROR) {
3538 // this will in fact render into our dequeued buffer
3539 // via an FBO, which means we didn't have to create
3540 // an EGLSurface and therefore we're not
3541 // dependent on the context's EGLConfig.
3542 renderScreenImplLocked(
3543 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3544 useIdentityTransform, rotation);
3546 // Attempt to create a sync khr object that can produce a sync point. If that
3547 // isn't available, create a non-dupable sync object in the fallback path and
3548 // wait on it directly.
3550 if (!DEBUG_SCREENSHOTS) {
3551 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3552 // native fence fd will not be populated until flush() is done.
3553 getRenderEngine().flush();
3555 sync = EGL_NO_SYNC_KHR;
3557 if (sync != EGL_NO_SYNC_KHR) {
3559 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3560 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3561 ALOGW("captureScreen: failed to dup sync khr object");
3564 eglDestroySyncKHR(mEGLDisplay, sync);
3567 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3568 if (sync != EGL_NO_SYNC_KHR) {
3569 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3570 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3571 EGLint eglErr = eglGetError();
3572 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3573 ALOGW("captureScreen: fence wait timed out");
3575 ALOGW_IF(eglErr != EGL_SUCCESS,
3576 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3578 eglDestroySyncKHR(mEGLDisplay, sync);
3580 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3583 if (useReadPixels) {
3584 sp<GraphicBuffer> buf = static_cast<GraphicBuffer*>(buffer);
3586 if (buf->lock(GRALLOC_USAGE_SW_WRITE_OFTEN, &vaddr) == NO_ERROR) {
3587 getRenderEngine().readPixels(0, 0, buffer->stride, reqHeight,
3592 if (DEBUG_SCREENSHOTS) {
3593 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3594 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3595 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3596 hw, minLayerZ, maxLayerZ);
3601 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3602 result = INVALID_OPERATION;
3604 // destroy our image
3605 eglDestroyImageKHR(mEGLDisplay, image);
3609 // queueBuffer takes ownership of syncFd
3610 result = window->queueBuffer(window, buffer, syncFd);
3615 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3621 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3622 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3623 if (DEBUG_SCREENSHOTS) {
3624 for (size_t y=0 ; y<h ; y++) {
3625 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3626 for (size_t x=0 ; x<w ; x++) {
3627 if (p[x] != 0xFF000000) return;
3630 ALOGE("*** we just took a black screenshot ***\n"
3631 "requested minz=%d, maxz=%d, layerStack=%d",
3632 minLayerZ, maxLayerZ, hw->getLayerStack());
3633 const LayerVector& layers( mDrawingState.layersSortedByZ );
3634 const size_t count = layers.size();
3635 for (size_t i=0 ; i<count ; ++i) {
3636 const sp<Layer>& layer(layers[i]);
3637 const Layer::State& state(layer->getDrawingState());
3638 const bool visible = (state.layerStack == hw->getLayerStack())
3639 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3640 && (layer->isVisible());
3641 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3642 visible ? '+' : '-',
3643 i, layer->getName().string(), state.layerStack, state.z,
3644 layer->isVisible(), state.flags, state.alpha);
3649 /* ------------------------------------------------------------------------
3653 bool SurfaceFlinger::updateLayerVisibleNonTransparentRegion(const int& /*dpy*/,
3654 const sp<Layer>& layer, bool& /*bIgnoreLayers*/, int& /*indexLOI*/,
3655 uint32_t layerStack, const int& /*i*/) {
3657 const Layer::State& s(layer->getDrawingState());
3659 // only consider the layers on the given layer stack
3660 if (s.layerStack != layerStack) {
3661 /* set the visible region as empty since we have removed the
3662 * layerstack check in rebuildLayerStack() function
3664 Region visibleNonTransRegion;
3665 visibleNonTransRegion.set(Rect(0,0));
3666 layer->setVisibleNonTransparentRegion(visibleNonTransRegion);
3674 bool SurfaceFlinger::canDrawLayerinScreenShot(
3675 const sp<const DisplayDevice>& /*hw*/,
3676 const sp<Layer>& layer) {
3677 return layer->isVisible();
3680 void SurfaceFlinger::drawWormHoleIfRequired(HWComposer::LayerListIterator& /*cur*/,
3681 const HWComposer::LayerListIterator& /*end*/,
3682 const sp<const DisplayDevice>& hw,
3683 const Region& region) {
3684 drawWormhole(hw, region);
3687 // ---------------------------------------------------------------------------
3689 SurfaceFlinger::LayerVector::LayerVector() {
3692 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3693 : SortedVector<sp<Layer> >(rhs) {
3696 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3697 const void* rhs) const
3699 // sort layers per layer-stack, then by z-order and finally by sequence
3700 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3701 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3703 uint32_t ls = l->getCurrentState().layerStack;
3704 uint32_t rs = r->getCurrentState().layerStack;
3708 uint32_t lz = l->getCurrentState().z;
3709 uint32_t rz = r->getCurrentState().z;
3713 return l->sequence - r->sequence;
3716 // ---------------------------------------------------------------------------
3718 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3719 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3722 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3723 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3724 viewport.makeInvalid();
3725 frame.makeInvalid();
3728 // ---------------------------------------------------------------------------
3730 }; // namespace android
3733 #if defined(__gl_h_)
3734 #error "don't include gl/gl.h in this file"
3737 #if defined(__gl2_h_)
3738 #error "don't include gl2/gl2.h in this file"