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 mForceFullDamage(false),
149 mPrimaryHWVsyncEnabled(false),
150 mHWVsyncAvailable(false),
152 mHasColorMatrix(false),
153 mHasPoweredOff(false),
158 ALOGI("SurfaceFlinger is starting");
160 // debugging stuff...
161 char value[PROPERTY_VALUE_MAX];
163 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
164 mGpuToCpuSupported = !atoi(value);
166 property_get("debug.sf.drop_missed_frames", value, "0");
167 mDropMissedFrames = atoi(value);
169 property_get("debug.sf.showupdates", value, "0");
170 mDebugRegion = atoi(value);
172 property_get("debug.sf.ddms", value, "0");
173 mDebugDDMS = atoi(value);
175 if (!startDdmConnection()) {
176 // start failed, and DDMS debugging not enabled
180 ALOGI_IF(mDebugRegion, "showupdates enabled");
181 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
184 void SurfaceFlinger::onFirstRef()
186 mEventQueue.init(this);
189 SurfaceFlinger::~SurfaceFlinger()
191 EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
192 eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
193 eglTerminate(display);
196 void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
198 // the window manager died on us. prepare its eulogy.
200 // restore initial conditions (default device unblank, etc)
201 initializeDisplays();
203 // restart the boot-animation
207 sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
209 sp<ISurfaceComposerClient> bclient;
210 sp<Client> client(new Client(this));
211 status_t err = client->initCheck();
212 if (err == NO_ERROR) {
218 sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
221 class DisplayToken : public BBinder {
222 sp<SurfaceFlinger> flinger;
223 virtual ~DisplayToken() {
224 // no more references, this display must be terminated
225 Mutex::Autolock _l(flinger->mStateLock);
226 flinger->mCurrentState.displays.removeItem(this);
227 flinger->setTransactionFlags(eDisplayTransactionNeeded);
230 DisplayToken(const sp<SurfaceFlinger>& flinger)
235 sp<BBinder> token = new DisplayToken(this);
237 Mutex::Autolock _l(mStateLock);
238 DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
239 info.displayName = displayName;
240 info.isSecure = secure;
241 mCurrentState.displays.add(token, info);
246 void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
247 Mutex::Autolock _l(mStateLock);
249 ssize_t idx = mCurrentState.displays.indexOfKey(display);
251 ALOGW("destroyDisplay: invalid display token");
255 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
256 if (!info.isVirtualDisplay()) {
257 ALOGE("destroyDisplay called for non-virtual display");
261 mCurrentState.displays.removeItemsAt(idx);
262 setTransactionFlags(eDisplayTransactionNeeded);
265 void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
266 ALOGW_IF(mBuiltinDisplays[type],
267 "Overwriting display token for display type %d", type);
268 mBuiltinDisplays[type] = new BBinder();
269 DisplayDeviceState info(type);
270 // All non-virtual displays are currently considered secure.
271 info.isSecure = true;
272 mCurrentState.displays.add(mBuiltinDisplays[type], info);
275 sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
276 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
277 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
280 return mBuiltinDisplays[id];
283 sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
285 sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
289 void SurfaceFlinger::bootFinished()
291 const nsecs_t now = systemTime();
292 const nsecs_t duration = now - mBootTime;
293 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
294 mBootFinished = true;
296 // wait patiently for the window manager death
297 const String16 name("window");
298 sp<IBinder> window(defaultServiceManager()->getService(name));
300 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
303 // stop boot animation
304 // formerly we would just kill the process, but we now ask it to exit so it
305 // can choose where to stop the animation.
306 property_set("service.bootanim.exit", "1");
309 void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
310 class MessageDestroyGLTexture : public MessageBase {
311 RenderEngine& engine;
314 MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
315 : engine(engine), texture(texture) {
317 virtual bool handler() {
318 engine.deleteTextures(1, &texture);
322 postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
325 class DispSyncSource : public VSyncSource, private DispSync::Callback {
327 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
330 mTraceVsync(traceVsync),
331 mVsyncOnLabel(String8::format("VsyncOn-%s", label)),
332 mVsyncEventLabel(String8::format("VSYNC-%s", label)),
337 mPhaseOffset(phaseOffset),
340 virtual ~DispSyncSource() {}
342 virtual void setVSyncEnabled(bool enable) {
343 Mutex::Autolock lock(mVsyncMutex);
345 status_t err = mDispSync->addEventListener(mPhaseOffset,
346 static_cast<DispSync::Callback*>(this));
347 if (err != NO_ERROR) {
348 ALOGE("error registering vsync callback: %s (%d)",
349 strerror(-err), err);
351 //ATRACE_INT(mVsyncOnLabel.string(), 1);
353 status_t err = mDispSync->removeEventListener(
354 static_cast<DispSync::Callback*>(this));
355 if (err != NO_ERROR) {
356 ALOGE("error unregistering vsync callback: %s (%d)",
357 strerror(-err), err);
359 //ATRACE_INT(mVsyncOnLabel.string(), 0);
364 virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
365 Mutex::Autolock lock(mCallbackMutex);
366 mCallback = callback;
369 virtual void setPhaseOffset(nsecs_t phaseOffset) {
370 Mutex::Autolock lock(mVsyncMutex);
372 // Normalize phaseOffset to [0, period)
373 auto period = mDispSync->getPeriod();
374 phaseOffset %= period;
375 if (phaseOffset < 0) {
376 // If we're here, then phaseOffset is in (-period, 0). After this
377 // operation, it will be in (0, period)
378 phaseOffset += period;
380 mPhaseOffset = phaseOffset;
382 // If we're not enabled, we don't need to mess with the listeners
387 // Remove the listener with the old offset
388 status_t err = mDispSync->removeEventListener(
389 static_cast<DispSync::Callback*>(this));
390 if (err != NO_ERROR) {
391 ALOGE("error unregistering vsync callback: %s (%d)",
392 strerror(-err), err);
395 // Add a listener with the new offset
396 err = mDispSync->addEventListener(mPhaseOffset,
397 static_cast<DispSync::Callback*>(this));
398 if (err != NO_ERROR) {
399 ALOGE("error registering vsync callback: %s (%d)",
400 strerror(-err), err);
405 virtual void onDispSyncEvent(nsecs_t when) {
406 sp<VSyncSource::Callback> callback;
408 Mutex::Autolock lock(mCallbackMutex);
409 callback = mCallback;
412 mValue = (mValue + 1) % 2;
413 ATRACE_INT(mVsyncEventLabel.string(), mValue);
417 if (callback != NULL) {
418 callback->onVSyncEvent(when);
424 const bool mTraceVsync;
425 const String8 mVsyncOnLabel;
426 const String8 mVsyncEventLabel;
430 Mutex mCallbackMutex; // Protects the following
431 sp<VSyncSource::Callback> mCallback;
433 Mutex mVsyncMutex; // Protects the following
434 nsecs_t mPhaseOffset;
438 void SurfaceFlinger::init() {
439 ALOGI( "SurfaceFlinger's main thread ready to run. "
440 "Initializing graphics H/W...");
442 Mutex::Autolock _l(mStateLock);
444 // initialize EGL for the default display
445 mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
446 eglInitialize(mEGLDisplay, NULL, NULL);
448 // start the EventThread
449 sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
450 vsyncPhaseOffsetNs, true, "app");
451 mEventThread = new EventThread(vsyncSrc);
452 sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
453 sfVsyncPhaseOffsetNs, true, "sf");
454 mSFEventThread = new EventThread(sfVsyncSrc);
455 mEventQueue.setEventThread(mSFEventThread);
457 // Initialize the H/W composer object. There may or may not be an
458 // actual hardware composer underneath.
459 mHwc = new HWComposer(this,
460 *static_cast<HWComposer::EventHandler *>(this));
462 // get a RenderEngine for the given display / config (can't fail)
463 mRenderEngine = RenderEngine::create(mEGLDisplay, mHwc->getVisualID());
465 // retrieve the EGL context that was selected/created
466 mEGLContext = mRenderEngine->getEGLContext();
468 LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
469 "couldn't create EGLContext");
471 // initialize our non-virtual displays
472 for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
473 DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
474 // set-up the displays that are already connected
475 if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
476 // All non-virtual displays are currently considered secure.
477 bool isSecure = true;
478 createBuiltinDisplayLocked(type);
479 wp<IBinder> token = mBuiltinDisplays[i];
481 sp<IGraphicBufferProducer> producer;
482 sp<IGraphicBufferConsumer> consumer;
483 BufferQueue::createBufferQueue(&producer, &consumer,
484 new GraphicBufferAlloc());
486 sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i,
488 int32_t hwcId = allocateHwcDisplayId(type);
489 sp<DisplayDevice> hw = new DisplayDevice(this,
490 type, hwcId, mHwc->getFormat(hwcId), isSecure, token,
492 mRenderEngine->getEGLConfig());
493 if (i > DisplayDevice::DISPLAY_PRIMARY) {
494 // FIXME: currently we don't get blank/unblank requests
495 // for displays other than the main display, so we always
496 // assume a connected display is unblanked.
497 ALOGD("marking display %zu as acquired/unblanked", i);
498 hw->setPowerMode(HWC_POWER_MODE_NORMAL);
500 mDisplays.add(token, hw);
504 // make the GLContext current so that we can create textures when creating Layers
505 // (which may happens before we render something)
506 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
508 mEventControlThread = new EventControlThread(this);
509 mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
511 // set a fake vsync period if there is no HWComposer
512 if (mHwc->initCheck() != NO_ERROR) {
513 mPrimaryDispSync.setPeriod(16666667);
516 // initialize our drawing state
517 mDrawingState = mCurrentState;
519 // set initial conditions (e.g. unblank default device)
520 initializeDisplays();
522 // start boot animation
526 int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
527 return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
528 type : mHwc->allocateDisplayId();
531 void SurfaceFlinger::startBootAnim() {
532 // start boot animation
533 property_set("service.bootanim.exit", "0");
534 property_set("ctl.start", "bootanim");
537 size_t SurfaceFlinger::getMaxTextureSize() const {
538 return mRenderEngine->getMaxTextureSize();
541 size_t SurfaceFlinger::getMaxViewportDims() const {
542 return mRenderEngine->getMaxViewportDims();
545 // ----------------------------------------------------------------------------
547 bool SurfaceFlinger::authenticateSurfaceTexture(
548 const sp<IGraphicBufferProducer>& bufferProducer) const {
549 Mutex::Autolock _l(mStateLock);
550 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
551 return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
554 status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& display,
555 Vector<DisplayInfo>* configs) {
556 if ((configs == NULL) || (display.get() == NULL)) {
561 return NAME_NOT_FOUND;
563 int32_t type = NAME_NOT_FOUND;
564 for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
565 if (display == mBuiltinDisplays[i]) {
575 // TODO: Not sure if display density should handled by SF any longer
577 static int getDensityFromProperty(char const* propName) {
578 char property[PROPERTY_VALUE_MAX];
580 if (property_get(propName, property, NULL) > 0) {
581 density = atoi(property);
586 static int getEmuDensity() {
587 return getDensityFromProperty("qemu.sf.lcd_density"); }
588 static int getBuildDensity() {
589 return getDensityFromProperty("ro.sf.lcd_density"); }
594 const Vector<HWComposer::DisplayConfig>& hwConfigs =
595 getHwComposer().getConfigs(type);
596 for (size_t c = 0; c < hwConfigs.size(); ++c) {
597 const HWComposer::DisplayConfig& hwConfig = hwConfigs[c];
598 DisplayInfo info = DisplayInfo();
600 float xdpi = hwConfig.xdpi;
601 float ydpi = hwConfig.ydpi;
603 if (type == DisplayDevice::DISPLAY_PRIMARY) {
604 // The density of the device is provided by a build property
605 float density = Density::getBuildDensity() / 160.0f;
607 // the build doesn't provide a density -- this is wrong!
609 ALOGE("ro.sf.lcd_density must be defined as a build property");
610 density = xdpi / 160.0f;
612 if (Density::getEmuDensity()) {
613 // if "qemu.sf.lcd_density" is specified, it overrides everything
614 xdpi = ydpi = density = Density::getEmuDensity();
617 info.density = density;
619 // TODO: this needs to go away (currently needed only by webkit)
620 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
621 info.orientation = hw->getOrientation();
623 // TODO: where should this value come from?
624 static const int TV_DENSITY = 213;
625 info.density = TV_DENSITY / 160.0f;
626 info.orientation = 0;
629 info.w = hwConfig.width;
630 info.h = hwConfig.height;
633 info.fps = float(1e9 / hwConfig.refresh);
634 info.appVsyncOffset = VSYNC_EVENT_PHASE_OFFSET_NS;
635 info.colorTransform = hwConfig.colorTransform;
637 // This is how far in advance a buffer must be queued for
638 // presentation at a given time. If you want a buffer to appear
639 // on the screen at time N, you must submit the buffer before
640 // (N - presentationDeadline).
642 // Normally it's one full refresh period (to give SF a chance to
643 // latch the buffer), but this can be reduced by configuring a
644 // DispSync offset. Any additional delays introduced by the hardware
645 // composer or panel must be accounted for here.
647 // We add an additional 1ms to allow for processing time and
648 // differences between the ideal and actual refresh rate.
649 info.presentationDeadline =
650 hwConfig.refresh - SF_VSYNC_EVENT_PHASE_OFFSET_NS + 1000000;
652 // All non-virtual displays are currently considered secure.
655 configs->push_back(info);
661 status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>& /* display */,
662 DisplayStatInfo* stats) {
667 // FIXME for now we always return stats for the primary display
668 memset(stats, 0, sizeof(*stats));
669 stats->vsyncTime = mPrimaryDispSync.computeNextRefresh(0);
670 stats->vsyncPeriod = mPrimaryDispSync.getPeriod();
674 int SurfaceFlinger::getActiveConfig(const sp<IBinder>& display) {
675 sp<DisplayDevice> device(getDisplayDevice(display));
676 if (device != NULL) {
677 return device->getActiveConfig();
682 void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode) {
683 ALOGD("Set active config mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
685 int32_t type = hw->getDisplayType();
686 int currentMode = hw->getActiveConfig();
688 if (mode == currentMode) {
689 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
693 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
694 ALOGW("Trying to set config for virtual display");
698 hw->setActiveConfig(mode);
699 getHwComposer().setActiveConfig(type, mode);
702 status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& display, int mode) {
703 class MessageSetActiveConfig: public MessageBase {
704 SurfaceFlinger& mFlinger;
705 sp<IBinder> mDisplay;
708 MessageSetActiveConfig(SurfaceFlinger& flinger, const sp<IBinder>& disp,
710 mFlinger(flinger), mDisplay(disp) { mMode = mode; }
711 virtual bool handler() {
712 Vector<DisplayInfo> configs;
713 mFlinger.getDisplayConfigs(mDisplay, &configs);
714 if (mMode < 0 || mMode >= static_cast<int>(configs.size())) {
715 ALOGE("Attempt to set active config = %d for display with %zu configs",
716 mMode, configs.size());
718 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
720 ALOGE("Attempt to set active config = %d for null display %p",
721 mMode, mDisplay.get());
722 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
723 ALOGW("Attempt to set active config = %d for virtual display",
726 mFlinger.setActiveConfigInternal(hw, mMode);
731 sp<MessageBase> msg = new MessageSetActiveConfig(*this, display, mode);
732 postMessageSync(msg);
736 status_t SurfaceFlinger::clearAnimationFrameStats() {
737 Mutex::Autolock _l(mStateLock);
738 mAnimFrameTracker.clearStats();
742 status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
743 Mutex::Autolock _l(mStateLock);
744 mAnimFrameTracker.getStats(outStats);
748 // ----------------------------------------------------------------------------
750 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
751 return mEventThread->createEventConnection();
754 // ----------------------------------------------------------------------------
756 void SurfaceFlinger::waitForEvent() {
757 mEventQueue.waitMessage();
760 void SurfaceFlinger::signalTransaction() {
761 mEventQueue.invalidate();
764 void SurfaceFlinger::signalLayerUpdate() {
765 mEventQueue.invalidate();
768 void SurfaceFlinger::signalRefresh() {
769 mEventQueue.refresh();
772 status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
773 nsecs_t reltime, uint32_t /* flags */) {
774 return mEventQueue.postMessage(msg, reltime);
777 status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
778 nsecs_t reltime, uint32_t /* flags */) {
779 status_t res = mEventQueue.postMessage(msg, reltime);
780 if (res == NO_ERROR) {
786 void SurfaceFlinger::run() {
792 void SurfaceFlinger::enableHardwareVsync() {
793 Mutex::Autolock _l(mHWVsyncLock);
794 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
795 mPrimaryDispSync.beginResync();
796 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
797 mEventControlThread->setVsyncEnabled(true);
798 mPrimaryHWVsyncEnabled = true;
802 void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
803 Mutex::Autolock _l(mHWVsyncLock);
806 mHWVsyncAvailable = true;
807 } else if (!mHWVsyncAvailable) {
808 ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
812 const nsecs_t period =
813 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
815 mPrimaryDispSync.reset();
816 mPrimaryDispSync.setPeriod(period);
818 if (!mPrimaryHWVsyncEnabled) {
819 mPrimaryDispSync.beginResync();
820 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
821 mEventControlThread->setVsyncEnabled(true);
822 mPrimaryHWVsyncEnabled = true;
826 void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
827 Mutex::Autolock _l(mHWVsyncLock);
828 if (mPrimaryHWVsyncEnabled) {
829 //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
830 mEventControlThread->setVsyncEnabled(false);
831 mPrimaryDispSync.endResync();
832 mPrimaryHWVsyncEnabled = false;
834 if (makeUnavailable) {
835 mHWVsyncAvailable = false;
839 void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
840 bool needsHwVsync = false;
842 { // Scope for the lock
843 Mutex::Autolock _l(mHWVsyncLock);
844 if (type == 0 && mPrimaryHWVsyncEnabled) {
845 needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
850 enableHardwareVsync();
852 disableHardwareVsync(false);
856 void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
857 if (mEventThread == NULL) {
858 // This is a temporary workaround for b/7145521. A non-null pointer
859 // does not mean EventThread has finished initializing, so this
860 // is not a correct fix.
861 ALOGW("WARNING: EventThread not started, ignoring hotplug");
865 if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
866 Mutex::Autolock _l(mStateLock);
868 createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
870 mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
871 mBuiltinDisplays[type].clear();
873 setTransactionFlags(eDisplayTransactionNeeded);
875 // Defer EventThread notification until SF has updated mDisplays.
879 void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
881 getHwComposer().eventControl(disp, event, enabled);
884 void SurfaceFlinger::onMessageReceived(int32_t what) {
887 case MessageQueue::TRANSACTION: {
888 handleMessageTransaction();
891 case MessageQueue::INVALIDATE: {
892 bool refreshNeeded = handleMessageTransaction();
893 refreshNeeded |= handleMessageInvalidate();
894 refreshNeeded |= mRepaintEverything;
896 // Signal a refresh if a transaction modified the window state,
897 // a new buffer was latched, or if HWC has requested a full
903 case MessageQueue::REFRESH: {
904 handleMessageRefresh();
910 bool SurfaceFlinger::handleMessageTransaction() {
911 uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
912 if (transactionFlags) {
913 handleTransaction(transactionFlags);
919 bool SurfaceFlinger::handleMessageInvalidate() {
921 return handlePageFlip();
924 void SurfaceFlinger::handleMessageRefresh() {
927 static nsecs_t previousExpectedPresent = 0;
928 nsecs_t expectedPresent = mPrimaryDispSync.computeNextRefresh(0);
929 static bool previousFrameMissed = false;
930 bool frameMissed = (expectedPresent == previousExpectedPresent);
931 if (frameMissed != previousFrameMissed) {
932 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
934 previousFrameMissed = frameMissed;
936 if (CC_UNLIKELY(mDropMissedFrames && frameMissed)) {
937 // Latch buffers, but don't send anything to HWC, then signal another
938 // wakeup for the next vsync
943 rebuildLayerStacks();
945 doDebugFlashRegions();
950 previousExpectedPresent = mPrimaryDispSync.computeNextRefresh(0);
953 void SurfaceFlinger::doDebugFlashRegions()
955 // is debugging enabled
956 if (CC_LIKELY(!mDebugRegion))
959 const bool repaintEverything = mRepaintEverything;
960 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
961 const sp<DisplayDevice>& hw(mDisplays[dpy]);
962 if (hw->isDisplayOn()) {
963 // transform the dirty region into this screen's coordinate space
964 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
965 if (!dirtyRegion.isEmpty()) {
966 // redraw the whole screen
967 doComposeSurfaces(hw, Region(hw->bounds()));
969 // and draw the dirty region
970 const int32_t height = hw->getHeight();
971 RenderEngine& engine(getRenderEngine());
972 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
974 hw->compositionComplete();
975 hw->swapBuffers(getHwComposer());
982 if (mDebugRegion > 1) {
983 usleep(mDebugRegion * 1000);
986 HWComposer& hwc(getHwComposer());
987 if (hwc.initCheck() == NO_ERROR) {
988 status_t err = hwc.prepare();
989 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
993 void SurfaceFlinger::preComposition()
995 bool needExtraInvalidate = false;
996 const LayerVector& layers(mDrawingState.layersSortedByZ);
997 const size_t count = layers.size();
998 for (size_t i=0 ; i<count ; i++) {
999 if (layers[i]->onPreComposition()) {
1000 needExtraInvalidate = true;
1003 if (needExtraInvalidate) {
1004 signalLayerUpdate();
1008 void SurfaceFlinger::postComposition()
1010 const LayerVector& layers(mDrawingState.layersSortedByZ);
1011 const size_t count = layers.size();
1012 for (size_t i=0 ; i<count ; i++) {
1013 layers[i]->onPostComposition();
1016 const HWComposer& hwc = getHwComposer();
1017 sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
1019 if (presentFence->isValid()) {
1020 if (mPrimaryDispSync.addPresentFence(presentFence)) {
1021 enableHardwareVsync();
1023 disableHardwareVsync(false);
1027 const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1028 if (kIgnorePresentFences) {
1029 if (hw->isDisplayOn()) {
1030 enableHardwareVsync();
1034 if (mAnimCompositionPending) {
1035 mAnimCompositionPending = false;
1037 if (presentFence->isValid()) {
1038 mAnimFrameTracker.setActualPresentFence(presentFence);
1040 // The HWC doesn't support present fences, so use the refresh
1041 // timestamp instead.
1042 nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
1043 mAnimFrameTracker.setActualPresentTime(presentTime);
1045 mAnimFrameTracker.advanceFrame();
1048 if (hw->getPowerMode() == HWC_POWER_MODE_OFF) {
1052 nsecs_t currentTime = systemTime();
1053 if (mHasPoweredOff) {
1054 mHasPoweredOff = false;
1056 nsecs_t period = mPrimaryDispSync.getPeriod();
1057 nsecs_t elapsedTime = currentTime - mLastSwapTime;
1058 size_t numPeriods = static_cast<size_t>(elapsedTime / period);
1059 if (numPeriods < NUM_BUCKETS - 1) {
1060 mFrameBuckets[numPeriods] += elapsedTime;
1062 mFrameBuckets[NUM_BUCKETS - 1] += elapsedTime;
1064 mTotalTime += elapsedTime;
1066 mLastSwapTime = currentTime;
1069 void SurfaceFlinger::rebuildLayerStacks() {
1070 // rebuild the visible layer list per screen
1071 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1073 mVisibleRegionsDirty = false;
1074 invalidateHwcGeometry();
1076 const LayerVector& layers(mDrawingState.layersSortedByZ);
1077 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1078 Region opaqueRegion;
1080 Vector< sp<Layer> > layersSortedByZ;
1081 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1082 const Transform& tr(hw->getTransform());
1083 const Rect bounds(hw->getBounds());
1084 if (hw->isDisplayOn()) {
1085 SurfaceFlinger::computeVisibleRegions(layers,
1086 hw->getLayerStack(), dirtyRegion, opaqueRegion);
1088 const size_t count = layers.size();
1089 for (size_t i=0 ; i<count ; i++) {
1090 const sp<Layer>& layer(layers[i]);
1091 const Layer::State& s(layer->getDrawingState());
1092 if (s.layerStack == hw->getLayerStack()) {
1093 Region drawRegion(tr.transform(
1094 layer->visibleNonTransparentRegion));
1095 drawRegion.andSelf(bounds);
1096 if (!drawRegion.isEmpty()) {
1097 layersSortedByZ.add(layer);
1102 hw->setVisibleLayersSortedByZ(layersSortedByZ);
1103 hw->undefinedRegion.set(bounds);
1104 hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1105 hw->dirtyRegion.orSelf(dirtyRegion);
1110 void SurfaceFlinger::setUpHWComposer() {
1111 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1112 bool dirty = !mDisplays[dpy]->getDirtyRegion(false).isEmpty();
1113 bool empty = mDisplays[dpy]->getVisibleLayersSortedByZ().size() == 0;
1114 bool wasEmpty = !mDisplays[dpy]->lastCompositionHadVisibleLayers;
1116 // If nothing has changed (!dirty), don't recompose.
1117 // If something changed, but we don't currently have any visible layers,
1118 // and didn't when we last did a composition, then skip it this time.
1119 // The second rule does two things:
1120 // - When all layers are removed from a display, we'll emit one black
1121 // frame, then nothing more until we get new layers.
1122 // - When a display is created with a private layer stack, we won't
1123 // emit any black frames until a layer is added to the layer stack.
1124 bool mustRecompose = dirty && !(empty && wasEmpty);
1126 ALOGV_IF(mDisplays[dpy]->getDisplayType() == DisplayDevice::DISPLAY_VIRTUAL,
1127 "dpy[%zu]: %s composition (%sdirty %sempty %swasEmpty)", dpy,
1128 mustRecompose ? "doing" : "skipping",
1131 wasEmpty ? "+" : "-");
1133 mDisplays[dpy]->beginFrame(mustRecompose);
1135 if (mustRecompose) {
1136 mDisplays[dpy]->lastCompositionHadVisibleLayers = !empty;
1140 HWComposer& hwc(getHwComposer());
1141 if (hwc.initCheck() == NO_ERROR) {
1142 // build the h/w work list
1143 if (CC_UNLIKELY(mHwWorkListDirty)) {
1144 mHwWorkListDirty = false;
1145 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1146 sp<const DisplayDevice> hw(mDisplays[dpy]);
1147 const int32_t id = hw->getHwcDisplayId();
1149 const Vector< sp<Layer> >& currentLayers(
1150 hw->getVisibleLayersSortedByZ());
1151 const size_t count = currentLayers.size();
1152 if (hwc.createWorkList(id, count) == NO_ERROR) {
1153 HWComposer::LayerListIterator cur = hwc.begin(id);
1154 const HWComposer::LayerListIterator end = hwc.end(id);
1155 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1156 const sp<Layer>& layer(currentLayers[i]);
1157 layer->setGeometry(hw, *cur);
1158 if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1167 // set the per-frame data
1168 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1169 sp<const DisplayDevice> hw(mDisplays[dpy]);
1170 const int32_t id = hw->getHwcDisplayId();
1172 const Vector< sp<Layer> >& currentLayers(
1173 hw->getVisibleLayersSortedByZ());
1174 const size_t count = currentLayers.size();
1175 HWComposer::LayerListIterator cur = hwc.begin(id);
1176 const HWComposer::LayerListIterator end = hwc.end(id);
1177 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1179 * update the per-frame h/w composer data for each layer
1180 * and build the transparent region of the FB
1182 const sp<Layer>& layer(currentLayers[i]);
1183 layer->setPerFrameData(hw, *cur);
1188 // If possible, attempt to use the cursor overlay on each display.
1189 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1190 sp<const DisplayDevice> hw(mDisplays[dpy]);
1191 const int32_t id = hw->getHwcDisplayId();
1193 const Vector< sp<Layer> >& currentLayers(
1194 hw->getVisibleLayersSortedByZ());
1195 const size_t count = currentLayers.size();
1196 HWComposer::LayerListIterator cur = hwc.begin(id);
1197 const HWComposer::LayerListIterator end = hwc.end(id);
1198 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1199 const sp<Layer>& layer(currentLayers[i]);
1200 if (layer->isPotentialCursor()) {
1201 cur->setIsCursorLayerHint();
1208 status_t err = hwc.prepare();
1209 ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1211 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1212 sp<const DisplayDevice> hw(mDisplays[dpy]);
1213 hw->prepareFrame(hwc);
1218 void SurfaceFlinger::doComposition() {
1220 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1221 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1222 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1223 if (hw->isDisplayOn()) {
1224 // transform the dirty region into this screen's coordinate space
1225 const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1227 // repaint the framebuffer (if needed)
1228 doDisplayComposition(hw, dirtyRegion);
1230 hw->dirtyRegion.clear();
1231 hw->flip(hw->swapRegion);
1232 hw->swapRegion.clear();
1234 // inform the h/w that we're done compositing
1235 hw->compositionComplete();
1240 void SurfaceFlinger::postFramebuffer()
1244 const nsecs_t now = systemTime();
1245 mDebugInSwapBuffers = now;
1247 HWComposer& hwc(getHwComposer());
1248 if (hwc.initCheck() == NO_ERROR) {
1249 if (!hwc.supportsFramebufferTarget()) {
1251 // "surface must be bound to the calling thread's current context,
1252 // for the current rendering API."
1253 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1258 // make the default display current because the VirtualDisplayDevice code cannot
1259 // deal with dequeueBuffer() being called outside of the composition loop; however
1260 // the code below can call glFlush() which is allowed (and does in some case) call
1262 getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1264 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1265 sp<const DisplayDevice> hw(mDisplays[dpy]);
1266 const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1267 hw->onSwapBuffersCompleted(hwc);
1268 const size_t count = currentLayers.size();
1269 int32_t id = hw->getHwcDisplayId();
1270 if (id >=0 && hwc.initCheck() == NO_ERROR) {
1271 HWComposer::LayerListIterator cur = hwc.begin(id);
1272 const HWComposer::LayerListIterator end = hwc.end(id);
1273 for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1274 currentLayers[i]->onLayerDisplayed(hw, &*cur);
1277 for (size_t i = 0; i < count; i++) {
1278 currentLayers[i]->onLayerDisplayed(hw, NULL);
1283 mLastSwapBufferTime = systemTime() - now;
1284 mDebugInSwapBuffers = 0;
1286 uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1287 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1292 void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1296 // here we keep a copy of the drawing state (that is the state that's
1297 // going to be overwritten by handleTransactionLocked()) outside of
1298 // mStateLock so that the side-effects of the State assignment
1299 // don't happen with mStateLock held (which can cause deadlocks).
1300 State drawingState(mDrawingState);
1302 Mutex::Autolock _l(mStateLock);
1303 const nsecs_t now = systemTime();
1304 mDebugInTransaction = now;
1306 // Here we're guaranteed that some transaction flags are set
1307 // so we can call handleTransactionLocked() unconditionally.
1308 // We call getTransactionFlags(), which will also clear the flags,
1309 // with mStateLock held to guarantee that mCurrentState won't change
1310 // until the transaction is committed.
1312 transactionFlags = getTransactionFlags(eTransactionMask);
1313 handleTransactionLocked(transactionFlags);
1315 mLastTransactionTime = systemTime() - now;
1316 mDebugInTransaction = 0;
1317 invalidateHwcGeometry();
1318 // here the transaction has been committed
1321 void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1323 const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1324 const size_t count = currentLayers.size();
1327 * Traversal of the children
1328 * (perform the transaction for each of them if needed)
1331 if (transactionFlags & eTraversalNeeded) {
1332 for (size_t i=0 ; i<count ; i++) {
1333 const sp<Layer>& layer(currentLayers[i]);
1334 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1335 if (!trFlags) continue;
1337 const uint32_t flags = layer->doTransaction(0);
1338 if (flags & Layer::eVisibleRegion)
1339 mVisibleRegionsDirty = true;
1344 * Perform display own transactions if needed
1347 if (transactionFlags & eDisplayTransactionNeeded) {
1348 // here we take advantage of Vector's copy-on-write semantics to
1349 // improve performance by skipping the transaction entirely when
1350 // know that the lists are identical
1351 const KeyedVector< wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1352 const KeyedVector< wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1353 if (!curr.isIdenticalTo(draw)) {
1354 mVisibleRegionsDirty = true;
1355 const size_t cc = curr.size();
1356 size_t dc = draw.size();
1358 // find the displays that were removed
1359 // (ie: in drawing state but not in current state)
1360 // also handle displays that changed
1361 // (ie: displays that are in both lists)
1362 for (size_t i=0 ; i<dc ; i++) {
1363 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1365 // in drawing state but not in current state
1366 if (!draw[i].isMainDisplay()) {
1367 // Call makeCurrent() on the primary display so we can
1368 // be sure that nothing associated with this display
1370 const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1371 defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1372 sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1374 hw->disconnect(getHwComposer());
1375 if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1376 mEventThread->onHotplugReceived(draw[i].type, false);
1377 mDisplays.removeItem(draw.keyAt(i));
1379 ALOGW("trying to remove the main display");
1382 // this display is in both lists. see if something changed.
1383 const DisplayDeviceState& state(curr[j]);
1384 const wp<IBinder>& display(curr.keyAt(j));
1385 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
1386 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
1387 if (state_binder != draw_binder) {
1388 // changing the surface is like destroying and
1389 // recreating the DisplayDevice, so we just remove it
1390 // from the drawing state, so that it get re-added
1392 sp<DisplayDevice> hw(getDisplayDevice(display));
1394 hw->disconnect(getHwComposer());
1395 mDisplays.removeItem(display);
1396 mDrawingState.displays.removeItemsAt(i);
1398 // at this point we must loop to the next item
1402 const sp<DisplayDevice> disp(getDisplayDevice(display));
1404 if (state.layerStack != draw[i].layerStack) {
1405 disp->setLayerStack(state.layerStack);
1407 if ((state.orientation != draw[i].orientation)
1408 || (state.viewport != draw[i].viewport)
1409 || (state.frame != draw[i].frame))
1411 disp->setProjection(state.orientation,
1412 state.viewport, state.frame);
1414 if (state.width != draw[i].width || state.height != draw[i].height) {
1415 disp->setDisplaySize(state.width, state.height);
1421 // find displays that were added
1422 // (ie: in current state but not in drawing state)
1423 for (size_t i=0 ; i<cc ; i++) {
1424 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1425 const DisplayDeviceState& state(curr[i]);
1427 sp<DisplaySurface> dispSurface;
1428 sp<IGraphicBufferProducer> producer;
1429 sp<IGraphicBufferProducer> bqProducer;
1430 sp<IGraphicBufferConsumer> bqConsumer;
1431 BufferQueue::createBufferQueue(&bqProducer, &bqConsumer,
1432 new GraphicBufferAlloc());
1434 int32_t hwcDisplayId = -1;
1435 if (state.isVirtualDisplay()) {
1436 // Virtual displays without a surface are dormant:
1437 // they have external state (layer stack, projection,
1438 // etc.) but no internal state (i.e. a DisplayDevice).
1439 if (state.surface != NULL) {
1442 int status = state.surface->query(
1443 NATIVE_WINDOW_WIDTH, &width);
1444 ALOGE_IF(status != NO_ERROR,
1445 "Unable to query width (%d)", status);
1447 status = state.surface->query(
1448 NATIVE_WINDOW_HEIGHT, &height);
1449 ALOGE_IF(status != NO_ERROR,
1450 "Unable to query height (%d)", status);
1451 if (MAX_VIRTUAL_DISPLAY_DIMENSION == 0 ||
1452 (width <= MAX_VIRTUAL_DISPLAY_DIMENSION &&
1453 height <= MAX_VIRTUAL_DISPLAY_DIMENSION)) {
1454 hwcDisplayId = allocateHwcDisplayId(state.type);
1457 sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1458 *mHwc, hwcDisplayId, state.surface,
1459 bqProducer, bqConsumer, state.displayName);
1465 ALOGE_IF(state.surface!=NULL,
1466 "adding a supported display, but rendering "
1467 "surface is provided (%p), ignoring it",
1468 state.surface.get());
1469 hwcDisplayId = allocateHwcDisplayId(state.type);
1470 // for supported (by hwc) displays we provide our
1471 // own rendering surface
1472 dispSurface = new FramebufferSurface(*mHwc, state.type,
1474 producer = bqProducer;
1477 const wp<IBinder>& display(curr.keyAt(i));
1478 if (dispSurface != NULL) {
1479 sp<DisplayDevice> hw = new DisplayDevice(this,
1480 state.type, hwcDisplayId,
1481 mHwc->getFormat(hwcDisplayId), state.isSecure,
1482 display, dispSurface, producer,
1483 mRenderEngine->getEGLConfig());
1484 hw->setLayerStack(state.layerStack);
1485 hw->setProjection(state.orientation,
1486 state.viewport, state.frame);
1487 hw->setDisplayName(state.displayName);
1488 mDisplays.add(display, hw);
1489 if (state.isVirtualDisplay()) {
1490 if (hwcDisplayId >= 0) {
1491 mHwc->setVirtualDisplayProperties(hwcDisplayId,
1492 hw->getWidth(), hw->getHeight(),
1496 mEventThread->onHotplugReceived(state.type, true);
1504 if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1505 // The transform hint might have changed for some layers
1506 // (either because a display has changed, or because a layer
1509 // Walk through all the layers in currentLayers,
1510 // and update their transform hint.
1512 // If a layer is visible only on a single display, then that
1513 // display is used to calculate the hint, otherwise we use the
1516 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1517 // the hint is set before we acquire a buffer from the surface texture.
1519 // NOTE: layer transactions have taken place already, so we use their
1520 // drawing state. However, SurfaceFlinger's own transaction has not
1521 // happened yet, so we must use the current state layer list
1522 // (soon to become the drawing state list).
1524 sp<const DisplayDevice> disp;
1525 uint32_t currentlayerStack = 0;
1526 for (size_t i=0; i<count; i++) {
1527 // NOTE: we rely on the fact that layers are sorted by
1528 // layerStack first (so we don't have to traverse the list
1529 // of displays for every layer).
1530 const sp<Layer>& layer(currentLayers[i]);
1531 uint32_t layerStack = layer->getDrawingState().layerStack;
1532 if (i==0 || currentlayerStack != layerStack) {
1533 currentlayerStack = layerStack;
1534 // figure out if this layerstack is mirrored
1535 // (more than one display) if so, pick the default display,
1536 // if not, pick the only display it's on.
1538 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1539 sp<const DisplayDevice> hw(mDisplays[dpy]);
1540 if (hw->getLayerStack() == currentlayerStack) {
1551 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1552 // redraw after transform hint changes. See bug 8508397.
1554 // could be null when this layer is using a layerStack
1555 // that is not visible on any display. Also can occur at
1556 // screen off/on times.
1557 disp = getDefaultDisplayDevice();
1559 layer->updateTransformHint(disp);
1565 * Perform our own transaction if needed
1568 const LayerVector& layers(mDrawingState.layersSortedByZ);
1569 if (currentLayers.size() > layers.size()) {
1570 // layers have been added
1571 mVisibleRegionsDirty = true;
1574 // some layers might have been removed, so
1575 // we need to update the regions they're exposing.
1576 if (mLayersRemoved) {
1577 mLayersRemoved = false;
1578 mVisibleRegionsDirty = true;
1579 const size_t count = layers.size();
1580 for (size_t i=0 ; i<count ; i++) {
1581 const sp<Layer>& layer(layers[i]);
1582 if (currentLayers.indexOf(layer) < 0) {
1583 // this layer is not visible anymore
1584 // TODO: we could traverse the tree from front to back and
1585 // compute the actual visible region
1586 // TODO: we could cache the transformed region
1587 const Layer::State& s(layer->getDrawingState());
1588 Region visibleReg = s.transform.transform(
1589 Region(Rect(s.active.w, s.active.h)));
1590 invalidateLayerStack(s.layerStack, visibleReg);
1595 commitTransaction();
1597 updateCursorAsync();
1600 void SurfaceFlinger::updateCursorAsync()
1602 HWComposer& hwc(getHwComposer());
1603 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1604 sp<const DisplayDevice> hw(mDisplays[dpy]);
1605 const int32_t id = hw->getHwcDisplayId();
1609 const Vector< sp<Layer> >& currentLayers(
1610 hw->getVisibleLayersSortedByZ());
1611 const size_t count = currentLayers.size();
1612 HWComposer::LayerListIterator cur = hwc.begin(id);
1613 const HWComposer::LayerListIterator end = hwc.end(id);
1614 for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1615 if (cur->getCompositionType() != HWC_CURSOR_OVERLAY) {
1618 const sp<Layer>& layer(currentLayers[i]);
1619 Rect cursorPos = layer->getPosition(hw);
1620 hwc.setCursorPositionAsync(id, cursorPos);
1626 void SurfaceFlinger::commitTransaction()
1628 if (!mLayersPendingRemoval.isEmpty()) {
1629 // Notify removed layers now that they can't be drawn from
1630 for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1631 mLayersPendingRemoval[i]->onRemoved();
1633 mLayersPendingRemoval.clear();
1636 // If this transaction is part of a window animation then the next frame
1637 // we composite should be considered an animation as well.
1638 mAnimCompositionPending = mAnimTransactionPending;
1640 mDrawingState = mCurrentState;
1641 mTransactionPending = false;
1642 mAnimTransactionPending = false;
1643 mTransactionCV.broadcast();
1646 void SurfaceFlinger::computeVisibleRegions(
1647 const LayerVector& currentLayers, uint32_t layerStack,
1648 Region& outDirtyRegion, Region& outOpaqueRegion)
1652 Region aboveOpaqueLayers;
1653 Region aboveCoveredLayers;
1656 outDirtyRegion.clear();
1658 size_t i = currentLayers.size();
1660 const sp<Layer>& layer = currentLayers[i];
1662 // start with the whole surface at its current location
1663 const Layer::State& s(layer->getDrawingState());
1665 // only consider the layers on the given layer stack
1666 if (s.layerStack != layerStack)
1670 * opaqueRegion: area of a surface that is fully opaque.
1672 Region opaqueRegion;
1675 * visibleRegion: area of a surface that is visible on screen
1676 * and not fully transparent. This is essentially the layer's
1677 * footprint minus the opaque regions above it.
1678 * Areas covered by a translucent surface are considered visible.
1680 Region visibleRegion;
1683 * coveredRegion: area of a surface that is covered by all
1684 * visible regions above it (which includes the translucent areas).
1686 Region coveredRegion;
1689 * transparentRegion: area of a surface that is hinted to be completely
1690 * transparent. This is only used to tell when the layer has no visible
1691 * non-transparent regions and can be removed from the layer list. It
1692 * does not affect the visibleRegion of this layer or any layers
1693 * beneath it. The hint may not be correct if apps don't respect the
1694 * SurfaceView restrictions (which, sadly, some don't).
1696 Region transparentRegion;
1699 // handle hidden surfaces by setting the visible region to empty
1700 if (CC_LIKELY(layer->isVisible())) {
1701 const bool translucent = !layer->isOpaque(s);
1702 Rect bounds(s.transform.transform(layer->computeBounds()));
1703 visibleRegion.set(bounds);
1704 if (!visibleRegion.isEmpty()) {
1705 // Remove the transparent area from the visible region
1707 const Transform tr(s.transform);
1708 if (tr.transformed()) {
1709 if (tr.preserveRects()) {
1710 // transform the transparent region
1711 transparentRegion = tr.transform(s.activeTransparentRegion);
1713 // transformation too complex, can't do the
1714 // transparent region optimization.
1715 transparentRegion.clear();
1718 transparentRegion = s.activeTransparentRegion;
1722 // compute the opaque region
1723 const int32_t layerOrientation = s.transform.getOrientation();
1724 if (s.alpha==255 && !translucent &&
1725 ((layerOrientation & Transform::ROT_INVALID) == false)) {
1726 // the opaque region is the layer's footprint
1727 opaqueRegion = visibleRegion;
1732 // Clip the covered region to the visible region
1733 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1735 // Update aboveCoveredLayers for next (lower) layer
1736 aboveCoveredLayers.orSelf(visibleRegion);
1738 // subtract the opaque region covered by the layers above us
1739 visibleRegion.subtractSelf(aboveOpaqueLayers);
1741 // compute this layer's dirty region
1742 if (layer->contentDirty) {
1743 // we need to invalidate the whole region
1744 dirty = visibleRegion;
1745 // as well, as the old visible region
1746 dirty.orSelf(layer->visibleRegion);
1747 layer->contentDirty = false;
1749 /* compute the exposed region:
1750 * the exposed region consists of two components:
1751 * 1) what's VISIBLE now and was COVERED before
1752 * 2) what's EXPOSED now less what was EXPOSED before
1754 * note that (1) is conservative, we start with the whole
1755 * visible region but only keep what used to be covered by
1756 * something -- which mean it may have been exposed.
1758 * (2) handles areas that were not covered by anything but got
1759 * exposed because of a resize.
1761 const Region newExposed = visibleRegion - coveredRegion;
1762 const Region oldVisibleRegion = layer->visibleRegion;
1763 const Region oldCoveredRegion = layer->coveredRegion;
1764 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1765 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1767 dirty.subtractSelf(aboveOpaqueLayers);
1769 // accumulate to the screen dirty region
1770 outDirtyRegion.orSelf(dirty);
1772 // Update aboveOpaqueLayers for next (lower) layer
1773 aboveOpaqueLayers.orSelf(opaqueRegion);
1775 // Store the visible region in screen space
1776 layer->setVisibleRegion(visibleRegion);
1777 layer->setCoveredRegion(coveredRegion);
1778 layer->setVisibleNonTransparentRegion(
1779 visibleRegion.subtract(transparentRegion));
1782 outOpaqueRegion = aboveOpaqueLayers;
1785 void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1786 const Region& dirty) {
1787 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1788 const sp<DisplayDevice>& hw(mDisplays[dpy]);
1789 if (hw->getLayerStack() == layerStack) {
1790 hw->dirtyRegion.orSelf(dirty);
1795 bool SurfaceFlinger::handlePageFlip()
1799 bool visibleRegions = false;
1800 const LayerVector& layers(mDrawingState.layersSortedByZ);
1801 bool frameQueued = false;
1803 // Store the set of layers that need updates. This set must not change as
1804 // buffers are being latched, as this could result in a deadlock.
1805 // Example: Two producers share the same command stream and:
1806 // 1.) Layer 0 is latched
1807 // 2.) Layer 0 gets a new frame
1808 // 2.) Layer 1 gets a new frame
1809 // 3.) Layer 1 is latched.
1810 // Display is now waiting on Layer 1's frame, which is behind layer 0's
1811 // second frame. But layer 0's second frame could be waiting on display.
1812 Vector<Layer*> layersWithQueuedFrames;
1813 for (size_t i = 0, count = layers.size(); i<count ; i++) {
1814 const sp<Layer>& layer(layers[i]);
1815 if (layer->hasQueuedFrame()) {
1817 if (layer->shouldPresentNow(mPrimaryDispSync)) {
1818 layersWithQueuedFrames.push_back(layer.get());
1820 layer->useEmptyDamage();
1823 layer->useEmptyDamage();
1826 for (size_t i = 0, count = layersWithQueuedFrames.size() ; i<count ; i++) {
1827 Layer* layer = layersWithQueuedFrames[i];
1828 const Region dirty(layer->latchBuffer(visibleRegions));
1829 layer->useSurfaceDamage();
1830 const Layer::State& s(layer->getDrawingState());
1831 invalidateLayerStack(s.layerStack, dirty);
1834 mVisibleRegionsDirty |= visibleRegions;
1836 // If we will need to wake up at some time in the future to deal with a
1837 // queued frame that shouldn't be displayed during this vsync period, wake
1838 // up during the next vsync period to check again.
1839 if (frameQueued && layersWithQueuedFrames.empty()) {
1840 signalLayerUpdate();
1843 // Only continue with the refresh if there is actually new work to do
1844 return !layersWithQueuedFrames.empty();
1847 void SurfaceFlinger::invalidateHwcGeometry()
1849 mHwWorkListDirty = true;
1853 void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1854 const Region& inDirtyRegion)
1856 // We only need to actually compose the display if:
1857 // 1) It is being handled by hardware composer, which may need this to
1858 // keep its virtual display state machine in sync, or
1859 // 2) There is work to be done (the dirty region isn't empty)
1860 bool isHwcDisplay = hw->getHwcDisplayId() >= 0;
1861 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
1865 Region dirtyRegion(inDirtyRegion);
1867 // compute the invalid region
1868 hw->swapRegion.orSelf(dirtyRegion);
1870 uint32_t flags = hw->getFlags();
1871 if (flags & DisplayDevice::SWAP_RECTANGLE) {
1872 // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1873 // takes a rectangle, we must make sure to update that whole
1874 // rectangle in that case
1875 dirtyRegion.set(hw->swapRegion.bounds());
1877 if (flags & DisplayDevice::PARTIAL_UPDATES) {
1878 // We need to redraw the rectangle that will be updated
1879 // (pushed to the framebuffer).
1880 // This is needed because PARTIAL_UPDATES only takes one
1881 // rectangle instead of a region (see DisplayDevice::flip())
1882 dirtyRegion.set(hw->swapRegion.bounds());
1884 // we need to redraw everything (the whole screen)
1885 dirtyRegion.set(hw->bounds());
1886 hw->swapRegion = dirtyRegion;
1890 if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1891 if (!doComposeSurfaces(hw, dirtyRegion)) return;
1893 RenderEngine& engine(getRenderEngine());
1894 mat4 colorMatrix = mColorMatrix;
1896 colorMatrix = colorMatrix * mDaltonizer();
1898 mat4 oldMatrix = engine.setupColorTransform(colorMatrix);
1899 doComposeSurfaces(hw, dirtyRegion);
1900 engine.setupColorTransform(oldMatrix);
1903 // update the swap region and clear the dirty region
1904 hw->swapRegion.orSelf(dirtyRegion);
1906 // swap buffers (presentation)
1907 hw->swapBuffers(getHwComposer());
1910 bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1912 RenderEngine& engine(getRenderEngine());
1913 const int32_t id = hw->getHwcDisplayId();
1914 HWComposer& hwc(getHwComposer());
1915 HWComposer::LayerListIterator cur = hwc.begin(id);
1916 const HWComposer::LayerListIterator end = hwc.end(id);
1918 bool hasGlesComposition = hwc.hasGlesComposition(id);
1919 if (hasGlesComposition) {
1920 if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1921 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1922 hw->getDisplayName().string());
1923 eglMakeCurrent(mEGLDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
1924 if(!getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext)) {
1925 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
1930 // Never touch the framebuffer if we don't have any framebuffer layers
1931 const bool hasHwcComposition = hwc.hasHwcComposition(id);
1932 if (hasHwcComposition) {
1933 // when using overlays, we assume a fully transparent framebuffer
1934 // NOTE: we could reduce how much we need to clear, for instance
1935 // remove where there are opaque FB layers. however, on some
1936 // GPUs doing a "clean slate" clear might be more efficient.
1937 // We'll revisit later if needed.
1938 engine.clearWithColor(0, 0, 0, 0);
1940 // we start with the whole screen area
1941 const Region bounds(hw->getBounds());
1943 // we remove the scissor part
1944 // we're left with the letterbox region
1945 // (common case is that letterbox ends-up being empty)
1946 const Region letterbox(bounds.subtract(hw->getScissor()));
1948 // compute the area to clear
1949 Region region(hw->undefinedRegion.merge(letterbox));
1951 // but limit it to the dirty region
1952 region.andSelf(dirty);
1954 // screen is already cleared here
1955 if (!region.isEmpty()) {
1956 // can happen with SurfaceView
1957 drawWormhole(hw, region);
1961 if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1962 // just to be on the safe side, we don't set the
1963 // scissor on the main display. It should never be needed
1964 // anyways (though in theory it could since the API allows it).
1965 const Rect& bounds(hw->getBounds());
1966 const Rect& scissor(hw->getScissor());
1967 if (scissor != bounds) {
1968 // scissor doesn't match the screen's dimensions, so we
1969 // need to clear everything outside of it and enable
1970 // the GL scissor so we don't draw anything where we shouldn't
1972 // enable scissor for this frame
1973 const uint32_t height = hw->getHeight();
1974 engine.setScissor(scissor.left, height - scissor.bottom,
1975 scissor.getWidth(), scissor.getHeight());
1981 * and then, render the layers targeted at the framebuffer
1984 const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1985 const size_t count = layers.size();
1986 const Transform& tr = hw->getTransform();
1988 // we're using h/w composer
1989 for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1990 const sp<Layer>& layer(layers[i]);
1991 const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1992 if (!clip.isEmpty()) {
1993 switch (cur->getCompositionType()) {
1994 case HWC_CURSOR_OVERLAY:
1996 const Layer::State& state(layer->getDrawingState());
1997 if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1999 && layer->isOpaque(state) && (state.alpha == 0xFF)
2000 && hasGlesComposition) {
2001 // never clear the very first layer since we're
2002 // guaranteed the FB is already cleared
2003 layer->clearWithOpenGL(hw, clip);
2007 case HWC_FRAMEBUFFER: {
2008 layer->draw(hw, clip);
2011 case HWC_FRAMEBUFFER_TARGET: {
2012 // this should not happen as the iterator shouldn't
2013 // let us get there.
2014 ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%zu)", i);
2019 layer->setAcquireFence(hw, *cur);
2022 // we're not using h/w composer
2023 for (size_t i=0 ; i<count ; ++i) {
2024 const sp<Layer>& layer(layers[i]);
2025 const Region clip(dirty.intersect(
2026 tr.transform(layer->visibleRegion)));
2027 if (!clip.isEmpty()) {
2028 layer->draw(hw, clip);
2033 // disable scissor at the end of the frame
2034 engine.disableScissor();
2038 void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
2039 const int32_t height = hw->getHeight();
2040 RenderEngine& engine(getRenderEngine());
2041 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
2044 status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
2045 const sp<IBinder>& handle,
2046 const sp<IGraphicBufferProducer>& gbc,
2047 const sp<Layer>& lbc)
2049 // add this layer to the current state list
2051 Mutex::Autolock _l(mStateLock);
2052 if (mCurrentState.layersSortedByZ.size() >= MAX_LAYERS) {
2055 mCurrentState.layersSortedByZ.add(lbc);
2056 mGraphicBufferProducerList.add(IInterface::asBinder(gbc));
2059 // attach this layer to the client
2060 client->attachLayer(handle, lbc);
2065 status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
2066 Mutex::Autolock _l(mStateLock);
2067 ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
2069 mLayersPendingRemoval.push(layer);
2070 mLayersRemoved = true;
2071 setTransactionFlags(eTransactionNeeded);
2074 return status_t(index);
2077 uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t /* flags */) {
2078 return android_atomic_release_load(&mTransactionFlags);
2081 uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
2082 return android_atomic_and(~flags, &mTransactionFlags) & flags;
2085 uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
2086 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
2087 if ((old & flags)==0) { // wake the server up
2088 signalTransaction();
2093 void SurfaceFlinger::setTransactionState(
2094 const Vector<ComposerState>& state,
2095 const Vector<DisplayState>& displays,
2099 Mutex::Autolock _l(mStateLock);
2100 uint32_t transactionFlags = 0;
2102 if (flags & eAnimation) {
2103 // For window updates that are part of an animation we must wait for
2104 // previous animation "frames" to be handled.
2105 while (mAnimTransactionPending) {
2106 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2107 if (CC_UNLIKELY(err != NO_ERROR)) {
2108 // just in case something goes wrong in SF, return to the
2109 // caller after a few seconds.
2110 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2111 "waiting for previous animation frame");
2112 mAnimTransactionPending = false;
2118 size_t count = displays.size();
2119 for (size_t i=0 ; i<count ; i++) {
2120 const DisplayState& s(displays[i]);
2121 transactionFlags |= setDisplayStateLocked(s);
2124 count = state.size();
2125 for (size_t i=0 ; i<count ; i++) {
2126 const ComposerState& s(state[i]);
2127 // Here we need to check that the interface we're given is indeed
2128 // one of our own. A malicious client could give us a NULL
2129 // IInterface, or one of its own or even one of our own but a
2130 // different type. All these situations would cause us to crash.
2132 // NOTE: it would be better to use RTTI as we could directly check
2133 // that we have a Client*. however, RTTI is disabled in Android.
2134 if (s.client != NULL) {
2135 sp<IBinder> binder = IInterface::asBinder(s.client);
2136 if (binder != NULL) {
2137 String16 desc(binder->getInterfaceDescriptor());
2138 if (desc == ISurfaceComposerClient::descriptor) {
2139 sp<Client> client( static_cast<Client *>(s.client.get()) );
2140 transactionFlags |= setClientStateLocked(client, s.state);
2146 if (transactionFlags) {
2147 // this triggers the transaction
2148 setTransactionFlags(transactionFlags);
2150 // if this is a synchronous transaction, wait for it to take effect
2151 // before returning.
2152 if (flags & eSynchronous) {
2153 mTransactionPending = true;
2155 if (flags & eAnimation) {
2156 mAnimTransactionPending = true;
2158 while (mTransactionPending) {
2159 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2160 if (CC_UNLIKELY(err != NO_ERROR)) {
2161 // just in case something goes wrong in SF, return to the
2162 // called after a few seconds.
2163 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
2164 mTransactionPending = false;
2171 uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
2173 ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
2178 DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
2179 if (disp.isValid()) {
2180 const uint32_t what = s.what;
2181 if (what & DisplayState::eSurfaceChanged) {
2182 if (IInterface::asBinder(disp.surface) != IInterface::asBinder(s.surface)) {
2183 disp.surface = s.surface;
2184 flags |= eDisplayTransactionNeeded;
2187 if (what & DisplayState::eLayerStackChanged) {
2188 if (disp.layerStack != s.layerStack) {
2189 disp.layerStack = s.layerStack;
2190 flags |= eDisplayTransactionNeeded;
2193 if (what & DisplayState::eDisplayProjectionChanged) {
2194 if (disp.orientation != s.orientation) {
2195 disp.orientation = s.orientation;
2196 flags |= eDisplayTransactionNeeded;
2198 if (disp.frame != s.frame) {
2199 disp.frame = s.frame;
2200 flags |= eDisplayTransactionNeeded;
2202 if (disp.viewport != s.viewport) {
2203 disp.viewport = s.viewport;
2204 flags |= eDisplayTransactionNeeded;
2207 if (what & DisplayState::eDisplaySizeChanged) {
2208 if (disp.width != s.width) {
2209 disp.width = s.width;
2210 flags |= eDisplayTransactionNeeded;
2212 if (disp.height != s.height) {
2213 disp.height = s.height;
2214 flags |= eDisplayTransactionNeeded;
2221 uint32_t SurfaceFlinger::setClientStateLocked(
2222 const sp<Client>& client,
2223 const layer_state_t& s)
2226 sp<Layer> layer(client->getLayerUser(s.surface));
2228 const uint32_t what = s.what;
2229 if (what & layer_state_t::ePositionChanged) {
2230 if (layer->setPosition(s.x, s.y))
2231 flags |= eTraversalNeeded;
2233 if (what & layer_state_t::eLayerChanged) {
2234 // NOTE: index needs to be calculated before we update the state
2235 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2236 if (layer->setLayer(s.z)) {
2237 mCurrentState.layersSortedByZ.removeAt(idx);
2238 mCurrentState.layersSortedByZ.add(layer);
2239 // we need traversal (state changed)
2240 // AND transaction (list changed)
2241 flags |= eTransactionNeeded|eTraversalNeeded;
2244 if (what & layer_state_t::eSizeChanged) {
2245 if (layer->setSize(s.w, s.h)) {
2246 flags |= eTraversalNeeded;
2249 if (what & layer_state_t::eAlphaChanged) {
2250 if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2251 flags |= eTraversalNeeded;
2253 if (what & layer_state_t::eMatrixChanged) {
2254 if (layer->setMatrix(s.matrix))
2255 flags |= eTraversalNeeded;
2257 if (what & layer_state_t::eTransparentRegionChanged) {
2258 if (layer->setTransparentRegionHint(s.transparentRegion))
2259 flags |= eTraversalNeeded;
2261 if (what & layer_state_t::eFlagsChanged) {
2262 if (layer->setFlags(s.flags, s.mask))
2263 flags |= eTraversalNeeded;
2265 if (what & layer_state_t::eCropChanged) {
2266 if (layer->setCrop(s.crop))
2267 flags |= eTraversalNeeded;
2269 if (what & layer_state_t::eLayerStackChanged) {
2270 // NOTE: index needs to be calculated before we update the state
2271 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2272 if (layer->setLayerStack(s.layerStack)) {
2273 mCurrentState.layersSortedByZ.removeAt(idx);
2274 mCurrentState.layersSortedByZ.add(layer);
2275 // we need traversal (state changed)
2276 // AND transaction (list changed)
2277 flags |= eTransactionNeeded|eTraversalNeeded;
2284 status_t SurfaceFlinger::createLayer(
2285 const String8& name,
2286 const sp<Client>& client,
2287 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2288 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2290 //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2291 if (int32_t(w|h) < 0) {
2292 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2297 status_t result = NO_ERROR;
2301 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2302 case ISurfaceComposerClient::eFXSurfaceNormal:
2303 result = createNormalLayer(client,
2304 name, w, h, flags, format,
2305 handle, gbp, &layer);
2307 case ISurfaceComposerClient::eFXSurfaceDim:
2308 result = createDimLayer(client,
2310 handle, gbp, &layer);
2317 if (result != NO_ERROR) {
2321 result = addClientLayer(client, *handle, *gbp, layer);
2322 if (result != NO_ERROR) {
2326 setTransactionFlags(eTransactionNeeded);
2330 status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2331 const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2332 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2334 // initialize the surfaces
2336 case PIXEL_FORMAT_TRANSPARENT:
2337 case PIXEL_FORMAT_TRANSLUCENT:
2338 format = PIXEL_FORMAT_RGBA_8888;
2340 case PIXEL_FORMAT_OPAQUE:
2341 format = PIXEL_FORMAT_RGBX_8888;
2345 *outLayer = new Layer(this, client, name, w, h, flags);
2346 status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2347 if (err == NO_ERROR) {
2348 *handle = (*outLayer)->getHandle();
2349 *gbp = (*outLayer)->getProducer();
2352 ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2356 status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2357 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2358 sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2360 *outLayer = new LayerDim(this, client, name, w, h, flags);
2361 *handle = (*outLayer)->getHandle();
2362 *gbp = (*outLayer)->getProducer();
2366 status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2368 // called by the window manager when it wants to remove a Layer
2369 status_t err = NO_ERROR;
2370 sp<Layer> l(client->getLayerUser(handle));
2372 err = removeLayer(l);
2373 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2374 "error removing layer=%p (%s)", l.get(), strerror(-err));
2379 status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2381 // called by ~LayerCleaner() when all references to the IBinder (handle)
2383 status_t err = NO_ERROR;
2384 sp<Layer> l(layer.promote());
2386 err = removeLayer(l);
2387 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2388 "error removing layer=%p (%s)", l.get(), strerror(-err));
2393 // ---------------------------------------------------------------------------
2395 void SurfaceFlinger::onInitializeDisplays() {
2396 // reset screen orientation and use primary layer stack
2397 Vector<ComposerState> state;
2398 Vector<DisplayState> displays;
2400 d.what = DisplayState::eDisplayProjectionChanged |
2401 DisplayState::eLayerStackChanged;
2402 d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2404 d.orientation = DisplayState::eOrientationDefault;
2405 d.frame.makeInvalid();
2406 d.viewport.makeInvalid();
2410 setTransactionState(state, displays, 0);
2411 setPowerModeInternal(getDisplayDevice(d.token), HWC_POWER_MODE_NORMAL);
2413 const nsecs_t period =
2414 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2415 mAnimFrameTracker.setDisplayRefreshPeriod(period);
2418 void SurfaceFlinger::initializeDisplays() {
2419 class MessageScreenInitialized : public MessageBase {
2420 SurfaceFlinger* flinger;
2422 MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2423 virtual bool handler() {
2424 flinger->onInitializeDisplays();
2428 sp<MessageBase> msg = new MessageScreenInitialized(this);
2429 postMessageAsync(msg); // we may be called from main thread, use async message
2432 void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& hw,
2434 ALOGD("Set power mode=%d, type=%d flinger=%p", mode, hw->getDisplayType(),
2436 int32_t type = hw->getDisplayType();
2437 int currentMode = hw->getPowerMode();
2439 if (mode == currentMode) {
2440 ALOGD("Screen type=%d is already mode=%d", hw->getDisplayType(), mode);
2444 hw->setPowerMode(mode);
2445 if (type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2446 ALOGW("Trying to set power mode for virtual display");
2450 if (currentMode == HWC_POWER_MODE_OFF) {
2451 getHwComposer().setPowerMode(type, mode);
2452 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2453 // FIXME: eventthread only knows about the main display right now
2454 mEventThread->onScreenAcquired();
2455 resyncToHardwareVsync(true);
2458 mVisibleRegionsDirty = true;
2459 mHasPoweredOff = true;
2460 repaintEverything();
2461 } else if (mode == HWC_POWER_MODE_OFF) {
2462 if (type == DisplayDevice::DISPLAY_PRIMARY) {
2463 disableHardwareVsync(true); // also cancels any in-progress resync
2465 // FIXME: eventthread only knows about the main display right now
2466 mEventThread->onScreenReleased();
2469 getHwComposer().setPowerMode(type, mode);
2470 mVisibleRegionsDirty = true;
2471 // from this point on, SF will stop drawing on this display
2473 getHwComposer().setPowerMode(type, mode);
2477 void SurfaceFlinger::setPowerMode(const sp<IBinder>& display, int mode) {
2478 class MessageSetPowerMode: public MessageBase {
2479 SurfaceFlinger& mFlinger;
2480 sp<IBinder> mDisplay;
2483 MessageSetPowerMode(SurfaceFlinger& flinger,
2484 const sp<IBinder>& disp, int mode) : mFlinger(flinger),
2485 mDisplay(disp) { mMode = mode; }
2486 virtual bool handler() {
2487 sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2489 ALOGE("Attempt to set power mode = %d for null display %p",
2490 mMode, mDisplay.get());
2491 } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2492 ALOGW("Attempt to set power mode = %d for virtual display",
2495 mFlinger.setPowerModeInternal(hw, mMode);
2500 sp<MessageBase> msg = new MessageSetPowerMode(*this, display, mode);
2501 postMessageSync(msg);
2504 // ---------------------------------------------------------------------------
2506 status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2510 IPCThreadState* ipc = IPCThreadState::self();
2511 const int pid = ipc->getCallingPid();
2512 const int uid = ipc->getCallingUid();
2513 if ((uid != AID_SHELL) &&
2514 !PermissionCache::checkPermission(sDump, pid, uid)) {
2515 result.appendFormat("Permission Denial: "
2516 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2518 // Try to get the main lock, but give up after one second
2519 // (this would indicate SF is stuck, but we want to be able to
2520 // print something in dumpsys).
2521 status_t err = mStateLock.timedLock(s2ns(1));
2522 bool locked = (err == NO_ERROR);
2524 result.appendFormat(
2525 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
2526 "dumping anyways (no locks held)\n", strerror(-err), err);
2529 bool dumpAll = true;
2531 size_t numArgs = args.size();
2533 if ((index < numArgs) &&
2534 (args[index] == String16("--list"))) {
2536 listLayersLocked(args, index, result);
2540 if ((index < numArgs) &&
2541 (args[index] == String16("--latency"))) {
2543 dumpStatsLocked(args, index, result);
2547 if ((index < numArgs) &&
2548 (args[index] == String16("--latency-clear"))) {
2550 clearStatsLocked(args, index, result);
2554 if ((index < numArgs) &&
2555 (args[index] == String16("--dispsync"))) {
2557 mPrimaryDispSync.dump(result);
2561 if ((index < numArgs) &&
2562 (args[index] == String16("--static-screen"))) {
2564 dumpStaticScreenStats(result);
2570 dumpAllLocked(args, index, result);
2574 mStateLock.unlock();
2577 write(fd, result.string(), result.size());
2581 void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
2582 size_t& /* index */, String8& result) const
2584 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2585 const size_t count = currentLayers.size();
2586 for (size_t i=0 ; i<count ; i++) {
2587 const sp<Layer>& layer(currentLayers[i]);
2588 result.appendFormat("%s\n", layer->getName().string());
2592 void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2593 String8& result) const
2596 if (index < args.size()) {
2597 name = String8(args[index]);
2601 const nsecs_t period =
2602 getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2603 result.appendFormat("%" PRId64 "\n", period);
2605 if (name.isEmpty()) {
2606 mAnimFrameTracker.dumpStats(result);
2608 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2609 const size_t count = currentLayers.size();
2610 for (size_t i=0 ; i<count ; i++) {
2611 const sp<Layer>& layer(currentLayers[i]);
2612 if (name == layer->getName()) {
2613 layer->dumpFrameStats(result);
2619 void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2620 String8& /* result */)
2623 if (index < args.size()) {
2624 name = String8(args[index]);
2628 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2629 const size_t count = currentLayers.size();
2630 for (size_t i=0 ; i<count ; i++) {
2631 const sp<Layer>& layer(currentLayers[i]);
2632 if (name.isEmpty() || (name == layer->getName())) {
2633 layer->clearFrameStats();
2637 mAnimFrameTracker.clearStats();
2640 // This should only be called from the main thread. Otherwise it would need
2641 // the lock and should use mCurrentState rather than mDrawingState.
2642 void SurfaceFlinger::logFrameStats() {
2643 const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2644 const size_t count = drawingLayers.size();
2645 for (size_t i=0 ; i<count ; i++) {
2646 const sp<Layer>& layer(drawingLayers[i]);
2647 layer->logFrameStats();
2650 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2653 /*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2655 static const char* config =
2657 #ifdef HAS_CONTEXT_PRIORITY
2658 " HAS_CONTEXT_PRIORITY"
2660 #ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2661 " NEVER_DEFAULT_TO_ASYNC_MODE"
2663 #ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2664 " TARGET_DISABLE_TRIPLE_BUFFERING"
2667 result.append(config);
2670 void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
2672 result.appendFormat("Static screen stats:\n");
2673 for (size_t b = 0; b < NUM_BUCKETS - 1; ++b) {
2674 float bucketTimeSec = mFrameBuckets[b] / 1e9;
2675 float percent = 100.0f *
2676 static_cast<float>(mFrameBuckets[b]) / mTotalTime;
2677 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
2678 b + 1, bucketTimeSec, percent);
2680 float bucketTimeSec = mFrameBuckets[NUM_BUCKETS - 1] / 1e9;
2681 float percent = 100.0f *
2682 static_cast<float>(mFrameBuckets[NUM_BUCKETS - 1]) / mTotalTime;
2683 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
2684 NUM_BUCKETS - 1, bucketTimeSec, percent);
2687 void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2688 String8& result) const
2690 bool colorize = false;
2691 if (index < args.size()
2692 && (args[index] == String16("--color"))) {
2697 Colorizer colorizer(colorize);
2699 // figure out if we're stuck somewhere
2700 const nsecs_t now = systemTime();
2701 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2702 const nsecs_t inTransaction(mDebugInTransaction);
2703 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2704 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2707 * Dump library configuration.
2710 colorizer.bold(result);
2711 result.append("Build configuration:");
2712 colorizer.reset(result);
2713 appendSfConfigString(result);
2714 appendUiConfigString(result);
2715 appendGuiConfigString(result);
2716 result.append("\n");
2718 colorizer.bold(result);
2719 result.append("Sync configuration: ");
2720 colorizer.reset(result);
2721 result.append(SyncFeatures::getInstance().toString());
2722 result.append("\n");
2724 colorizer.bold(result);
2725 result.append("DispSync configuration: ");
2726 colorizer.reset(result);
2727 result.appendFormat("app phase %" PRId64 " ns, sf phase %" PRId64 " ns, "
2728 "present offset %d ns (refresh %" PRId64 " ns)",
2729 vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs, PRESENT_TIME_OFFSET_FROM_VSYNC_NS,
2730 mHwc->getRefreshPeriod(HWC_DISPLAY_PRIMARY));
2731 result.append("\n");
2733 // Dump static screen stats
2734 result.append("\n");
2735 dumpStaticScreenStats(result);
2736 result.append("\n");
2739 * Dump the visible layer list
2741 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2742 const size_t count = currentLayers.size();
2743 colorizer.bold(result);
2744 result.appendFormat("Visible layers (count = %zu)\n", count);
2745 colorizer.reset(result);
2746 for (size_t i=0 ; i<count ; i++) {
2747 const sp<Layer>& layer(currentLayers[i]);
2748 layer->dump(result, colorizer);
2752 * Dump Display state
2755 colorizer.bold(result);
2756 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
2757 colorizer.reset(result);
2758 for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2759 const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2764 * Dump SurfaceFlinger global state
2767 colorizer.bold(result);
2768 result.append("SurfaceFlinger global state:\n");
2769 colorizer.reset(result);
2771 HWComposer& hwc(getHwComposer());
2772 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2774 colorizer.bold(result);
2775 result.appendFormat("EGL implementation : %s\n",
2776 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2777 colorizer.reset(result);
2778 result.appendFormat("%s\n",
2779 eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2781 mRenderEngine->dump(result);
2783 hw->undefinedRegion.dump(result, "undefinedRegion");
2784 result.appendFormat(" orientation=%d, isDisplayOn=%d\n",
2785 hw->getOrientation(), hw->isDisplayOn());
2786 result.appendFormat(
2787 " last eglSwapBuffers() time: %f us\n"
2788 " last transaction time : %f us\n"
2789 " transaction-flags : %08x\n"
2790 " refresh-rate : %f fps\n"
2793 " gpu_to_cpu_unsupported : %d\n"
2795 mLastSwapBufferTime/1000.0,
2796 mLastTransactionTime/1000.0,
2798 1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2799 hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2800 hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2801 !mGpuToCpuSupported);
2803 result.appendFormat(" eglSwapBuffers time: %f us\n",
2804 inSwapBuffersDuration/1000.0);
2806 result.appendFormat(" transaction time: %f us\n",
2807 inTransactionDuration/1000.0);
2812 mEventThread->dump(result);
2815 * Dump HWComposer state
2817 colorizer.bold(result);
2818 result.append("h/w composer state:\n");
2819 colorizer.reset(result);
2820 result.appendFormat(" h/w composer %s and %s\n",
2821 hwc.initCheck()==NO_ERROR ? "present" : "not present",
2822 (mDebugDisableHWC || mDebugRegion || mDaltonize
2823 || mHasColorMatrix) ? "disabled" : "enabled");
2827 * Dump gralloc state
2829 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2833 const Vector< sp<Layer> >&
2834 SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2835 // Note: mStateLock is held here
2837 for (size_t i=0 ; i<mDisplays.size() ; i++) {
2838 if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2839 dpy = mDisplays.keyAt(i);
2844 ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2845 // Just use the primary display so we have something to return
2846 dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2848 return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2851 bool SurfaceFlinger::startDdmConnection()
2853 void* libddmconnection_dso =
2854 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2855 if (!libddmconnection_dso) {
2858 void (*DdmConnection_start)(const char* name);
2859 DdmConnection_start =
2860 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
2861 if (!DdmConnection_start) {
2862 dlclose(libddmconnection_dso);
2865 (*DdmConnection_start)(getServiceName());
2869 status_t SurfaceFlinger::onTransact(
2870 uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2873 case CREATE_CONNECTION:
2874 case CREATE_DISPLAY:
2875 case SET_TRANSACTION_STATE:
2877 case CLEAR_ANIMATION_FRAME_STATS:
2878 case GET_ANIMATION_FRAME_STATS:
2879 case SET_POWER_MODE:
2881 // codes that require permission check
2882 IPCThreadState* ipc = IPCThreadState::self();
2883 const int pid = ipc->getCallingPid();
2884 const int uid = ipc->getCallingUid();
2885 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
2886 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2887 ALOGE("Permission Denial: "
2888 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2889 return PERMISSION_DENIED;
2893 case CAPTURE_SCREEN:
2895 // codes that require permission check
2896 IPCThreadState* ipc = IPCThreadState::self();
2897 const int pid = ipc->getCallingPid();
2898 const int uid = ipc->getCallingUid();
2899 if ((uid != AID_GRAPHICS) &&
2900 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2901 ALOGE("Permission Denial: "
2902 "can't read framebuffer pid=%d, uid=%d", pid, uid);
2903 return PERMISSION_DENIED;
2909 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2910 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2911 CHECK_INTERFACE(ISurfaceComposer, data, reply);
2912 if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2913 IPCThreadState* ipc = IPCThreadState::self();
2914 const int pid = ipc->getCallingPid();
2915 const int uid = ipc->getCallingUid();
2916 ALOGE("Permission Denial: "
2917 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2918 return PERMISSION_DENIED;
2922 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2923 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2925 case 1002: // SHOW_UPDATES
2926 n = data.readInt32();
2927 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2928 invalidateHwcGeometry();
2929 repaintEverything();
2931 case 1004:{ // repaint everything
2932 repaintEverything();
2935 case 1005:{ // force transaction
2936 setTransactionFlags(
2938 eDisplayTransactionNeeded|
2942 case 1006:{ // send empty update
2946 case 1008: // toggle use of hw composer
2947 n = data.readInt32();
2948 mDebugDisableHWC = n ? 1 : 0;
2949 invalidateHwcGeometry();
2950 repaintEverything();
2952 case 1009: // toggle use of transform hint
2953 n = data.readInt32();
2954 mDebugDisableTransformHint = n ? 1 : 0;
2955 invalidateHwcGeometry();
2956 repaintEverything();
2958 case 1010: // interrogate.
2959 reply->writeInt32(0);
2960 reply->writeInt32(0);
2961 reply->writeInt32(mDebugRegion);
2962 reply->writeInt32(0);
2963 reply->writeInt32(mDebugDisableHWC);
2966 Mutex::Autolock _l(mStateLock);
2967 sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2968 reply->writeInt32(hw->getPageFlipCount());
2973 n = data.readInt32();
2975 case 1: mDaltonizer.setType(Daltonizer::protanomaly); break;
2976 case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2977 case 3: mDaltonizer.setType(Daltonizer::tritanomaly); break;
2980 mDaltonizer.setMode(Daltonizer::correction);
2982 mDaltonizer.setMode(Daltonizer::simulation);
2985 invalidateHwcGeometry();
2986 repaintEverything();
2990 // apply a color matrix
2991 n = data.readInt32();
2992 mHasColorMatrix = n ? 1 : 0;
2994 // color matrix is sent as mat3 matrix followed by vec3
2995 // offset, then packed into a mat4 where the last row is
2996 // the offset and extra values are 0
2997 for (size_t i = 0 ; i < 4; i++) {
2998 for (size_t j = 0; j < 4; j++) {
2999 mColorMatrix[i][j] = data.readFloat();
3003 mColorMatrix = mat4();
3005 invalidateHwcGeometry();
3006 repaintEverything();
3009 // This is an experimental interface
3010 // Needs to be shifted to proper binder interface when we productize
3012 n = data.readInt32();
3013 mPrimaryDispSync.setRefreshSkipCount(n);
3017 n = data.readInt32();
3018 mForceFullDamage = static_cast<bool>(n);
3021 case 1018: { // Modify Choreographer's phase offset
3022 n = data.readInt32();
3023 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3026 case 1019: { // Modify SurfaceFlinger's phase offset
3027 n = data.readInt32();
3028 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
3036 void SurfaceFlinger::repaintEverything() {
3037 android_atomic_or(1, &mRepaintEverything);
3038 signalTransaction();
3041 // ---------------------------------------------------------------------------
3042 // Capture screen into an IGraphiBufferProducer
3043 // ---------------------------------------------------------------------------
3045 /* The code below is here to handle b/8734824
3047 * We create a IGraphicBufferProducer wrapper that forwards all calls
3048 * from the surfaceflinger thread to the calling binder thread, where they
3049 * are executed. This allows the calling thread in the calling process to be
3050 * reused and not depend on having "enough" binder threads to handle the
3053 class GraphicProducerWrapper : public BBinder, public MessageHandler {
3054 /* Parts of GraphicProducerWrapper are run on two different threads,
3055 * communicating by sending messages via Looper but also by shared member
3056 * data. Coherence maintenance is subtle and in places implicit (ugh).
3058 * Don't rely on Looper's sendMessage/handleMessage providing
3059 * release/acquire semantics for any data not actually in the Message.
3060 * Data going from surfaceflinger to binder threads needs to be
3061 * synchronized explicitly.
3063 * Barrier open/wait do provide release/acquire semantics. This provides
3064 * implicit synchronization for data coming back from binder to
3065 * surfaceflinger threads.
3068 sp<IGraphicBufferProducer> impl;
3084 * Called on surfaceflinger thread. This is called by our "fake"
3085 * BpGraphicBufferProducer. We package the data and reply Parcel and
3086 * forward them to the binder thread.
3088 virtual status_t transact(uint32_t code,
3089 const Parcel& data, Parcel* reply, uint32_t /* flags */) {
3092 this->reply = reply;
3094 // if we've exited, we run the message synchronously right here.
3095 // note (JH): as far as I can tell from looking at the code, this
3096 // never actually happens. if it does, i'm not sure if it happens
3097 // on the surfaceflinger or binder thread.
3098 handleMessage(Message(MSG_API_CALL));
3101 // Prevent stores to this->{code, data, reply} from being
3102 // reordered later than the construction of Message.
3103 atomic_thread_fence(memory_order_release);
3104 looper->sendMessage(this, Message(MSG_API_CALL));
3111 * here we run on the binder thread. All we've got to do is
3112 * call the real BpGraphicBufferProducer.
3114 virtual void handleMessage(const Message& message) {
3115 int what = message.what;
3116 // Prevent reads below from happening before the read from Message
3117 atomic_thread_fence(memory_order_acquire);
3118 if (what == MSG_API_CALL) {
3119 result = IInterface::asBinder(impl)->transact(code, data[0], reply);
3121 } else if (what == MSG_EXIT) {
3122 exitRequested = true;
3127 GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl)
3129 looper(new Looper(true)),
3131 exitRequested(false)
3135 status_t waitForResponse() {
3137 looper->pollOnce(-1);
3138 } while (!exitRequested);
3143 void exit(status_t result) {
3144 this->result = result;
3146 // Ensure this->result is visible to the binder thread before it
3147 // handles the message.
3148 atomic_thread_fence(memory_order_release);
3149 looper->sendMessage(this, Message(MSG_EXIT));
3154 status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
3155 const sp<IGraphicBufferProducer>& producer,
3156 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3157 uint32_t minLayerZ, uint32_t maxLayerZ,
3158 bool useIdentityTransform, ISurfaceComposer::Rotation rotation) {
3160 if (CC_UNLIKELY(display == 0))
3163 if (CC_UNLIKELY(producer == 0))
3166 // if we have secure windows on this display, never allow the screen capture
3167 // unless the producer interface is local (i.e.: we can take a screenshot for
3169 if (!IInterface::asBinder(producer)->localBinder()) {
3170 Mutex::Autolock _l(mStateLock);
3171 sp<const DisplayDevice> hw(getDisplayDevice(display));
3172 if (hw->getSecureLayerVisible()) {
3173 ALOGW("FB is protected: PERMISSION_DENIED");
3174 return PERMISSION_DENIED;
3178 // Convert to surfaceflinger's internal rotation type.
3179 Transform::orientation_flags rotationFlags;
3181 case ISurfaceComposer::eRotateNone:
3182 rotationFlags = Transform::ROT_0;
3184 case ISurfaceComposer::eRotate90:
3185 rotationFlags = Transform::ROT_90;
3187 case ISurfaceComposer::eRotate180:
3188 rotationFlags = Transform::ROT_180;
3190 case ISurfaceComposer::eRotate270:
3191 rotationFlags = Transform::ROT_270;
3194 rotationFlags = Transform::ROT_0;
3195 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
3199 class MessageCaptureScreen : public MessageBase {
3200 SurfaceFlinger* flinger;
3201 sp<IBinder> display;
3202 sp<IGraphicBufferProducer> producer;
3204 uint32_t reqWidth, reqHeight;
3205 uint32_t minLayerZ,maxLayerZ;
3206 bool useIdentityTransform;
3207 Transform::orientation_flags rotation;
3210 MessageCaptureScreen(SurfaceFlinger* flinger,
3211 const sp<IBinder>& display,
3212 const sp<IGraphicBufferProducer>& producer,
3213 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3214 uint32_t minLayerZ, uint32_t maxLayerZ,
3215 bool useIdentityTransform, Transform::orientation_flags rotation)
3216 : flinger(flinger), display(display), producer(producer),
3217 sourceCrop(sourceCrop), reqWidth(reqWidth), reqHeight(reqHeight),
3218 minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
3219 useIdentityTransform(useIdentityTransform),
3221 result(PERMISSION_DENIED)
3224 status_t getResult() const {
3227 virtual bool handler() {
3228 Mutex::Autolock _l(flinger->mStateLock);
3229 sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
3230 result = flinger->captureScreenImplLocked(hw, producer,
3231 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3232 useIdentityTransform, rotation);
3233 static_cast<GraphicProducerWrapper*>(IInterface::asBinder(producer).get())->exit(result);
3238 // make sure to process transactions before screenshots -- a transaction
3239 // might already be pending but scheduled for VSYNC; this guarantees we
3240 // will handle it before the screenshot. When VSYNC finally arrives
3241 // the scheduled transaction will be a no-op. If no transactions are
3242 // scheduled at this time, this will end-up being a no-op as well.
3243 mEventQueue.invalidateTransactionNow();
3245 // this creates a "fake" BBinder which will serve as a "fake" remote
3246 // binder to receive the marshaled calls and forward them to the
3247 // real remote (a BpGraphicBufferProducer)
3248 sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
3250 // the asInterface() call below creates our "fake" BpGraphicBufferProducer
3251 // which does the marshaling work forwards to our "fake remote" above.
3252 sp<MessageBase> msg = new MessageCaptureScreen(this,
3253 display, IGraphicBufferProducer::asInterface( wrapper ),
3254 sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ,
3255 useIdentityTransform, rotationFlags);
3257 status_t res = postMessageAsync(msg);
3258 if (res == NO_ERROR) {
3259 res = wrapper->waitForResponse();
3265 void SurfaceFlinger::renderScreenImplLocked(
3266 const sp<const DisplayDevice>& hw,
3267 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3268 uint32_t minLayerZ, uint32_t maxLayerZ,
3269 bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation)
3272 RenderEngine& engine(getRenderEngine());
3274 // get screen geometry
3275 const int32_t hw_w = hw->getWidth();
3276 const int32_t hw_h = hw->getHeight();
3277 const bool filtering = static_cast<int32_t>(reqWidth) != hw_w ||
3278 static_cast<int32_t>(reqHeight) != hw_h;
3280 // if a default or invalid sourceCrop is passed in, set reasonable values
3281 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 ||
3282 !sourceCrop.isValid()) {
3283 sourceCrop.setLeftTop(Point(0, 0));
3284 sourceCrop.setRightBottom(Point(hw_w, hw_h));
3287 // ensure that sourceCrop is inside screen
3288 if (sourceCrop.left < 0) {
3289 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
3291 if (sourceCrop.right > hw_w) {
3292 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, hw_w);
3294 if (sourceCrop.top < 0) {
3295 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
3297 if (sourceCrop.bottom > hw_h) {
3298 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, hw_h);
3301 // make sure to clear all GL error flags
3302 engine.checkErrors();
3304 // set-up our viewport
3305 engine.setViewportAndProjection(
3306 reqWidth, reqHeight, sourceCrop, hw_h, yswap, rotation);
3307 engine.disableTexturing();
3309 // redraw the screen entirely...
3310 engine.clearWithColor(0, 0, 0, 1);
3312 const LayerVector& layers( mDrawingState.layersSortedByZ );
3313 const size_t count = layers.size();
3314 for (size_t i=0 ; i<count ; ++i) {
3315 const sp<Layer>& layer(layers[i]);
3316 const Layer::State& state(layer->getDrawingState());
3317 if (state.layerStack == hw->getLayerStack()) {
3318 if (state.z >= minLayerZ && state.z <= maxLayerZ) {
3319 if (layer->isVisible()) {
3320 if (filtering) layer->setFiltering(true);
3321 layer->draw(hw, useIdentityTransform);
3322 if (filtering) layer->setFiltering(false);
3328 // compositionComplete is needed for older driver
3329 hw->compositionComplete();
3330 hw->setViewportAndProjection();
3334 status_t SurfaceFlinger::captureScreenImplLocked(
3335 const sp<const DisplayDevice>& hw,
3336 const sp<IGraphicBufferProducer>& producer,
3337 Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
3338 uint32_t minLayerZ, uint32_t maxLayerZ,
3339 bool useIdentityTransform, Transform::orientation_flags rotation)
3343 // get screen geometry
3344 uint32_t hw_w = hw->getWidth();
3345 uint32_t hw_h = hw->getHeight();
3347 if (rotation & Transform::ROT_90) {
3348 std::swap(hw_w, hw_h);
3351 if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3352 ALOGE("size mismatch (%d, %d) > (%d, %d)",
3353 reqWidth, reqHeight, hw_w, hw_h);
3357 reqWidth = (!reqWidth) ? hw_w : reqWidth;
3358 reqHeight = (!reqHeight) ? hw_h : reqHeight;
3360 // create a surface (because we're a producer, and we need to
3361 // dequeue/queue a buffer)
3362 sp<Surface> sur = new Surface(producer, false);
3363 ANativeWindow* window = sur.get();
3365 status_t result = native_window_api_connect(window, NATIVE_WINDOW_API_EGL);
3366 if (result == NO_ERROR) {
3367 uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3368 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3371 err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3372 err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3373 err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3374 err |= native_window_set_usage(window, usage);
3376 if (err == NO_ERROR) {
3377 ANativeWindowBuffer* buffer;
3378 /* TODO: Once we have the sync framework everywhere this can use
3379 * server-side waits on the fence that dequeueBuffer returns.
3381 result = native_window_dequeue_buffer_and_wait(window, &buffer);
3382 if (result == NO_ERROR) {
3384 // create an EGLImage from the buffer so we can later
3385 // turn it into a texture
3386 EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3387 EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3388 if (image != EGL_NO_IMAGE_KHR) {
3389 // this binds the given EGLImage as a framebuffer for the
3390 // duration of this scope.
3391 RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3392 if (imageBond.getStatus() == NO_ERROR) {
3393 // this will in fact render into our dequeued buffer
3394 // via an FBO, which means we didn't have to create
3395 // an EGLSurface and therefore we're not
3396 // dependent on the context's EGLConfig.
3397 renderScreenImplLocked(
3398 hw, sourceCrop, reqWidth, reqHeight, minLayerZ, maxLayerZ, true,
3399 useIdentityTransform, rotation);
3401 // Attempt to create a sync khr object that can produce a sync point. If that
3402 // isn't available, create a non-dupable sync object in the fallback path and
3403 // wait on it directly.
3405 if (!DEBUG_SCREENSHOTS) {
3406 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_NATIVE_FENCE_ANDROID, NULL);
3407 // native fence fd will not be populated until flush() is done.
3408 getRenderEngine().flush();
3410 sync = EGL_NO_SYNC_KHR;
3412 if (sync != EGL_NO_SYNC_KHR) {
3414 syncFd = eglDupNativeFenceFDANDROID(mEGLDisplay, sync);
3415 if (syncFd == EGL_NO_NATIVE_FENCE_FD_ANDROID) {
3416 ALOGW("captureScreen: failed to dup sync khr object");
3419 eglDestroySyncKHR(mEGLDisplay, sync);
3422 sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3423 if (sync != EGL_NO_SYNC_KHR) {
3424 EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3425 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3426 EGLint eglErr = eglGetError();
3427 if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3428 ALOGW("captureScreen: fence wait timed out");
3430 ALOGW_IF(eglErr != EGL_SUCCESS,
3431 "captureScreen: error waiting on EGL fence: %#x", eglErr);
3433 eglDestroySyncKHR(mEGLDisplay, sync);
3435 ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3438 if (DEBUG_SCREENSHOTS) {
3439 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3440 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3441 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3442 hw, minLayerZ, maxLayerZ);
3447 ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3448 result = INVALID_OPERATION;
3450 // destroy our image
3451 eglDestroyImageKHR(mEGLDisplay, image);
3455 // queueBuffer takes ownership of syncFd
3456 result = window->queueBuffer(window, buffer, syncFd);
3461 native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3467 void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3468 const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3469 if (DEBUG_SCREENSHOTS) {
3470 for (size_t y=0 ; y<h ; y++) {
3471 uint32_t const * p = (uint32_t const *)vaddr + y*s;
3472 for (size_t x=0 ; x<w ; x++) {
3473 if (p[x] != 0xFF000000) return;
3476 ALOGE("*** we just took a black screenshot ***\n"
3477 "requested minz=%d, maxz=%d, layerStack=%d",
3478 minLayerZ, maxLayerZ, hw->getLayerStack());
3479 const LayerVector& layers( mDrawingState.layersSortedByZ );
3480 const size_t count = layers.size();
3481 for (size_t i=0 ; i<count ; ++i) {
3482 const sp<Layer>& layer(layers[i]);
3483 const Layer::State& state(layer->getDrawingState());
3484 const bool visible = (state.layerStack == hw->getLayerStack())
3485 && (state.z >= minLayerZ && state.z <= maxLayerZ)
3486 && (layer->isVisible());
3487 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3488 visible ? '+' : '-',
3489 i, layer->getName().string(), state.layerStack, state.z,
3490 layer->isVisible(), state.flags, state.alpha);
3495 // ---------------------------------------------------------------------------
3497 SurfaceFlinger::LayerVector::LayerVector() {
3500 SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3501 : SortedVector<sp<Layer> >(rhs) {
3504 int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3505 const void* rhs) const
3507 // sort layers per layer-stack, then by z-order and finally by sequence
3508 const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3509 const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3511 uint32_t ls = l->getCurrentState().layerStack;
3512 uint32_t rs = r->getCurrentState().layerStack;
3516 uint32_t lz = l->getCurrentState().z;
3517 uint32_t rz = r->getCurrentState().z;
3521 return l->sequence - r->sequence;
3524 // ---------------------------------------------------------------------------
3526 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3527 : type(DisplayDevice::DISPLAY_ID_INVALID), width(0), height(0) {
3530 SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3531 : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0), width(0), height(0) {
3532 viewport.makeInvalid();
3533 frame.makeInvalid();
3536 // ---------------------------------------------------------------------------
3538 }; // namespace android
3541 #if defined(__gl_h_)
3542 #error "don't include gl/gl.h in this file"
3545 #if defined(__gl2_h_)
3546 #error "don't include gl2/gl2.h in this file"