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 ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
25 #include <stdatomic.h>
29 #include <cutils/log.h>
30 #include <cutils/properties.h>
32 #include <binder/IPCThreadState.h>
33 #include <binder/IServiceManager.h>
34 #include <binder/MemoryHeapBase.h>
35 #include <binder/PermissionCache.h>
37 #include <ui/DisplayInfo.h>
38 #include <ui/DisplayStatInfo.h>
40 #include <gui/BitTube.h>
41 #include <gui/BufferQueue.h>
42 #include <gui/GuiConfig.h>
43 #include <gui/IDisplayEventConnection.h>
44 #include <gui/Surface.h>
45 #include <gui/GraphicBufferAlloc.h>
47 #include <ui/GraphicBufferAllocator.h>
48 #include <ui/PixelFormat.h>
49 #include <ui/UiConfig.h>
51 #include <utils/misc.h>
52 #include <utils/String8.h>
53 #include <utils/String16.h>
54 #include <utils/StopWatch.h>
55 #include <utils/Trace.h>
57 #include <private/android_filesystem_config.h>
58 #include <private/gui/SyncFeatures.h>
62 #include "Colorizer.h"
63 #include "DdmConnection.h"
64 #include "DisplayDevice.h"
66 #include "EventControlThread.h"
67 #include "EventThread.h"
70 #include "SurfaceFlinger.h"
72 #include "DisplayHardware/FramebufferSurface.h"
73 #include "DisplayHardware/HWComposer.h"
74 #include "DisplayHardware/VirtualDisplaySurface.h"
76 #include "Effects/Daltonizer.h"
78 #include "RenderEngine/RenderEngine.h"
79 #include <cutils/compiler.h>
81 #define DISPLAY_COUNT 1
84 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
87 #define DEBUG_SCREENSHOTS false
89 EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
93 // This is the phase offset in nanoseconds of the software vsync event
94 // relative to the vsync event reported by HWComposer. The software vsync
95 // event is when SurfaceFlinger and Choreographer-based applications run each
98 // This phase offset allows adjustment of the minimum latency from application
99 // wake-up (by Choregographer) time to the time at which the resulting window
100 // image is displayed. This value may be either positive (after the HW vsync)
101 // or negative (before the HW vsync). Setting it to 0 will result in a
102 // minimum latency of two vsync periods because the app and SurfaceFlinger
103 // will run just after the HW vsync. Setting it to a positive number will
104 // result in the minimum latency being:
106 // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
108 // Note that reducing this latency makes it more likely for the applications
109 // to not have their window content image ready in time. When this happens
110 // the latency will end up being an additional vsync period, and animations
111 // will hiccup. Therefore, this latency should be tuned somewhat
112 // conservatively (or at least with awareness of the trade-off being made).
113 static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
115 // This is the phase offset at which SurfaceFlinger's composition runs.
116 static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
118 // ---------------------------------------------------------------------------
120 const String16 sHardwareTest("android.permission.HARDWARE_TEST");
121 const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
122 const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
123 const String16 sDump("android.permission.DUMP");
125 // ---------------------------------------------------------------------------
127 SurfaceFlinger::SurfaceFlinger()
128 : BnSurfaceComposer(),
129 mTransactionFlags(0),
130 mTransactionPending(false),
131 mAnimTransactionPending(false),
132 mLayersRemoved(false),
133 mRepaintEverything(0),
135 mBootTime(systemTime()),
136 mVisibleRegionsDirty(false),
137 mHwWorkListDirty(false),
138 mAnimCompositionPending(false),
142 mDebugDisableTransformHint(0),
143 mDebugInSwapBuffers(0),
144 mLastSwapBufferTime(0),
145 mDebugInTransaction(0),
146 mLastTransactionTime(0),
147 mBootFinished(false),
148 mPrimaryHWVsyncEnabled(false),
149 mHWVsyncAvailable(false),
151 mHasColorMatrix(false)
153 ALOGI("SurfaceFlinger is starting");
155 // debugging stuff...
156 char value[PROPERTY_VALUE_MAX];
158 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
159 mGpuToCpuSupported = !atoi(value);
161 property_get("debug.sf.showupdates", value, "0");
162 mDebugRegion = atoi(value);
164 property_get("debug.sf.ddms", value, "0");
165 mDebugDDMS = atoi(value);
167 if (!startDdmConnection()) {
168 // start failed, and DDMS debugging not enabled
172 ALOGI_IF(mDebugRegion, "showupdates enabled");
173 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
176 void SurfaceFlinger::onFirstRef()
178 mEventQueue.init(this);
181 SurfaceFlinger::~SurfaceFlinger()
183 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
184 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
185 eglTerminate(display);
188 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
190 // the window manager died on us. prepare its eulogy.
192 // restore initial conditions (default device unblank, etc)
193 initializeDisplays();
195 // restart the boot-animation
199 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
201 sp<ISurfaceComposerClient> bclient;
202 sp<Client> client(new Client(this));
203 status_t err = client->initCheck();
204 if (err == NO_ERROR) {
210 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
213 class DisplayToken : public BBinder {
214 sp<SurfaceFlinger> flinger;
215 virtual ~DisplayToken() {
216 // no more references, this display must be terminated
217 Mutex::Autolock _l(flinger->mStateLock);
218 flinger->mCurrentState.displays.removeItem(this);
219 flinger->setTransactionFlags(eDisplayTransactionNeeded);
222 DisplayToken(const sp<SurfaceFlinger>& flinger)
227 sp<BBinder> token = new DisplayToken(this);
229 Mutex::Autolock _l(mStateLock);
230 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
231 info.displayName = displayName;
232 info.isSecure = secure;
233 mCurrentState.displays.add(token, info);
238 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
239 Mutex::Autolock _l(mStateLock);
241 ssize_t idx = mCurrentState.displays.indexOfKey(display);
243 ALOGW("destroyDisplay: invalid display token");
247 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
248 if (!info.isVirtualDisplay()) {
249 ALOGE("destroyDisplay called for non-virtual display");
253 mCurrentState.displays.removeItemsAt(idx);
254 setTransactionFlags(eDisplayTransactionNeeded);
257 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
258 ALOGW_IF(mBuiltinDisplays[type],
259 "Overwriting display token for display type %d", type);
260 mBuiltinDisplays[type] = new BBinder();
261 DisplayDeviceState info(type);
262 // All non-virtual displays are currently considered secure.
263 info.isSecure = true;
264 mCurrentState.displays.add(mBuiltinDisplays[type], info);
267 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
268 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
269 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
272 return mBuiltinDisplays[id];
275 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
277 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
281 void SurfaceFlinger::bootFinished()
283 const nsecs_t now = systemTime();
284 const nsecs_t duration = now - mBootTime;
285 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
286 mBootFinished = true;
288 // wait patiently for the window manager death
289 const String16 name("window");
290 sp<IBinder> window(defaultServiceManager()->getService(name));
292 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
295 // stop boot animation
296 // formerly we would just kill the process, but we now ask it to exit so it
297 // can choose where to stop the animation.
298 property_set("service.bootanim.exit", "1");
301 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
302 class MessageDestroyGLTexture : public MessageBase {
303 RenderEngine& engine;
306 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
307 : engine(engine), texture(texture) {
309 virtual bool handler() {
310 engine.deleteTextures(1, &texture);
314 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
317 class DispSyncSource : public VSyncSource, private DispSync::Callback {
319 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
322 mPhaseOffset(phaseOffset),
323 mTraceVsync(traceVsync),
324 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
325 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
326 mDispSync(dispSync) {}
328 virtual ~DispSyncSource() {}
330 virtual void setVSyncEnabled(bool enable) {
331 // Do NOT lock the mutex here so as to avoid any mutex ordering issues
332 // with locking it in the onDispSyncEvent callback.
334 status_t err = mDispSync->addEventListener(mPhaseOffset,
335 static_cast<DispSync::Callback*>(this));
336 if (err != NO_ERROR) {
337 ALOGE("error registering vsync callback: %s (%d)",
338 strerror(-err), err);
340 //ATRACE_INT(mVsyncOnLabel.string(), 1);
342 status_t err = mDispSync->removeEventListener(
343 static_cast<DispSync::Callback*>(this));
344 if (err != NO_ERROR) {
345 ALOGE("error unregistering vsync callback: %s (%d)",
346 strerror(-err), err);
348 //ATRACE_INT(mVsyncOnLabel.string(), 0);
352 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
353 Mutex::Autolock lock(mMutex);
354 mCallback = callback;
358 virtual void onDispSyncEvent(nsecs_t when) {
359 sp<VSyncSource::Callback> callback;
361 Mutex::Autolock lock(mMutex);
362 callback = mCallback;
365 mValue = (mValue + 1) % 2;
366 ATRACE_INT(mVsyncEventLabel.string(), mValue);
370 if (callback != NULL) {
371 callback->onVSyncEvent(when);
377 const nsecs_t mPhaseOffset;
378 const bool mTraceVsync;
379 const String8 mVsyncOnLabel;
380 const String8 mVsyncEventLabel;
383 sp<VSyncSource::Callback> mCallback;
387 void SurfaceFlinger::init() {
388 ALOGI( "SurfaceFlinger's main thread ready to run. "
389 "Initializing graphics H/W...");
392 Mutex::Autolock _l(mStateLock);
394 // initialize EGL for the default display
395 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
396 eglInitialize(mEGLDisplay, NULL, NULL);
398 // Initialize the H/W composer object. There may or may not be an
399 // actual hardware composer underneath.
400 mHwc = new HWComposer(this,
401 *static_cast<HWComposer::EventHandler *>(this));
403 // get a RenderEngine for the given display / config (can't fail)
404 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
406 // retrieve the EGL context that was selected/created
407 mEGLContext = mRenderEngine->getEGLContext();
409 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
410 "couldn't create EGLContext");
412 // initialize our non-virtual displays
413 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
414 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
415 // set-up the displays that are already connected
416 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
417 // All non-virtual displays are currently considered secure.
418 bool isSecure = true;
419 createBuiltinDisplayLocked(type);
420 wp<IBinder> token = mBuiltinDisplays[i];
422 sp<IGraphicBufferProducer> producer;
423 sp<IGraphicBufferConsumer> consumer;
424 BufferQueue::createBufferQueue(&producer, &consumer,
425 new GraphicBufferAlloc());
427 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
429 int32_t hwcId = allocateHwcDisplayId(type);
430 sp<DisplayDevice> hw = new DisplayDevice(this,
431 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
433 mRenderEngine->getEGLConfig());
434 if (i > DisplayDevice::DISPLAY_PRIMARY) {
435 // FIXME: currently we don't get blank/unblank requests
436 // for displays other than the main display, so we always
437 // assume a connected display is unblanked.
438 ALOGD("marking display %zu as acquired/unblanked", i);
439 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
441 mDisplays.add(token, hw);
445 // make the GLContext current so that we can create textures when creating Layers
446 // (which may happens before we render something)
447 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
449 // start the EventThread
450 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
451 vsyncPhaseOffsetNs, true, "app");
452 mEventThread = new EventThread(vsyncSrc);
453 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
454 sfVsyncPhaseOffsetNs, true, "sf");
455 mSFEventThread = new EventThread(sfVsyncSrc);
456 mEventQueue.setEventThread(mSFEventThread);
458 mEventControlThread = new EventControlThread(this);
459 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
461 // set a fake vsync period if there is no HWComposer
462 if (mHwc->initCheck() != NO_ERROR) {
463 mPrimaryDispSync.setPeriod(16666667);
466 // initialize our drawing state
467 mDrawingState = mCurrentState;
469 // set initial conditions (e.g. unblank default device)
470 initializeDisplays();
472 // start boot animation
476 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
477 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
478 type : mHwc->allocateDisplayId();
481 void SurfaceFlinger::startBootAnim() {
482 // start boot animation
483 property_set("service.bootanim.exit", "0");
484 property_set("ctl.start", "bootanim");
487 size_t SurfaceFlinger::getMaxTextureSize() const {
488 return mRenderEngine->getMaxTextureSize();
491 size_t SurfaceFlinger::getMaxViewportDims() const {
492 return mRenderEngine->getMaxViewportDims();
495 // ----------------------------------------------------------------------------
497 bool SurfaceFlinger::authenticateSurfaceTexture(
498 const sp<IGraphicBufferProducer>& bufferProducer) const {
499 Mutex::Autolock _l(mStateLock);
500 sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
501 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
504 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
505 Vector<DisplayInfo>* configs) {
506 if (configs == NULL) {
511 return NAME_NOT_FOUND;
513 int32_t type = NAME_NOT_FOUND;
514 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
515 if (display == mBuiltinDisplays[i]) {
525 // TODO: Not sure if display density should handled by SF any longer
527 static int getDensityFromProperty(char const* propName) {
528 char property[PROPERTY_VALUE_MAX];
530 if (property_get(propName, property, NULL) > 0) {
531 density = atoi(property);
536 static int getEmuDensity() {
537 return getDensityFromProperty("qemu.sf.lcd_density"); }
538 static int getBuildDensity() {
539 return getDensityFromProperty("ro.sf.lcd_density"); }
544 const Vector<HWComposer::DisplayConfig>& hwConfigs =
545 getHwComposer().getConfigs(type);
546 for (size_t c = 0; c < hwConfigs.size(); ++c) {
547 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
548 DisplayInfo info = DisplayInfo();
550 float xdpi = hwConfig.xdpi;
551 float ydpi = hwConfig.ydpi;
553 if (type == DisplayDevice::DISPLAY_PRIMARY) {
554 // The density of the device is provided by a build property
555 float density = Density::getBuildDensity() / 160.0f;
557 // the build doesn't provide a density -- this is wrong!
559 ALOGE("ro.sf.lcd_density must be defined as a build property");
560 density = xdpi / 160.0f;
562 if (Density::getEmuDensity()) {
563 // if "qemu.sf.lcd_density" is specified, it overrides everything
564 xdpi = ydpi = density = Density::getEmuDensity();
567 info.density = density;
569 // TODO: this needs to go away (currently needed only by webkit)
570 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
571 info.orientation = hw->getOrientation();
573 // TODO: where should this value come from?
574 static const int TV_DENSITY = 213;
575 info.density = TV_DENSITY / 160.0f;
576 info.orientation = 0;
579 info.w = hwConfig.width;
580 info.h = hwConfig.height;
583 info.fps = float(1e9 / hwConfig.refresh);
584 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
586 // This is how far in advance a buffer must be queued for
587 // presentation at a given time. If you want a buffer to appear
588 // on the screen at time N, you must submit the buffer before
589 // (N - presentationDeadline).
591 // Normally it's one full refresh period (to give SF a chance to
592 // latch the buffer), but this can be reduced by configuring a
593 // DispSync offset. Any additional delays introduced by the hardware
594 // composer or panel must be accounted for here.
596 // We add an additional 1ms to allow for processing time and
597 // differences between the ideal and actual refresh rate.
598 info.presentationDeadline =
599 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
601 // All non-virtual displays are currently considered secure.
604 configs->push_back(info);
610 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& display,
611 DisplayStatInfo* stats) {
616 // FIXME for now we always return stats for the primary display
617 memset(stats, 0, sizeof(*stats));
618 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
619 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
623 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
624 return getDisplayDevice(display)->getActiveConfig();
627 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
628 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
630 int32_t type = hw->getDisplayType();
631 int currentMode = hw->getActiveConfig();
633 if (mode == currentMode) {
634 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
638 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
639 ALOGW("Trying to set config for virtual display");
643 hw->setActiveConfig(mode);
644 getHwComposer().setActiveConfig(type, mode);
647 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
648 class MessageSetActiveConfig: public MessageBase {
649 SurfaceFlinger& mFlinger;
650 sp<IBinder> mDisplay;
653 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
655 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
656 virtual bool handler() {
657 Vector<DisplayInfo> configs;
658 mFlinger.getDisplayConfigs(mDisplay, &configs);
659 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
660 ALOGE("Attempt to set active config = %d for display with %zu configs",
661 mMode, configs.size());
663 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
665 ALOGE("Attempt to set active config = %d for null display %p",
666 mMode, mDisplay.get());
667 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
668 ALOGW("Attempt to set active config = %d for virtual display",
671 mFlinger.setActiveConfigInternal(hw, mMode);
676 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
677 postMessageSync(msg);
681 status_t SurfaceFlinger::clearAnimationFrameStats() {
682 Mutex::Autolock _l(mStateLock);
683 mAnimFrameTracker.clearStats();
687 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
688 Mutex::Autolock _l(mStateLock);
689 mAnimFrameTracker.getStats(outStats);
693 // ----------------------------------------------------------------------------
695 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
696 return mEventThread->createEventConnection();
699 // ----------------------------------------------------------------------------
701 void SurfaceFlinger::waitForEvent() {
702 mEventQueue.waitMessage();
705 void SurfaceFlinger::signalTransaction() {
706 mEventQueue.invalidate();
709 void SurfaceFlinger::signalLayerUpdate() {
710 mEventQueue.invalidate();
713 void SurfaceFlinger::signalRefresh() {
714 mEventQueue.refresh();
717 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
718 nsecs_t reltime, uint32_t /* flags */) {
719 return mEventQueue.postMessage(msg, reltime);
722 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
723 nsecs_t reltime, uint32_t /* flags */) {
724 status_t res = mEventQueue.postMessage(msg, reltime);
725 if (res == NO_ERROR) {
731 void SurfaceFlinger::run() {
737 void SurfaceFlinger::enableHardwareVsync() {
738 Mutex::Autolock _l(mHWVsyncLock);
739 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
740 mPrimaryDispSync.beginResync();
741 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
742 mEventControlThread->setVsyncEnabled(true);
743 mPrimaryHWVsyncEnabled = true;
747 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
748 Mutex::Autolock _l(mHWVsyncLock);
751 mHWVsyncAvailable = true;
752 } else if (!mHWVsyncAvailable) {
753 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
757 const nsecs_t period =
758 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
760 mPrimaryDispSync.reset();
761 mPrimaryDispSync.setPeriod(period);
763 if (!mPrimaryHWVsyncEnabled) {
764 mPrimaryDispSync.beginResync();
765 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
766 mEventControlThread->setVsyncEnabled(true);
767 mPrimaryHWVsyncEnabled = true;
771 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
772 Mutex::Autolock _l(mHWVsyncLock);
773 if (mPrimaryHWVsyncEnabled) {
774 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
775 mEventControlThread->setVsyncEnabled(false);
776 mPrimaryDispSync.endResync();
777 mPrimaryHWVsyncEnabled = false;
779 if (makeUnavailable) {
780 mHWVsyncAvailable = false;
784 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
785 bool needsHwVsync = false;
787 { // Scope for the lock
788 Mutex::Autolock _l(mHWVsyncLock);
789 if (type == 0 && mPrimaryHWVsyncEnabled) {
790 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
795 enableHardwareVsync();
797 disableHardwareVsync(false);
801 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
802 if (mEventThread == NULL) {
803 // This is a temporary workaround for b/7145521. A non-null pointer
804 // does not mean EventThread has finished initializing, so this
805 // is not a correct fix.
806 ALOGW("WARNING: EventThread not started, ignoring hotplug");
810 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
811 Mutex::Autolock _l(mStateLock);
813 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
815 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
816 mBuiltinDisplays[type].clear();
818 setTransactionFlags(eDisplayTransactionNeeded);
820 // Defer EventThread notification until SF has updated mDisplays.
824 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
826 getHwComposer().eventControl(disp, event, enabled);
829 void SurfaceFlinger::onMessageReceived(int32_t what) {
832 case MessageQueue::TRANSACTION: {
833 handleMessageTransaction();
836 case MessageQueue::INVALIDATE: {
837 bool refreshNeeded = handleMessageTransaction();
838 refreshNeeded |= handleMessageInvalidate();
839 refreshNeeded |= mRepaintEverything;
841 // Signal a refresh if a transaction modified the window state,
842 // a new buffer was latched, or if HWC has requested a full
848 case MessageQueue::REFRESH: {
849 handleMessageRefresh();
855 bool SurfaceFlinger::handleMessageTransaction() {
856 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
857 if (transactionFlags) {
858 handleTransaction(transactionFlags);
864 bool SurfaceFlinger::handleMessageInvalidate() {
866 return handlePageFlip();
869 void SurfaceFlinger::handleMessageRefresh() {
872 rebuildLayerStacks();
874 doDebugFlashRegions();
879 void SurfaceFlinger::doDebugFlashRegions()
881 // is debugging enabled
882 if (CC_LIKELY(!mDebugRegion))
885 const bool repaintEverything = mRepaintEverything;
886 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
887 const sp<DisplayDevice>& hw(mDisplays[dpy]);
888 if (hw->isDisplayOn()) {
889 // transform the dirty region into this screen's coordinate space
890 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
891 if (!dirtyRegion.isEmpty()) {
892 // redraw the whole screen
893 doComposeSurfaces(hw, Region(hw->bounds()));
895 // and draw the dirty region
896 const int32_t height = hw->getHeight();
897 RenderEngine& engine(getRenderEngine());
898 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
900 hw->compositionComplete();
901 hw->swapBuffers(getHwComposer());
908 if (mDebugRegion > 1) {
909 usleep(mDebugRegion * 1000);
912 HWComposer& hwc(getHwComposer());
913 if (hwc.initCheck() == NO_ERROR) {
914 status_t err = hwc.prepare();
915 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
919 void SurfaceFlinger::preComposition()
921 bool needExtraInvalidate = false;
922 const LayerVector& layers(mDrawingState.layersSortedByZ);
923 const size_t count = layers.size();
924 for (size_t i=0 ; i<count ; i++) {
925 if (layers[i]->onPreComposition()) {
926 needExtraInvalidate = true;
929 if (needExtraInvalidate) {
934 void SurfaceFlinger::postComposition()
936 const LayerVector& layers(mDrawingState.layersSortedByZ);
937 const size_t count = layers.size();
938 for (size_t i=0 ; i<count ; i++) {
939 layers[i]->onPostComposition();
942 const HWComposer& hwc = getHwComposer();
943 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
945 if (presentFence->isValid()) {
946 if (mPrimaryDispSync.addPresentFence(presentFence)) {
947 enableHardwareVsync();
949 disableHardwareVsync(false);
953 if (kIgnorePresentFences) {
954 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
955 if (hw->isDisplayOn()) {
956 enableHardwareVsync();
960 if (mAnimCompositionPending) {
961 mAnimCompositionPending = false;
963 if (presentFence->isValid()) {
964 mAnimFrameTracker.setActualPresentFence(presentFence);
966 // The HWC doesn't support present fences, so use the refresh
967 // timestamp instead.
968 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
969 mAnimFrameTracker.setActualPresentTime(presentTime);
971 mAnimFrameTracker.advanceFrame();
975 void SurfaceFlinger::rebuildLayerStacks() {
976 // rebuild the visible layer list per screen
977 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
979 mVisibleRegionsDirty = false;
980 invalidateHwcGeometry();
982 const LayerVector& layers(mDrawingState.layersSortedByZ);
983 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
986 Vector< sp<Layer> > layersSortedByZ;
987 const sp<DisplayDevice>& hw(mDisplays[dpy]);
988 const Transform& tr(hw->getTransform());
989 const Rect bounds(hw->getBounds());
990 if (hw->isDisplayOn()) {
991 SurfaceFlinger::computeVisibleRegions(layers,
992 hw->getLayerStack(), dirtyRegion, opaqueRegion);
994 const size_t count = layers.size();
995 for (size_t i=0 ; i<count ; i++) {
996 const sp<Layer>& layer(layers[i]);
997 const Layer::State& s(layer->getDrawingState());
998 if (s.layerStack == hw->getLayerStack()) {
999 Region drawRegion(tr.transform(
1000 layer->visibleNonTransparentRegion));
1001 drawRegion.andSelf(bounds);
1002 if (!drawRegion.isEmpty()) {
1003 layersSortedByZ.add(layer);
1008 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1009 hw->undefinedRegion.set(bounds);
1010 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1011 hw->dirtyRegion.orSelf(dirtyRegion);
1016 void SurfaceFlinger::setUpHWComposer() {
1017 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1018 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1019 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1020 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1022 // If nothing has changed (!dirty), don't recompose.
1023 // If something changed, but we don't currently have any visible layers,
1024 // and didn't when we last did a composition, then skip it this time.
1025 // The second rule does two things:
1026 // - When all layers are removed from a display, we'll emit one black
1027 // frame, then nothing more until we get new layers.
1028 // - When a display is created with a private layer stack, we won't
1029 // emit any black frames until a layer is added to the layer stack.
1030 bool mustRecompose = dirty && !(empty && wasEmpty);
1032 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1033 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1034 mustRecompose ? "doing" : "skipping",
1037 wasEmpty ? "+" : "-");
1039 mDisplays[dpy]->beginFrame(mustRecompose);
1041 if (mustRecompose) {
1042 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1046 HWComposer& hwc(getHwComposer());
1047 if (hwc.initCheck() == NO_ERROR) {
1048 // build the h/w work list
1049 if (CC_UNLIKELY(mHwWorkListDirty)) {
1050 mHwWorkListDirty = false;
1051 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1052 sp<const DisplayDevice> hw(mDisplays[dpy]);
1053 const int32_t id = hw->getHwcDisplayId();
1055 const Vector< sp<Layer> >& currentLayers(
1056 hw->getVisibleLayersSortedByZ());
1057 const size_t count = currentLayers.size();
1058 if (hwc.createWorkList(id, count) == NO_ERROR) {
1059 HWComposer::LayerListIterator cur = hwc.begin(id);
1060 const HWComposer::LayerListIterator end = hwc.end(id);
1061 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1062 const sp<Layer>& layer(currentLayers[i]);
1063 layer->setGeometry(hw, *cur);
1064 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1073 // set the per-frame data
1074 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1075 sp<const DisplayDevice> hw(mDisplays[dpy]);
1076 const int32_t id = hw->getHwcDisplayId();
1078 const Vector< sp<Layer> >& currentLayers(
1079 hw->getVisibleLayersSortedByZ());
1080 const size_t count = currentLayers.size();
1081 HWComposer::LayerListIterator cur = hwc.begin(id);
1082 const HWComposer::LayerListIterator end = hwc.end(id);
1083 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1085 * update the per-frame h/w composer data for each layer
1086 * and build the transparent region of the FB
1088 const sp<Layer>& layer(currentLayers[i]);
1089 layer->setPerFrameData(hw, *cur);
1094 // If possible, attempt to use the cursor overlay on each display.
1095 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1096 sp<const DisplayDevice> hw(mDisplays[dpy]);
1097 const int32_t id = hw->getHwcDisplayId();
1099 const Vector< sp<Layer> >& currentLayers(
1100 hw->getVisibleLayersSortedByZ());
1101 const size_t count = currentLayers.size();
1102 HWComposer::LayerListIterator cur = hwc.begin(id);
1103 const HWComposer::LayerListIterator end = hwc.end(id);
1104 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1105 const sp<Layer>& layer(currentLayers[i]);
1106 if (layer->isPotentialCursor()) {
1107 cur->setIsCursorLayerHint();
1114 status_t err = hwc.prepare();
1115 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1117 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1118 sp<const DisplayDevice> hw(mDisplays[dpy]);
1119 hw->prepareFrame(hwc);
1124 void SurfaceFlinger::doComposition() {
1126 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1127 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1128 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1129 if (hw->isDisplayOn()) {
1130 // transform the dirty region into this screen's coordinate space
1131 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1133 // repaint the framebuffer (if needed)
1134 doDisplayComposition(hw, dirtyRegion);
1136 hw->dirtyRegion.clear();
1137 hw->flip(hw->swapRegion);
1138 hw->swapRegion.clear();
1140 // inform the h/w that we're done compositing
1141 hw->compositionComplete();
1146 void SurfaceFlinger::postFramebuffer()
1150 const nsecs_t now = systemTime();
1151 mDebugInSwapBuffers = now;
1153 HWComposer& hwc(getHwComposer());
1154 if (hwc.initCheck() == NO_ERROR) {
1155 if (!hwc.supportsFramebufferTarget()) {
1157 // "surface must be bound to the calling thread's current context,
1158 // for the current rendering API."
1159 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1164 // make the default display current because the VirtualDisplayDevice code cannot
1165 // deal with dequeueBuffer() being called outside of the composition loop; however
1166 // the code below can call glFlush() which is allowed (and does in some case) call
1168 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1170 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1171 sp<const DisplayDevice> hw(mDisplays[dpy]);
1172 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1173 hw->onSwapBuffersCompleted(hwc);
1174 const size_t count = currentLayers.size();
1175 int32_t id = hw->getHwcDisplayId();
1176 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1177 HWComposer::LayerListIterator cur = hwc.begin(id);
1178 const HWComposer::LayerListIterator end = hwc.end(id);
1179 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1180 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1183 for (size_t i = 0; i < count; i++) {
1184 currentLayers[i]->onLayerDisplayed(hw, NULL);
1189 mLastSwapBufferTime = systemTime() - now;
1190 mDebugInSwapBuffers = 0;
1192 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1193 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1198 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1202 // here we keep a copy of the drawing state (that is the state that's
1203 // going to be overwritten by handleTransactionLocked()) outside of
1204 // mStateLock so that the side-effects of the State assignment
1205 // don't happen with mStateLock held (which can cause deadlocks).
1206 State drawingState(mDrawingState);
1208 Mutex::Autolock _l(mStateLock);
1209 const nsecs_t now = systemTime();
1210 mDebugInTransaction = now;
1212 // Here we're guaranteed that some transaction flags are set
1213 // so we can call handleTransactionLocked() unconditionally.
1214 // We call getTransactionFlags(), which will also clear the flags,
1215 // with mStateLock held to guarantee that mCurrentState won't change
1216 // until the transaction is committed.
1218 transactionFlags = getTransactionFlags(eTransactionMask);
1219 handleTransactionLocked(transactionFlags);
1221 mLastTransactionTime = systemTime() - now;
1222 mDebugInTransaction = 0;
1223 invalidateHwcGeometry();
1224 // here the transaction has been committed
1227 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1229 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1230 const size_t count = currentLayers.size();
1233 * Traversal of the children
1234 * (perform the transaction for each of them if needed)
1237 if (transactionFlags & eTraversalNeeded) {
1238 for (size_t i=0 ; i<count ; i++) {
1239 const sp<Layer>& layer(currentLayers[i]);
1240 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1241 if (!trFlags) continue;
1243 const uint32_t flags = layer->doTransaction(0);
1244 if (flags & Layer::eVisibleRegion)
1245 mVisibleRegionsDirty = true;
1250 * Perform display own transactions if needed
1253 if (transactionFlags & eDisplayTransactionNeeded) {
1254 // here we take advantage of Vector's copy-on-write semantics to
1255 // improve performance by skipping the transaction entirely when
1256 // know that the lists are identical
1257 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1258 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1259 if (!curr.isIdenticalTo(draw)) {
1260 mVisibleRegionsDirty = true;
1261 const size_t cc = curr.size();
1262 size_t dc = draw.size();
1264 // find the displays that were removed
1265 // (ie: in drawing state but not in current state)
1266 // also handle displays that changed
1267 // (ie: displays that are in both lists)
1268 for (size_t i=0 ; i<dc ; i++) {
1269 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1271 // in drawing state but not in current state
1272 if (!draw[i].isMainDisplay()) {
1273 // Call makeCurrent() on the primary display so we can
1274 // be sure that nothing associated with this display
1276 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1277 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1278 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1280 hw->disconnect(getHwComposer());
1281 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1282 mEventThread->onHotplugReceived(draw[i].type, false);
1283 mDisplays.removeItem(draw.keyAt(i));
1285 ALOGW("trying to remove the main display");
1288 // this display is in both lists. see if something changed.
1289 const DisplayDeviceState& state(curr[j]);
1290 const wp<IBinder>& display(curr.keyAt(j));
1291 if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1292 // changing the surface is like destroying and
1293 // recreating the DisplayDevice, so we just remove it
1294 // from the drawing state, so that it get re-added
1296 sp<DisplayDevice> hw(getDisplayDevice(display));
1298 hw->disconnect(getHwComposer());
1299 mDisplays.removeItem(display);
1300 mDrawingState.displays.removeItemsAt(i);
1302 // at this point we must loop to the next item
1306 const sp<DisplayDevice> disp(getDisplayDevice(display));
1308 if (state.layerStack != draw[i].layerStack) {
1309 disp->setLayerStack(state.layerStack);
1311 if ((state.orientation != draw[i].orientation)
1312 || (state.viewport != draw[i].viewport)
1313 || (state.frame != draw[i].frame))
1315 disp->setProjection(state.orientation,
1316 state.viewport, state.frame);
1318 if (state.width != draw[i].width || state.height != draw[i].height) {
1319 disp->setDisplaySize(state.width, state.height);
1325 // find displays that were added
1326 // (ie: in current state but not in drawing state)
1327 for (size_t i=0 ; i<cc ; i++) {
1328 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1329 const DisplayDeviceState& state(curr[i]);
1331 sp<DisplaySurface> dispSurface;
1332 sp<IGraphicBufferProducer> producer;
1333 sp<IGraphicBufferProducer> bqProducer;
1334 sp<IGraphicBufferConsumer> bqConsumer;
1335 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1336 new GraphicBufferAlloc());
1338 int32_t hwcDisplayId = -1;
1339 if (state.isVirtualDisplay()) {
1340 // Virtual displays without a surface are dormant:
1341 // they have external state (layer stack, projection,
1342 // etc.) but no internal state (i.e. a DisplayDevice).
1343 if (state.surface != NULL) {
1346 int status = state.surface->query(
1347 NATIVE_WINDOW_WIDTH, &width);
1348 ALOGE_IF(status != NO_ERROR,
1349 "Unable to query width (%d)", status);
1351 status = state.surface->query(
1352 NATIVE_WINDOW_HEIGHT, &height);
1353 ALOGE_IF(status != NO_ERROR,
1354 "Unable to query height (%d)", status);
1355 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1356 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1357 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1358 hwcDisplayId = allocateHwcDisplayId(state.type);
1361 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1362 *mHwc, hwcDisplayId, state.surface,
1363 bqProducer, bqConsumer, state.displayName);
1369 ALOGE_IF(state.surface!=NULL,
1370 "adding a supported display, but rendering "
1371 "surface is provided (%p), ignoring it",
1372 state.surface.get());
1373 hwcDisplayId = allocateHwcDisplayId(state.type);
1374 // for supported (by hwc) displays we provide our
1375 // own rendering surface
1376 dispSurface = new FramebufferSurface(*mHwc, state.type,
1378 producer = bqProducer;
1381 const wp<IBinder>& display(curr.keyAt(i));
1382 if (dispSurface != NULL) {
1383 sp<DisplayDevice> hw = new DisplayDevice(this,
1384 state.type, hwcDisplayId,
1385 mHwc->getFormat(hwcDisplayId), state.isSecure,
1386 display, dispSurface, producer,
1387 mRenderEngine->getEGLConfig());
1388 hw->setLayerStack(state.layerStack);
1389 hw->setProjection(state.orientation,
1390 state.viewport, state.frame);
1391 hw->setDisplayName(state.displayName);
1392 mDisplays.add(display, hw);
1393 if (state.isVirtualDisplay()) {
1394 if (hwcDisplayId >= 0) {
1395 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1396 hw->getWidth(), hw->getHeight(),
1400 mEventThread->onHotplugReceived(state.type, true);
1408 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1409 // The transform hint might have changed for some layers
1410 // (either because a display has changed, or because a layer
1413 // Walk through all the layers in currentLayers,
1414 // and update their transform hint.
1416 // If a layer is visible only on a single display, then that
1417 // display is used to calculate the hint, otherwise we use the
1420 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1421 // the hint is set before we acquire a buffer from the surface texture.
1423 // NOTE: layer transactions have taken place already, so we use their
1424 // drawing state. However, SurfaceFlinger's own transaction has not
1425 // happened yet, so we must use the current state layer list
1426 // (soon to become the drawing state list).
1428 sp<const DisplayDevice> disp;
1429 uint32_t currentlayerStack = 0;
1430 for (size_t i=0; i<count; i++) {
1431 // NOTE: we rely on the fact that layers are sorted by
1432 // layerStack first (so we don't have to traverse the list
1433 // of displays for every layer).
1434 const sp<Layer>& layer(currentLayers[i]);
1435 uint32_t layerStack = layer->getDrawingState().layerStack;
1436 if (i==0 || currentlayerStack != layerStack) {
1437 currentlayerStack = layerStack;
1438 // figure out if this layerstack is mirrored
1439 // (more than one display) if so, pick the default display,
1440 // if not, pick the only display it's on.
1442 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1443 sp<const DisplayDevice> hw(mDisplays[dpy]);
1444 if (hw->getLayerStack() == currentlayerStack) {
1455 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1456 // redraw after transform hint changes. See bug 8508397.
1458 // could be null when this layer is using a layerStack
1459 // that is not visible on any display. Also can occur at
1460 // screen off/on times.
1461 disp = getDefaultDisplayDevice();
1463 layer->updateTransformHint(disp);
1469 * Perform our own transaction if needed
1472 const LayerVector& layers(mDrawingState.layersSortedByZ);
1473 if (currentLayers.size() > layers.size()) {
1474 // layers have been added
1475 mVisibleRegionsDirty = true;
1478 // some layers might have been removed, so
1479 // we need to update the regions they're exposing.
1480 if (mLayersRemoved) {
1481 mLayersRemoved = false;
1482 mVisibleRegionsDirty = true;
1483 const size_t count = layers.size();
1484 for (size_t i=0 ; i<count ; i++) {
1485 const sp<Layer>& layer(layers[i]);
1486 if (currentLayers.indexOf(layer) < 0) {
1487 // this layer is not visible anymore
1488 // TODO: we could traverse the tree from front to back and
1489 // compute the actual visible region
1490 // TODO: we could cache the transformed region
1491 const Layer::State& s(layer->getDrawingState());
1492 Region visibleReg = s.transform.transform(
1493 Region(Rect(s.active.w, s.active.h)));
1494 invalidateLayerStack(s.layerStack, visibleReg);
1499 commitTransaction();
1501 updateCursorAsync();
1504 void SurfaceFlinger::updateCursorAsync()
1506 HWComposer& hwc(getHwComposer());
1507 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1508 sp<const DisplayDevice> hw(mDisplays[dpy]);
1509 const int32_t id = hw->getHwcDisplayId();
1513 const Vector< sp<Layer> >& currentLayers(
1514 hw->getVisibleLayersSortedByZ());
1515 const size_t count = currentLayers.size();
1516 HWComposer::LayerListIterator cur = hwc.begin(id);
1517 const HWComposer::LayerListIterator end = hwc.end(id);
1518 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1519 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1522 const sp<Layer>& layer(currentLayers[i]);
1523 Rect cursorPos = layer->getPosition(hw);
1524 hwc.setCursorPositionAsync(id, cursorPos);
1530 void SurfaceFlinger::commitTransaction()
1532 if (!mLayersPendingRemoval.isEmpty()) {
1533 // Notify removed layers now that they can't be drawn from
1534 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1535 mLayersPendingRemoval[i]->onRemoved();
1537 mLayersPendingRemoval.clear();
1540 // If this transaction is part of a window animation then the next frame
1541 // we composite should be considered an animation as well.
1542 mAnimCompositionPending = mAnimTransactionPending;
1544 mDrawingState = mCurrentState;
1545 mTransactionPending = false;
1546 mAnimTransactionPending = false;
1547 mTransactionCV.broadcast();
1550 void SurfaceFlinger::computeVisibleRegions(
1551 const LayerVector& currentLayers, uint32_t layerStack,
1552 Region& outDirtyRegion, Region& outOpaqueRegion)
1556 Region aboveOpaqueLayers;
1557 Region aboveCoveredLayers;
1560 outDirtyRegion.clear();
1562 size_t i = currentLayers.size();
1564 const sp<Layer>& layer = currentLayers[i];
1566 // start with the whole surface at its current location
1567 const Layer::State& s(layer->getDrawingState());
1569 // only consider the layers on the given layer stack
1570 if (s.layerStack != layerStack)
1574 * opaqueRegion: area of a surface that is fully opaque.
1576 Region opaqueRegion;
1579 * visibleRegion: area of a surface that is visible on screen
1580 * and not fully transparent. This is essentially the layer's
1581 * footprint minus the opaque regions above it.
1582 * Areas covered by a translucent surface are considered visible.
1584 Region visibleRegion;
1587 * coveredRegion: area of a surface that is covered by all
1588 * visible regions above it (which includes the translucent areas).
1590 Region coveredRegion;
1593 * transparentRegion: area of a surface that is hinted to be completely
1594 * transparent. This is only used to tell when the layer has no visible
1595 * non-transparent regions and can be removed from the layer list. It
1596 * does not affect the visibleRegion of this layer or any layers
1597 * beneath it. The hint may not be correct if apps don't respect the
1598 * SurfaceView restrictions (which, sadly, some don't).
1600 Region transparentRegion;
1603 // handle hidden surfaces by setting the visible region to empty
1604 if (CC_LIKELY(layer->isVisible())) {
1605 const bool translucent = !layer->isOpaque(s);
1606 Rect bounds(s.transform.transform(layer->computeBounds()));
1607 visibleRegion.set(bounds);
1608 if (!visibleRegion.isEmpty()) {
1609 // Remove the transparent area from the visible region
1611 const Transform tr(s.transform);
1612 if (tr.transformed()) {
1613 if (tr.preserveRects()) {
1614 // transform the transparent region
1615 transparentRegion = tr.transform(s.activeTransparentRegion);
1617 // transformation too complex, can't do the
1618 // transparent region optimization.
1619 transparentRegion.clear();
1622 transparentRegion = s.activeTransparentRegion;
1626 // compute the opaque region
1627 const int32_t layerOrientation = s.transform.getOrientation();
1628 if (s.alpha==255 && !translucent &&
1629 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1630 // the opaque region is the layer's footprint
1631 opaqueRegion = visibleRegion;
1636 // Clip the covered region to the visible region
1637 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1639 // Update aboveCoveredLayers for next (lower) layer
1640 aboveCoveredLayers.orSelf(visibleRegion);
1642 // subtract the opaque region covered by the layers above us
1643 visibleRegion.subtractSelf(aboveOpaqueLayers);
1645 // compute this layer's dirty region
1646 if (layer->contentDirty) {
1647 // we need to invalidate the whole region
1648 dirty = visibleRegion;
1649 // as well, as the old visible region
1650 dirty.orSelf(layer->visibleRegion);
1651 layer->contentDirty = false;
1653 /* compute the exposed region:
1654 * the exposed region consists of two components:
1655 * 1) what's VISIBLE now and was COVERED before
1656 * 2) what's EXPOSED now less what was EXPOSED before
1658 * note that (1) is conservative, we start with the whole
1659 * visible region but only keep what used to be covered by
1660 * something -- which mean it may have been exposed.
1662 * (2) handles areas that were not covered by anything but got
1663 * exposed because of a resize.
1665 const Region newExposed = visibleRegion - coveredRegion;
1666 const Region oldVisibleRegion = layer->visibleRegion;
1667 const Region oldCoveredRegion = layer->coveredRegion;
1668 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1669 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1671 dirty.subtractSelf(aboveOpaqueLayers);
1673 // accumulate to the screen dirty region
1674 outDirtyRegion.orSelf(dirty);
1676 // Update aboveOpaqueLayers for next (lower) layer
1677 aboveOpaqueLayers.orSelf(opaqueRegion);
1679 // Store the visible region in screen space
1680 layer->setVisibleRegion(visibleRegion);
1681 layer->setCoveredRegion(coveredRegion);
1682 layer->setVisibleNonTransparentRegion(
1683 visibleRegion.subtract(transparentRegion));
1686 outOpaqueRegion = aboveOpaqueLayers;
1689 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1690 const Region& dirty) {
1691 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1692 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1693 if (hw->getLayerStack() == layerStack) {
1694 hw->dirtyRegion.orSelf(dirty);
1699 bool SurfaceFlinger::handlePageFlip()
1703 bool visibleRegions = false;
1704 const LayerVector& layers(mDrawingState.layersSortedByZ);
1705 bool frameQueued = false;
1707 // Store the set of layers that need updates. This set must not change as
1708 // buffers are being latched, as this could result in a deadlock.
1709 // Example: Two producers share the same command stream and:
1710 // 1.) Layer 0 is latched
1711 // 2.) Layer 0 gets a new frame
1712 // 2.) Layer 1 gets a new frame
1713 // 3.) Layer 1 is latched.
1714 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1715 // second frame. But layer 0's second frame could be waiting on display.
1716 Vector<Layer*> layersWithQueuedFrames;
1717 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1718 const sp<Layer>& layer(layers[i]);
1719 if (layer->hasQueuedFrame()) {
1721 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1722 layersWithQueuedFrames.push_back(layer.get());
1726 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1727 Layer* layer = layersWithQueuedFrames[i];
1728 const Region dirty(layer->latchBuffer(visibleRegions));
1729 const Layer::State& s(layer->getDrawingState());
1730 invalidateLayerStack(s.layerStack, dirty);
1733 mVisibleRegionsDirty |= visibleRegions;
1735 // If we will need to wake up at some time in the future to deal with a
1736 // queued frame that shouldn't be displayed during this vsync period, wake
1737 // up during the next vsync period to check again.
1738 if (frameQueued && layersWithQueuedFrames.empty()) {
1739 signalLayerUpdate();
1742 // Only continue with the refresh if there is actually new work to do
1743 return !layersWithQueuedFrames.empty();
1746 void SurfaceFlinger::invalidateHwcGeometry()
1748 mHwWorkListDirty = true;
1752 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1753 const Region& inDirtyRegion)
1755 // We only need to actually compose the display if:
1756 // 1) It is being handled by hardware composer, which may need this to
1757 // keep its virtual display state machine in sync, or
1758 // 2) There is work to be done (the dirty region isn't empty)
1759 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1760 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1764 Region dirtyRegion(inDirtyRegion);
1766 // compute the invalid region
1767 hw->swapRegion.orSelf(dirtyRegion);
1769 uint32_t flags = hw->getFlags();
1770 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1771 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1772 // takes a rectangle, we must make sure to update that whole
1773 // rectangle in that case
1774 dirtyRegion.set(hw->swapRegion.bounds());
1776 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1777 // We need to redraw the rectangle that will be updated
1778 // (pushed to the framebuffer).
1779 // This is needed because PARTIAL_UPDATES only takes one
1780 // rectangle instead of a region (see DisplayDevice::flip())
1781 dirtyRegion.set(hw->swapRegion.bounds());
1783 // we need to redraw everything (the whole screen)
1784 dirtyRegion.set(hw->bounds());
1785 hw->swapRegion = dirtyRegion;
1789 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1790 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1792 RenderEngine& engine(getRenderEngine());
1793 mat4 colorMatrix = mColorMatrix;
1795 colorMatrix = colorMatrix * mDaltonizer();
1797 engine.beginGroup(colorMatrix);
1798 doComposeSurfaces(hw, dirtyRegion);
1802 // update the swap region and clear the dirty region
1803 hw->swapRegion.orSelf(dirtyRegion);
1805 // swap buffers (presentation)
1806 hw->swapBuffers(getHwComposer());
1809 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1811 RenderEngine& engine(getRenderEngine());
1812 const int32_t id = hw->getHwcDisplayId();
1813 HWComposer& hwc(getHwComposer());
1814 HWComposer::LayerListIterator cur = hwc.begin(id);
1815 const HWComposer::LayerListIterator end = hwc.end(id);
1817 bool hasGlesComposition = hwc.hasGlesComposition(id);
1818 if (hasGlesComposition) {
1819 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1820 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1821 hw->getDisplayName().string());
1822 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1823 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1824 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1829 // Never touch the framebuffer if we don't have any framebuffer layers
1830 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1831 if (hasHwcComposition) {
1832 // when using overlays, we assume a fully transparent framebuffer
1833 // NOTE: we could reduce how much we need to clear, for instance
1834 // remove where there are opaque FB layers. however, on some
1835 // GPUs doing a "clean slate" clear might be more efficient.
1836 // We'll revisit later if needed.
1837 engine.clearWithColor(0, 0, 0, 0);
1839 // we start with the whole screen area
1840 const Region bounds(hw->getBounds());
1842 // we remove the scissor part
1843 // we're left with the letterbox region
1844 // (common case is that letterbox ends-up being empty)
1845 const Region letterbox(bounds.subtract(hw->getScissor()));
1847 // compute the area to clear
1848 Region region(hw->undefinedRegion.merge(letterbox));
1850 // but limit it to the dirty region
1851 region.andSelf(dirty);
1853 // screen is already cleared here
1854 if (!region.isEmpty()) {
1855 // can happen with SurfaceView
1856 drawWormhole(hw, region);
1860 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1861 // just to be on the safe side, we don't set the
1862 // scissor on the main display. It should never be needed
1863 // anyways (though in theory it could since the API allows it).
1864 const Rect& bounds(hw->getBounds());
1865 const Rect& scissor(hw->getScissor());
1866 if (scissor != bounds) {
1867 // scissor doesn't match the screen's dimensions, so we
1868 // need to clear everything outside of it and enable
1869 // the GL scissor so we don't draw anything where we shouldn't
1871 // enable scissor for this frame
1872 const uint32_t height = hw->getHeight();
1873 engine.setScissor(scissor.left, height - scissor.bottom,
1874 scissor.getWidth(), scissor.getHeight());
1880 * and then, render the layers targeted at the framebuffer
1883 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1884 const size_t count = layers.size();
1885 const Transform& tr = hw->getTransform();
1887 // we're using h/w composer
1888 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1889 const sp<Layer>& layer(layers[i]);
1890 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1891 if (!clip.isEmpty()) {
1892 switch (cur->getCompositionType()) {
1893 case HWC_CURSOR_OVERLAY:
1895 const Layer::State& state(layer->getDrawingState());
1896 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1898 && layer->isOpaque(state) && (state.alpha == 0xFF)
1899 && hasGlesComposition) {
1900 // never clear the very first layer since we're
1901 // guaranteed the FB is already cleared
1902 layer->clearWithOpenGL(hw, clip);
1906 case HWC_FRAMEBUFFER: {
1907 layer->draw(hw, clip);
1910 case HWC_FRAMEBUFFER_TARGET: {
1911 // this should not happen as the iterator shouldn't
1912 // let us get there.
1913 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
1918 layer->setAcquireFence(hw, *cur);
1921 // we're not using h/w composer
1922 for (size_t i=0 ; i<count ; ++i) {
1923 const sp<Layer>& layer(layers[i]);
1924 const Region clip(dirty.intersect(
1925 tr.transform(layer->visibleRegion)));
1926 if (!clip.isEmpty()) {
1927 layer->draw(hw, clip);
1932 // disable scissor at the end of the frame
1933 engine.disableScissor();
1937 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1938 const int32_t height = hw->getHeight();
1939 RenderEngine& engine(getRenderEngine());
1940 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1943 void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1944 const sp<IBinder>& handle,
1945 const sp<IGraphicBufferProducer>& gbc,
1946 const sp<Layer>& lbc)
1948 // attach this layer to the client
1949 client->attachLayer(handle, lbc);
1951 // add this layer to the current state list
1952 Mutex::Autolock _l(mStateLock);
1953 mCurrentState.layersSortedByZ.add(lbc);
1954 mGraphicBufferProducerList.add(gbc->asBinder());
1957 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1958 Mutex::Autolock _l(mStateLock);
1959 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1961 mLayersPendingRemoval.push(layer);
1962 mLayersRemoved = true;
1963 setTransactionFlags(eTransactionNeeded);
1966 return status_t(index);
1969 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
1970 return android_atomic_release_load(&mTransactionFlags);
1973 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1974 return android_atomic_and(~flags, &mTransactionFlags) & flags;
1977 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1978 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1979 if ((old & flags)==0) { // wake the server up
1980 signalTransaction();
1985 void SurfaceFlinger::setTransactionState(
1986 const Vector<ComposerState>& state,
1987 const Vector<DisplayState>& displays,
1991 Mutex::Autolock _l(mStateLock);
1992 uint32_t transactionFlags = 0;
1994 if (flags & eAnimation) {
1995 // For window updates that are part of an animation we must wait for
1996 // previous animation "frames" to be handled.
1997 while (mAnimTransactionPending) {
1998 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1999 if (CC_UNLIKELY(err != NO_ERROR)) {
2000 // just in case something goes wrong in SF, return to the
2001 // caller after a few seconds.
2002 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2003 "waiting for previous animation frame");
2004 mAnimTransactionPending = false;
2010 size_t count = displays.size();
2011 for (size_t i=0 ; i<count ; i++) {
2012 const DisplayState& s(displays[i]);
2013 transactionFlags |= setDisplayStateLocked(s);
2016 count = state.size();
2017 for (size_t i=0 ; i<count ; i++) {
2018 const ComposerState& s(state[i]);
2019 // Here we need to check that the interface we're given is indeed
2020 // one of our own. A malicious client could give us a NULL
2021 // IInterface, or one of its own or even one of our own but a
2022 // different type. All these situations would cause us to crash.
2024 // NOTE: it would be better to use RTTI as we could directly check
2025 // that we have a Client*. however, RTTI is disabled in Android.
2026 if (s.client != NULL) {
2027 sp<IBinder> binder = s.client->asBinder();
2028 if (binder != NULL) {
2029 String16 desc(binder->getInterfaceDescriptor());
2030 if (desc == ISurfaceComposerClient::descriptor) {
2031 sp<Client> client( static_cast<Client *>(s.client.get()) );
2032 transactionFlags |= setClientStateLocked(client, s.state);
2038 if (transactionFlags) {
2039 // this triggers the transaction
2040 setTransactionFlags(transactionFlags);
2042 // if this is a synchronous transaction, wait for it to take effect
2043 // before returning.
2044 if (flags & eSynchronous) {
2045 mTransactionPending = true;
2047 if (flags & eAnimation) {
2048 mAnimTransactionPending = true;
2050 while (mTransactionPending) {
2051 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2052 if (CC_UNLIKELY(err != NO_ERROR)) {
2053 // just in case something goes wrong in SF, return to the
2054 // called after a few seconds.
2055 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2056 mTransactionPending = false;
2063 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2065 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2070 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2071 if (disp.isValid()) {
2072 const uint32_t what = s.what;
2073 if (what & DisplayState::eSurfaceChanged) {
2074 if (disp.surface->asBinder() != s.surface->asBinder()) {
2075 disp.surface = s.surface;
2076 flags |= eDisplayTransactionNeeded;
2079 if (what & DisplayState::eLayerStackChanged) {
2080 if (disp.layerStack != s.layerStack) {
2081 disp.layerStack = s.layerStack;
2082 flags |= eDisplayTransactionNeeded;
2085 if (what & DisplayState::eDisplayProjectionChanged) {
2086 if (disp.orientation != s.orientation) {
2087 disp.orientation = s.orientation;
2088 flags |= eDisplayTransactionNeeded;
2090 if (disp.frame != s.frame) {
2091 disp.frame = s.frame;
2092 flags |= eDisplayTransactionNeeded;
2094 if (disp.viewport != s.viewport) {
2095 disp.viewport = s.viewport;
2096 flags |= eDisplayTransactionNeeded;
2099 if (what & DisplayState::eDisplaySizeChanged) {
2100 if (disp.width != s.width) {
2101 disp.width = s.width;
2102 flags |= eDisplayTransactionNeeded;
2104 if (disp.height != s.height) {
2105 disp.height = s.height;
2106 flags |= eDisplayTransactionNeeded;
2113 uint32_t SurfaceFlinger::setClientStateLocked(
2114 const sp<Client>& client,
2115 const layer_state_t& s)
2118 sp<Layer> layer(client->getLayerUser(s.surface));
2120 const uint32_t what = s.what;
2121 if (what & layer_state_t::ePositionChanged) {
2122 if (layer->setPosition(s.x, s.y))
2123 flags |= eTraversalNeeded;
2125 if (what & layer_state_t::eLayerChanged) {
2126 // NOTE: index needs to be calculated before we update the state
2127 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2128 if (layer->setLayer(s.z)) {
2129 mCurrentState.layersSortedByZ.removeAt(idx);
2130 mCurrentState.layersSortedByZ.add(layer);
2131 // we need traversal (state changed)
2132 // AND transaction (list changed)
2133 flags |= eTransactionNeeded|eTraversalNeeded;
2136 if (what & layer_state_t::eSizeChanged) {
2137 if (layer->setSize(s.w, s.h)) {
2138 flags |= eTraversalNeeded;
2141 if (what & layer_state_t::eAlphaChanged) {
2142 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2143 flags |= eTraversalNeeded;
2145 if (what & layer_state_t::eMatrixChanged) {
2146 if (layer->setMatrix(s.matrix))
2147 flags |= eTraversalNeeded;
2149 if (what & layer_state_t::eTransparentRegionChanged) {
2150 if (layer->setTransparentRegionHint(s.transparentRegion))
2151 flags |= eTraversalNeeded;
2153 if ((what & layer_state_t::eVisibilityChanged) ||
2154 (what & layer_state_t::eOpacityChanged)) {
2155 // TODO: should we just use an eFlagsChanged for this?
2156 if (layer->setFlags(s.flags, s.mask))
2157 flags |= eTraversalNeeded;
2159 if (what & layer_state_t::eCropChanged) {
2160 if (layer->setCrop(s.crop))
2161 flags |= eTraversalNeeded;
2163 if (what & layer_state_t::eLayerStackChanged) {
2164 // NOTE: index needs to be calculated before we update the state
2165 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2166 if (layer->setLayerStack(s.layerStack)) {
2167 mCurrentState.layersSortedByZ.removeAt(idx);
2168 mCurrentState.layersSortedByZ.add(layer);
2169 // we need traversal (state changed)
2170 // AND transaction (list changed)
2171 flags |= eTransactionNeeded|eTraversalNeeded;
2178 status_t SurfaceFlinger::createLayer(
2179 const String8& name,
2180 const sp<Client>& client,
2181 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2182 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2184 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2185 if (int32_t(w|h) < 0) {
2186 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2191 status_t result = NO_ERROR;
2195 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2196 case ISurfaceComposerClient::eFXSurfaceNormal:
2197 result = createNormalLayer(client,
2198 name, w, h, flags, format,
2199 handle, gbp, &layer);
2201 case ISurfaceComposerClient::eFXSurfaceDim:
2202 result = createDimLayer(client,
2204 handle, gbp, &layer);
2211 if (result == NO_ERROR) {
2212 addClientLayer(client, *handle, *gbp, layer);
2213 setTransactionFlags(eTransactionNeeded);
2218 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2219 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2220 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2222 // initialize the surfaces
2224 case PIXEL_FORMAT_TRANSPARENT:
2225 case PIXEL_FORMAT_TRANSLUCENT:
2226 format = PIXEL_FORMAT_RGBA_8888;
2228 case PIXEL_FORMAT_OPAQUE:
2229 format = PIXEL_FORMAT_RGBX_8888;
2233 *outLayer = new Layer(this, client, name, w, h, flags);
2234 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2235 if (err == NO_ERROR) {
2236 *handle = (*outLayer)->getHandle();
2237 *gbp = (*outLayer)->getProducer();
2240 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2244 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2245 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2246 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2248 *outLayer = new LayerDim(this, client, name, w, h, flags);
2249 *handle = (*outLayer)->getHandle();
2250 *gbp = (*outLayer)->getProducer();
2254 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2256 // called by the window manager when it wants to remove a Layer
2257 status_t err = NO_ERROR;
2258 sp<Layer> l(client->getLayerUser(handle));
2260 err = removeLayer(l);
2261 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2262 "error removing layer=%p (%s)", l.get(), strerror(-err));
2267 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2269 // called by ~LayerCleaner() when all references to the IBinder (handle)
2271 status_t err = NO_ERROR;
2272 sp<Layer> l(layer.promote());
2274 err = removeLayer(l);
2275 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2276 "error removing layer=%p (%s)", l.get(), strerror(-err));
2281 // ---------------------------------------------------------------------------
2283 void SurfaceFlinger::onInitializeDisplays() {
2284 // reset screen orientation and use primary layer stack
2285 Vector<ComposerState> state;
2286 Vector<DisplayState> displays;
2288 d.what = DisplayState::eDisplayProjectionChanged |
2289 DisplayState::eLayerStackChanged;
2290 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2292 d.orientation = DisplayState::eOrientationDefault;
2293 d.frame.makeInvalid();
2294 d.viewport.makeInvalid();
2298 setTransactionState(state, displays, 0);
2299 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2301 const nsecs_t period =
2302 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2303 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2306 void SurfaceFlinger::initializeDisplays() {
2307 class MessageScreenInitialized : public MessageBase {
2308 SurfaceFlinger* flinger;
2310 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2311 virtual bool handler() {
2312 flinger->onInitializeDisplays();
2316 sp<MessageBase> msg = new MessageScreenInitialized(this);
2317 postMessageAsync(msg); // we may be called from main thread, use async message
2320 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2322 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2324 int32_t type = hw->getDisplayType();
2325 int currentMode = hw->getPowerMode();
2327 if (mode == currentMode) {
2328 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2332 hw->setPowerMode(mode);
2333 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2334 ALOGW("Trying to set power mode for virtual display");
2338 if (currentMode == HWC_POWER_MODE_OFF) {
2339 getHwComposer().setPowerMode(type, mode);
2340 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2341 // FIXME: eventthread only knows about the main display right now
2342 mEventThread->onScreenAcquired();
2343 resyncToHardwareVsync(true);
2346 mVisibleRegionsDirty = true;
2347 repaintEverything();
2348 } else if (mode == HWC_POWER_MODE_OFF) {
2349 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2350 disableHardwareVsync(true); // also cancels any in-progress resync
2352 // FIXME: eventthread only knows about the main display right now
2353 mEventThread->onScreenReleased();
2356 getHwComposer().setPowerMode(type, mode);
2357 mVisibleRegionsDirty = true;
2358 // from this point on, SF will stop drawing on this display
2360 getHwComposer().setPowerMode(type, mode);
2364 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2365 class MessageSetPowerMode: public MessageBase {
2366 SurfaceFlinger& mFlinger;
2367 sp<IBinder> mDisplay;
2370 MessageSetPowerMode(SurfaceFlinger& flinger,
2371 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2372 mDisplay(disp) { mMode = mode; }
2373 virtual bool handler() {
2374 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2376 ALOGE("Attempt to set power mode = %d for null display %p",
2377 mMode, mDisplay.get());
2378 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2379 ALOGW("Attempt to set power mode = %d for virtual display",
2382 mFlinger.setPowerModeInternal(hw, mMode);
2387 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2388 postMessageSync(msg);
2391 // ---------------------------------------------------------------------------
2393 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2397 IPCThreadState* ipc = IPCThreadState::self();
2398 const int pid = ipc->getCallingPid();
2399 const int uid = ipc->getCallingUid();
2400 if ((uid != AID_SHELL) &&
2401 !PermissionCache::checkPermission(sDump, pid, uid)) {
2402 result.appendFormat("Permission Denial: "
2403 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2405 // Try to get the main lock, but don't insist if we can't
2406 // (this would indicate SF is stuck, but we want to be able to
2407 // print something in dumpsys).
2409 while (mStateLock.tryLock()<0 && --retry>=0) {
2412 const bool locked(retry >= 0);
2415 "SurfaceFlinger appears to be unresponsive, "
2416 "dumping anyways (no locks held)\n");
2419 bool dumpAll = true;
2421 size_t numArgs = args.size();
2423 if ((index < numArgs) &&
2424 (args[index] == String16("--list"))) {
2426 listLayersLocked(args, index, result);
2430 if ((index < numArgs) &&
2431 (args[index] == String16("--latency"))) {
2433 dumpStatsLocked(args, index, result);
2437 if ((index < numArgs) &&
2438 (args[index] == String16("--latency-clear"))) {
2440 clearStatsLocked(args, index, result);
2444 if ((index < numArgs) &&
2445 (args[index] == String16("--dispsync"))) {
2447 mPrimaryDispSync.dump(result);
2453 dumpAllLocked(args, index, result);
2457 mStateLock.unlock();
2460 write(fd, result.string(), result.size());
2464 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2465 size_t& /* index */, String8& result) const
2467 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2468 const size_t count = currentLayers.size();
2469 for (size_t i=0 ; i<count ; i++) {
2470 const sp<Layer>& layer(currentLayers[i]);
2471 result.appendFormat("%s\n", layer->getName().string());
2475 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2476 String8& result) const
2479 if (index < args.size()) {
2480 name = String8(args[index]);
2484 const nsecs_t period =
2485 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2486 result.appendFormat("%" PRId64 "\n", period);
2488 if (name.isEmpty()) {
2489 mAnimFrameTracker.dumpStats(result);
2491 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2492 const size_t count = currentLayers.size();
2493 for (size_t i=0 ; i<count ; i++) {
2494 const sp<Layer>& layer(currentLayers[i]);
2495 if (name == layer->getName()) {
2496 layer->dumpFrameStats(result);
2502 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2503 String8& /* result */)
2506 if (index < args.size()) {
2507 name = String8(args[index]);
2511 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2512 const size_t count = currentLayers.size();
2513 for (size_t i=0 ; i<count ; i++) {
2514 const sp<Layer>& layer(currentLayers[i]);
2515 if (name.isEmpty() || (name == layer->getName())) {
2516 layer->clearFrameStats();
2520 mAnimFrameTracker.clearStats();
2523 // This should only be called from the main thread. Otherwise it would need
2524 // the lock and should use mCurrentState rather than mDrawingState.
2525 void SurfaceFlinger::logFrameStats() {
2526 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2527 const size_t count = drawingLayers.size();
2528 for (size_t i=0 ; i<count ; i++) {
2529 const sp<Layer>& layer(drawingLayers[i]);
2530 layer->logFrameStats();
2533 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2536 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2538 static const char* config =
2540 #ifdef HAS_CONTEXT_PRIORITY
2541 " HAS_CONTEXT_PRIORITY"
2543 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2544 " NEVER_DEFAULT_TO_ASYNC_MODE"
2546 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2547 " TARGET_DISABLE_TRIPLE_BUFFERING"
2550 result.append(config);
2553 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2554 String8& result) const
2556 bool colorize = false;
2557 if (index < args.size()
2558 && (args[index] == String16("--color"))) {
2563 Colorizer colorizer(colorize);
2565 // figure out if we're stuck somewhere
2566 const nsecs_t now = systemTime();
2567 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2568 const nsecs_t inTransaction(mDebugInTransaction);
2569 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2570 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2573 * Dump library configuration.
2576 colorizer.bold(result);
2577 result.append("Build configuration:");
2578 colorizer.reset(result);
2579 appendSfConfigString(result);
2580 appendUiConfigString(result);
2581 appendGuiConfigString(result);
2582 result.append("\n");
2584 colorizer.bold(result);
2585 result.append("Sync configuration: ");
2586 colorizer.reset(result);
2587 result.append(SyncFeatures::getInstance().toString());
2588 result.append("\n");
2590 colorizer.bold(result);
2591 result.append("DispSync configuration: ");
2592 colorizer.reset(result);
2593 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2594 "present offset %d ns (refresh %" PRId64 " ns)",
2595 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2596 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2597 result.append("\n");
2600 * Dump the visible layer list
2602 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2603 const size_t count = currentLayers.size();
2604 colorizer.bold(result);
2605 result.appendFormat("Visible layers (count = %zu)\n", count);
2606 colorizer.reset(result);
2607 for (size_t i=0 ; i<count ; i++) {
2608 const sp<Layer>& layer(currentLayers[i]);
2609 layer->dump(result, colorizer);
2613 * Dump Display state
2616 colorizer.bold(result);
2617 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2618 colorizer.reset(result);
2619 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2620 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2625 * Dump SurfaceFlinger global state
2628 colorizer.bold(result);
2629 result.append("SurfaceFlinger global state:\n");
2630 colorizer.reset(result);
2632 HWComposer& hwc(getHwComposer());
2633 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2635 colorizer.bold(result);
2636 result.appendFormat("EGL implementation : %s\n",
2637 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2638 colorizer.reset(result);
2639 result.appendFormat("%s\n",
2640 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2642 mRenderEngine->dump(result);
2644 hw->undefinedRegion.dump(result, "undefinedRegion");
2645 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2646 hw->getOrientation(), hw->isDisplayOn());
2647 result.appendFormat(
2648 " last eglSwapBuffers() time: %f us\n"
2649 " last transaction time : %f us\n"
2650 " transaction-flags : %08x\n"
2651 " refresh-rate : %f fps\n"
2654 " gpu_to_cpu_unsupported : %d\n"
2656 mLastSwapBufferTime/1000.0,
2657 mLastTransactionTime/1000.0,
2659 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2660 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2661 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2662 !mGpuToCpuSupported);
2664 result.appendFormat(" eglSwapBuffers time: %f us\n",
2665 inSwapBuffersDuration/1000.0);
2667 result.appendFormat(" transaction time: %f us\n",
2668 inTransactionDuration/1000.0);
2673 mEventThread->dump(result);
2676 * Dump HWComposer state
2678 colorizer.bold(result);
2679 result.append("h/w composer state:\n");
2680 colorizer.reset(result);
2681 result.appendFormat(" h/w composer %s and %s\n",
2682 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2683 (mDebugDisableHWC || mDebugRegion || mDaltonize
2684 || mHasColorMatrix) ? "disabled" : "enabled");
2688 * Dump gralloc state
2690 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2694 const Vector< sp<Layer> >&
2695 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2696 // Note: mStateLock is held here
2698 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2699 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2700 dpy = mDisplays.keyAt(i);
2705 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2706 // Just use the primary display so we have something to return
2707 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2709 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2712 bool SurfaceFlinger::startDdmConnection()
2714 void* libddmconnection_dso =
2715 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2716 if (!libddmconnection_dso) {
2719 void (*DdmConnection_start)(const char* name);
2720 DdmConnection_start =
2721 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2722 if (!DdmConnection_start) {
2723 dlclose(libddmconnection_dso);
2726 (*DdmConnection_start)(getServiceName());
2730 status_t SurfaceFlinger::onTransact(
2731 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2734 case CREATE_CONNECTION:
2735 case CREATE_DISPLAY:
2736 case SET_TRANSACTION_STATE:
2738 case CLEAR_ANIMATION_FRAME_STATS:
2739 case GET_ANIMATION_FRAME_STATS:
2740 case SET_POWER_MODE:
2742 // codes that require permission check
2743 IPCThreadState* ipc = IPCThreadState::self();
2744 const int pid = ipc->getCallingPid();
2745 const int uid = ipc->getCallingUid();
2746 if ((uid != AID_GRAPHICS) &&
2747 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2748 ALOGE("Permission Denial: "
2749 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2750 return PERMISSION_DENIED;
2754 case CAPTURE_SCREEN:
2756 // codes that require permission check
2757 IPCThreadState* ipc = IPCThreadState::self();
2758 const int pid = ipc->getCallingPid();
2759 const int uid = ipc->getCallingUid();
2760 if ((uid != AID_GRAPHICS) &&
2761 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2762 ALOGE("Permission Denial: "
2763 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2764 return PERMISSION_DENIED;
2770 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2771 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2772 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2773 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2774 IPCThreadState* ipc = IPCThreadState::self();
2775 const int pid = ipc->getCallingPid();
2776 const int uid = ipc->getCallingUid();
2777 ALOGE("Permission Denial: "
2778 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2779 return PERMISSION_DENIED;
2783 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2784 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2786 case 1002: // SHOW_UPDATES
2787 n = data.readInt32();
2788 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2789 invalidateHwcGeometry();
2790 repaintEverything();
2792 case 1004:{ // repaint everything
2793 repaintEverything();
2796 case 1005:{ // force transaction
2797 setTransactionFlags(
2799 eDisplayTransactionNeeded|
2803 case 1006:{ // send empty update
2807 case 1008: // toggle use of hw composer
2808 n = data.readInt32();
2809 mDebugDisableHWC = n ? 1 : 0;
2810 invalidateHwcGeometry();
2811 repaintEverything();
2813 case 1009: // toggle use of transform hint
2814 n = data.readInt32();
2815 mDebugDisableTransformHint = n ? 1 : 0;
2816 invalidateHwcGeometry();
2817 repaintEverything();
2819 case 1010: // interrogate.
2820 reply->writeInt32(0);
2821 reply->writeInt32(0);
2822 reply->writeInt32(mDebugRegion);
2823 reply->writeInt32(0);
2824 reply->writeInt32(mDebugDisableHWC);
2827 Mutex::Autolock _l(mStateLock);
2828 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2829 reply->writeInt32(hw->getPageFlipCount());
2834 n = data.readInt32();
2836 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2837 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2838 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2841 mDaltonizer.setMode(Daltonizer::correction);
2843 mDaltonizer.setMode(Daltonizer::simulation);
2846 invalidateHwcGeometry();
2847 repaintEverything();
2851 // apply a color matrix
2852 n = data.readInt32();
2853 mHasColorMatrix = n ? 1 : 0;
2855 // color matrix is sent as mat3 matrix followed by vec3
2856 // offset, then packed into a mat4 where the last row is
2857 // the offset and extra values are 0
2858 for (size_t i = 0 ; i < 4; i++) {
2859 for (size_t j = 0; j < 4; j++) {
2860 mColorMatrix[i][j] = data.readFloat();
2864 mColorMatrix = mat4();
2866 invalidateHwcGeometry();
2867 repaintEverything();
2870 // This is an experimental interface
2871 // Needs to be shifted to proper binder interface when we productize
2873 n = data.readInt32();
2874 mPrimaryDispSync.setRefreshSkipCount(n);
2882 void SurfaceFlinger::repaintEverything() {
2883 android_atomic_or(1, &mRepaintEverything);
2884 signalTransaction();
2887 // ---------------------------------------------------------------------------
2888 // Capture screen into an IGraphiBufferProducer
2889 // ---------------------------------------------------------------------------
2891 /* The code below is here to handle b/8734824
2893 * We create a IGraphicBufferProducer wrapper that forwards all calls
2894 * from the surfaceflinger thread to the calling binder thread, where they
2895 * are executed. This allows the calling thread in the calling process to be
2896 * reused and not depend on having "enough" binder threads to handle the
2899 class GraphicProducerWrapper : public BBinder, public MessageHandler {
2900 /* Parts of GraphicProducerWrapper are run on two different threads,
2901 * communicating by sending messages via Looper but also by shared member
2902 * data. Coherence maintenance is subtle and in places implicit (ugh).
2904 * Don't rely on Looper's sendMessage/handleMessage providing
2905 * release/acquire semantics for any data not actually in the Message.
2906 * Data going from surfaceflinger to binder threads needs to be
2907 * synchronized explicitly.
2909 * Barrier open/wait do provide release/acquire semantics. This provides
2910 * implicit synchronization for data coming back from binder to
2911 * surfaceflinger threads.
2914 sp<IGraphicBufferProducer> impl;
2930 * Called on surfaceflinger thread. This is called by our "fake"
2931 * BpGraphicBufferProducer. We package the data and reply Parcel and
2932 * forward them to the binder thread.
2934 virtual status_t transact(uint32_t code,
2935 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
2938 this->reply = reply;
2940 // if we've exited, we run the message synchronously right here.
2941 // note (JH): as far as I can tell from looking at the code, this
2942 // never actually happens. if it does, i'm not sure if it happens
2943 // on the surfaceflinger or binder thread.
2944 handleMessage(Message(MSG_API_CALL));
2947 // Prevent stores to this->{code, data, reply} from being
2948 // reordered later than the construction of Message.
2949 atomic_thread_fence(memory_order_release);
2950 looper->sendMessage(this, Message(MSG_API_CALL));
2957 * here we run on the binder thread. All we've got to do is
2958 * call the real BpGraphicBufferProducer.
2960 virtual void handleMessage(const Message& message) {
2961 int what = message.what;
2962 // Prevent reads below from happening before the read from Message
2963 atomic_thread_fence(memory_order_acquire);
2964 if (what == MSG_API_CALL) {
2965 result = impl->asBinder()->transact(code, data[0], reply);
2967 } else if (what == MSG_EXIT) {
2968 exitRequested = true;
2973 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
2975 looper(new Looper(true)),
2977 exitRequested(false)
2981 status_t waitForResponse() {
2983 looper->pollOnce(-1);
2984 } while (!exitRequested);
2989 void exit(status_t result) {
2990 this->result = result;
2992 // Ensure this->result is visible to the binder thread before it
2993 // handles the message.
2994 atomic_thread_fence(memory_order_release);
2995 looper->sendMessage(this, Message(MSG_EXIT));
3000 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3001 const sp<IGraphicBufferProducer>& producer,
3002 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3003 uint32_t minLayerZ, uint32_t maxLayerZ,
3004 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3006 if (CC_UNLIKELY(display == 0))
3009 if (CC_UNLIKELY(producer == 0))
3012 // if we have secure windows on this display, never allow the screen capture
3013 // unless the producer interface is local (i.e.: we can take a screenshot for
3015 if (!producer->asBinder()->localBinder()) {
3016 Mutex::Autolock _l(mStateLock);
3017 sp<const DisplayDevice> hw(getDisplayDevice(display));
3018 if (hw->getSecureLayerVisible()) {
3019 ALOGW("FB is protected: PERMISSION_DENIED");
3020 return PERMISSION_DENIED;
3024 // Convert to surfaceflinger's internal rotation type.
3025 Transform::orientation_flags rotationFlags;
3027 case ISurfaceComposer::eRotateNone:
3028 rotationFlags = Transform::ROT_0;
3030 case ISurfaceComposer::eRotate90:
3031 rotationFlags = Transform::ROT_90;
3033 case ISurfaceComposer::eRotate180:
3034 rotationFlags = Transform::ROT_180;
3036 case ISurfaceComposer::eRotate270:
3037 rotationFlags = Transform::ROT_270;
3040 rotationFlags = Transform::ROT_0;
3041 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3045 class MessageCaptureScreen : public MessageBase {
3046 SurfaceFlinger* flinger;
3047 sp<IBinder> display;
3048 sp<IGraphicBufferProducer> producer;
3050 uint32_t reqWidth, reqHeight;
3051 uint32_t minLayerZ,maxLayerZ;
3052 bool useIdentityTransform;
3053 Transform::orientation_flags rotation;
3056 MessageCaptureScreen(SurfaceFlinger* flinger,
3057 const sp<IBinder>& display,
3058 const sp<IGraphicBufferProducer>& producer,
3059 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3060 uint32_t minLayerZ, uint32_t maxLayerZ,
3061 bool useIdentityTransform, Transform::orientation_flags rotation)
3062 : flinger(flinger), display(display), producer(producer),
3063 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3064 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3065 useIdentityTransform(useIdentityTransform),
3067 result(PERMISSION_DENIED)
3070 status_t getResult() const {
3073 virtual bool handler() {
3074 Mutex::Autolock _l(flinger->mStateLock);
3075 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3076 result = flinger->captureScreenImplLocked(hw, producer,
3077 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3078 useIdentityTransform, rotation);
3079 static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
3084 // make sure to process transactions before screenshots -- a transaction
3085 // might already be pending but scheduled for VSYNC; this guarantees we
3086 // will handle it before the screenshot. When VSYNC finally arrives
3087 // the scheduled transaction will be a no-op. If no transactions are
3088 // scheduled at this time, this will end-up being a no-op as well.
3089 mEventQueue.invalidateTransactionNow();
3091 // this creates a "fake" BBinder which will serve as a "fake" remote
3092 // binder to receive the marshaled calls and forward them to the
3093 // real remote (a BpGraphicBufferProducer)
3094 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3096 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3097 // which does the marshaling work forwards to our "fake remote" above.
3098 sp<MessageBase> msg = new MessageCaptureScreen(this,
3099 display, IGraphicBufferProducer::asInterface( wrapper ),
3100 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3101 useIdentityTransform, rotationFlags);
3103 status_t res = postMessageAsync(msg);
3104 if (res == NO_ERROR) {
3105 res = wrapper->waitForResponse();
3111 void SurfaceFlinger::renderScreenImplLocked(
3112 const sp<const DisplayDevice>& hw,
3113 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3114 uint32_t minLayerZ, uint32_t maxLayerZ,
3115 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3118 RenderEngine& engine(getRenderEngine());
3120 // get screen geometry
3121 const uint32_t hw_w = hw->getWidth();
3122 const uint32_t hw_h = hw->getHeight();
3123 const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
3125 // if a default or invalid sourceCrop is passed in, set reasonable values
3126 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3127 !sourceCrop.isValid()) {
3128 sourceCrop.setLeftTop(Point(0, 0));
3129 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3132 // ensure that sourceCrop is inside screen
3133 if (sourceCrop.left < 0) {
3134 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3136 if (static_cast<uint32_t>(sourceCrop.right) > hw_w) {
3137 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3139 if (sourceCrop.top < 0) {
3140 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3142 if (static_cast<uint32_t>(sourceCrop.bottom) > hw_h) {
3143 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3146 // make sure to clear all GL error flags
3147 engine.checkErrors();
3149 // set-up our viewport
3150 engine.setViewportAndProjection(
3151 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3152 engine.disableTexturing();
3154 // redraw the screen entirely...
3155 engine.clearWithColor(0, 0, 0, 1);
3157 const LayerVector& layers( mDrawingState.layersSortedByZ );
3158 const size_t count = layers.size();
3159 for (size_t i=0 ; i<count ; ++i) {
3160 const sp<Layer>& layer(layers[i]);
3161 const Layer::State& state(layer->getDrawingState());
3162 if (state.layerStack == hw->getLayerStack()) {
3163 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3164 if (layer->isVisible()) {
3165 if (filtering) layer->setFiltering(true);
3166 layer->draw(hw, useIdentityTransform);
3167 if (filtering) layer->setFiltering(false);
3173 // compositionComplete is needed for older driver
3174 hw->compositionComplete();
3175 hw->setViewportAndProjection();
3179 status_t SurfaceFlinger::captureScreenImplLocked(
3180 const sp<const DisplayDevice>& hw,
3181 const sp<IGraphicBufferProducer>& producer,
3182 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3183 uint32_t minLayerZ, uint32_t maxLayerZ,
3184 bool useIdentityTransform, Transform::orientation_flags rotation)
3188 // get screen geometry
3189 const uint32_t hw_w = hw->getWidth();
3190 const uint32_t hw_h = hw->getHeight();
3192 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3193 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3194 reqWidth, reqHeight, hw_w, hw_h);
3198 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3199 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3201 // create a surface (because we're a producer, and we need to
3202 // dequeue/queue a buffer)
3203 sp<Surface> sur = new Surface(producer, false);
3204 ANativeWindow* window = sur.get();
3206 status_t result = NO_ERROR;
3207 if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
3208 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3209 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3212 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3213 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3214 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3215 err |= native_window_set_usage(window, usage);
3217 if (err == NO_ERROR) {
3218 ANativeWindowBuffer* buffer;
3219 /* TODO: Once we have the sync framework everywhere this can use
3220 * server-side waits on the fence that dequeueBuffer returns.
3222 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3223 if (result == NO_ERROR) {
3225 // create an EGLImage from the buffer so we can later
3226 // turn it into a texture
3227 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3228 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3229 if (image != EGL_NO_IMAGE_KHR) {
3230 // this binds the given EGLImage as a framebuffer for the
3231 // duration of this scope.
3232 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3233 if (imageBond.getStatus() == NO_ERROR) {
3234 // this will in fact render into our dequeued buffer
3235 // via an FBO, which means we didn't have to create
3236 // an EGLSurface and therefore we're not
3237 // dependent on the context's EGLConfig.
3238 renderScreenImplLocked(
3239 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3240 useIdentityTransform, rotation);
3242 // Attempt to create a sync khr object that can produce a sync point. If that
3243 // isn't available, create a non-dupable sync object in the fallback path and
3244 // wait on it directly.
3246 if (!DEBUG_SCREENSHOTS) {
3247 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3248 // native fence fd will not be populated until flush() is done.
3249 getRenderEngine().flush();
3251 sync = EGL_NO_SYNC_KHR;
3253 if (sync != EGL_NO_SYNC_KHR) {
3255 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3256 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3257 ALOGW("captureScreen: failed to dup sync khr object");
3260 eglDestroySyncKHR(mEGLDisplay, sync);
3263 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3264 if (sync != EGL_NO_SYNC_KHR) {
3265 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3266 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3267 EGLint eglErr = eglGetError();
3268 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3269 ALOGW("captureScreen: fence wait timed out");
3271 ALOGW_IF(eglErr != EGL_SUCCESS,
3272 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3274 eglDestroySyncKHR(mEGLDisplay, sync);
3276 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3279 if (DEBUG_SCREENSHOTS) {
3280 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3281 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3282 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3283 hw, minLayerZ, maxLayerZ);
3288 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3289 result = INVALID_OPERATION;
3291 // destroy our image
3292 eglDestroyImageKHR(mEGLDisplay, image);
3296 // queueBuffer takes ownership of syncFd
3297 window->queueBuffer(window, buffer, syncFd);
3302 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3308 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3309 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3310 if (DEBUG_SCREENSHOTS) {
3311 for (size_t y=0 ; y<h ; y++) {
3312 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3313 for (size_t x=0 ; x<w ; x++) {
3314 if (p[x] != 0xFF000000) return;
3317 ALOGE("*** we just took a black screenshot ***\n"
3318 "requested minz=%d, maxz=%d, layerStack=%d",
3319 minLayerZ, maxLayerZ, hw->getLayerStack());
3320 const LayerVector& layers( mDrawingState.layersSortedByZ );
3321 const size_t count = layers.size();
3322 for (size_t i=0 ; i<count ; ++i) {
3323 const sp<Layer>& layer(layers[i]);
3324 const Layer::State& state(layer->getDrawingState());
3325 const bool visible = (state.layerStack == hw->getLayerStack())
3326 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3327 && (layer->isVisible());
3328 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3329 visible ? '+' : '-',
3330 i, layer->getName().string(), state.layerStack, state.z,
3331 layer->isVisible(), state.flags, state.alpha);
3336 // ---------------------------------------------------------------------------
3338 SurfaceFlinger::LayerVector::LayerVector() {
3341 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3342 : SortedVector<sp<Layer> >(rhs) {
3345 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3346 const void* rhs) const
3348 // sort layers per layer-stack, then by z-order and finally by sequence
3349 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3350 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3352 uint32_t ls = l->getCurrentState().layerStack;
3353 uint32_t rs = r->getCurrentState().layerStack;
3357 uint32_t lz = l->getCurrentState().z;
3358 uint32_t rz = r->getCurrentState().z;
3362 return l->sequence - r->sequence;
3365 // ---------------------------------------------------------------------------
3367 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3368 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3371 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3372 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3373 viewport.makeInvalid();
3374 frame.makeInvalid();
3377 // ---------------------------------------------------------------------------
3379 }; // namespace android
3382 #if defined(__gl_h_)
3383 #error "don't include gl/gl.h in this file"
3386 #if defined(__gl2_h_)
3387 #error "don't include gl2/gl2.h in this file"